Jump to content
Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
If you make an edit, a temporary account will be created for you.

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

MediaWiki interface page
ReisuDesign (talk | contribs)
No edit summary
ReisuDesign (talk | contribs)
No edit summary
 
(23 intermediate revisions by the same user not shown)
Line 1: Line 1:
(function (mw, $) {
(function (mw, $) {
'use strict';
    'use strict';


    const PreloadEditor = {
        version: '1.2.0',


const PreloadEditor = {
        state: {
    version: '0.2.0',
            preloadTitle: '',
            preloadSource: '',
            preloadContent: '',
            config: null,
            variables: [],
            conditions: [],
            selectedVariable: 'PAGE',
            deletedVariables: [],
            mode: 'idle',
            dirty: false,
            dirtyPreload: false,
            dirtyConfig: false,
 
            // Local draft state
            localDraftSavedAt: null,
            localDraftAvailable: false
        },


    state: {
         editor: null,
         preloadTitle: '',
         editorView: null,
         preloadSource: '',
         analysis: null,
         preloadContent: '',
         root: null,
         config: null,
         workspace: null,
         variables: [],
         status: null,
         conditions: [],
         localDraftStatus: null,
         mode: 'idle',
         editorTools: null,
         dirty: false
    },


    editor: null,
        draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',
    editorView: null,
    analysis: null,
    root: null,
    workspace: null,
    status: null,


    defaults: {
        defaults: {
        preload:
            preload: '<includeonly>\n<!-- preload here -->\n</includeonly>\n<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            '<includeonly>\n' +
        },
            '<!-- preload here -->\n' +
            '</includeonly>\n' +
            '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
    },


    // API
        // =========================================================
        // Browser-local draft storage
        // =========================================================


    async getPage(title) {
        getDraftStorage() {
        const api = new mw.Api();
            try {
                const raw = window.localStorage.getItem(this.draftStorageKey);


        const response = await api.get({
                if (!raw) {
            action: 'query',
                    return {
            prop: 'revisions',
                        active: null,
            titles: title,
                        drafts: {}
            rvprop: 'content',
                    };
            rvslots: 'main',
                }
            formatversion: 2
        });


        const page =
                const parsed = JSON.parse(raw);
            response &&
            response.query &&
            response.query.pages &&
            response.query.pages[0];


        if (!page || page.missing) {
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
                    return {
        }
                        active: null,
                        drafts: {}
                    };
                }


        const content =
                if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
            page.revisions &&
                    parsed.drafts = {};
            page.revisions[0] &&
                }
            page.revisions[0].slots &&
            page.revisions[0].slots.main &&
            page.revisions[0].slots.main.content;


        return {
                return parsed;
             title: page.title || title,
             } catch (error) {
            content:
                 console.warn('Preload Editor: Could not read local drafts.', error);
                 typeof content === 'string'
                    ? content
                    : ''
        };
    },


    async pageExists(title) {
                return {
        return !!await this.getPage(title);
                    active: null,
    },
                    drafts: {}
                };
            }
        },


    async searchPages(query) {
        setDraftStorage(storage) {
        const api = new mw.Api();
            try {
                window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                return true;
            } catch (error) {
                console.warn('Preload Editor: Could not save local draft.', error);
                return false;
            }
        },


         const response = await api.get({
         getDraftId(title) {
             action: 'query',
             title = String(title || '').trim();
             list: 'search',
             return title ? title.toLowerCase() : '__untitled__';
            srsearch: query,
         },
            srlimit: 10,
            srnamespace: 10,
            formatversion: 2
         });


         return (
         getDraftSnapshot() {
             response &&
             let content = this.getEditorContent();
            response.query &&
            response.query.search
                ? response.query.search
                : []
        );
    },


    async savePage(title, content, summary, createOnly) {
            if (!this.editorView && !content) {
        const api = new mw.Api();
                content = this.state.preloadContent || '';
            }


        const params = {
            let config = null;
            action: 'edit',
            title: title,
            text: content,
            summary: summary || 'Updated with Preload Editor',
            formatversion: 2
        };


        if (createOnly) {
            try {
            params.createonly = true;
                config = this.state.config
        }
                    ? JSON.parse(JSON.stringify(this.state.config))
                    : this.emptyConfig();
            } catch (error) {
                console.warn('Preload Editor: Could not clone config for local draft.', error);
                config = this.emptyConfig();
            }


        return api.postWithToken('csrf', params);
            return {
    },
                version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,


    // Preload parsing
                variables: Array.isArray(this.state.variables)
                    ? this.state.variables.slice()
                    : [],


    extractIncludeonly(source) {
                conditions: Array.isArray(this.state.conditions)
        const match = String(source || '').match(
                    ? this.state.conditions.slice()
            /<includeonly>([\s\S]*?)<\/includeonly>/i
                    : [],
        );


        return match
                selectedVariable: String(this.state.selectedVariable || 'PAGE'),
            ? match[1].trim()
            : String(source || '').trim();
    },


    findVariables(content) {
                deletedVariables: Array.isArray(this.state.deletedVariables)
        const variables = [];
                    ? this.state.deletedVariables.slice()
        const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                    : [],
        let match;


        while ((match = pattern.exec(content)) !== null) {
                mode: this.state.mode || 'edit',
            const name = match[1].toUpperCase();
                dirty: !!this.state.dirty,
                dirtyPreload: !!this.state.dirtyPreload,
                dirtyConfig: !!this.state.dirtyConfig,
                savedAt: Date.now()
            };
        },


             if (!variables.includes(name)) {
        updateLocalDraftStatus(message, type) {
                 variables.push(name);
             if (!this.localDraftStatus) {
                 return;
             }
             }
        }


        return variables;
            this.localDraftStatus.removeClass(
    },
                'is-saved',
                'is-warning',
                'is-error',
                'is-empty'
            );


    findConditions(content) {
            if (type) {
        const conditions = [];
                this.localDraftStatus.addClass('is-' + type);
        const pattern =
            }
            /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
        let match;


        while ((match = pattern.exec(content)) !== null) {
             this.localDraftStatus.text(message || '');
             conditions.push({
         },
                type: match[1].toLowerCase(),
                expression: match[2].trim(),
                index: match.index
            });
         }


         return conditions;
         formatLocalDraftTime(timestamp) {
    },
            if (!timestamp) {
                return '';
            }


    findConditionVariables(content) {
            try {
        const variables = [];
                return new Date(timestamp).toLocaleTimeString([], {
        const conditions = this.findConditions(content);
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            } catch (error) {
                return '';
            }
        },


         conditions.forEach(condition => {
         updateLocalDraftIndicator() {
             if (
             if (!this.localDraftStatus) {
                condition.type !== 'if' &&
                condition.type !== 'elseif'
            ) {
                 return;
                 return;
             }
             }


             const matches =
             if (this.state.localDraftSavedAt) {
                condition.expression.match(
                const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);
                    /[A-Za-z0-9_-]+/g
                ) || [];


            matches.forEach(name => {
                this.updateLocalDraftStatus(
                 const upper = name.toUpperCase();
                    time ? 'Saved locally at ' + time : 'Saved locally',
                    'saved'
                 );
 
                return;
            }


                if (!variables.includes(upper)) {
            this.updateLocalDraftStatus('No local draft', 'empty');
                    variables.push(upper);
         },
                }
            });
         });


         return variables;
         saveDraft() {
    },
            if (!this.state.dirty) {
                return false;
            }


    analyzePreload(content) {
            const snapshot = this.getDraftSnapshot();
        const variables = this.findVariables(content);
            const id = this.getDraftId(snapshot.preloadTitle);
        const conditions = this.findConditions(content);
            const storage = this.getDraftStorage();
        const conditionVariables =
            this.findConditionVariables(content);


        return {
             storage.drafts[id] = snapshot;
             variables,
             storage.active = id;
            conditions,
             conditionVariables
        };
    },


    // Config
            const saved = this.setDraftStorage(storage);


    emptyConfig() {
            if (saved) {
        return {
                this.state.localDraftSavedAt = snapshot.savedAt;
            settings: {
                this.state.localDraftAvailable = true;
                 incomplete: 'add-stub'
                 this.updateLocalDraftIndicator();
             },
             } else {
            fields: {
                 this.state.localDraftAvailable = false;
                 PAGE: {
                this.updateLocalDraftStatus('Could not save local draft', 'error');
                    label: 'Page Name',
                    description: 'Name of the page.',
                    type: 'page',
                    required: true,
                    namespace: 'Main',
                    'allow-new': true
                }
             }
             }
        };
    },


    normalizeConfig(config) {
             return saved;
        if (
         },
            !config ||
            typeof config !== 'object' ||
            Array.isArray(config)
        ) {
             config = this.emptyConfig();
         }


         if (
         clearDraft(title) {
             !config.settings ||
             const storage = this.getDraftStorage();
             typeof config.settings !== 'object' ||
             const id = this.getDraftId(title);
            Array.isArray(config.settings)
        ) {
            config.settings = {};
        }


        if (
            if (storage.drafts && storage.drafts[id]) {
            !config.fields ||
                delete storage.drafts[id];
            typeof config.fields !== 'object' ||
            }
            Array.isArray(config.fields)
        ) {
            config.fields = {};
        }


        if (!config.fields.PAGE) {
            if (storage.active === id) {
            config.fields.PAGE = {
                storage.active = null;
                label: 'Page Name',
            }
                description: 'Name of the page.',
 
                type: 'page',
            this.setDraftStorage(storage);
                required: true,
 
                namespace: 'Main',
            this.state.localDraftSavedAt = null;
                'allow-new': true
             this.state.localDraftAvailable = false;
             };
        }


        return config;
            this.updateLocalDraftIndicator();
    },
        },


    createDefaultField(name, analysis) {
        getMostRecentDraft() {
        const isConditionVariable =
            const storage = this.getDraftStorage();
            analysis.conditionVariables.includes(name);


        return {
             if (!storage.drafts || !Object.keys(storage.drafts).length) {
             label: this.humanizeName(name),
                return null;
            description: '',
             }
             type: isConditionVariable ? 'boolean' : 'text'
        };
    },


    humanizeName(name) {
            if (storage.active && storage.drafts[storage.active]) {
        return String(name || '')
                return {
            .replace(/[_-]+/g, ' ')
                    id: storage.active,
            .replace(/([a-z])([A-Z])/g, '$1 $2')
                    draft: storage.drafts[storage.active]
            .replace(/\s+/g, ' ')
                };
             .trim()
             }
            .replace(/\b\w/g, char => char.toUpperCase());
    },


    prepareConfigForVariables(config, analysis) {
            let latestId = null;
        config = this.normalizeConfig(config);
            let latestDraft = null;


        const existing = config.fields || {};
            Object.entries(storage.drafts).forEach(([id, draft]) => {
        const fields = {};
                if (!draft || typeof draft !== 'object') {
                    return;
                }


        fields.PAGE = existing.PAGE || {
                if (
            label: 'Page Name',
                    !latestDraft ||
            description: 'Name of the page.',
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
            type: 'page',
                ) {
            required: true,
                    latestId = id;
             namespace: 'Main',
                    latestDraft = draft;
            'allow-new': true
                }
        };
             });


        analysis.variables.forEach(name => {
             if (!latestDraft) {
             if (name === 'PAGE') {
                 return null;
                 return;
             }
             }


             fields[name] =
             return {
                 existing[name] ||
                 id: latestId,
                 this.createDefaultField(name, analysis);
                 draft: latestDraft
         });
            };
         },


         Object.keys(existing).forEach(name => {
         async restoreDraft() {
             const upper = name.toUpperCase();
             const result = this.getMostRecentDraft();


             if (!fields[upper]) {
             if (!result || !result.draft) {
                 fields[upper] = existing[name];
                 return false;
             }
             }
        });


        config.fields = fields;
            const draft = result.draft;
        return config;
            const title = String(draft.preloadTitle || '').trim();
    },
            const displayTitle = title || 'an untitled preload';


    validateConfig(config, analysis) {
            const savedAt = draft.savedAt
        const errors = [];
                ? new Date(draft.savedAt).toLocaleString()
        const warnings = [];
                : '';


        if (
             const message =
             !config ||
                'Preload Editor found unsaved local work for ' +
            typeof config !== 'object' ||
                displayTitle +
            Array.isArray(config)
                 (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
        ) {
                 '\n\nRestore it?';
            return {
                 valid: false,
                errors: ['Config must be an object.'],
                 warnings: []
            };
        }


        if (
             const restore = await this.createConfirmDialog(
             !config.fields ||
                'Restore unsaved work',
            typeof config.fields !== 'object' ||
                message,
            Array.isArray(config.fields)
                'Restore',
        ) {
                'Discard'
            errors.push('"fields" must be an object.');
            );


             return {
             if (!restore) {
                 valid: false,
                 this.clearDraft(title);
                 errors,
                 return false;
                warnings
             }
             };
        }


        const configured =
             let config = this.emptyConfig();
             Object.keys(config.fields).map(
                name => name.toUpperCase()
            );


        analysis.variables.forEach(name => {
            if (
            if (!configured.includes(name)) {
                draft.config &&
                 errors.push(
                typeof draft.config === 'object' &&
                     'Variable "' +
                !Array.isArray(draft.config)
                     name +
            ) {
                    '" is not configured.'
                 try {
                );
                    config = this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                     );
                } catch (error) {
                     console.warn(
                        'Preload Editor: Could not restore local config.',
                        error
                    );
                }
             }
             }
        });


        configured.forEach(name => {
            const hasDirtyFlags =
             if (!analysis.variables.includes(name)) {
                typeof draft.dirtyPreload === 'boolean' ||
                 warnings.push(
                typeof draft.dirtyConfig === 'boolean';
                    'Field "' +
 
                    name +
             this.state = {
                    '" is not used by the preload.'
                 preloadTitle: title,
                 );
                preloadSource: String(draft.preloadSource || ''),
            }
                preloadContent: String(draft.preloadContent || ''),
        });
                 config,


        if (!configured.includes('PAGE')) {
                variables: Array.isArray(draft.variables)
            errors.push('PAGE must always be configured.');
                    ? draft.variables.slice()
        }
                    : [],


        Object.entries(config.fields).forEach(
                conditions: Array.isArray(draft.conditions)
            ([name, field]) => {
                    ? draft.conditions.slice()
                 if (
                    : [],
                    !field ||
 
                    typeof field !== 'object' ||
                 selectedVariable: String(draft.selectedVariable || 'PAGE'),
                    Array.isArray(field)
 
                ) {
                deletedVariables: Array.isArray(draft.deletedVariables)
                    errors.push(
                    ? draft.deletedVariables
                         'Field "' +
                        .map(name => String(name).toUpperCase())
                        name +
                         .filter(name => name !== 'PAGE')
                        '" must be an object.'
                    : [],
                     );
 
                     return;
                mode: draft.mode || 'edit',
                 }
 
                dirty: hasDirtyFlags
                     ? !!(draft.dirtyPreload || draft.dirtyConfig)
                     : true,
 
                dirtyPreload: hasDirtyFlags
                    ? !!draft.dirtyPreload
                    : true,
 
                 dirtyConfig: hasDirtyFlags
                    ? !!draft.dirtyConfig
                    : true,


                 if (!field.type) {
                 localDraftSavedAt: Number(draft.savedAt) || null,
                    warnings.push(
                localDraftAvailable: true
                        'Field "' +
            };
                        name +
                        '" has no type.'
                    );
                }


                if (
            this.reanalyze();
                    (
            this.renderEditor();
                        field.type === 'select' ||
             this.updateLocalDraftIndicator();
                        field.type === 'multiselect'
                    ) &&
                    !field.source &&
                    !Array.isArray(field.options)
                ) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                    );
                }
             }
        );


        return {
            this.setStatus(
            valid: errors.length === 0,
                'Restored unsaved local work from this browser.',
            errors,
                'warning'
             warnings
             );
        };
    },


    // Transformation helpers
            mw.notify('Unsaved Preload Editor work restored.', {
                type: 'success'
            });


    transformationObject(
             return true;
        transform,
         },
        prefix,
        suffix,
        from,
        to
    ) {
        if (!transform) {
             return null;
         }


         switch (transform) {
         // =========================================================
            case 'remove-prefix':
        // API
                return prefix
        // =========================================================
                    ? {
                        transform: 'remove-prefix',
                        prefix
                    }
                    : null;


             case 'remove-suffix':
        async getPage(title) {
                 return suffix
             const response = await new mw.Api().get({
                    ? {
                action: 'query',
                        transform: 'remove-suffix',
                prop: 'info|revisions',
                        suffix
                 titles: title,
                    }
                rvprop: 'content',
                    : null;
                rvslots: 'main',
                formatversion: 2
            });


             case 'replace':
             const page =
                 return from === ''
                 response &&
                    ? null
                response.query &&
                    : {
                response.query.pages &&
                        transform: 'replace',
                response.query.pages[0];
                        from,
                        to: to || ''
                    };


             default:
             if (!page || page.missing) {
                 return null;
                 return null;
        }
            }
    },


    // UI helpers
            const content =
                page.revisions &&
                page.revisions[0] &&
                page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;


    createSection(title, className) {
            return {
        const section =
                title: page.title || title,
            $('<section>')
                content: typeof content === 'string' ? content : '',
                 .addClass('preload-editor-section');
                 contentmodel: page.contentmodel || 'wikitext'
            };
        },


         if (className) {
         async pageExists(title) {
             section.addClass(className);
             return !!await this.getPage(title);
         }
         },


         $('<h2>')
         async searchPages(query) {
             .addClass('preload-editor-section-title')
             const response = await new mw.Api().get({
            .text(title)
                action: 'query',
             .appendTo(section);
                list: 'search',
                srsearch: query,
                srlimit: 10,
                srnamespace: 10,
                formatversion: 2
             });


        return section;
            return (
    },
                response &&
                response.query &&
                response.query.search
            ) || [];
        },


    createButton(label, className, callback) {
        /*
        const button =
        * Save a page.
            $('<button>')
        *
                 .attr('type', 'button')
        * contentModel is mainly used when creating a page.
                 .addClass('preload-editor-button')
        *
                 .text(label);
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
        async savePage(title, content, summary, createOnly, contentModel) {
            const params = {
                action: 'edit',
                title,
                 text: content,
                 summary: summary || 'Updated with Preload Editor',
                 formatversion: 2
            };


        if (className) {
            if (createOnly) {
            button.addClass(className);
                params.createonly = true;
        }
            }


        if (callback) {
            if (contentModel) {
            button.on(
                 params.contentmodel = contentModel;
                 'click.preloadEditor',
             }
                callback
             );
        }


        return button;
            return new mw.Api().postWithToken('csrf', params);
    },
        },


    fieldRow(label, input, description) {
        /*
        const row =
        * Change the content model of an existing page.
             $('<div>')
        *
                 .addClass('preload-editor-field');
        * This is the API equivalent of using
        * Special:ChangeContentModel manually.
        *
        * The page must already exist.
        */
        async changeContentModel(title, model, summary) {
             return new mw.Api().postWithToken('csrf', {
                action: 'changecontentmodel',
                title,
                model,
                 reason: summary || 'Changed content model with Preload Editor'
            });
        },


         $('<label>')
         /*
            .addClass('preload-editor-label')
        * Save config.json and make sure its content model
            .text(label)
        * is JSON.
             .appendTo(row);
        *
        * New page:
        *  create directly with contentmodel=json.
        *
        * Existing page:
        *  if not already JSON, change its model first,
        *  then save the JSON normally.
        */
        async saveConfigPage(title, content, summary) {
             const page = await this.getPage(title);


        if (description) {
            if (!page) {
            $('<div>')
                 return this.savePage(
                 .addClass('preload-editor-help')
                    title,
                .text(description)
                    content,
                 .appendTo(row);
                    summary,
        }
                    true,
                    'json'
                 );
            }


        row.append(input);
            if (String(page.contentmodel || '').toLowerCase() !== 'json') {
        return row;
                await this.changeContentModel(
    },
                    title,
                    'json',
                    'Changed preload config content model to JSON'
                );
            }


    textInput(value, placeholder) {
            return this.savePage(
        return $('<input>')
                 title,
            .attr({
                 content,
                 type: 'text',
                summary,
                 value:
                 false
                    value === undefined ||
             );
                    value === null
        },
                        ? ''
                        : value,
                 placeholder: placeholder || ''
            })
             .addClass('preload-editor-input');
    },


    textarea(value) {
        // =========================================================
         return $('<textarea>')
         // Config import helpers
            .val(
        // =========================================================
                value === undefined ||
                value === null
                    ? ''
                    : value
            )
            .addClass('preload-editor-textarea');
    },


    checkbox(checked) {
        /*
         return $('<input>')
        * Accept either:
             .attr('type', 'checkbox')
        *
            .prop('checked', !!checked)
        *  Template:Example/Preload
             .addClass('preload-editor-checkbox');
        *
    },
        * or:
        *
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
         normalizeConfigTitle(title) {
             title = String(title || '').trim();
             title = title.replace(/\/+$/, '');


    select(options, value) {
            if (/\/config\.json$/i.test(title)) {
        const select =
                 return title;
            $('<select>')
            }
                 .addClass('preload-editor-select');


        options.forEach(option => {
             return title + '/config.json';
             $('<option>')
         },
                .attr('value', option.value)
                .text(option.label)
                .prop(
                    'selected',
                    String(option.value) ===
                        String(
                            value === undefined
                                ? ''
                                : value
                        )
                )
                .appendTo(select);
         });


         return select;
         /*
    },
        * Return a safe clone of a config field.
 
        *
    // CodeMirror
        * This is deliberately JSON-based because config
        * definitions are JSON-compatible objects.
        */
        cloneConfigField(field) {
            try {
                return JSON.parse(JSON.stringify(field));
            } catch (error) {
                console.warn(
                    'Preload Editor: Could not clone imported field.',
                    error
                );


    destroyEditor() {
                return null;
        if (!this.editor) {
             }
            this.editorView = null;
         },
             return;
         }


         const {
         /*
            view,
        * Normalize imported field names to the same uppercase
            inputHandler
        * convention used throughout the editor.
         } = this.editor;
        */
         getImportableFields(sourceConfig) {
            const fields = sourceConfig && sourceConfig.fields;


        if (view && inputHandler) {
            if (
            view.dom.removeEventListener(
                !fields ||
                 'input',
                 typeof fields !== 'object' ||
                 inputHandler
                 Array.isArray(fields)
             );
             ) {
        }
                return {};
            }


        if (view) {
            const result = {};
            view.destroy();
        }


        this.editor = null;
            Object.entries(fields).forEach(([name, field]) => {
        this.editorView = null;
                const upper = String(name || '').trim().toUpperCase();
    },


    getEditorView() {
                if (!upper || upper === 'PAGE') {
        return this.editorView;
                    return;
    },
                }


    getEditorContent() {
                if (
        if (
                    !field ||
            this.editorView &&
                    typeof field !== 'object' ||
            this.editorView.state
                    Array.isArray(field)
        ) {
                ) {
            return this.editorView.state.doc.toString();
                    return;
        }
                }


        return this.state.preloadContent || '';
                const clone = this.cloneConfigField(field);
    },


    setEditorContent(content) {
                if (!clone) {
        content = String(content || '');
                    return;
                }


        if (!this.editorView) {
                result[upper] = clone;
            this.state.preloadContent = content;
             });
             return;
        }


        const current =
             return result;
             this.editorView.state.doc.toString();
        },


         if (current === content) {
         /*
             return;
        * Show the variable-selection dialog after a source
        }
        * config has been loaded.
        *
        * Resolves:
        *  null -> cancelled
        *  []  -> confirmed with no selections
        *  [...] -> selected field names
        */
        createImportDefinitionsDialog(sourceTitle, fields) {
             return new Promise(resolve => {
                const names = Object.keys(fields).sort((a, b) => a.localeCompare(b));


        this.editorView.dispatch({
                const overlay = $('<div>')
            changes: {
                    .addClass(
                from: 0,
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                to: this.editorView.state.doc.length,
                    );
                insert: content
            }
        });
    },


    // Preload syntax highlighting
                const box = $('<div>')
                    .addClass(
                        'preload-editor-prompt preload-editor-import-dialog'
                    );


    getKnownVariables() {
                $('<h2>')
        const known = new Set(['PAGE']);
                    .text('Import variable definitions')
                    .appendTo(box);


        const fields =
                $('<p>')
            this.state.config &&
                    .text(
            this.state.config.fields;
                        'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                    )
                    .appendTo(box);


        if (fields && typeof fields === 'object') {
                if (!names.length) {
            Object.keys(fields).forEach(name => {
                    $('<div>')
                known.add(
                        .addClass(
                    String(name).toUpperCase()
                            'preload-editor-empty preload-editor-import-empty'
                );
                        )
            });
                        .text(
        }
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);


        return known;
                    const emptyButtons = $('<div>')
    },
                        .addClass('preload-editor-prompt-buttons');


    createSyntaxDecorations(state, Decoration) {
                    const close = this.createButton(
        const decorations = [];
                        'Close',
        const source = state.doc.toString();
                        'preload-editor-button-primary',
        const knownVariables =
                        () => {
            this.getKnownVariables();
                            overlay.remove();
                            resolve(null);
                        }
                    );


        const variablePattern =
                    emptyButtons.append(close);
            /%%([A-Za-z0-9_-]+)%%/g;
                    box.append(emptyButtons);
                    overlay.append(box);


        let match;
                    $(document.body).append(overlay);


        while (
                    overlay.attr('tabindex', '-1');
            (match = variablePattern.exec(source)) !== null
                    overlay.trigger('focus');
        ) {
            const name =
                match[1].toUpperCase();


            const known =
                    return;
                 knownVariables.has(name);
                 }


            const classes = [
                const search = this.textInput('', 'Search variables...')
                'preload-editor-syntax-variable',
                     .addClass('preload-editor-import-search');
                known
                    ? 'preload-editor-syntax-variable-known'
                     : 'preload-editor-syntax-variable-unknown'
            ];


            decorations.push(
                 const searchWrap = $('<div>')
                 Decoration.mark({
                     .addClass('preload-editor-import-search-wrap')
                     class: classes.join(' ')
                    .append(search);
                }).range(
                    match.index,
                    match.index + match[0].length
                )
            );
        }


        const conditionPattern =
                box.append(searchWrap);
            /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


        while (
                const controls = $('<div>')
            (match = conditionPattern.exec(source)) !== null
                    .addClass('preload-editor-import-controls');
        ) {
            const fullStart = match.index;
            const fullEnd =
                match.index + match[0].length;


            decorations.push(
                const selectAll = this.createButton(
                Decoration.mark({
                    'Select all',
                    class:
                    '',
                        'preload-editor-syntax-condition'
                    () => {
                 }).range(
                        list
                     fullStart,
                            .find('input[type="checkbox"]:visible')
                     fullEnd
                            .prop('checked', true);
                )
 
            );
                        updateSummary();
                    }
                 );
 
                const deselectAll = this.createButton(
                     'Deselect all',
                     '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);
 
                        updateSummary();
                    }
                );


            const directiveStart =
                 controls.append(selectAll, deselectAll);
                 match.index +
                 box.append(controls);
                 match[0].indexOf('@');


            const directiveEnd =
                const list = $('<div>')
                directiveStart +
                    .addClass('preload-editor-import-list');
                match[1].length +
                1;


            decorations.push(
                 const localFields =
                 Decoration.mark({
                     this.state.config && this.state.config.fields
                     class:
                         ? this.state.config.fields
                         'preload-editor-syntax-directive'
                        : {};
                }).range(
                    directiveStart,
                    directiveEnd
                )
            );


            if (
                 names.forEach(name => {
                 match[1].toLowerCase() === 'if' ||
                    const existing = !!localFields[name];
                match[1].toLowerCase() === 'elseif'
                    const field = fields[name];
            ) {
                const expression =
                    match[2];


                const expressionStart =
                    const type = field && field.type
                    match.index +
                        ? String(field.type)
                    match[0].indexOf(
                         : 'text';
                         expression
                    );


                const expressionPattern =
                    const label = field && field.label
                    /[A-Za-z0-9_-]+/g;
                        ? String(field.label)
                        : this.humanizeName(name);


                let expressionMatch;
                    const row = $('<label>')
                        .addClass('preload-editor-import-row')
                        .attr('data-variable', name)
                        .attr(
                            'data-search',
                            (name + ' ' + label + ' ' + type).toLowerCase()
                        );


                while (
                     const checkbox = this.checkbox(false)
                     (
                         .attr('data-import-variable', name)
                         expressionMatch =
                        .addClass('preload-editor-import-checkbox');
                            expressionPattern.exec(
 
                                expression
                     const content = $('<span>')
                            )
                         .addClass('preload-editor-import-content');
                    ) !== null
                ) {
                     const name =
                         expressionMatch[0]
                            .toUpperCase();


                     if (
                     const header = $('<span>')
                         !knownVariables.has(name)
                         .addClass('preload-editor-import-header');
                    ) {
                        continue;
                    }


                     const start =
                     $('<strong>')
                         expressionStart +
                         .text(name)
                         expressionMatch.index;
                         .appendTo(header);


                     const end =
                     $('<span>')
                         start +
                         .addClass('preload-editor-import-type')
                         expressionMatch[0].length;
                        .text(type)
                         .appendTo(header);


                     decorations.push(
                     const meta = $('<span>')
                         Decoration.mark({
                         .addClass('preload-editor-import-meta');
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            end
                        )
                    );
                }
            }
        }


        return Decoration.set(
                    $('<span>')
            decorations,
                        .text(label)
            true
                        .appendTo(meta);
        );
    },


    async installSyntaxHighlighting(view) {
                    const status = $('<span>')
        await mw.loader.using(
                        .addClass('preload-editor-import-status')
            'ext.CodeMirror.v6.lib'
                        .toggleClass('is-existing', existing)
        );
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');


        const require =
                    content.append(header, meta, status);
            mw.loader.require;
                    row.append(checkbox, content);
                    list.append(row);
                });


        const {
                box.append(list);
            StateField,
            StateEffect,
            EditorView,
            Decoration
        } = require(
            'ext.CodeMirror.v6.lib'
        );


        const syntaxField =
                const summary = $('<div>')
            StateField.define({
                     .addClass('preload-editor-import-summary');
                create: state =>
                     this.createSyntaxDecorations(
                        state,
                        Decoration
                    ),


                 update: (decorations, transaction) => {
                 const updateSummary = () => {
                     if (
                     const selected = list.find(
                         !transaction.docChanged
                         'input[type="checkbox"]:checked'
                     ) {
                     ).length;
                        return decorations;
                    }


                     return this.createSyntaxDecorations(
                     const existingSelected = list
                         transaction.state,
                        .find('input[type="checkbox"]:checked')
                        Decoration
                         .filter(function () {
                    );
                            const name = $(this).attr(
                },
                                'data-import-variable'
                            );


                provide: field =>
                            return !!localFields[name];
                    EditorView.decorations.from(
                         }).length;
                         field
                    )
            });


        view.dispatch({
                    let text =
            effects:
                        selected +
                StateEffect.appendConfig.of(
                        ' ' +
                    syntaxField
                        (selected === 1 ? 'variable' : 'variables') +
                )
                        ' selected.';
        });


        this.editor.syntaxField =
                    if (existingSelected) {
            syntaxField;
                        text +=
    },
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


    async mountCodeMirror(textarea) {
                    summary.text(text);
        return new Promise((resolve, reject) => {
            let settled = false;


            const cleanup = () => {
                     importButton.prop('disabled', selected === 0);
                mw.hook('dev.CCM.ready').remove(
                 };
                     onReady
                );
                mw.hook('dev.CCM.load').remove(
                    onLoad
                );
            };
 
            const onReady = async cm => {
                if (
                    settled ||
                    !cm ||
                    cm.textarea !== textarea ||
                    !cm.view
                ) {
                    return;
                 }


                 settled = true;
                 const filterRows = () => {
                cleanup();
                    const query = String(search.val() || '')
                        .trim()
                        .toLowerCase();


                const view = cm.view;
                    list.find('.preload-editor-import-row').each(function () {
 
                        const row = $(this);
                const inputHandler = () => {
                        const haystack = String(
                    this.state.preloadContent =
                            row.attr('data-search') || ''
                        view.state.doc.toString();
                        );
 
                    this.state.dirty = true;
                    this.reanalyze();


                    this.renderVariablesBySelector();
                        row.toggle(!query || haystack.includes(query));
                    this.renderAnalysisBySelector();
                     });
                     this.renderConfigPreviewBySelector();
                 };
                 };


                 view.dom.addEventListener(
                 search.on(
                     'input',
                     'input.preloadEditor',
                     inputHandler
                     filterRows
                 );
                 );


                 view.dom.classList.add(
                 list.on(
                     'preload-editor-codemirror'
                    'change.preloadEditor',
                     'input[type="checkbox"]',
                    updateSummary
                 );
                 );


                 const wrapper =
                 const buttons = $('<div>')
                     view.dom.closest(
                     .addClass('preload-editor-prompt-buttons');
                        '.ext-codemirror-wrapper'
                    );


                 if (wrapper) {
                 const cancel = this.createButton(
                     wrapper.classList.add(
                     'Cancel',
                        'preload-editor-codemirror-wrapper'
                    '',
                     );
                     () => {
                }
                        overlay.remove();
 
                        resolve(null);
                this.editor = {
                     }
                    cm,
                 );
                    view,
                     textarea,
                    inputHandler
                 };


                 this.editorView = view;
                 const importButton = this.createButton(
                    'Import selected',
                    'preload-editor-button-primary',
                    () => {
                        const selected = [];


                this.state.preloadContent =
                        list
                    view.state.doc.toString();
                            .find('input[type="checkbox"]:checked')
                            .each(function () {
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });


                try {
                        overlay.remove();
                    await this.installSyntaxHighlighting(
                         resolve(selected);
                         view
                     }
                     );
                );


                    resolve(view);
                buttons.append(cancel, importButton);
                 } catch (error) {
                 box.append(summary, buttons);
                    reject(error);
                overlay.append(box);
                }
            };


            const onLoad = loader => {
                 $(document.body).append(overlay);
                 if (
                    settled ||
                    typeof loader !== 'function'
                ) {
                    return;
                }


                 try {
                 overlay.attr('tabindex', '-1');
                    loader(textarea);
                 overlay.trigger('focus');
                 } catch (error) {
                    settled = true;
                    cleanup();
                    reject(error);
                }
            };


            mw.hook('dev.CCM.ready').add(onReady);
                updateSummary();
            mw.hook('dev.CCM.load').add(onLoad);
                search.trigger('focus');
        });
    },


    // Main UI
                const close = event => {
                    if (event.key === 'Escape') {
                        cancel.trigger('click');
                    }
                };


    init() {
                overlay.on(
        const root = $('#mw-content-text');
                    'keydown.preloadEditor',
                    close
                );


        if (!root.length) {
                overlay.on(
             return;
                    'click.preloadEditor',
         }
                    event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                    }
                );
             });
         },


         this.root =
         /*
            $('<div>')
        * Main import workflow.
                .attr('id', 'preload-editor')
        */
                 .addClass('preload-editor');
        async importVariableDefinitions() {
            const source = await this.createPromptDialog(
                'Import variable definitions',
                 'Enter a preload title or its config.json title.'
            );


        root.append(this.root);
            if (!source) {
        this.renderShell();
                return;
    },
            }


    renderShell() {
            const configTitle = this.normalizeConfigTitle(source);
        this.destroyEditor();
        this.root.empty();


        const loader =
             this.setStatus(
            this.createSection('Preload');
                 'Loading source config...',
 
                 'loading'
        const titleInput =
             this.textInput(
                 this.state.preloadTitle,
                'Template:Example/Preload'
            ).attr(
                'id',
                 'preload-editor-title-input'
             );
             );


        const loadButton =
             try {
             this.createButton(
                 const page = await this.getPage(configTitle);
                 'Load',
                'preload-editor-button-primary',
                () => this.loadExisting(titleInput.val())
            );


        const newButton =
                if (!page) {
            this.createButton(
                    throw new Error(
                'New',
                        'No config.json was found at "' +
                '',
                        configTitle +
                () => this.startNew()
                        '".'
            );
                    );
                }


        const sampleButton =
                 let sourceConfig;
            this.createButton(
                 'Load Sample Page',
                '',
                () => this.loadSamplePage()
            );


        const loadRow =
                try {
            $('<div>')
                    sourceConfig = JSON.parse(page.content);
                 .addClass('preload-editor-toolbar')
                 } catch (error) {
                .append(
                    throw new Error(
                    titleInput,
                        'The source config.json contains invalid JSON: ' +
                    loadButton,
                        error.message
                     newButton,
                     );
                    sampleButton
                 }
                 );


        loader.append(loadRow);
                if (
        this.root.append(loader);
                    !sourceConfig ||
                    typeof sourceConfig !== 'object' ||
                    Array.isArray(sourceConfig)
                ) {
                    throw new Error(
                        'The source config.json must contain a JSON object.'
                    );
                }


        this.status =
                if (
            $('<div>')
                    !sourceConfig.fields ||
                 .addClass('preload-editor-status');
                    typeof sourceConfig.fields !== 'object' ||
                    Array.isArray(sourceConfig.fields)
                 ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }


        this.root.append(this.status);
                const fields = this.getImportableFields(sourceConfig);


        this.workspace =
                const selected =
            $('<div>')
                    await this.createImportDefinitionsDialog(
                .addClass('preload-editor-workspace');
                        configTitle,
                        fields
                    );


        this.root.append(this.workspace);
                if (selected === null) {
        this.renderWelcome();
                    this.setStatus(
    },
                        'Variable import cancelled.',
                        'warning'
                    );


    renderWelcome() {
                    return;
        this.workspace.empty();
                }


        const section =
                if (!selected.length) {
            this.createSection('Get started');
                    this.setStatus(
                        'No variable definitions were imported.',
                        'warning'
                    );


        $('<p>')
                    return;
            .text(
                 }
                 'Load an existing preload, create a new one, or start from a sample wiki page.'
            )
            .appendTo(section);


        const tips =
                if (!this.state.config) {
            $('<ul>')
                    this.state.config = this.emptyConfig();
                .addClass('preload-editor-tips');
                }


        [
                if (!this.state.config.fields) {
            'Existing preload: loads the preload and its config.json if available.',
                    this.state.config.fields = {};
            'New preload: starts with the standard Preload Template structure.',
                 }
            'Sample page: loads normal wiki page content so you can turn it into a preload.'
        ].forEach(text => {
            $('<li>')
                .text(text)
                 .appendTo(tips);
        });


        section.append(tips);
                const imported = [];
        this.workspace.append(section);
                const replaced = [];
    },


    setStatus(message, type) {
                selected.forEach(name => {
        if (!this.status) {
                    if (name === 'PAGE') {
            return;
                        return;
        }
                    }


        this.status
                    const field = fields[name];
            .removeClass(
                'is-error',
                'is-success',
                'is-warning',
                'is-loading'
            );


        if (type) {
                    if (!field) {
            this.status.addClass('is-' + type);
                        return;
        }
                    }


        this.status.text(message || '');
                    if (this.state.config.fields[name]) {
    },
                        replaced.push(name);
                    } else {
                        imported.push(name);
                    }


    // Load / create
                    const clone = this.cloneConfigField(field);


    async loadExisting(title) {
                    if (!clone) {
        title = String(title || '').trim();
                        return;
                    }


        if (!title) {
                    this.state.config.fields[name] = clone;
            mw.notify(
                'Enter a preload page title first.',
                { type: 'warn' }
            );
            return;
        }


        this.setStatus(
                    /*
            'Loading preload...',
                    * If this variable was previously deleted,
            'loading'
                    * importing its definition explicitly should
        );
                    * restore it.
                    */
                    if (Array.isArray(this.state.deletedVariables)) {
                        this.state.deletedVariables =
                            this.state.deletedVariables.filter(
                                deletedName =>
                                    String(deletedName).toUpperCase() !== name
                            );
                    }
                });


        try {
                /*
            const page = await this.getPage(title);
                * Keep PAGE automatic regardless of what the
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();


            if (!page) {
                 this.markConfigDirty();
                 const suggestions =
                    await this.findSimilarPreloads(title);


                 this.renderMissingPage(
                 /*
                     title,
                * Keep the current selection when possible.
                     suggestions
                * Otherwise select the first imported definition.
                */
                const selectedStillExists = !!(
                     this.state.config.fields[
                        this.state.selectedVariable
                     ]
                 );
                 );


                 this.setStatus(
                 if (
                     'Preload not found.',
                     !selectedStillExists ||
                     'warning'
                    this.state.selectedVariable === 'PAGE'
                 );
                ) {
                     this.state.selectedVariable =
                        selected[0] ||
                        'PAGE';
                 }


                 return;
                 this.reanalyze();
            }


            await this.loadDefinition(
                this.renderVariablesBySelector();
                 page.title,
                 this.renderVariableConfigurationBySelector();
                 page.content
                 this.renderAnalysisBySelector();
            );
                this.updateEditorTools();


            this.setStatus(
                this.saveDraft();
                'Preload loaded.',
                'success'
            );
        } catch (error) {
            console.error(
                'Preload Editor:',
                error
            );


            this.setStatus(
                let status =
                error.message ||
                    'Imported ' +
                     'Could not load preload.',
                    selected.length +
                'error'
                     ' variable ' +
            );
                    (selected.length === 1
        }
                        ? 'definition'
    },
                        : 'definitions') +
                    '.';


    async findSimilarPreloads(title) {
                if (replaced.length) {
        let query =
                    status +=
            title
                        ' Replaced: ' +
                .replace(/\/Preload$/i, '')
                        replaced.join(', ') +
                .trim();
                        '.';
                }


        if (!query) {
                this.setStatus(status, 'success');
            query = title;
        }


        try {
                mw.notify(status, {
             const results =
                    type: 'success'
                 await this.searchPages(query);
                });
             } catch (error) {
                 console.error(
                    'Preload Editor variable import:',
                    error
                );


            return results.filter(
                this.setStatus(
                result =>
                     error.message ||
                     /\/Preload$/i.test(
                         'Could not import variable definitions.',
                         result.title
                     'error'
                     )
                 );
            );
        } catch (error) {
            console.error(
                'Preload Editor search:',
                 error
            );


            return [];
                mw.notify(
        }
                    error.message ||
    },
                        'Could not import variable definitions.',
                    {
                        type: 'error'
                    }
                );
            }
        },


    renderMissingPage(title, suggestions) {
        // =========================================================
         this.workspace.empty();
        // Preload parsing
         // =========================================================


         const section =
         extractIncludeonly(source) {
            this.createSection(
            const match = String(source || '').match(
                 'Preload not found'
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
             );
             );


        $('<p>')
            return match
            .text(
                ? match[1].trim()
                 'No preload exists at "' +
                 : String(source || '').trim();
                title +
        },
                '".'
            )
            .appendTo(section);


         if (suggestions.length) {
         findVariables(content) {
             $('<h3>')
             const variables = [];
                .text('Similar preloads')
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                .appendTo(section);


             const list =
             let match;
                $('<div>')
                    .addClass(
                        'preload-editor-suggestions'
                    );


             suggestions.forEach(result => {
             while ((match = pattern.exec(content)) !== null) {
                 list.append(
                 const name = match[1].toUpperCase();
                    this.createButton(
                        result.title,
                        'preload-editor-suggestion',
                        () =>
                            this.loadExisting(
                                result.title
                            )
                    )
                );
            });


            section.append(list);
                if (!variables.includes(name)) {
        }
                    variables.push(name);
                }
            }


        section.append(
             return variables;
             this.createButton(
        },
                'Create this preload',
                'preload-editor-button-primary',
                () => this.startNew(title)
            )
        );


         this.workspace.append(section);
         findConditions(content) {
    },
            const conditions = [];
            const pattern =
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


    async startNew(title) {
            let match;
        title = String(title || '').trim();


        this.state = {
            while ((match = pattern.exec(content)) !== null) {
            preloadTitle: title,
                conditions.push({
            preloadSource: '',
                    type: match[1].toLowerCase(),
            preloadContent: this.defaults.preload,
                    expression: match[2].trim(),
            config: this.emptyConfig(),
                    index: match.index
            variables: ['PAGE'],
                });
            conditions: [],
             }
            mode: 'new',
             dirty: true
        };


         this.renderEditor();
            return conditions;
         },


         this.setStatus(
         findConditionVariables(content) {
             'Creating a new preload.',
             const variables = [];
            'success'
        );
    },


    async loadSamplePage() {
            this.findConditions(content).forEach(condition => {
        const result =
                if (
            await this.createPromptDialog(
                    condition.type !== 'if' &&
                'Load Sample Page',
                    condition.type !== 'elseif'
                'Enter the title of a normal wiki page to use as the starting point.'
                ) {
            );
                    return;
                }


        if (!result) {
                const matches =
            return;
                    condition.expression.match(
        }
                        /[A-Za-z0-9_-]+/g
                    ) || [];


        this.setStatus(
                matches.forEach(name => {
            'Loading sample page...',
                    name = name.toUpperCase();
            'loading'
        );


        try {
                    if (!variables.includes(name)) {
            const page =
                        variables.push(name);
                 await this.getPage(result);
                    }
                 });
            });
 
            return variables;
        },


             if (!page) {
        analyzePreload(content) {
                 throw new Error(
             return {
                    'Sample page not found: ' +
                variables: this.findVariables(content),
                     result
                 conditions: this.findConditions(content),
                );
                conditionVariables:
            }
                     this.findConditionVariables(content)
            };
        },


            const sample =
        // =========================================================
                this.convertSampleToPreload(
        // Config
                    page.content
        // =========================================================
                );


             this.state = {
        getAutomaticPageField() {
                 preloadTitle: '',
             return {
                 preloadSource: '',
                 label: 'Page Name',
                 preloadContent: sample,
                 description: 'Name of the page.',
                 config: this.emptyConfig(),
                 type: 'page',
                 variables: ['PAGE'],
                 required: true,
                 conditions: [],
                 namespace: 'Main',
                mode: 'new',
                 'allow-new': true
                dirty: true
             };
             };
        },


            this.reanalyze();
        emptyConfig() {
             this.renderEditor();
             return {
                settings: {
                    incomplete: 'add-stub'
                },


            this.setStatus(
                fields: {
                 'Sample page loaded.',
                    PAGE: this.getAutomaticPageField()
                'success'
                 }
             );
             };
         } catch (error) {
         },
             console.error(
 
                 'Preload Editor sample:',
        normalizeConfig(config) {
                 error
             if (
             );
                 !config ||
                typeof config !== 'object' ||
                 Array.isArray(config)
             ) {
                config = this.emptyConfig();
            }


             this.setStatus(
             if (
                 error.message ||
                 !config.settings ||
                    'Could not load sample page.',
                typeof config.settings !== 'object' ||
                 'error'
                 Array.isArray(config.settings)
             );
             ) {
        }
                config.settings = {};
    },
            }


    convertSampleToPreload(source) {
            if (
        let content =
                !config.fields ||
            String(source || '').trim();
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
            ) {
                config.fields = {};
            }


        const include =
             config.fields.PAGE =
             content.match(
                 this.getAutomaticPageField();
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
            );


        if (include) {
             return config;
             content = include[1].trim();
         },
         }


         content =
         createDefaultField(name, analysis) {
             content
             return {
                 .replace(
                 label: this.humanizeName(name),
                    /<noinclude>[\s\S]*?<\/noinclude>/gi,
                description: '',
                    ''
                 type: analysis.conditionVariables.includes(name)
                 )
                    ? 'boolean'
                .trim();
                    : 'text'
            };
        },


         return (
         humanizeName(name) {
             '<includeonly>\n' +
             return String(name || '')
            content +
                .replace(/[_-]+/g, ' ')
            '\n</includeonly>\n' +
                .replace(/([a-z])([A-Z])/g, '$1 $2')
            '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
                .replace(/\s+/g, ' ')
        );
                .trim()
    },
                .replace(/\b\w/g, char => char.toUpperCase());
        },


    createPromptDialog(title, message) {
        prepareConfigForVariables(config, analysis) {
        return new Promise(resolve => {
             config = this.normalizeConfig(config);
             const overlay =
                $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay'
                    );


             const box =
             const existing = config.fields || {};
                $('<div>')
                    .addClass(
                        'preload-editor-prompt'
                    );


             $('<h2>')
             const deleted = new Set(
                 .text(title)
                 Array.isArray(this.state.deletedVariables)
                .appendTo(box);
                    ? this.state.deletedVariables.map(
                        name => String(name).toUpperCase()
                    )
                    : []
            );


             $('<p>')
             const fields = {};
                .text(message)
                .appendTo(box);


             const input = this.textInput();
             fields.PAGE =
                this.getAutomaticPageField();


             const buttons =
             analysis.variables.forEach(name => {
                 $('<div>')
                 if (
                     .addClass(
                    name === 'PAGE' ||
                         'preload-editor-prompt-buttons'
                    deleted.has(name)
                ) {
                     return;
                }
 
                fields[name] =
                    existing[name] ||
                    this.createDefaultField(
                         name,
                        analysis
                     );
                     );
            });


             const cancel =
             Object.keys(existing).forEach(name => {
                this.createButton(
                const upper = name.toUpperCase();
                    'Cancel',
                    '',
                    () => {
                        overlay.remove();
                        resolve(null);
                    }
                );


            const confirm =
                 if (
                 this.createButton(
                     upper !== 'PAGE' &&
                     'Load',
                     !fields[upper] &&
                     'preload-editor-button-primary',
                     !deleted.has(upper)
                     () => {
                ) {
                         const value =
                    fields[upper] =
                            String(
                         existing[name];
                                input.val() || ''
                }
                            ).trim();
            });
 
            config.fields = fields;


                        if (!value) {
            return config;
                            return;
        },
                        }


                        overlay.remove();
        validateConfig(config, analysis) {
                        resolve(value);
            const errors = [];
                    }
            const warnings = [];
                );


             buttons.append(cancel, confirm);
             if (
             box.append(input, buttons);
                !config ||
            overlay.append(box);
                typeof config !== 'object' ||
             $(document.body).append(overlay);
                Array.isArray(config)
             ) {
                return {
                    valid: false,
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                };
             }


             input.trigger('focus');
             if (
                !config.fields ||
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
            ) {
                return {
                    valid: false,
                    errors: [
                        '"fields" must be an object.'
                    ],
                    warnings
                };
            }


             input.on(
             const configured =
                'keydown.preloadEditor',
                Object.keys(
                 event => {
                    config.fields
                     if (event.key === 'Enter') {
                 ).map(
                         confirm.trigger('click');
                     name =>
                    }
                         name.toUpperCase()
                );


                    if (event.key === 'Escape') {
            analysis.variables.forEach(name => {
                        cancel.trigger('click');
                if (!configured.includes(name)) {
                    }
                    errors.push(
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                 }
                 }
             );
             });
        });
    },


    async loadDefinition(title, source) {
            configured.forEach(name => {
        const content =
                if (!analysis.variables.includes(name)) {
             this.extractIncludeonly(source);
                    warnings.push(
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                    );
                }
             });


        let config = this.emptyConfig();
            if (!configured.includes('PAGE')) {
 
                 errors.push(
        const configTitle =
                     'PAGE must always be configured.'
            title.replace(/\/+$/, '') +
            '/config.json';
 
        const configPage =
            await this.getPage(configTitle);
 
        if (configPage) {
            try {
                 config =
                    JSON.parse(
                        configPage.content
                    );
            } catch (error) {
                throw new Error(
                     'The existing config.json contains invalid JSON: ' +
                    error.message
                 );
                 );
             }
             }
        }


        const analysis =
            Object.entries(config.fields).forEach(([name, field]) => {
            this.analyzePreload(content);
                if (
                    !field ||
                    typeof field !== 'object' ||
                    Array.isArray(field)
                ) {
                    errors.push(
                        'Field "' +
                        name +
                        '" must be an object.'
                    );


        config =
                    return;
            this.prepareConfigForVariables(
                 }
                config,
                 analysis
            );


        this.state = {
                if (!field.type) {
            preloadTitle: title,
                    warnings.push(
            preloadSource: source,
                        'Field "' +
            preloadContent: source,
                        name +
            config,
                        '" has no type.'
            variables: analysis.variables,
                    );
            conditions: analysis.conditions,
                }
            mode: 'edit',
               
            dirty: false
                if (
        };
                    field.type === 'file'
                ) {
                    if (
                        field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }


        this.renderEditor();
                    if (
    },
                        Array.isArray(field.accept) &&
                        field.accept.some(
                            value =>
                                !String(
                                    value || ''
                                ).trim()
                        )
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" contains an empty accepted MIME type.'
                        );
                    }


    // Editor
                    if (
                        field.filename !== undefined &&
                        typeof field.filename !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                        );
                    }


    renderEditor() {
                    if (
        this.destroyEditor();
                        field.filetext !== undefined &&
        this.workspace.empty();
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


        const layout =
                    if (
            $('<div>')
                        !field.accept ||
                .addClass(
                        !field.accept.length
                    'preload-editor-layout'
                    ) {
                );
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


        const left =
                    if (
            $('<div>')
                        !field.filename
                .addClass(
                    ) {
                    'preload-editor-left'
                        warnings.push(
                );
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


        const right =
                if (
            $('<div>')
                    (
                 .addClass(
                        field.type === 'select' ||
                    'preload-editor-right'
                        field.type === 'multiselect'
                );
                    ) &&
                    !field.source &&
                    !Array.isArray(field.options)
                 ) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                    );
                }


        const editorSection =
                if (field.type === 'file') {
            this.createSection(
                    if (
                'Preload',
                        field.filename !== undefined &&
                'preload-editor-main-section'
                        typeof field.filename !== 'string'
            );
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filename" value.'
                        );
                    }


        const meta =
                    if (
            $('<div>')
                        field.filetext !== undefined &&
                .addClass(
                        typeof field.filetext !== 'string'
                    'preload-editor-meta'
                    ) {
                );
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }


        $('<strong>')
                    if (
            .text(
                        field.accept !== undefined &&
                this.state.preloadTitle ||
                        (
                'New preload'
                            !Array.isArray(field.accept) ||
            )
                            field.accept.some(
            .appendTo(meta);
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                            )
                        )
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                    }
                }
            });


        if (this.state.mode === 'new') {
            return {
            $('<span>')
                 valid: !errors.length,
                 .addClass(
                 errors,
                    'preload-editor-badge'
                 warnings
                 )
            };
                 .text('NEW')
         },
                .appendTo(meta);
         }


         editorSection.append(meta);
         // =========================================================
        // Transformation helpers
        // =========================================================


         const textarea =
         transformationObject(
             this.textarea(
            transform,
                 this.state.preloadContent
            prefix,
             )
            suffix,
                 .attr(
            from,
                    'id',
            to
                     'preload-editor-content'
        ) {
                )
             if (!transform) {
                .addClass(
                 return null;
                    'preload-editor-content'
             }
                );
 
            switch (transform) {
                 case 'remove-prefix':
                     return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;


        const editorMount =
                case 'remove-suffix':
            $('<div>')
                    return suffix
                .addClass(
                        ? {
                    'preload-editor-codemirror-mount'
                            transform,
                )
                            suffix
                .append(textarea);
                        }
                        : null;


        editorSection.append(
                case 'replace':
            editorMount
                    return from === ''
        );
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


         left.append(editorSection);
                default:
                    return null;
            }
         },


         const analysisSection =
         // =========================================================
            this.createSection('Analysis');
        // UI helpers
        // =========================================================


         const analysisContainer =
         createSection(title, className) {
            $('<div>')
            const section = $('<section>')
                 .addClass(
                 .addClass('preload-editor-section');
                    'preload-editor-analysis'
                );


        analysisSection.append(
            if (className) {
             analysisContainer
                section.addClass(className);
        );
             }


        const variablesSection =
            $('<h2>')
            this.createSection('Variables');
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);


        const variableContainer =
             return section;
             $('<div>')
        },
                .addClass(
                    'preload-editor-variables'
                );


         variablesSection.append(
         createButton(label, className, callback) {
            variableContainer
            const button = $('<button>')
        );
                .attr('type', 'button')
                .addClass('preload-editor-button')
                .text(label);


        const configSection =
             if (className) {
             this.createSection(
                 button.addClass(className);
                 'Generated configuration'
             }
             );


        const configPreview =
             if (callback) {
             $('<pre>')
                 button.on(
                 .addClass(
                     'click.preloadEditor',
                     'preload-editor-config-preview'
                    callback
                 );
                 );
            }
            return button;
        },


         configSection.append(configPreview);
         fieldRow(label, input, description) {
            const row = $('<div>')
                .addClass('preload-editor-field');


        const actions =
             $('<label>')
             $('<div>')
                 .addClass('preload-editor-label')
                 .addClass(
                .text(label)
                    'preload-editor-actions'
                 .appendTo(row);
                 );


        const save =
             if (description) {
             this.createButton(
                 $('<div>')
                 'Save Preload + Config',
                    .addClass('preload-editor-help')
                'preload-editor-button-primary',
                    .text(description)
                () => this.saveAll()
                    .appendTo(row);
             );
             }


        const savePreload =
             row.append(input);
             this.createButton(
                'Save Preload Only',
                '',
                () => this.savePreloadOnly()
            );


         actions.append(save, savePreload);
            return row;
         },


         right.append(
         textInput(value, placeholder) {
            analysisSection,
            return $('<input>')
            variablesSection,
                .attr({
            configSection,
                    type: 'text',
            actions
                    value: value == null ? '' : value,
        );
                    placeholder: placeholder || ''
                })
                .addClass('preload-editor-input');
        },


         layout.append(left, right);
         textarea(value) {
        this.workspace.append(layout);
            return $('<textarea>')
                .val(value == null ? '' : value)
                .addClass('preload-editor-textarea');
        },


         this.reanalyze();
         checkbox(checked) {
        this.renderVariables(variableContainer);
            return $('<input>')
        this.renderAnalysis(analysisContainer);
                .attr('type', 'checkbox')
        this.renderConfigPreview(configPreview);
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },


         this.mountCodeMirror(textarea.get(0))
         select(options, value) {
             .catch(error => {
             const select = $('<select>')
                 console.error(
                 .addClass('preload-editor-select');
                    'Preload Editor CodeMirror:',
                    error
                );


                 this.setStatus(
            options.forEach(option => {
                     error.message ||
                 $('<option>')
                         'Could not initialize CodeMirror.',
                    .attr('value', option.value)
                    'error'
                    .text(option.label)
                );
                     .prop(
                         'selected',
                        String(option.value) ===
                        String(value === undefined ? '' : value)
                    )
                    .appendTo(select);
             });
             });
    },


    reanalyze() {
            return select;
        const source = this.getEditorContent();
         },
        const content = this.extractIncludeonly(source);
         const analysis = this.analyzePreload(content);


         this.state.preloadContent = source;
         // =========================================================
         this.state.variables = analysis.variables;
         // In-wiki dialogs
         this.state.conditions = analysis.conditions;
         // =========================================================


         this.state.config =
         createConfirmDialog(
             this.prepareConfigForVariables(
            title,
                 this.state.config ||
            message,
                     this.emptyConfig(),
            confirmLabel,
                analysis
            cancelLabel
            );
        ) {
             return new Promise(resolve => {
                 const overlay = $('<div>')
                     .addClass('preload-editor-prompt-overlay');


        this.analysis = analysis;
                const box = $('<div>')
    },
                    .addClass('preload-editor-prompt');


    renderAnalysis(container) {
                $('<h2>')
        container.empty();
                    .text(title)
                    .appendTo(box);


        const analysis =
                const messageLines =
            this.analysis ||
                    String(message || '').split('\n');
            this.analyzePreload(
                this.extractIncludeonly(
                    this.getEditorContent()
                )
            );


        const variableCount =
                messageLines.forEach(line => {
            analysis.variables.length;
                    if (line === '') {
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);


        const conditionCount =
                        return;
            analysis.conditions.length;
                    }


        const summary =
                    $('<p>')
            $('<div>')
                        .text(line)
                .addClass(
                        .appendTo(box);
                    'preload-editor-analysis-summary'
                 });
                 );


        summary.append(
                 const buttons = $('<div>')
            $('<span>').text(
                    .addClass(
                variableCount +
                        'preload-editor-prompt-buttons'
                ' variable' +
                    );
                 (variableCount === 1 ? '' : 's')
            ),
            $('<span>').text(
                conditionCount +
                ' condition marker' +
                (conditionCount === 1 ? '' : 's')
            )
        );


        container.append(summary);
                const cancel = this.createButton(
                    cancelLabel || 'Cancel',
                    '',
                    () => {
                        overlay.remove();
                        resolve(false);
                    }
                );


        if (analysis.conditionVariables.length) {
                const confirm = this.createButton(
            container.append(
                    confirmLabel || 'Confirm',
                $('<div>')
                     'preload-editor-button-primary',
                     .addClass(
                     () => {
                        'preload-editor-analysis-note'
                        overlay.remove();
                     )
                         resolve(true);
                    .text(
                     }
                         'Condition variables: ' +
                );
                        analysis.conditionVariables.join(', ')
                     )
            );
        }


        const validation =
                buttons.append(cancel, confirm);
            this.validateConfig(
                 box.append(buttons);
                 this.state.config,
                 overlay.append(box);
                 analysis
            );


        if (validation.errors.length) {
                 $(document.body).append(overlay);
            const errors =
                 $('<ul>')
                    .addClass(
                        'preload-editor-validation-errors'
                    );


            validation.errors.forEach(error => {
                const close = value => {
                $('<li>')
                    if (value === 'Escape') {
                    .text(error)
                        cancel.trigger('click');
                     .appendTo(errors);
                     }
            });
                };


            container.append(errors);
                overlay.on(
        }
                    'keydown.preloadEditor',
                    event => {
                        close(event.key);
                    }
                );


        if (validation.warnings.length) {
                overlay.attr('tabindex', '-1');
            const warnings =
                overlay.trigger('focus');
                $('<ul>')
                    .addClass(
                        'preload-editor-validation-warnings'
                    );


            validation.warnings.forEach(warning => {
                overlay.on(
                $('<li>')
                    'click.preloadEditor',
                    .text(warning)
                    event => {
                     .appendTo(warnings);
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                     }
                );
             });
             });
        },


             container.append(warnings);
        createPromptDialog(title, message) {
        }
             return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay'
                    );


        if (
                 const box = $('<div>')
            !validation.errors.length &&
            !validation.warnings.length
        ) {
            container.append(
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-validation-success'
                         'preload-editor-prompt'
                     )
                     );
                    .text(
                        'Preload and configuration are in sync.'
                    )
            );
        }
    },


    renderAnalysisBySelector() {
                $('<h2>')
        const container =
                    .text(title)
            this.root &&
                    .appendTo(box);
            this.root.find(
                '.preload-editor-analysis'
            );


        if (container && container.length) {
                $('<p>')
            this.renderAnalysis(container);
                    .text(message)
        }
                    .appendTo(box);
    },


    renderVariables(container) {
                const input = this.textInput();
        container.empty();


        const analysis =
                const buttons = $('<div>')
            this.analysis ||
                     .addClass(
            this.analyzePreload(
                        'preload-editor-prompt-buttons'
                this.extractIncludeonly(
                    );
                     this.getEditorContent()
                )
            );


        const variables =
                const cancel = this.createButton(
            analysis.variables.slice();
                    'Cancel',
                    '',
                    () => {
                        overlay.remove();
                        resolve(null);
                    }
                );


        const ordered = ['PAGE'];
                const confirm = this.createButton(
                    'Load',
                    'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();


        variables.forEach(name => {
                        if (!value) {
            if (
                            return;
                name !== 'PAGE' &&
                        }
                !ordered.includes(name)
            ) {
                ordered.push(name);
            }
        });


        Object.keys(
                        overlay.remove();
            this.state.config.fields || {}
                        resolve(value);
        ).forEach(name => {
                    }
            const upper = name.toUpperCase();
                );


            if (!ordered.includes(upper)) {
                 buttons.append(cancel, confirm);
                 ordered.push(upper);
            }
        });


        ordered.forEach(name => {
                 box.append(
            const field =
                     input,
                this.state.config.fields[name] ||
                     buttons
                 this.createDefaultField(
                     name,
                     analysis
                 );
                 );


            this.state.config.fields[name] = field;
                overlay.append(box);


            container.append(
                $(document.body).append(overlay);
                 this.createVariableCard(
 
                    name,
                 input.trigger('focus');
                     field,
 
                     analysis
                input.on(
                )
                     'keydown.preloadEditor',
            );
                     event => {
        });
                        if (event.key === 'Enter') {
    },
                            confirm.trigger('click');
                        }


    renderVariablesBySelector() {
                        if (event.key === 'Escape') {
        const container =
                            cancel.trigger('click');
            this.root &&
                        }
            this.root.find(
                    }
                 '.preload-editor-variables'
                 );
             );
             });
        },


         if (container && container.length) {
         createConfigReviewDialog() {
             this.renderVariables(container);
             return new Promise(resolve => {
        }
                const overlay = $('<div>')
    },
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );


    createVariableCard(name, field, analysis) {
                const box = $('<div>')
        const card =
                    .addClass(
            $('<div>')
                        'preload-editor-prompt preload-editor-code-review'
                .addClass(
                     );
                    'preload-editor-variable'
                )
                .attr(
                    'data-variable',
                     name
                );


        const header =
                $('<h2>')
            $('<div>')
                    .text('Review config.json')
                .addClass(
                    .appendTo(box);
                    'preload-editor-variable-header'
                );


        header.append(
                $('<p>')
            $('<h3>').text(name)
                    .text(
        );
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);


        if (name === 'PAGE') {
                const code = $('<pre>')
            header.append(
                $('<span>')
                     .addClass(
                     .addClass(
                         'preload-editor-badge'
                         'preload-editor-config-review'
                     )
                     )
                     .text('AUTOMATIC')
                     .text(this.getConfigJSON());
            );
 
        } else if (
                 const codeWrap = $('<div>')
            !analysis.variables.includes(name)
        ) {
            header.append(
                 $('<span>')
                     .addClass(
                     .addClass(
                         'preload-editor-badge is-warning'
                         'preload-editor-config-review-wrap'
                     )
                     )
                     .text('UNUSED')
                     .append(code);
            );
        }


        card.append(header);
                box.append(codeWrap);


        const label =
                const buttons = $('<div>')
            this.textInput(field.label || '');
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


        label.on(
                const close = this.createButton(
            'input.preloadEditor',
                    'Close',
            () => {
                    'preload-editor-button-primary',
                field.label = label.val();
                    () => {
                this.markDirty();
                        overlay.remove();
                this.renderConfigPreviewBySelector();
                        resolve();
            }
                    }
        );
                );


        card.append(
                buttons.append(close);
            this.fieldRow('Label', label)
                box.append(buttons);
        );
                overlay.append(box);


        const description =
                $(document.body).append(overlay);
            this.textarea(
                field.description || ''
            )
                .addClass(
                    'preload-editor-small-textarea'
                );


        description.on(
                overlay.attr('tabindex', '-1');
            'input.preloadEditor',
                 overlay.trigger('focus');
            () => {
                field.description = description.val();
                 this.markDirty();
                this.renderConfigPreviewBySelector();
            }
        );


        card.append(
                overlay.on(
            this.fieldRow(
                    'keydown.preloadEditor',
                'Description',
                    event => {
                description
                        if (event.key === 'Escape') {
            )
                            close.trigger('click');
        );
                        }
                    }
                );


        const types = [
                overlay.on(
            ['text', 'Text'],
                    'click.preloadEditor',
            ['textarea', 'Textarea'],
                    event => {
            ['number', 'Number'],
                        if (event.target === overlay.get(0)) {
            ['boolean', 'Boolean'],
                            close.trigger('click');
            ['select', 'Select'],
                        }
            ['multiselect', 'Multi-select'],
                    }
            ['page', 'Page'],
                );
            ['user', 'User'],
             });
             ['date', 'Date']
         },
         ];


         const typeSelect =
         async confirmSave(mode, title) {
            this.select(
            const configTitle =
                 types.map(
                 title.replace(/\/+$/, '') +
                    ([value, label]) => ({
                 '/config.json';
                        value,
                        label
                    })
                 ),
                field.type || 'text'
            );


        typeSelect.on(
             let saveDescription;
             'change.preloadEditor',
            () => {
                field.type = typeSelect.val();
                this.markDirty();


                 card.replaceWith(
            if (mode === 'preload') {
                     this.createVariableCard(
                 saveDescription =
                        name,
                     'Save the preload page only?';
                        field,
            } else if (mode === 'config') {
                        analysis
                saveDescription =
                     )
                     'Save the config.json page only?';
                );
            } else {
 
                 saveDescription =
                 this.renderConfigPreviewBySelector();
                    'Save both the preload and config.json?';
             }
             }
        );


        card.append(
             const pages = [];
             this.fieldRow(
                'Type',
                typeSelect
            )
        );


        if (name === 'PAGE') {
            if (mode === 'preload' || mode === 'both') {
            field.type = 'page';
                pages.push(
                    'Preload: ' +
                    title
                );
            }


             const required =
             if (mode === 'config' || mode === 'both') {
                 this.checkbox(
                 pages.push(
                     field.required !== false
                     'Config: ' +
                    configTitle
                 );
                 );


            required.on(
                pages.push(
                'change.preloadEditor',
                    'Config content model: JSON'
                 () => {
                 );
                    field.required =
            }
                        required.prop('checked');


                    this.markDirty();
            const message =
                    this.renderConfigPreviewBySelector();
                saveDescription +
                 }
                '\n\n' +
            );
                pages.join('\n') +
                 '\n\nThis will write the changes to the wiki.';


             card.append(
             return this.createConfirmDialog(
                 this.fieldRow(
                 'Confirm save',
                    'Required',
                message,
                    required
                'Save',
                 )
                 'Cancel'
             );
             );
        },


            const namespace =
        // =========================================================
                 this.select(
        // CodeMirror
                    [
        // =========================================================
                        {
                 destroyEditor() {
                            value: 'Main',
            if (!this.editor) {
                            label: 'Main'
                this.editorView = null;
                        },
                this.editorTools = null;
                        {
                return;
                            value: 'Template',
            }
                            label: 'Template'
 
                        },
            const {
                        {
                view,
                            value: 'File',
                inputHandler
                            label: 'File'
            } = this.editor;
                        },
 
                        {
            if (view && inputHandler) {
                            value: 'Category',
                view.dom.removeEventListener(
                            label: 'Category'
                    'input',
                        },
                     inputHandler
                        {
                            value: 'User',
                            label: 'User'
                        }
                    ],
                     field.namespace || 'Main'
                 );
                 );
            }
            if (view) {
                view.destroy();
            }


             namespace.on(
             this.editor = null;
                'change.preloadEditor',
            this.editorView = null;
                () => {
            this.editorTools = null;
                    field.namespace =
        },
                        namespace.val();


                    this.markDirty();
        getEditorView() {
                    this.renderConfigPreviewBySelector();
            return this.editorView;
                }
        },
            );


             card.append(
        getEditorContent() {
                 this.fieldRow(
             if (
                    'Namespace',
                 this.editorView &&
                    namespace
                this.editorView.state
                 )
            ) {
             );
                 return this.editorView.state.doc.toString();
             }


             const allowNew =
             return this.state.preloadContent || '';
                this.checkbox(
        },
                    field['allow-new'] === true
                );


            allowNew.on(
        setEditorContent(content) {
                'change.preloadEditor',
            content = String(content || '');
                () => {
                    field['allow-new'] =
                        allowNew.prop('checked');


                    this.markDirty();
            if (!this.editorView) {
                    this.renderConfigPreviewBySelector();
                this.state.preloadContent = content;
                 }
                 return;
             );
             }


             card.append(
             const current =
                 this.fieldRow(
                 this.editorView.state.doc.toString();
                    'Allow new page',
                    allowNew
                )
            );


             return card;
             if (current === content) {
        }
                return;
            }


        const required =
             this.editorView.dispatch({
             this.checkbox(
                 changes: {
                 field.required === true
                    from: 0,
             );
                    to: this.editorView.state.doc.length,
                    insert: content
                }
             });
        },


         required.on(
         getEditorSelection() {
             'change.preloadEditor',
             if (
             () => {
                !this.editorView ||
                 field.required =
                !this.editorView.state
                    required.prop('checked');
             ) {
                 return null;
            }
 
            const selection =
                this.editorView.state.selection.main;


                 this.markDirty();
            return {
                 this.renderConfigPreviewBySelector();
                from: selection.from,
                to: selection.to,
                 text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
            };
        },
 
        focusEditor() {
            if (this.editorView) {
                 this.editorView.focus();
             }
             }
         );
         },


         card.append(
         insertEditorText(
             this.fieldRow(
             text,
                'Required',
            selectionFrom,
                required
            selectionTo,
             )
             cursorPosition
        );
        ) {
            if (!this.editorView) {
                return;
            }


        const placeholder =
            const view = this.editorView;
             this.textInput(
             const selection = view.state.selection.main;
                 field.placeholder || ''
 
             );
            const from =
                 selectionFrom === undefined
                    ? selection.from
                    : selectionFrom;
 
             const to =
                selectionTo === undefined
                    ? selection.to
                    : selectionTo;


        placeholder.on(
             const cursor =
             'input.preloadEditor',
                 cursorPosition === undefined
            () => {
                    ? from + text.length
                 const value = placeholder.val();
                    : cursorPosition;


                 if (value) {
            view.dispatch({
                     field.placeholder = value;
                 changes: {
                 } else {
                     from,
                     delete field.placeholder;
                    to,
                    insert: text
                 },
                selection: {
                     anchor: cursor
                 }
                 }
            });
            view.focus();
        },
        // =========================================================
        // Editor tools
        // =========================================================
        wrapSelectionWithVariable() {
            const selected =
                this.getEditorSelection();


                 this.markDirty();
            if (
                 this.renderConfigPreviewBySelector();
                !selected ||
                 selected.from === selected.to
            ) {
                 this.focusEditor();
                return;
             }
             }
        );


        card.append(
             const replacement =
             this.fieldRow(
                 '%%' +
                 'Placeholder',
                 selected.text +
                 placeholder
                '%%';
            )
        );


        const defaultInput =
             this.insertEditorText(
             this.textInput(
                 replacement,
                 field.default === undefined
                selected.from,
                    ? ''
                selected.to,
                    : field.default
                selected.from + replacement.length
             );
             );
        },


         defaultInput.on(
         insertVariable(name) {
             'input.preloadEditor',
             name = String(name || '')
            () => {
                .trim()
                 const value = defaultInput.val();
                 .toUpperCase();


                if (value) {
            if (!name) {
                    field.default = value;
                 return;
                } else {
                    delete field.default;
                 }
 
                this.markDirty();
                this.renderConfigPreviewBySelector();
             }
             }
        );


        card.append(
             const selected =
             this.fieldRow(
                 this.getEditorSelection();
                'Default',
                 defaultInput,
                'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
            )
        );


        if (field.type === 'textarea') {
            if (!selected) {
             const maxRows =
                return;
                 this.textInput(
            }
                    field.maxRows || ''
 
                ).attr(
            this.insertEditorText(
                     'type',
                '%%' + name + '%%',
                    'number'
                selected.from,
                );
                selected.to
            );
        },
 
        insertCondition(
            type,
            variable
        ) {
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();
 
             const selected =
                 this.getEditorSelection();
 
            if (!selected) {
                return;
            }
 
            let text;
            let cursorOffset;
 
            switch (type) {
                case 'if': {
                    if (!variable) {
                        return;
                    }
 
                     const opening =
                        '<!-- @if ' +
                        variable +
                        ' -->';


            maxRows.on(
                     const closing =
                'input.preloadEditor',
                         '<!-- @endif -->';
                () => {
                     const value =
                         parseInt(
                            maxRows.val(),
                            10
                        );


                     if (
                     if (
                         Number.isFinite(value) &&
                         selected.from !==
                         value > 0
                         selected.to
                     ) {
                     ) {
                         field.maxRows = value;
                         text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;
 
                        cursorOffset = text.length;
                     } else {
                     } else {
                         delete field.maxRows;
                         text =
                            opening +
                            '\n\n' +
                            closing;
 
                        cursorOffset =
                            opening.length + 1;
                     }
                     }


                     this.markDirty();
                     break;
                    this.renderConfigPreviewBySelector();
                 }
                 }
            );


            card.append(
                 case 'elseif':
                 this.fieldRow(
                     text =
                     'Maximum rows',
                        '<!-- @elseif -->';
                     maxRows
 
                )
                     cursorOffset =
            );
                        text.length;
        }


        if (
                    break;
            field.type === 'select' ||
            field.type === 'multiselect'
        ) {
            this.renderSelectConfiguration(
                card,
                field
            );
        }


        return card;
                case 'else':
    },
                    text =
                        '<!-- @else -->';


    renderSelectConfiguration(card, field) {
                    cursorOffset =
        const source =
                        text.length;
            this.textInput(
                field.source || '',
                'category:Example'
            );


        source.on(
                    break;
            'input.preloadEditor',
            () => {
                const value = source.val();


                 if (value) {
                 case 'endif':
                     field.source = value;
                     text =
                } else {
                        '<!-- @endif -->';
                    delete field.source;
                }


                this.markDirty();
                    cursorOffset =
                this.renderConfigPreviewBySelector();
                        text.length;
            }
        );


        card.append(
                    break;
            this.fieldRow(
                'Source',
                source,
                'Currently supported source format: category:Category Name'
            )
        );


        const sourcePrefix =
                 default:
            this.textInput(
                     return;
                 field['source-prefix'] || ''
            );
 
        sourcePrefix.on(
            'input.preloadEditor',
            () => {
                const value =
                     sourcePrefix.val();
 
                if (value) {
                    field['source-prefix'] = value;
                } else {
                    delete field['source-prefix'];
                }
 
                this.markDirty();
                this.renderConfigPreviewBySelector();
             }
             }
        );
        card.append(
            this.fieldRow(
                'Source prefix',
                sourcePrefix,
                'Only source values beginning with this text are included.'
            )
        );


        const excludeCategory =
             this.insertEditorText(
             this.textInput(
                 text,
                 field.exclude &&
                selected.from,
                 field.exclude.category
                 selected.to,
                    ? field.exclude.category
                selected.from + cursorOffset
                    : ''
             );
             );
        },


         excludeCategory.on(
         getToolVariables() {
            'input.preloadEditor',
            const variables =
            () => {
                new Set(['PAGE']);
                const value =
                    excludeCategory.val();


                if (value) {
            if (
                     field.exclude =
                this.analysis &&
                         Object.assign(
                this.analysis.variables
                             {},
            ) {
                            field.exclude || {},
                this.analysis.variables.forEach(
                            { category: value }
                     name => {
                         variables.add(
                             String(name).toUpperCase()
                         );
                         );
                } else if (field.exclude) {
                    delete field.exclude.category;
                    if (
                        !Object.keys(
                            field.exclude
                        ).length
                    ) {
                        delete field.exclude;
                     }
                     }
                 }
                 );
 
                this.markDirty();
                this.renderConfigPreviewBySelector();
             }
             }
        );


        card.append(
             return Array.from(variables);
             this.fieldRow(
         },
                'Exclude category',
                excludeCategory
            )
         );


         card.append(
         createToolSelect(
             this.createTransformControls(
             options,
                field,
            className
                'value',
        ) {
                 'Value transformation'
            const select =
            ),
                 $('<select>')
            this.createTransformControls(
                    .addClass(
                field,
                        'preload-editor-tool-select'
                'label',
                    );
                'Label transformation'
            )
        );


        const optionsValue =
             if (className) {
             Array.isArray(field.options)
                 select.addClass(className);
                 ? field.options
            }
                    .map(option => {
                        if (
                            typeof option === 'string'
                        ) {
                            return option;
                        }


                        return (
            options.forEach(
                            String(
                option => {
                                option.value || ''
                    $('<option>')
                            ) +
                        .attr(
                             ' | ' +
                             'value',
                             String(
                             option.value
                                option.label ||
                        )
                                option.value ||
                        .text(option.label)
                                ''
                         .appendTo(select);
                            )
                }
                         );
            );
                    })
                    .join('\n')
                : '';


        const options =
             return select;
             this.textarea(optionsValue)
        },
                .addClass(
                    'preload-editor-small-textarea'
                );


         options.on(
         updateEditorToolVariables() {
            'input.preloadEditor',
            if (!this.editorTools) {
            () => {
                return;
                const lines =
            }
                    options.val()
                        .split('\n')
                        .map(line => line.trim())
                        .filter(Boolean);
 
                if (!lines.length) {
                    delete field.options;
                } else {
                    field.options =
                        lines.map(line => {
                            const parts =
                                line.split(
                                    /\s*\|\s*/
                                );


                            if (parts.length === 1) {
            const variables =
                                return parts[0];
                this.getToolVariables();
                            }


                            return {
            const current =
                                value: parts[0],
                this.editorTools
                                label:
                    .variableSelect
                                    parts
                    .val();
                                        .slice(1)
                                        .join(' | ')
                            };
                        });
                }


                 this.markDirty();
            const currentCondition =
                this.renderConfigPreviewBySelector();
                 this.editorTools
            }
                    .conditionVariableSelect
        );
                    .val();


        card.append(
             const populate = (
             this.fieldRow(
                 select,
                 'Manual options',
                 value
                 options,
             ) => {
                'One per line. Optional label format: value | label. Leave empty when using a source.'
                select.empty();
             )
        );
    },


    createTransformControls(field, property, title) {
                variables.forEach(
        const wrapper =
                    name => {
            $('<div>')
                        $('<option>')
                .addClass(
                            .attr(
                    'preload-editor-transform'
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                 );
                 );


        $('<h4>')
                if (
            .text(title)
                    value &&
            .appendTo(wrapper);
                    variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                        variables[0]
                    );
                }
            };


        const existing =
             populate(
             field[property] &&
                this.editorTools.variableSelect,
            typeof field[property] === 'object'
                 current
                 ? field[property]
            );
                : {};


        const transform =
             populate(
             this.select(
                 this.editorTools.conditionVariableSelect,
                 [
                 currentCondition
                    {
                        value: '',
                        label: 'No transformation'
                    },
                    {
                        value: 'remove-prefix',
                        label: 'Remove prefix'
                    },
                    {
                        value: 'remove-suffix',
                        label: 'Remove suffix'
                    },
                    {
                        value: 'replace',
                        label: 'Replace'
                    }
                ],
                 existing.transform || ''
             );
             );
        },


         const prefix =
         updateConditionVariableVisibility() {
             this.textInput(
             if (!this.editorTools) {
                 existing.prefix || ''
                 return;
             );
             }


        const suffix =
            const type =
            this.textInput(
                this.editorTools
                existing.suffix || ''
                    .conditionTypeSelect
            );
                    .val();
 
        const from =
            this.textInput(
                existing.from || ''
            );


        const to =
             this.editorTools
             this.textInput(
                 .conditionVariableWrap
                 existing.to || ''
                 .toggle(
            );
                     type === 'if'
 
        const controls =
            $('<div>')
                 .addClass(
                     'preload-editor-transform-controls'
                 );
                 );
        },


         const prefixRow =
         renderEditorTools() {
            this.fieldRow(
            const tools =
                'Prefix',
                $('<div>')
                prefix
                    .addClass(
            );
                        'preload-editor-tools'
                    );


        const suffixRow =
            const wrapGroup =
            this.fieldRow(
                $('<div>')
                'Suffix',
                    .addClass(
                suffix
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
            );
                    );


        const fromRow =
            wrapGroup.append(
            this.fieldRow(
                this.createButton(
                'From',
                    'Wrap selection',
                 from
                    'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                 )
             );
             );


        const toRow =
            const variableGroup =
            this.fieldRow(
                $('<div>')
                'To',
                    .addClass(
                to
                        'preload-editor-tool-group preload-editor-tool-group-variable'
            );
                    );


        const renderInputs = () => {
            $('<span>')
            const type = transform.val();
                .addClass(
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);


             prefixRow.toggle(
             const variableSelect =
                type === 'remove-prefix'
                this.createToolSelect(
            );
                    [],
                    'preload-editor-variable-select'
                );


             suffixRow.toggle(
             variableGroup.append(
                 type === 'remove-suffix'
                 variableSelect,
            );


            fromRow.toggle(
                this.createButton(
                type === 'replace'
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                )
             );
             );


             toRow.toggle(
             const conditionGroup =
                type === 'replace'
                $('<div>')
            );
                    .addClass(
        };
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


        const update = () => {
            $('<span>')
            const type = transform.val();
                .addClass(
            let object = null;
                    'preload-editor-tool-label'
                )
                .text('Insert condition')
                .appendTo(conditionGroup);


             if (type === 'remove-prefix') {
             const conditionTypeSelect =
                 if (prefix.val()) {
                 this.createToolSelect(
                     object = {
                     [
                        transform: type,
                        {
                        prefix: prefix.val()
                            value: 'if',
                    };
                            label: '@if'
                }
                        },
            } else if (type === 'remove-suffix') {
                        {
                if (suffix.val()) {
                            value: 'elseif',
                    object = {
                            label: '@elseif'
                        transform: type,
                        },
                        suffix: suffix.val()
                        {
                    };
                            value: 'else',
                }
                            label: '@else'
            } else if (type === 'replace') {
                        },
                if (from.val()) {
                        {
                    object = {
                            value: 'endif',
                        transform: type,
                            label: '@endif'
                        from: from.val(),
                         }
                         to: to.val()
                    ],
                     };
                     'preload-editor-condition-type-select'
                 }
                 );
            }


             if (object) {
             const conditionVariableSelect =
                field[property] = object;
                this.createToolSelect(
            } else {
                    [],
                 delete field[property];
                    'preload-editor-condition-variable-select'
            }
                 );


             this.markDirty();
             const conditionVariableWrap =
            this.renderConfigPreviewBySelector();
                $('<span>')
        };
                    .addClass(
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


        transform.on(
            const insertCondition =
            'change.preloadEditor',
                this.createButton(
            () => {
                    'Insert',
                update();
                    'preload-editor-tool-button',
                renderInputs();
                    () =>
            }
                        this.insertCondition(
        );
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


        [
             conditionTypeSelect.on(
            prefix,
                 'change.preloadEditor',
            suffix,
                 () =>
            from,
                    this.updateConditionVariableVisibility()
             to
        ].forEach(input => {
            input.on(
                 'input.preloadEditor',
                 update
             );
             );
        });


        controls.append(
            conditionGroup.append(
            this.fieldRow(
                 conditionTypeSelect,
                 'Transformation',
                 conditionVariableWrap,
                 transform
                insertCondition
            ),
             );
            prefixRow,
            suffixRow,
            fromRow,
             toRow
        );


        renderInputs();
            tools.append(
                wrapGroup,
                variableGroup,
                conditionGroup
            );


        wrapper.append(controls);
            this.editorTools = {
        return wrapper;
                root: tools,
    },
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };


    // Config output
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();


    getCleanConfig() {
            return tools;
         const config =
         },
            JSON.parse(
                JSON.stringify(
                    this.state.config
                )
            );


         const fields = config.fields || {};
         updateEditorTools() {
         const orderedFields = {};
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
         },


         if (fields.PAGE) {
         // =========================================================
            orderedFields.PAGE = fields.PAGE;
        // Syntax highlighting
         }
         // =========================================================


         Object.keys(fields)
         getKnownVariables() {
             .filter(
             const known =
                 name =>
                 new Set(['PAGE']);
                    name.toUpperCase() !== 'PAGE'
            )
            .forEach(name => {
                orderedFields[name] = fields[name];
            });


        config.fields = orderedFields;
            const fields =
        return config;
                this.state.config &&
    },
                this.state.config.fields;


    getConfigJSON() {
            if (
        return JSON.stringify(
                fields &&
            this.getCleanConfig(),
                typeof fields === 'object'
            null,
            ) {
            4
                Object.keys(fields).forEach(
        );
                    name => {
    },
                        known.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }


    renderConfigPreview(container) {
             return known;
        if (!container) {
         },
             return;
         }


         container.text(
         createSyntaxDecorations(
             this.getConfigJSON()
             state,
         );
            Decoration
    },
         ) {
            const decorations = [];
            const source =
                state.doc.toString();


    renderConfigPreviewBySelector() {
            const knownVariables =
        const preview =
                this.getKnownVariables();
            this.root &&
            this.root.find(
                '.preload-editor-config-preview'
            );


        if (preview && preview.length) {
            const variablePattern =
            this.renderConfigPreview(preview);
                /%%([A-Za-z0-9_-]+)%%/g;
        }


        this.renderAnalysisBySelector();
            let match;
    },


    markDirty() {
            while (
        this.state.dirty = true;
                (
    },
                    match =
                        variablePattern.exec(source)
                ) !== null
            ) {
                const name =
                    match[1].toUpperCase();


    // Save
                const known =
                    knownVariables.has(name);


    async savePreloadOnly() {
                decorations.push(
        let title =
                    Decoration.mark({
            String(
                        class: [
                this.state.preloadTitle || ''
                            'preload-editor-syntax-variable',
            ).trim();
                            known
 
                                ? 'preload-editor-syntax-variable-known'
        if (!title) {
                                : 'preload-editor-syntax-variable-unknown'
            const result =
                        ].join(' ')
                await this.createPromptDialog(
                    }).range(
                    'Preload title',
                        match.index,
                     'Enter the full title for the preload.'
                        match.index +
                            match[0].length
                     )
                 );
                 );
            if (!result) {
                return;
             }
             }


             title = result;
             const conditionPattern =
            this.state.preloadTitle = title;
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
        }


        this.state.preloadContent =
            while (
             this.getEditorContent();
                (
                    match =
                        conditionPattern.exec(source)
                ) !== null
             ) {
                decorations.push(
                    Decoration.mark({
                        class:
                            'preload-editor-syntax-condition'
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


        const validation =
                const directiveStart =
            this.validateBeforeSave();
                    match.index +
                    match[0].indexOf('@');


        if (validation.errors.length) {
                decorations.push(
            this.showValidationErrors(validation);
                    Decoration.mark({
            return;
                        class:
        }
                            'preload-editor-syntax-directive'
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


        this.setStatus(
                const type =
            'Saving preload...',
                    match[1].toLowerCase();
            'loading'
        );


        try {
                if (
            const exists =
                    type !== 'if' &&
                 await this.pageExists(title);
                    type !== 'elseif'
                 ) {
                    continue;
                }


            await this.savePage(
                 const expression =
                title,
                     match[2];
                this.state.preloadContent,
                 exists
                    ? 'Updated preload with Preload Editor'
                     : 'Created preload with Preload Editor',
                !exists
            );


            this.state.mode = 'edit';
                const expressionStart =
            this.state.dirty = false;
                    match.index +
                    match[0].indexOf(
                        expression
                    );


            this.setStatus(
                 const expressionPattern =
                'Preload saved successfully.',
                    /[A-Za-z0-9_-]+/g;
                 'success'
            );


            mw.notify(
                 let expressionMatch;
                 'Preload saved.',
                { type: 'success' }
            );
        } catch (error) {
            console.error(
                'Preload Editor save:',
                error
            );


            this.setStatus(
                while (
                error.message ||
                    (
                    'Could not save preload.',
                        expressionMatch =
                'error'
                            expressionPattern.exec(
            );
                                expression
 
                            )
            mw.notify(
                    ) !== null
                 error.message ||
                 ) {
                     'Could not save preload.',
                     const name =
                { type: 'error' }
                        expressionMatch[0]
            );
                            .toUpperCase();
        }
    },


    async saveAll() {
                    if (
        let title =
                        !knownVariables.has(name)
            String(
                    ) {
                this.state.preloadTitle || ''
                        continue;
            ).trim();
                    }


        if (!title) {
                    const start =
            const result =
                        expressionStart +
                await this.createPromptDialog(
                        expressionMatch.index;
                    'Preload title',
                    'Enter the full title for the preload.'
                );


            if (!result) {
                    decorations.push(
                 return;
                        Decoration.mark({
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                 }
             }
             }


             title = result;
             return Decoration.set(
             this.state.preloadTitle = title;
                decorations,
         }
                true
             );
         },


         this.state.preloadContent =
         async installSyntaxHighlighting(view) {
             this.getEditorContent();
            await mw.loader.using(
                'ext.CodeMirror.v6.lib'
             );


        const validation =
            const require =
            this.validateBeforeSave();
                mw.loader.require;


        if (validation.errors.length) {
            const {
             this.showValidationErrors(validation);
                StateField,
            return;
                StateEffect,
        }
                EditorView,
                Decoration
            } = require(
                'ext.CodeMirror.v6.lib'
             );


        const configTitle =
            const syntaxField =
            title.replace(/\/+$/, '') +
                StateField.define({
            '/config.json';
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


        this.setStatus(
                    update: (
            'Saving preload and config...',
                        decorations,
            'loading'
                        transaction
        );
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


        try {
                    provide: field =>
            const preloadExists =
                        EditorView.decorations.from(
                await this.pageExists(title);
                            field
                        )
                });


             await this.savePage(
             view.dispatch({
                 title,
                 effects:
                this.state.preloadContent,
                    StateEffect.appendConfig.of(
                preloadExists
                        syntaxField
                    ? 'Updated preload with Preload Editor'
                     )
                     : 'Created preload with Preload Editor',
             });
                !preloadExists
             );


             const configExists =
             this.editor.syntaxField =
                 await this.pageExists(configTitle);
                 syntaxField;
        },


             await this.savePage(
        async mountCodeMirror(textarea) {
                 configTitle,
             return new Promise(
                this.getConfigJSON(),
                 (
                configExists
                     resolve,
                     ? 'Updated preload config with Preload Editor'
                     reject
                     : 'Created preload config with Preload Editor',
                 ) => {
                 !configExists
                    let settled = false;
            );


            this.state.mode = 'edit';
                    const cleanup = () => {
            this.state.dirty = false;
                        mw.hook(
            this.state.preloadTitle = title;
                            'dev.CCM.ready'
                        ).remove(onReady);


            this.setStatus(
                        mw.hook(
                'Preload and config saved successfully.',
                            'dev.CCM.load'
                'success'
                        ).remove(onLoad);
            );
                    };


            mw.notify(
                    const onReady =
                'Preload and config saved.',
                        async cm => {
                { type: 'success' }
                            if (
            );
                                settled ||
        } catch (error) {
                                !cm ||
            console.error(
                                cm.textarea !== textarea ||
                'Preload Editor save:',
                                !cm.view
                error
                            ) {
            );
                                return;
                            }


            this.setStatus(
                            settled = true;
                error.message ||
                            cleanup();
                    'Could not save preload/config.',
                'error'
            );


            mw.notify(
                            const view =
                error.message ||
                                cm.view;
                    'Could not save preload/config.',
                { type: 'error' }
            );
        }
    },


    validateBeforeSave() {
                            const inputHandler =
        const errors = [];
                                () => {
        const warnings = [];
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();


        const title =
                                    this.markPreloadDirty();
            String(
                this.state.preloadTitle || ''
            ).trim();


        if (!title) {
                                    this.reanalyze();
            errors.push(
                'A preload title is required.'
            );
        }


        if (
                                    this.renderVariablesBySelector();
            title &&
                                    this.renderVariableConfigurationBySelector();
            !/\/Preload$/i.test(title)
                                    this.renderAnalysisBySelector();
        ) {
                                    this.updateEditorTools();
            warnings.push(
 
                'The title does not end with "/Preload".'
                                    this.saveDraft();
            );
                                };
        }
 
                            view.dom.addEventListener(
                                'input',
                                inputHandler
                            );


        const content =
                            view.dom.classList.add(
            this.getEditorContent();
                                'preload-editor-codemirror'
                            );


        this.state.preloadContent = content;
                            const wrapper =
                                view.dom.closest(
                                    '.ext-codemirror-wrapper'
                                );


        if (!content.trim()) {
                            if (wrapper) {
            errors.push(
                                wrapper.classList.add(
                'The preload cannot be empty.'
                                    'preload-editor-codemirror-wrapper'
            );
                                );
        }
                            }


        if (!/<includeonly>/i.test(content)) {
                            this.editor = {
            warnings.push(
                                cm,
                'The preload does not contain an <includeonly> section.'
                                view,
            );
                                textarea,
        }
                                inputHandler
                            };


        if (!/<noinclude>/i.test(content)) {
                            this.editorView =
            warnings.push(
                                view;
                'The preload does not contain a <noinclude> section.'
            );
        }


        const analysis =
                            this.state.preloadContent =
            this.analyzePreload(
                                view.state.doc.toString();
                this.extractIncludeonly(content)
            );


        const configValidation =
                            try {
            this.validateConfig(
                                await this.installSyntaxHighlighting(
                this.state.config,
                                    view
                analysis
                                );
            );


        errors.push(
                                if (
            ...configValidation.errors
                                    this.state.dirty
        );
                                ) {
                                    this.saveDraft();
                                }


        warnings.push(
                                resolve(view);
            ...configValidation.warnings
                            } catch (error) {
        );
                                reject(error);
                            }
                        };


        let depth = 0;
                    const onLoad =
                        loader => {
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


        analysis.conditions.forEach(condition => {
                            try {
            if (condition.type === 'if') {
                                loader(textarea);
                depth++;
                            } catch (error) {
            } else if (
                                settled = true;
                condition.type === 'endif'
                                cleanup();
            ) {
                                reject(error);
                depth--;
                            }
                        };


                if (depth < 0) {
                     mw.hook(
                     errors.push(
                         'dev.CCM.ready'
                         'Found @endif without a matching @if.'
                     ).add(onReady);
                     );


                     depth = 0;
                     mw.hook(
                        'dev.CCM.load'
                    ).add(onLoad);
                 }
                 }
             } else if (
             );
                condition.type === 'elseif' ||
        },
                condition.type === 'else'
 
             ) {
        // =========================================================
                 if (depth === 0) {
        // Main UI
                     errors.push(
        // =========================================================
                         '@' +
 
                         condition.type +
        init() {
                         ' exists outside an @if block.'
            const root =
                $('#mw-content-text');
 
             if (!root.length) {
                 return;
            }
 
            this.root =
                $('<div>')
                     .attr(
                         'id',
                         'preload-editor'
                    )
                    .addClass(
                         'preload-editor'
                     );
                     );
                }
            }
        });


        if (depth > 0) {
             root.append(this.root);
             errors.push(
                'One or more @if blocks are missing @endif.'
            );
        }


        return {
             this.renderShell();
             errors,
            warnings,
            valid: errors.length === 0
        };
    },


    showValidationErrors(validation) {
            this.restoreDraft();
        this.renderAnalysisBySelector();


        this.setStatus(
            window.addEventListener(
            validation.errors.join(' '),
                'beforeunload',
             'error'
                () => {
        );
                    if (this.state.dirty) {
                        this.saveDraft();
                    }
                }
            );
        },
                renderShell() {
             this.destroyEditor();
            this.root.empty();


        mw.notify(
            const loader =
            validation.errors.join('\n'),
                this.createSection('Preload');
            { type: 'error' }
        );
    }
};


mw.PreloadEditor = PreloadEditor;
            const titleInput =
                this.textInput(
                    this.state.preloadTitle,
                    'Template:Example/Preload'
                ).attr(
                    'id',
                    'preload-editor-title-input'
                );


$(function () {
            titleInput.on(
    const title =
                'input.preloadEditor',
        mw.config.get('wgPageName');
                () => {
                    this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();


    if (
                    if (
         title !==
                        this.state.dirty &&
         'Petit_Planet:Preload_Editor'
                        this.state.mode === 'new'
     ) {
                    ) {
         return;
                        this.saveDraft();
    }
                    }
                }
            );
 
            const loadButton =
                this.createButton(
                    'Load',
                    'preload-editor-button-primary',
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                );
 
            const newButton =
                this.createButton(
                    'New',
                    '',
                    () => this.startNew()
                );
 
            const sampleButton =
                this.createButton(
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );
 
            loader.append(
                $('<div>')
                    .addClass(
                        'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );
 
            this.root.append(loader);
 
            this.workspace =
                $('<div>')
                    .addClass(
                        'preload-editor-workspace'
                    );
 
            this.root.append(
                this.workspace
            );
 
            /*
            * Fixed footer
            *
            * Local draft status, normal status messages,
            * and save actions live here.
            */
            const footer =
                $('<div>')
                    .addClass(
                        'preload-editor-footer'
                    );
 
            this.localDraftStatus =
                $('<div>')
                    .addClass(
                        'preload-editor-local-draft-status is-empty'
                    )
                    .text(
                        'No local draft'
                    );
 
            this.status =
                $('<div>')
                    .addClass(
                        'preload-editor-status'
                    );
 
            footer.append(
                this.localDraftStatus,
                this.status
            );
 
            this.root.append(
                footer
            );
 
            this.updateLocalDraftIndicator();
 
            this.renderWelcome();
        },
 
        renderWelcome() {
            this.workspace.empty();
 
            const section =
                this.createSection('Get started');
 
            $('<p>')
                .text(
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                )
                .appendTo(section);
 
            const tips =
                $('<ul>')
                    .addClass(
                        'preload-editor-tips'
                    );
 
            [
                'Existing preload: loads the preload and its config.json if available.',
                'New preload: starts with the standard Preload Template structure.',
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
            ].forEach(
                text => {
                    $('<li>')
                        .text(text)
                        .appendTo(tips);
                }
            );
 
            section.append(tips);
            this.workspace.append(section);
        },
 
        setStatus(
            message,
            type
        ) {
            if (!this.status) {
                return;
            }
 
            this.status.removeClass(
                'is-error',
                'is-success',
                'is-warning',
                'is-loading'
            );
 
            if (type) {
                this.status.addClass(
                    'is-' + type
                );
            }
 
            this.status.text(
                message || ''
            );
        },
 
        // =========================================================
        // Load / create
        // =========================================================
 
        async loadExisting(title) {
            title =
                String(title || '').trim();
 
            if (!title) {
                mw.notify(
                    'Enter a preload page title first.',
                    {
                        type: 'warn'
                    }
                );
 
                return;
            }
 
            this.setStatus(
                'Loading preload...',
                'loading'
            );
 
            try {
                const page =
                    await this.getPage(title);
 
                if (!page) {
                    const suggestions =
                        await this.findSimilarPreloads(
                            title
                        );
 
                    this.renderMissingPage(
                        title,
                        suggestions
                    );
 
                    this.setStatus(
                        'Preload not found.',
                        'warning'
                    );
 
                    return;
                }
 
                await this.loadDefinition(
                    page.title,
                    page.content
                );
 
                this.setStatus(
                    'Preload loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not load preload.',
                    'error'
                );
            }
        },
 
        async findSimilarPreloads(title) {
            let query =
                title
                    .replace(
                        /\/Preload$/i,
                        ''
                    )
                    .trim();
 
            if (!query) {
                query = title;
            }
 
            try {
                const results =
                    await this.searchPages(query);
 
                return results.filter(
                    result =>
                        /\/Preload$/i.test(
                            result.title
                        )
                );
            } catch (error) {
                console.error(
                    'Preload Editor search:',
                    error
                );
 
                return [];
            }
        },
 
        renderMissingPage(
            title,
            suggestions
        ) {
            this.workspace.empty();
 
            const section =
                this.createSection(
                    'Preload not found'
                );
 
            $('<p>')
                .text(
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);
 
            if (suggestions.length) {
                $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);
 
                const list =
                    $('<div>')
                        .addClass(
                            'preload-editor-suggestions'
                        );
 
                suggestions.forEach(
                    result => {
                        list.append(
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                        );
                    }
                );
 
                section.append(list);
            }
 
            section.append(
                this.createButton(
                    'Create this preload',
                    'preload-editor-button-primary',
                    () =>
                        this.startNew(title)
                )
            );
 
            this.workspace.append(section);
        },
 
        async startNew(title) {
            title =
                String(title || '').trim();
 
            this.state = {
                preloadTitle: title,
                preloadSource: '',
                preloadContent:
                    this.defaults.preload,
 
                config:
                    this.emptyConfig(),
 
                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };
 
            this.saveDraft();
            this.renderEditor();
 
            this.setStatus(
                'Creating a new preload.',
                'success'
            );
        },
 
        async loadSamplePage() {
            const result =
                await this.createPromptDialog(
                    'Load Sample Page',
                    'Enter the title of a normal wiki page to use as the starting point.'
                );
 
            if (!result) {
                return;
            }
 
            this.setStatus(
                'Loading sample page...',
                'loading'
            );
 
            try {
                const page =
                    await this.getPage(result);
 
                if (!page) {
                    throw new Error(
                        'Sample page not found: ' +
                        result
                    );
                }
 
                const sample =
                    this.convertSampleToPreload(
                        page.content
                    );
 
                this.state = {
                    preloadTitle: '',
                    preloadSource: '',
                    preloadContent: sample,
 
                    config:
                        this.emptyConfig(),
 
                    variables: ['PAGE'],
                    conditions: [],
                    selectedVariable: 'PAGE',
                    deletedVariables: [],
                    mode: 'new',
                    dirty: true,
                    dirtyPreload: true,
                    dirtyConfig: true,
 
                    localDraftSavedAt: null,
                    localDraftAvailable: false
                };
 
                this.reanalyze();
                this.saveDraft();
                this.renderEditor();
 
                this.setStatus(
                    'Sample page loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
        },
 
        convertSampleToPreload(source) {
            let content =
                String(source || '').trim();
 
            const include =
                content.match(
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                );
 
            if (include) {
                content =
                    include[1].trim();
            }
 
            content =
                content
                    .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();
 
            return (
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },
 
        async loadDefinition(
            title,
            source
        ) {
            const content =
                this.extractIncludeonly(source);
 
            let config =
                this.emptyConfig();
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            const configPage =
                await this.getPage(configTitle);
 
            if (configPage) {
                try {
                    config =
                        JSON.parse(
                            configPage.content
                        );
                } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }
 
            const analysis =
                this.analyzePreload(content);
 
            this.state.deletedVariables = [];
 
            config =
                this.prepareConfigForVariables(
                    config,
                    analysis
                );
 
            this.state = {
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,
 
                variables:
                    analysis.variables,
 
                conditions:
                    analysis.conditions,
 
                selectedVariable:
                    analysis.variables.includes('PAGE')
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),
 
                deletedVariables: [],
 
                mode: 'edit',
                dirty: false,
                dirtyPreload: false,
                dirtyConfig: false,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };
 
            this.clearDraft(title);
            this.renderEditor();
        },
 
        // =========================================================
        // Editor
        // =========================================================
 
        renderEditor() {
            this.destroyEditor();
            this.workspace.empty();
 
            const layout =
                $('<div>')
                    .addClass(
                        'preload-editor-layout'
                    );
 
            const left =
                $('<div>')
                    .addClass(
                        'preload-editor-left'
                    );
 
            const right =
                $('<div>')
                    .addClass(
                        'preload-editor-right'
                    );
 
            const editorSection =
                this.createSection(
                    'Preload',
                    'preload-editor-main-section'
                );
 
            const meta =
                $('<div>')
                    .addClass(
                        'preload-editor-meta'
                    );
 
            $('<strong>')
                .text(
                    this.state.preloadTitle ||
                    'New preload'
                )
                .appendTo(meta);
 
            if (
                this.state.mode === 'new'
            ) {
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
            }
 
            editorSection.append(meta);
            editorSection.append(
                this.renderEditorTools()
            );
 
            const textarea =
                this.textarea(
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );
 
            const editorMount =
                $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);
 
            editorSection.append(editorMount);
            left.append(editorSection);
 
            const analysisSection =
                this.createSection('Analysis');
 
            const analysisContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis'
                    );
 
            analysisSection.append(
                analysisContainer
            );
 
            const variablesSection =
                this.createSection('Variables');
 
            const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );
 
            const detectHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );
 
            variablesSection.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );
 
            const variableContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variables'
                    );
 
            variablesSection.append(
                variableContainer
            );
 
            const configurationSection =
                this.createSection(
                    'Variable configuration'
                );
 
            /*
            * Import button lives at the top of the
            * variable configuration section so the
            * workflow is always easy to find.
            */
            const importDefinitionsButton =
                this.createButton(
                    'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                        this.importVariableDefinitions()
                );
 
            const importHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-import-definitions-help'
                    )
                    .text(
                        'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );
 
            const importControls =
                $('<div>')
                    .addClass(
                        'preload-editor-import-definition-controls'
                    )
                    .append(
                        importDefinitionsButton,
                        importHelp
                    );
 
            configurationSection.append(
                importControls
            );
 
            const configurationContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-configuration'
                    );
 
            configurationSection.append(
                configurationContainer
            );
 
            const configSection =
                this.createSection(
                    'Configuration'
                );
 
            const configHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );
 
            const reviewConfigButton =
                this.createButton(
                    'Review config.json',
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );
 
            configSection.append(
                configHelp,
                reviewConfigButton
            );
 
            right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );
 
            layout.append(
                left,
                right
            );
 
            const saveBar =
                $('<div>')
                    .addClass(
                        'preload-editor-save-bar'
                    );
 
            saveBar.append(
                this.createButton(
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),
 
                this.createButton(
                    'Save Config',
                    '',
                    () =>
                        this.saveConfigOnly()
                ),
 
                this.createButton(
                    'Save',
                    'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                )
            );
 
            this.root
                .find('.preload-editor-footer')
                .append(saveBar);
 
            this.workspace.append(
                layout
            );
 
            this.reanalyze();
 
            this.renderVariables(
                variableContainer
            );
 
            this.renderAnalysis(
                analysisContainer
            );
 
            this.renderVariableConfiguration(
                configurationContainer
            );
 
            this.updateEditorTools();
            this.updateLocalDraftIndicator();
 
            this.mountCodeMirror(
                textarea.get(0)
            ).catch(
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                    );
 
                    this.setStatus(
                        error.message ||
                            'Could not initialize CodeMirror.',
                        'error'
                    );
                }
            );
        },
 
        // =========================================================
        // Variable detection
        // =========================================================
 
        detectVariables() {
            const source =
                this.getEditorContent();
 
            this.state.preloadContent =
                source;
 
            const content =
                this.extractIncludeonly(
                    source
                );
 
            const analysis =
                this.analyzePreload(
                    content
                );
 
            /*
            * If a variable was previously deleted from
            * the configuration, detecting the current
            * preload again should allow it to come back.
            */
            if (
                Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                const detected =
                    new Set(
                        analysis.variables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                    );
 
                this.state.deletedVariables =
                    this.state.deletedVariables
                        .filter(
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                this.state.deletedVariables = [];
            }
 
            this.markDirty();
 
            this.reanalyze();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.updateEditorTools();
 
            this.saveDraft();
 
            this.setStatus(
                'Variables detected from the current preload.',
                'success'
            );
        },
 
        reanalyze() {
            const source =
                this.getEditorContent();
 
            const content =
                this.extractIncludeonly(source);
 
            const analysis =
                this.analyzePreload(
                    content
                );
 
            this.state.preloadContent =
                source;
 
            this.state.variables =
                analysis.variables;
 
            this.state.conditions =
                analysis.conditions;
 
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );
 
            this.analysis =
                analysis;
 
            const available =
                ['PAGE'].concat(
                    analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );
 
            if (
                !available.includes(
                    this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },
 
        // =========================================================
        // Analysis
        // =========================================================
 
        renderAnalysis(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const variableCount =
                analysis.variables.length;
 
            const conditionCount =
                analysis.conditions.length;
 
            const configuredCount =
                Object.keys(
                    this.state.config &&
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;
 
            const summary =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis-summary'
                    );
 
            const createMetric =
                (
                    value,
                    label
                ) =>
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),
 
                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                        );
 
            summary.append(
                createMetric(
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),
 
                createMetric(
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),
 
                createMetric(
                    configuredCount,
                    configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                )
            );
 
            container.append(summary);
 
            if (
                analysis.conditionVariables.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }
 
            const validation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );
 
            if (validation.errors.length) {
                const errors =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-errors'
                        );
 
                validation.errors.forEach(
                    error => {
                        $('<li>')
                            .text(error)
                            .appendTo(errors);
                    }
                );
 
                container.append(errors);
            }
 
            if (validation.warnings.length) {
                const warnings =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );
 
                validation.warnings.forEach(
                    warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                );
 
                container.append(warnings);
            }
 
            if (
                !validation.errors.length &&
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },
 
        renderAnalysisBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderAnalysis(container);
            }
        },
 
        // =========================================================
        // Variables
        // =========================================================
 
        renderVariables(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const variables =
                analysis.variables.slice();
 
            const ordered =
                ['PAGE'];
 
            variables.forEach(
                name => {
                    if (
                        name !== 'PAGE' &&
                        !ordered.includes(name)
                    ) {
                        ordered.push(name);
                    }
                }
            );
 
            const configuredFields =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];
 
            configuredFields.forEach(
                name => {
                    const upper =
                        name.toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );
 
            const deleted =
                Array.isArray(
                    this.state.deletedVariables
                )
                    ? this.state.deletedVariables
                    : [];
 
            deleted.forEach(
                name => {
                    const upper =
                        String(name).toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );
 
            const list =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-list'
                    );
 
            ordered.forEach(
                name => {
                    const isSelected =
                        name ===
                        this.state.selectedVariable;
 
                    const isUsed =
                        analysis.variables.includes(
                            name
                        );
 
                    const isConfigured =
                        !!(
                            this.state.config &&
                            this.state.config.fields &&
                            this.state.config.fields[name]
                        );
 
                    const item =
                        $('<button>')
                            .attr({
                                type: 'button',
                                'data-variable':
                                    name
                            })
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );
 
                    $('<span>')
                        .addClass(
                            'preload-editor-variable-name'
                        )
                        .text(name)
                        .appendTo(item);
 
                    if (name === 'PAGE') {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge'
                                )
                                .text('AUTOMATIC')
                        );
                    } else if (!isConfigured) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    isUsed
                                        ? 'NOT CONFIGURED'
                                        : 'DELETED'
                                )
                        );
                    } else if (!isUsed) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                    }
 
                    list.append(item);
                }
            );
 
            container.append(list);
 
            if (!ordered.length) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                );
            }
        },
 
        renderVariablesBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variables'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderVariables(container);
            }
        },
 
        selectVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();
 
            if (!name) {
                return;
            }
 
            const available =
                ['PAGE'].concat(
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );
 
            const configuredUnused =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];
 
            configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                }
            );
 
            if (!available.includes(name)) {
                return;
            }
 
            this.state.selectedVariable =
                name;
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },
 
        renderVariableConfigurationBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variable-configuration'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
            }
        },
 
        renderVariableConfiguration(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const name =
                this.state.selectedVariable ||
                'PAGE';
 
            const fields =
                this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};
 
            const field =
                fields[name];
 
            if (name === 'PAGE') {
                container.append(
                    this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                );
 
                return;
            }
 
            if (!field) {
                const missing =
                    $('<div>')
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );
 
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    )
                    .append(
                        $('<h3>')
                            .text(name),
 
                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);
 
                $('<p>')
                    .addClass(
                        'preload-editor-analysis-note'
                    )
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);
 
                container.append(missing);
                return;
            }
 
            container.append(
                this.createVariableCard(
                    name,
                    field,
                    analysis
                )
            );
        },
 
        createAutomaticPageCard(field) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );
 
            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );
 
            header.append(
                $('<h3>').text('PAGE'),
 
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
            );
 
            card.append(header);
 
            $('<p>')
                .addClass(
                    'preload-editor-analysis-note'
                )
                .text(
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);
 
            const label =
                this.textInput(
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                );
 
            const description =
                this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                    .addClass(
                        'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                    );
 
            const type =
                this.textInput(
                    field.type || 'page'
                ).prop(
                    'disabled',
                    true
                );
 
            const required =
                this.checkbox(
                    field.required !== false
                ).prop(
                    'disabled',
                    true
                );
 
            const namespace =
                this.textInput(
                    field.namespace || 'Main'
                ).prop(
                    'disabled',
                    true
                );
 
            const allowNew =
                this.checkbox(
                    field['allow-new'] === true
                ).prop(
                    'disabled',
                    true
                );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                ),
 
                this.fieldRow(
                    'Description',
                    description
                ),
 
                this.fieldRow(
                    'Type',
                    type
                ),
 
                this.fieldRow(
                    'Required',
                    required
                ),
 
                this.fieldRow(
                    'Namespace',
                    namespace
                ),
 
                this.fieldRow(
                    'Allow new page',
                    allowNew
                )
            );
 
            return card;
        },
 
        createVariableCard(
            name,
            field,
            analysis
        ) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );
 
            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );
 
            header.append(
                $('<h3>').text(name)
            );
 
            if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }
 
            card.append(header);
 
            const label =
                this.textInput(
                    field.label || ''
                );
 
            label.on(
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                )
            );
 
            const description =
                this.textarea(
                    field.description || ''
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            description.on(
                'input.preloadEditor',
                () => {
                    field.description =
                        description.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Description',
                    description
                )
            );
 
            const types = [
                ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];
 
            const typeSelect =
                this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                );
 
            typeSelect.on(
                'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();
 
                    this.markDirty();
 
                    this.renderVariableConfigurationBySelector();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );
 
            const required =
                this.checkbox(
                    field.required === true
                );
 
            required.on(
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Required',
                    required
                )
            );
 
            const placeholder =
                this.textInput(
                    field.placeholder || ''
                );
 
            placeholder.on(
                'input.preloadEditor',
                () => {
                    const value =
                        placeholder.val();
 
                    if (value) {
                        field.placeholder =
                            value;
                    } else {
                        delete field.placeholder;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );
 
            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                );
 
            defaultInput.on(
                'input.preloadEditor',
                () => {
                    const value =
                        defaultInput.val();
 
                    if (value) {
                        field.default =
                            value;
                    } else {
                        delete field.default;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Default',
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
            );
 
            if (
                field.type === 'textarea'
            ) {
                const maxRows =
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );
 
                maxRows.on(
                    'input.preloadEditor',
                    () => {
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );
 
                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }
 
                        this.markDirty();
                        this.renderConfigReviewAvailability();
                    }
                );
 
                card.append(
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                );
            }
 
            if (
                field.type === 'select' ||
                field.type === 'multiselect'
            ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }
 
            if (
                field.type === 'file'
            ) {
                this.renderFileConfiguration(
                    card,
                    field
                );
            }
 
            const deleteButton =
                this.createButton(
                    'Delete variable',
                    'preload-editor-button-danger preload-editor-delete-variable',
                    async () => {
                        const confirmed =
                            await this.createConfirmDialog(
                                'Delete variable',
                                'Delete "' +
                                name +
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                                'Delete variable',
                                'Cancel'
                            );
 
                        if (!confirmed) {
                            return;
                        }
 
                        this.deleteVariable(name);
                    }
                );
 
            card.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );
 
            return card;
        },
 
        async deleteVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();
 
            if (
                !name ||
                name === 'PAGE'
            ) {
                return;
            }
 
            if (
                !this.state.config ||
                !this.state.config.fields
            ) {
                return;
            }
 
            delete this.state.config.fields[name];
 
            if (
                !Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                this.state.deletedVariables = [];
            }
 
            if (
                !this.state.deletedVariables.includes(
                    name
                )
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }
 
            this.state.selectedVariable =
                name;
 
            this.markDirty();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();
 
            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },
 
        // =========================================================
        // Select configuration
        // =========================================================
 
        renderSelectConfiguration(
            card,
            field
        ) {
            const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                );
 
            source.on(
                'input.preloadEditor',
                () => {
                    const value =
                        source.val();
 
                    if (value) {
                        field.source = value;
                    } else {
                        delete field.source;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source',
                    source,
                    'Currently supported source format: category:Category Name'
                )
            );
 
            const sourcePrefix =
                this.textInput(
                    field['source-prefix'] || ''
                );
 
            sourcePrefix.on(
                'input.preloadEditor',
                () => {
                    const value =
                        sourcePrefix.val();
 
                    if (value) {
                        field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );
 
            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );
 
            excludeCategory.on(
                'input.preloadEditor',
                () => {
                    const value =
                        excludeCategory.val();
 
                    if (value) {
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;
 
                        if (
                            !Object.keys(
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                )
            );
 
            card.append(
                this.createTransformControls(
                    field,
                    'value',
                    'Value transformation'
                ),
 
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );
 
            const optionsValue =
                Array.isArray(field.options)
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }
 
                                return (
                                    String(
                                        option.value || ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';
 
            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            options.on(
                'input.preloadEditor',
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);
 
                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );
 
                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }
 
                                    return {
                                        value:
                                            parts[0],
 
                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
       
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);
 
                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );
 
            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );
 
            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();
 
                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );
 
            const filetext =
                this.textarea(
                    field.filetext || ''
                );
 
            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();
 
                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },
 
        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                $('<div>')
                    .addClass(
                        'preload-editor-transform'
                    );
 
            $('<h4>')
                .text(title)
                .appendTo(wrapper);
 
            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );
 
            const prefix =
                this.textInput(
                    existing.prefix || ''
                );
 
            const suffix =
                this.textInput(
                    existing.suffix || ''
                );
 
            const from =
                this.textInput(
                    existing.from || ''
                );
 
            const to =
                this.textInput(
                    existing.to || ''
                );
 
            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );
 
            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );
 
            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );
 
            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );
 
            const toRow =
                this.fieldRow(
                    'To',
                    to
                );
 
            const renderInputs =
                () => {
                    const type =
                        transform.val();
 
                    prefixRow.toggle(
                        type === 'remove-prefix'
                    );
 
                    suffixRow.toggle(
                        type === 'remove-suffix'
                    );
 
                    fromRow.toggle(
                        type === 'replace'
                    );
 
                    toRow.toggle(
                        type === 'replace'
                    );
                };
 
            const update =
                () => {
                    const type =
                        transform.val();
 
                    let object = null;
 
                    if (
                        type === 'remove-prefix' &&
                        prefix.val()
                    ) {
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                    ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }
 
                    if (object) {
                        field[property] = object;
                    } else {
                        delete field[property];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                };
 
            transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );
 
            controls.append(
                this.fieldRow(
                    'Transformation',
                    transform
                ),
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );
 
            renderInputs();
 
            wrapper.append(controls);
 
            return wrapper;
        },
 
        // =========================================================
        // Config output
        // =========================================================
 
        getCleanConfig() {
            const config =
                JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );
 
            const fields =
                config.fields || {};
 
            const orderedFields = {};
 
            orderedFields.PAGE =
                this.getAutomaticPageField();
 
            Object.keys(fields)
                .filter(
                    name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );
 
            config.fields =
                orderedFields;
 
            return config;
        },
 
        getConfigJSON() {
            return JSON.stringify(
                this.getCleanConfig(),
                null,
                4
            );
        },
 
        renderConfigPreview(container) {
            if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },
 
        renderConfigPreviewBySelector() {
            this.renderAnalysisBySelector();
        },
 
        renderConfigReviewAvailability() {
            this.renderAnalysisBySelector();
        },
 
        // =========================================================
        // Dirty state
        // =========================================================
 
        updateDirtyState() {
            this.state.dirty =
                !!(
                    this.state.dirtyPreload ||
                    this.state.dirtyConfig
                );
        },
 
        markPreloadDirty() {
            this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markConfigDirty() {
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markDirty() {
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        // =========================================================
        // Save
        // =========================================================
 
        async savePreloadOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'preload',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            this.setStatus(
                'Saving preload...',
                'loading'
            );
 
            try {
                const exists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyPreload = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveConfigOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'config',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving config...',
                'loading'
            );
 
            try {
                /*
                * This now automatically creates or converts
                * config.json to the JSON content model.
                */
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    (
                        await this.pageExists(
                            configTitle
                        )
                    )
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyConfig = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor config save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
         async saveAll() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving preload and config...',
                'loading'
            );
 
            try {
                const preloadExists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );
 
                /*
                * Config is saved through the JSON-aware
                * helper. This means:
                *
                * - new config -> created as JSON
                * - old wikitext config -> converted to JSON
                * - existing JSON config -> simply updated
                */
                const configExists =
                    await this.pageExists(
                        configTitle
                    );
 
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.dirtyPreload = false;
                this.state.dirtyConfig = false;
                this.state.dirty = false;
                this.state.preloadTitle = title;
 
                this.clearDraft(title);
 
                this.setStatus(
                    'Preload and JSON config saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload and config saved. config.json is using the JSON content model.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        // =========================================================
        // Validation
        // =========================================================
 
        validateBeforeSave() {
            const errors = [];
            const warnings = [];
 
            const title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                errors.push(
                    'A preload title is required.'
                );
            }
 
            if (
                title &&
                !/\/Preload$/i.test(title)
            ) {
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }
 
            const content =
                this.getEditorContent();
 
            this.state.preloadContent =
                content;
 
            if (!content.trim()) {
                errors.push(
                    'The preload cannot be empty.'
                );
            }
 
            if (
                !/<includeonly>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }
 
            if (
                !/<noinclude>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain a <noinclude> section.'
                );
            }
 
            const analysis =
                this.analyzePreload(
                    this.extractIncludeonly(
                        content
                    )
                );
 
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );
 
            const configValidation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );
 
            errors.push(
                ...configValidation.errors
            );
 
            warnings.push(
                ...configValidation.warnings
            );
 
            let depth = 0;
                        analysis.conditions.forEach(
                condition => {
                    if (
                        condition.type === 'if'
                    ) {
                        depth++;
                    } else if (
                        condition.type === 'endif'
                    ) {
                        depth--;
 
                        if (depth < 0) {
                            errors.push(
                                'Found @endif without a matching @if.'
                            );
 
                            depth = 0;
                        }
                    } else if (
                        condition.type === 'elseif' ||
                        condition.type === 'else'
                    ) {
                        if (depth === 0) {
                            errors.push(
                                '@' +
                                condition.type +
                                ' exists outside an @if block.'
                            );
                        }
                    }
                }
            );
 
            if (depth > 0) {
                errors.push(
                    'One or more @if blocks are missing @endif.'
                );
            }
 
            return {
                errors,
                warnings,
                valid:
                    errors.length === 0
            };
         },
 
        showValidationErrors(validation) {
            this.renderAnalysisBySelector();
 
            this.saveDraft();
 
            this.setStatus(
                validation.errors.join(' '),
                'error'
            );
 
            mw.notify(
                validation.errors.join('\n'),
                {
                    type: 'error'
                }
            );
        }
    };
 
     mw.PreloadEditor =
        PreloadEditor;
 
    $(function () {
         if (
            mw.config.get('wgPageName') !==
            'Petit_Planet_Wiki:Preload_Editor'
        ) {
            return;
        }


    PreloadEditor.init();
        PreloadEditor.init();
});
    });


}(mediaWiki, jQuery));
}(mediaWiki, jQuery));