Jump to content

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

From The Petit Planet Wiki
ReisuDesign (talk | contribs)
No edit summary
ReisuDesign (talk | contribs)
No edit summary
 
(17 intermediate revisions by the same user not shown)
Line 3: Line 3:


     const PreloadEditor = {
     const PreloadEditor = {
         version: '0.4.0',
         version: '1.2.0',


         state: {
         state: {
Line 13: Line 13:
             conditions: [],
             conditions: [],
             selectedVariable: 'PAGE',
             selectedVariable: 'PAGE',
            deletedVariables: [],
             mode: 'idle',
             mode: 'idle',
             dirty: false
             dirty: false,
            dirtyPreload: false,
            dirtyConfig: false,
 
            // Local draft state
            localDraftSavedAt: null,
            localDraftAvailable: false
         },
         },


Line 23: Line 30:
         workspace: null,
         workspace: null,
         status: null,
         status: null,
        localDraftStatus: null,
         editorTools: null,
         editorTools: null,
        draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',


         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
        // =========================================================
 
        getDraftStorage() {
            try {
                const raw = window.localStorage.getItem(this.draftStorageKey);
 
                if (!raw) {
                    return {
                        active: null,
                        drafts: {}
                    };
                }


        async getPage(title) {
                const parsed = JSON.parse(raw);
            const response = await new mw.Api().get({
                action: 'query',
                prop: 'revisions',
                titles: title,
                rvprop: 'content',
                rvslots: 'main',
                formatversion: 2
            });


            const page =
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
                response &&
                    return {
                response.query &&
                        active: null,
                response.query.pages &&
                        drafts: {}
                 response.query.pages[0];
                    };
                 }


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


            const content =
                 return parsed;
                 page.revisions &&
            } catch (error) {
                page.revisions[0] &&
                 console.warn('Preload Editor: Could not read local drafts.', error);
                 page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;


            return {
                return {
                title: page.title || title,
                    active: null,
                 content: typeof content === 'string' ? content : ''
                    drafts: {}
             };
                 };
             }
         },
         },


         async pageExists(title) {
         setDraftStorage(storage) {
             return !!await this.getPage(title);
             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;
            }
         },
         },


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


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


        async savePage(title, content, summary, createOnly) {
            if (!this.editorView && !content) {
            const params = {
                 content = this.state.preloadContent || '';
                action: 'edit',
             }
                title,
                 text: content,
                summary: summary || 'Updated with Preload Editor',
                formatversion: 2
             };


             if (createOnly) params.createonly = true;
             let config = null;


             return new mw.Api().postWithToken('csrf', params);
             try {
        },
                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();
            }


        // Preload parsing
            return {
                version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,


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


            return match
                 conditions: Array.isArray(this.state.conditions)
                 ? match[1].trim()
                    ? this.state.conditions.slice()
                : String(source || '').trim();
                    : [],
        },


        findVariables(content) {
                selectedVariable: String(this.state.selectedVariable || 'PAGE'),
            const variables = [];
 
             const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                deletedVariables: Array.isArray(this.state.deletedVariables)
             let match;
                    ? this.state.deletedVariables.slice()
                    : [],
 
                mode: this.state.mode || 'edit',
                dirty: !!this.state.dirty,
                dirtyPreload: !!this.state.dirtyPreload,
                dirtyConfig: !!this.state.dirtyConfig,
                savedAt: Date.now()
            };
        },
 
        updateLocalDraftStatus(message, type) {
             if (!this.localDraftStatus) {
                return;
             }


             while ((match = pattern.exec(content)) !== null) {
             this.localDraftStatus.removeClass(
                 const name = match[1].toUpperCase();
                 'is-saved',
                'is-warning',
                'is-error',
                'is-empty'
            );


                if (!variables.includes(name)) {
            if (type) {
                    variables.push(name);
                this.localDraftStatus.addClass('is-' + type);
                }
             }
             }


             return variables;
             this.localDraftStatus.text(message || '');
         },
         },


         findConditions(content) {
         formatLocalDraftTime(timestamp) {
             const conditions = [];
             if (!timestamp) {
            const pattern =
                return '';
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
            }


             let match;
             try {
 
                return new Date(timestamp).toLocaleTimeString([], {
            while ((match = pattern.exec(content)) !== null) {
                     hour: '2-digit',
                conditions.push({
                     minute: '2-digit',
                     type: match[1].toLowerCase(),
                     second: '2-digit'
                     expression: match[2].trim(),
                     index: match.index
                 });
                 });
            } catch (error) {
                return '';
             }
             }
        },


             return conditions;
        updateLocalDraftIndicator() {
        },
             if (!this.localDraftStatus) {
                return;
            }


        findConditionVariables(content) {
            if (this.state.localDraftSavedAt) {
            const variables = [];
                const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);


            this.findConditions(content).forEach(condition => {
                this.updateLocalDraftStatus(
                 if (
                    time ? 'Saved locally at ' + time : 'Saved locally',
                    condition.type !== 'if' &&
                    'saved'
                    condition.type !== 'elseif'
                );
                ) {
 
                    return;
                 return;
                }
            }
 
            this.updateLocalDraftStatus('No local draft', 'empty');
        },
 
        saveDraft() {
            if (!this.state.dirty) {
                return false;
            }
 
            const snapshot = this.getDraftSnapshot();
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();


                const matches =
            storage.drafts[id] = snapshot;
                    condition.expression.match(
            storage.active = id;
                        /[A-Za-z0-9_-]+/g
                    ) || [];


                matches.forEach(name => {
            const saved = this.setDraftStorage(storage);
                    name = name.toUpperCase();


                    if (!variables.includes(name)) {
            if (saved) {
                        variables.push(name);
                this.state.localDraftSavedAt = snapshot.savedAt;
                    }
                this.state.localDraftAvailable = true;
                 });
                this.updateLocalDraftIndicator();
             });
            } else {
                this.state.localDraftAvailable = false;
                 this.updateLocalDraftStatus('Could not save local draft', 'error');
             }


             return variables;
             return saved;
         },
         },


         analyzePreload(content) {
         clearDraft(title) {
             return {
             const storage = this.getDraftStorage();
                variables: this.findVariables(content),
            const id = this.getDraftId(title);
                conditions: this.findConditions(content),
 
                conditionVariables:
            if (storage.drafts && storage.drafts[id]) {
                    this.findConditionVariables(content)
                delete storage.drafts[id];
            };
            }
        },


        // Config
            if (storage.active === id) {
                storage.active = null;
            }


        getAutomaticPageField() {
            this.setDraftStorage(storage);
             return {
 
                label: 'Page Name',
             this.state.localDraftSavedAt = null;
                description: 'Name of the page.',
            this.state.localDraftAvailable = false;
                type: 'page',
 
                required: true,
             this.updateLocalDraftIndicator();
                namespace: 'Main',
                'allow-new': true
             };
         },
         },


         emptyConfig() {
         getMostRecentDraft() {
             return {
             const storage = this.getDraftStorage();
                settings: {
                    incomplete: 'add-stub'
                },
                fields: {
                    PAGE: this.getAutomaticPageField()
                }
            };
        },


        normalizeConfig(config) {
             if (!storage.drafts || !Object.keys(storage.drafts).length) {
             if (
                 return null;
                !config ||
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                 config = this.emptyConfig();
             }
             }


             if (
             if (storage.active && storage.drafts[storage.active]) {
                 !config.settings ||
                 return {
                typeof config.settings !== 'object' ||
                    id: storage.active,
                Array.isArray(config.settings)
                    draft: storage.drafts[storage.active]
            ) {
                 };
                 config.settings = {};
             }
             }


             if (
             let latestId = null;
                !config.fields ||
             let latestDraft = null;
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
             ) {
                config.fields = {};
            }


             // PAGE is always a special, automatic field.
             Object.entries(storage.drafts).forEach(([id, draft]) => {
            // Its configuration is precompiled and only displayed
                if (!draft || typeof draft !== 'object') {
            // in the editor for reference.
                    return;
            config.fields.PAGE =
                }
                 this.getAutomaticPageField();
 
                if (
                    !latestDraft ||
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                ) {
                    latestId = id;
                    latestDraft = draft;
                 }
            });


             return config;
             if (!latestDraft) {
        },
                return null;
            }


        createDefaultField(name, analysis) {
             return {
             return {
                 label: this.humanizeName(name),
                 id: latestId,
                 description: '',
                 draft: latestDraft
                type:
                    analysis.conditionVariables.includes(name)
                        ? 'boolean'
                        : 'text'
             };
             };
         },
         },


         humanizeName(name) {
         async restoreDraft() {
             return String(name || '')
             const result = this.getMostRecentDraft();
                .replace(/[_-]+/g, ' ')
 
                .replace(/([a-z])([A-Z])/g, '$1 $2')
            if (!result || !result.draft) {
                .replace(/\s+/g, ' ')
                 return false;
                .trim()
            }
                 .replace(
                    /\b\w/g,
                    char => char.toUpperCase()
                );
        },


        prepareConfigForVariables(config, analysis) {
            const draft = result.draft;
             config = this.normalizeConfig(config);
             const title = String(draft.preloadTitle || '').trim();
            const displayTitle = title || 'an untitled preload';


             const existing = config.fields || {};
             const savedAt = draft.savedAt
            const fields = {};
                ? new Date(draft.savedAt).toLocaleString()
                : '';


             // PAGE is always automatic/precompiled.
             const message =
            fields.PAGE = this.getAutomaticPageField();
                'Preload Editor found unsaved local work for ' +
                displayTitle +
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                '\n\nRestore it?';


             analysis.variables.forEach(name => {
             const restore = await this.createConfirmDialog(
                 if (name === 'PAGE') return;
                 'Restore unsaved work',
                message,
                'Restore',
                'Discard'
            );


                 fields[name] =
            if (!restore) {
                    existing[name] ||
                 this.clearDraft(title);
                    this.createDefaultField(
                return false;
                        name,
             }
                        analysis
                    );
             });


             Object.keys(existing).forEach(name => {
             let config = this.emptyConfig();
                const upper = name.toUpperCase();


                if (
            if (
                    upper !== 'PAGE' &&
                draft.config &&
                     !fields[upper]
                typeof draft.config === 'object' &&
                 ) {
                !Array.isArray(draft.config)
                     fields[upper] = existing[name];
            ) {
                try {
                     config = this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                    );
                 } catch (error) {
                     console.warn(
                        'Preload Editor: Could not restore local config.',
                        error
                    );
                 }
                 }
             });
             }


             config.fields = fields;
             const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';


             return config;
             this.state = {
        },
                preloadTitle: title,
                preloadSource: String(draft.preloadSource || ''),
                preloadContent: String(draft.preloadContent || ''),
                config,


        validateConfig(config, analysis) {
                variables: Array.isArray(draft.variables)
            const errors = [];
                    ? draft.variables.slice()
            const warnings = [];
                    : [],


            if (
                 conditions: Array.isArray(draft.conditions)
                !config ||
                    ? draft.conditions.slice()
                typeof config !== 'object' ||
                     : [],
                 Array.isArray(config)
            ) {
                return {
                     valid: false,
                    errors: ['Config must be an object.'],
                    warnings: []
                };
            }


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


            const configured =
                 deletedVariables: Array.isArray(draft.deletedVariables)
                 Object.keys(config.fields).map(
                    ? draft.deletedVariables
                    name => name.toUpperCase()
                        .map(name => String(name).toUpperCase())
                );
                        .filter(name => name !== 'PAGE')
                    : [],


            analysis.variables.forEach(name => {
                 mode: draft.mode || 'edit',
                 if (!configured.includes(name)) {
 
                    errors.push(
                dirty: hasDirtyFlags
                        'Variable "' +
                     ? !!(draft.dirtyPreload || draft.dirtyConfig)
                        name +
                    : true,
                        '" is not configured.'
                     );
                }
            });


            configured.forEach(name => {
                 dirtyPreload: hasDirtyFlags
                 if (!analysis.variables.includes(name)) {
                     ? !!draft.dirtyPreload
                     warnings.push(
                     : true,
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                     );
                }
            });


            if (!configured.includes('PAGE')) {
                 dirtyConfig: hasDirtyFlags
                 errors.push(
                     ? !!draft.dirtyConfig
                     'PAGE must always be configured.'
                    : true,
                );
            }


            Object.entries(config.fields).forEach(
                localDraftSavedAt: Number(draft.savedAt) || null,
                ([name, field]) => {
                localDraftAvailable: true
                    if (
            };
                        !field ||
                        typeof field !== 'object' ||
                        Array.isArray(field)
                    ) {
                        errors.push(
                            'Field "' +
                            name +
                            '" must be an object.'
                        );
                        return;
                    }


                    if (!field.type) {
            this.reanalyze();
                        warnings.push(
            this.renderEditor();
                            'Field "' +
            this.updateLocalDraftIndicator();
                            name +
                            '" has no type.'
                        );
                    }


                    if (
            this.setStatus(
                        (
                'Restored unsaved local work from this browser.',
                            field.type === 'select' ||
                'warning'
                            field.type === 'multiselect'
                        ) &&
                        !field.source &&
                        !Array.isArray(field.options)
                    ) {
                        warnings.push(
                            'Field "' +
                            name +
                            '" is a ' +
                            field.type +
                            ' without a source or manual options.'
                        );
                    }
                }
             );
             );


             return {
             mw.notify('Unsaved Preload Editor work restored.', {
                 valid: !errors.length,
                 type: 'success'
                errors,
            });
                warnings
 
             };
             return true;
         },
         },


         // Transformation helpers
         // =========================================================
        // API
        // =========================================================


         transformationObject(
         async getPage(title) {
             transform,
             const response = await new mw.Api().get({
            prefix,
                action: 'query',
            suffix,
                prop: 'info|revisions',
            from,
                titles: title,
            to
                rvprop: 'content',
        ) {
                rvslots: 'main',
             if (!transform) return null;
                formatversion: 2
             });


             switch (transform) {
             const page =
                 case 'remove-prefix':
                 response &&
                    return prefix
                response.query &&
                        ? { transform, prefix }
                response.query.pages &&
                        : null;
                response.query.pages[0];


                 case 'remove-suffix':
            if (!page || page.missing) {
                    return suffix
                 return null;
                        ? { transform, suffix }
            }
                        : null;


                case 'replace':
            const content =
                    return from === ''
                page.revisions &&
                        ? null
                page.revisions[0] &&
                        : {
                page.revisions[0].slots &&
                            transform,
                page.revisions[0].slots.main &&
                            from,
                page.revisions[0].slots.main.content;
                            to: to || ''
                        };


                 default:
            return {
                    return null;
                title: page.title || title,
             }
                 content: typeof content === 'string' ? content : '',
                contentmodel: page.contentmodel || 'wikitext'
             };
         },
         },


         // UI helpers
         async pageExists(title) {
            return !!await this.getPage(title);
        },


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


             if (className) {
             return (
                 section.addClass(className);
                 response &&
            }
                 response.query &&
 
                 response.query.search
            $('<h2>')
             ) || [];
                 .addClass(
                    'preload-editor-section-title'
                )
                 .text(title)
                .appendTo(section);
 
             return section;
         },
         },


         createButton(label, className, callback) {
         /*
             const button = $('<button>')
        * Save a page.
                 .attr('type', 'button')
        *
                 .addClass('preload-editor-button')
        * contentModel is mainly used when creating a page.
                 .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 = $('<div>')
        * Change the content model of an existing page.
                 .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') {
                await this.changeContentModel(
                    title,
                    'json',
                    'Changed preload config content model to JSON'
                );
            }


             return row;
             return this.savePage(
                title,
                content,
                summary,
                false
            );
         },
         },


         textInput(value, placeholder) {
         // =========================================================
             return $('<input>')
        // Config import helpers
                .attr({
        // =========================================================
                    type: 'text',
 
                    value:
        /*
                        value == null
        * Accept either:
                            ? ''
        *
                            : value,
        *  Template:Example/Preload
                    placeholder:
        *
                        placeholder || ''
        * or:
                })
        *
                .addClass('preload-editor-input');
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
             title = String(title || '').trim();
            title = title.replace(/\/+$/, '');
 
            if (/\/config\.json$/i.test(title)) {
                return title;
            }
 
            return title + '/config.json';
         },
         },


         textarea(value) {
         /*
             return $('<textarea>')
        * Return a safe clone of a config field.
                 .val(
        *
                     value == null
        * This is deliberately JSON-based because config
                        ? ''
        * definitions are JSON-compatible objects.
                        : value
        */
                )
        cloneConfigField(field) {
                .addClass(
             try {
                     'preload-editor-textarea'
                return JSON.parse(JSON.stringify(field));
            } catch (error) {
                 console.warn(
                     'Preload Editor: Could not clone imported field.',
                     error
                 );
                 );
        },


        checkbox(checked) {
                return null;
             return $('<input>')
             }
                .attr('type', 'checkbox')
                .prop('checked', !!checked)
                .addClass(
                    'preload-editor-checkbox'
                );
         },
         },


         select(options, value) {
         /*
             const select = $('<select>')
        * Normalize imported field names to the same uppercase
                .addClass(
        * convention used throughout the editor.
                    'preload-editor-select'
        */
                );
        getImportableFields(sourceConfig) {
             const fields = sourceConfig && sourceConfig.fields;


             options.forEach(option => {
             if (
                 $('<option>')
                 !fields ||
                    .attr(
                typeof fields !== 'object' ||
                        'value',
                Array.isArray(fields)
                        option.value
            ) {
                    )
                return {};
                    .text(option.label)
             }
                    .prop(
                        'selected',
                        String(option.value) ===
                        String(
                            value === undefined
                                ? ''
                                : value
                        )
                    )
                    .appendTo(select);
             });


             return select;
             const result = {};
        },


        // CodeMirror
            Object.entries(fields).forEach(([name, field]) => {
                const upper = String(name || '').trim().toUpperCase();


        destroyEditor() {
                if (!upper || upper === 'PAGE') {
            if (!this.editor) {
                    return;
                this.editorView = null;
                 }
                 this.editorTools = null;
                return;
            }


            const {
                 if (
                 view,
                    !field ||
                inputHandler
                    typeof field !== 'object' ||
            } = this.editor;
                    Array.isArray(field)
                ) {
                    return;
                }


            if (view && inputHandler) {
                 const clone = this.cloneConfigField(field);
                 view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }


            if (view) {
                if (!clone) {
                view.destroy();
                    return;
            }
                }


            this.editor = null;
                result[upper] = clone;
             this.editorView = null;
             });
            this.editorTools = null;
        },


        getEditorView() {
             return result;
             return this.editorView;
         },
         },


         getEditorContent() {
         /*
             if (
        * Show the variable-selection dialog after a source
                 this.editorView &&
        * config has been loaded.
                 this.editorView.state
        *
            ) {
        * Resolves:
                 return this.editorView.state.doc.toString();
        *  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));
 
                 const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );
 
                const box = $('<div>')
                    .addClass(
                        'preload-editor-prompt preload-editor-import-dialog'
                    );
 
                $('<h2>')
                    .text('Import variable definitions')
                    .appendTo(box);
 
                 $('<p>')
                    .text(
                        'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                    )
                    .appendTo(box);
 
                if (!names.length) {
                    $('<div>')
                        .addClass(
                            'preload-editor-empty preload-editor-import-empty'
                        )
                        .text(
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);


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


        setEditorContent(content) {
                    const close = this.createButton(
            content = String(content || '');
                        'Close',
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );


            if (!this.editorView) {
                    emptyButtons.append(close);
                this.state.preloadContent = content;
                    box.append(emptyButtons);
                return;
                    overlay.append(box);
            }


            const current =
                    $(document.body).append(overlay);
                this.editorView.state.doc.toString();


            if (current === content) return;
                    overlay.attr('tabindex', '-1');
                    overlay.trigger('focus');


            this.editorView.dispatch({
                     return;
                changes: {
                     from: 0,
                    to: this.editorView.state.doc.length,
                    insert: content
                 }
                 }
            });
        },


        getEditorSelection() {
                const search = this.textInput('', 'Search variables...')
            if (
                    .addClass('preload-editor-import-search');
                 !this.editorView ||
 
                !this.editorView.state
                 const searchWrap = $('<div>')
            ) {
                    .addClass('preload-editor-import-search-wrap')
                return null;
                    .append(search);
            }


            const selection =
                 box.append(searchWrap);
                 this.editorView.state.selection.main;


            return {
                 const controls = $('<div>')
                 from: selection.from,
                     .addClass('preload-editor-import-controls');
                to: selection.to,
                text:
                     this.editorView.state.doc.sliceString(
                        selection.from,
                        selection.to
                    )
            };
        },


        focusEditor() {
                const selectAll = this.createButton(
            if (this.editorView) {
                    'Select all',
                this.editorView.focus();
                    '',
            }
                    () => {
        },
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', true);


        insertEditorText(
                        updateSummary();
            text,
                    }
            selectionFrom,
                );
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) return;


            const view = this.editorView;
                const deselectAll = this.createButton(
            const selection =
                    'Deselect all',
                view.state.selection.main;
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);


            const from =
                        updateSummary();
                selectionFrom === undefined
                     }
                     ? selection.from
                );
                    : selectionFrom;


            const to =
                controls.append(selectAll, deselectAll);
                 selectionTo === undefined
                box.append(controls);
                     ? selection.to
 
                    : selectionTo;
                 const list = $('<div>')
                     .addClass('preload-editor-import-list');


            const cursor =
                const localFields =
                cursorPosition === undefined
                    this.state.config && this.state.config.fields
                    ? from + text.length
                        ? this.state.config.fields
                    : cursorPosition;
                        : {};


            view.dispatch({
                names.forEach(name => {
                changes: {
                     const existing = !!localFields[name];
                    from,
                     const field = fields[name];
                    to,
                     insert: text
                },
                selection: {
                     anchor: cursor
                }
            });


            view.focus();
                    const type = field && field.type
        },
                        ? String(field.type)
                        : 'text';


        // V2.3 editor tools
                    const label = field && field.label
                        ? String(field.label)
                        : this.humanizeName(name);


        wrapSelectionWithVariable() {
                    const row = $('<label>')
            const selected =
                        .addClass('preload-editor-import-row')
                this.getEditorSelection();
                        .attr('data-variable', name)
                        .attr(
                            'data-search',
                            (name + ' ' + label + ' ' + type).toLowerCase()
                        );


            if (
                    const checkbox = this.checkbox(false)
                !selected ||
                        .attr('data-import-variable', name)
                selected.from === selected.to
                        .addClass('preload-editor-import-checkbox');
            ) {
                this.focusEditor();
                return;
            }


            const replacement =
                    const content = $('<span>')
                '%%' +
                        .addClass('preload-editor-import-content');
                selected.text +
                '%%';


            this.insertEditorText(
                    const header = $('<span>')
                replacement,
                        .addClass('preload-editor-import-header');
                selected.from,
                selected.to,
                selected.from +
                    replacement.length
            );
        },


        insertVariable(name) {
                    $('<strong>')
            name = String(name || '')
                        .text(name)
                .trim()
                        .appendTo(header);
                .toUpperCase();
 
                    $('<span>')
                        .addClass('preload-editor-import-type')
                        .text(type)
                        .appendTo(header);


            if (!name) return;
                    const meta = $('<span>')
                        .addClass('preload-editor-import-meta');


            const selected =
                    $('<span>')
                this.getEditorSelection();
                        .text(label)
                        .appendTo(meta);


            if (!selected) return;
                    const status = $('<span>')
                        .addClass('preload-editor-import-status')
                        .toggleClass('is-existing', existing)
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');


            const text =
                    content.append(header, meta, status);
                 '%%' +
                    row.append(checkbox, content);
                name +
                    list.append(row);
                 '%%';
                 });
 
                 box.append(list);


            this.insertEditorText(
                const summary = $('<div>')
                text,
                    .addClass('preload-editor-import-summary');
                selected.from,
                selected.to
            );
        },


        insertCondition(type, variable) {
                const updateSummary = () => {
            type =
                    const selected = list.find(
                String(type || '')
                        'input[type="checkbox"]:checked'
                     .toLowerCase();
                     ).length;


            variable =
                    const existingSelected = list
                String(variable || '')
                        .find('input[type="checkbox"]:checked')
                    .trim()
                        .filter(function () {
                    .toUpperCase();
                            const name = $(this).attr(
                                'data-import-variable'
                            );


            const selected =
                            return !!localFields[name];
                this.getEditorSelection();
                        }).length;


            if (!selected) return;
                    let text =
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';


            let text;
                    if (existingSelected) {
            let cursorOffset;
                        text +=
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


            switch (type) {
                     summary.text(text);
                case 'if': {
                     if (!variable) return;


                     const opening =
                     importButton.prop('disabled', selected === 0);
                        '<!-- @if ' +
                };
                        variable +
                        ' -->';


                     const closing =
                const filterRows = () => {
                         '<!-- @endif -->';
                     const query = String(search.val() || '')
                        .trim()
                         .toLowerCase();


                     if (
                     list.find('.preload-editor-import-row').each(function () {
                         selected.from !==
                         const row = $(this);
                         selected.to
                        const haystack = String(
                     ) {
                            row.attr('data-search') || ''
                        text =
                        );
                            opening +
 
                            '\n' +
                         row.toggle(!query || haystack.includes(query));
                            selected.text +
                     });
                            '\n' +
                };
                            closing;
 
                search.on(
                    'input.preloadEditor',
                    filterRows
                );
 
                list.on(
                    'change.preloadEditor',
                    'input[type="checkbox"]',
                    updateSummary
                );


                        cursorOffset =
                const buttons = $('<div>')
                            text.length;
                    .addClass('preload-editor-prompt-buttons');
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;


                        cursorOffset =
                const cancel = this.createButton(
                            opening.length + 1;
                    'Cancel',
                    '',
                    () => {
                        overlay.remove();
                        resolve(null);
                     }
                     }
                );


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


                case 'elseif':
                        list
                    text = '<!-- @elseif -->';
                            .find('input[type="checkbox"]:checked')
                    cursorOffset = text.length;
                            .each(function () {
                    break;
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });


                case 'else':
                        overlay.remove();
                    text = '<!-- @else -->';
                        resolve(selected);
                     cursorOffset = text.length;
                     }
                    break;
                );


                 case 'endif':
                 buttons.append(cancel, importButton);
                    text = '<!-- @endif -->';
                box.append(summary, buttons);
                    cursorOffset = text.length;
                overlay.append(box);
                    break;


                 default:
                 $(document.body).append(overlay);
                    return;
            }


            this.insertEditorText(
                overlay.attr('tabindex', '-1');
                text,
                 overlay.trigger('focus');
                 selected.from,
                selected.to,
                selected.from +
                    cursorOffset
            );
        },


        getToolVariables() {
                updateSummary();
            const variables =
                 search.trigger('focus');
                 new Set(['PAGE']);


            if (
                 const close = event => {
                 this.analysis &&
                    if (event.key === 'Escape') {
                this.analysis.variables
                         cancel.trigger('click');
            ) {
                this.analysis.variables.forEach(
                    name => {
                         variables.add(
                            String(name).toUpperCase()
                        );
                     }
                     }
                };
                overlay.on(
                    'keydown.preloadEditor',
                    close
                 );
                 );
            }


            return Array.from(variables);
                overlay.on(
                    'click.preloadEditor',
                    event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                    }
                );
            });
         },
         },


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


             if (className) {
             if (!source) {
                 select.addClass(className);
                 return;
             }
             }


             options.forEach(option => {
             const configTitle = this.normalizeConfigTitle(source);
                $('<option>')
 
                    .attr(
            this.setStatus(
                        'value',
                'Loading source config...',
                        option.value
                'loading'
                    )
             );
                    .text(option.label)
                    .appendTo(select);
             });


             return select;
             try {
        },
                const page = await this.getPage(configTitle);


        updateEditorToolVariables() {
                if (!page) {
            if (!this.editorTools) return;
                    throw new Error(
                        'No config.json was found at "' +
                        configTitle +
                        '".'
                    );
                }


            const variables =
                 let sourceConfig;
                 this.getToolVariables();


            const current =
                try {
                 this.editorTools.variableSelect.val();
                    sourceConfig = JSON.parse(page.content);
                 } catch (error) {
                    throw new Error(
                        'The source config.json contains invalid JSON: ' +
                        error.message
                    );
                }


            const currentCondition =
                if (
                 this.editorTools
                    !sourceConfig ||
                     .conditionVariableSelect
                    typeof sourceConfig !== 'object' ||
                     .val();
                    Array.isArray(sourceConfig)
                 ) {
                     throw new Error(
                        'The source config.json must contain a JSON object.'
                     );
                }


            const populate = (
                if (
                 select,
                    !sourceConfig.fields ||
                 value
                    typeof sourceConfig.fields !== 'object' ||
            ) => {
                    Array.isArray(sourceConfig.fields)
                 select.empty();
                 ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                 }
 
                 const fields = this.getImportableFields(sourceConfig);


                 variables.forEach(name => {
                 const selected =
                     $('<option>')
                     await this.createImportDefinitionsDialog(
                         .attr(
                         configTitle,
                            'value',
                         fields
                            name
                    );
                         )
                        .text(name)
                        .appendTo(select);
                });


                 if (
                 if (selected === null) {
                    value &&
                     this.setStatus(
                    variables.includes(value)
                        'Variable import cancelled.',
                ) {
                         'warning'
                     select.val(value);
                } else if (variables.length) {
                    select.val(
                         variables[0]
                     );
                     );
                    return;
                 }
                 }
            };


            populate(
                if (!selected.length) {
                this.editorTools.variableSelect,
                    this.setStatus(
                current
                        'No variable definitions were imported.',
            );
                        'warning'
                    );


            populate(
                     return;
                this.editorTools
                 }
                     .conditionVariableSelect,
                 currentCondition
            );
        },


        updateConditionVariableVisibility() {
                if (!this.state.config) {
            if (!this.editorTools) return;
                    this.state.config = this.emptyConfig();
                }


            const type =
                 if (!this.state.config.fields) {
                 this.editorTools
                     this.state.config.fields = {};
                     .conditionTypeSelect
                }
                    .val();
 
                const imported = [];
                const replaced = [];


            this.editorTools
                 selected.forEach(name => {
                 .conditionVariableWrap
                    if (name === 'PAGE') {
                .toggle(type === 'if');
                        return;
        },
                    }


        renderEditorTools() {
                    const field = fields[name];
            const tools = $('<div>')
                .addClass(
                    'preload-editor-tools'
                );


            const wrapGroup = $('<div>')
                    if (!field) {
                .addClass(
                        return;
                    'preload-editor-tool-group ' +
                     }
                     'preload-editor-tool-group-wrap'
                );


            wrapGroup.append(
                    if (this.state.config.fields[name]) {
                this.createButton(
                         replaced.push(name);
                    'Wrap selection with %%',
                    } else {
                    'preload-editor-tool-button',
                        imported.push(name);
                    () =>
                    }
                         this.wrapSelectionWithVariable()
                )
            );


            const variableGroup = $('<div>')
                    const clone = this.cloneConfigField(field);
                .addClass(
                    'preload-editor-tool-group ' +
                    'preload-editor-tool-group-variable'
                );


            $('<span>')
                    if (!clone) {
                .addClass(
                        return;
                     'preload-editor-tool-label'
                     }
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);


            const variableSelect =
                    this.state.config.fields[name] = clone;
                this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );


            variableGroup.append(
                    /*
                variableSelect,
                    * If this variable was previously deleted,
                this.createButton(
                    * importing its definition explicitly should
                    'Insert',
                    * restore it.
                    'preload-editor-tool-button',
                    */
                     () =>
                     if (Array.isArray(this.state.deletedVariables)) {
                        this.insertVariable(
                        this.state.deletedVariables =
                            variableSelect.val()
                            this.state.deletedVariables.filter(
                        )
                                deletedName =>
                 )
                                    String(deletedName).toUpperCase() !== name
            );
                            );
                    }
                });
 
                /*
                * Keep PAGE automatic regardless of what the
                * imported config contained.
                */
                 this.state.config.fields.PAGE =
                    this.getAutomaticPageField();
 
                this.markConfigDirty();


            const conditionGroup = $('<div>')
                /*
                .addClass(
                * Keep the current selection when possible.
                    'preload-editor-tool-group ' +
                * Otherwise select the first imported definition.
                     'preload-editor-tool-group-condition'
                */
                const selectedStillExists = !!(
                    this.state.config.fields[
                        this.state.selectedVariable
                     ]
                 );
                 );


            $('<span>')
                if (
                 .addClass(
                    !selectedStillExists ||
                     'preload-editor-tool-label'
                    this.state.selectedVariable === 'PAGE'
                 )
                ) {
                .text('Insert condition')
                    this.state.selectedVariable =
                 .appendTo(conditionGroup);
                        selected[0] ||
                        'PAGE';
                }
 
                this.reanalyze();
 
                this.renderVariablesBySelector();
                this.renderVariableConfigurationBySelector();
                this.renderAnalysisBySelector();
                this.updateEditorTools();
 
                 this.saveDraft();
 
                let status =
                    'Imported ' +
                    selected.length +
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                     '.';
 
                 if (replaced.length) {
                    status +=
                        ' Replaced: ' +
                        replaced.join(', ') +
                        '.';
                 }
 
                this.setStatus(status, 'success');


            const conditionTypeSelect =
                 mw.notify(status, {
                 this.createToolSelect(
                     type: 'success'
                     [
                });
                        {
            } catch (error) {
                            value: 'if',
                console.error(
                            label: '@if'
                    'Preload Editor variable import:',
                        },
                     error
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                     'preload-editor-condition-type-select'
                 );
                 );


            const conditionVariableSelect =
                 this.setStatus(
                 this.createToolSelect(
                     error.message ||
                     [],
                        'Could not import variable definitions.',
                     'preload-editor-condition-variable-select'
                     'error'
                 );
                 );


            const conditionVariableWrap =
                 mw.notify(
                 $('<span>')
                     error.message ||
                     .addClass(
                         'Could not import variable definitions.',
                         'preload-editor-condition-variable'
                     {
                     )
                         type: 'error'
                    .append(
                     }
                         conditionVariableSelect
                );
                     );
            }
        },


            const insertCondition =
        // =========================================================
                this.createButton(
        // Preload parsing
                    'Insert',
        // =========================================================
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


             conditionTypeSelect.on(
        extractIncludeonly(source) {
                'change.preloadEditor',
             const match = String(source || '').match(
                 () =>
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
                    this.updateConditionVariableVisibility()
             );
             );


             conditionGroup.append(
             return match
                 conditionTypeSelect,
                ? match[1].trim()
                conditionVariableWrap,
                 : String(source || '').trim();
                insertCondition
        },
            );


            tools.append(
        findVariables(content) {
                wrapGroup,
            const variables = [];
                variableGroup,
             const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                conditionGroup
             );


             this.editorTools = {
             let match;
                root: tools,
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };


             this.updateEditorToolVariables();
             while ((match = pattern.exec(content)) !== null) {
            this.updateConditionVariableVisibility();
                const name = match[1].toUpperCase();
 
                if (!variables.includes(name)) {
                    variables.push(name);
                }
            }


             return tools;
             return variables;
         },
         },


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


        // Preload syntax highlighting
            while ((match = pattern.exec(content)) !== null) {
                conditions.push({
                    type: match[1].toLowerCase(),
                    expression: match[2].trim(),
                    index: match.index
                });
            }


        getKnownVariables() {
             return conditions;
             const known =
        },
                new Set(['PAGE']);


             const fields =
        findConditionVariables(content) {
                this.state.config &&
             const variables = [];
                this.state.config.fields;


             if (
             this.findConditions(content).forEach(condition => {
                fields &&
                if (
                typeof fields === 'object'
                    condition.type !== 'if' &&
            ) {
                     condition.type !== 'elseif'
                Object.keys(fields).forEach(
                 ) {
                    name => {
                    return;
                        known.add(
                }
                            String(name).toUpperCase()
                        );
                     }
                 );
            }


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


        createSyntaxDecorations(
                matches.forEach(name => {
            state,
                    name = name.toUpperCase();
            Decoration
        ) {
            const decorations = [];
            const source =
                state.doc.toString();


            const knownVariables =
                    if (!variables.includes(name)) {
                this.getKnownVariables();
                        variables.push(name);
                    }
                });
            });


             const variablePattern =
             return variables;
                /%%([A-Za-z0-9_-]+)%%/g;
        },


             let match;
        analyzePreload(content) {
             return {
                variables: this.findVariables(content),
                conditions: this.findConditions(content),
                conditionVariables:
                    this.findConditionVariables(content)
            };
        },
 
        // =========================================================
        // Config
        // =========================================================


             while (
        getAutomaticPageField() {
                 (match =
             return {
                    variablePattern.exec(source)) !==
                 label: 'Page Name',
                 null
                description: 'Name of the page.',
            ) {
                type: 'page',
                 const name =
                 required: true,
                    match[1].toUpperCase();
                namespace: 'Main',
                 'allow-new': true
            };
        },


                 const known =
        emptyConfig() {
                     knownVariables.has(name);
            return {
                 settings: {
                     incomplete: 'add-stub'
                },


                 decorations.push(
                 fields: {
                     Decoration.mark({
                     PAGE: this.getAutomaticPageField()
                        class: [
                }
                            'preload-editor-syntax-variable',
            };
                            known
        },
                                ? 'preload-editor-syntax-variable-known'
 
                                : 'preload-editor-syntax-variable-unknown'
        normalizeConfig(config) {
                        ].join(' ')
            if (
                    }).range(
                !config ||
                        match.index,
                typeof config !== 'object' ||
                        match.index +
                Array.isArray(config)
                            match[0].length
            ) {
                    )
                 config = this.emptyConfig();
                 );
             }
             }


             const conditionPattern =
             if (
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                 !config.settings ||
                typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
            ) {
                config.settings = {};
            }


             while (
             if (
                 (match =
                 !config.fields ||
                    conditionPattern.exec(source)) !==
                typeof config.fields !== 'object' ||
                 null
                 Array.isArray(config.fields)
             ) {
             ) {
                 decorations.push(
                 config.fields = {};
                    Decoration.mark({
            }
                        class:
                            'preload-editor-syntax-condition'
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


                const directiveStart =
            config.fields.PAGE =
                    match.index +
                this.getAutomaticPageField();
                    match[0].indexOf('@');


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


                 const type =
        createDefaultField(name, analysis) {
                    match[1].toLowerCase();
            return {
                label: this.humanizeName(name),
                description: '',
                 type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                    : 'text'
            };
        },


                 if (
        humanizeName(name) {
                    type !== 'if' &&
            return String(name || '')
                    type !== 'elseif'
                 .replace(/[_-]+/g, ' ')
                 ) {
                .replace(/([a-z])([A-Z])/g, '$1 $2')
                    continue;
                .replace(/\s+/g, ' ')
                }
                 .trim()
                .replace(/\b\w/g, char => char.toUpperCase());
        },


                const expression =
        prepareConfigForVariables(config, analysis) {
                    match[2];
            config = this.normalizeConfig(config);
 
            const existing = config.fields || {};


                const expressionStart =
            const deleted = new Set(
                    match.index +
                Array.isArray(this.state.deletedVariables)
                     match[0].indexOf(
                     ? this.state.deletedVariables.map(
                         expression
                         name => String(name).toUpperCase()
                     );
                    )
                     : []
            );


                const expressionPattern =
            const fields = {};
                    /[A-Za-z0-9_-]+/g;


                 let expressionMatch;
            fields.PAGE =
                 this.getAutomaticPageField();


                 while (
            analysis.variables.forEach(name => {
                     (
                 if (
                        expressionMatch =
                     name === 'PAGE' ||
                            expressionPattern.exec(
                    deleted.has(name)
                                expression
                            )
                    ) !== null
                 ) {
                 ) {
                     const name =
                     return;
                        expressionMatch[0]
                }
                            .toUpperCase();


                     if (
                fields[name] =
                         !knownVariables.has(name)
                    existing[name] ||
                     ) {
                     this.createDefaultField(
                        continue;
                         name,
                    }
                        analysis
                     );
            });


                    const start =
            Object.keys(existing).forEach(name => {
                        expressionStart +
                const upper = name.toUpperCase();
                        expressionMatch.index;


                    decorations.push(
                if (
                        Decoration.mark({
                    upper !== 'PAGE' &&
                            class:
                    !fields[upper] &&
                                'preload-editor-syntax-condition-variable'
                    !deleted.has(upper)
                        }).range(
                ) {
                            start,
                    fields[upper] =
                            start +
                         existing[name];
                                expressionMatch[0]
                                    .length
                         )
                    );
                 }
                 }
             }
             });
 
            config.fields = fields;


             return Decoration.set(
             return config;
                decorations,
                true
            );
         },
         },


         async installSyntaxHighlighting(view) {
         validateConfig(config, analysis) {
             await mw.loader.using(
             const errors = [];
                'ext.CodeMirror.v6.lib'
             const warnings = [];
             );


             const require =
             if (
                 mw.loader.require;
                !config ||
 
                typeof config !== 'object' ||
             const {
                 Array.isArray(config)
                 StateField,
             ) {
                StateEffect,
                 return {
                EditorView,
                    valid: false,
                 Decoration
                    errors: [
             } = require(
                        'Config must be an object.'
                 'ext.CodeMirror.v6.lib'
                    ],
             );
                    warnings: []
                 };
             }
 
            if (
                 !config.fields ||
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
            ) {
                return {
                    valid: false,
                    errors: [
                        '"fields" must be an object.'
                    ],
                    warnings
                };
             }


             const syntaxField =
             const configured =
                 StateField.define({
                 Object.keys(
                     create: state =>
                     config.fields
                         this.createSyntaxDecorations(
                ).map(
                            state,
                    name =>
                            Decoration
                         name.toUpperCase()
                        ),
                );


                     update: (
            analysis.variables.forEach(name => {
                         decorations,
                if (!configured.includes(name)) {
                         transaction
                     errors.push(
                    ) =>
                         'Variable "' +
                         transaction.docChanged
                         name +
                            ? this.createSyntaxDecorations(
                         '" is not configured.'
                                transaction.state,
                    );
                                Decoration
                }
                            )
            });
                            : decorations,


                    provide: field =>
            configured.forEach(name => {
                        EditorView.decorations.from(
                if (!analysis.variables.includes(name)) {
                            field
                    warnings.push(
                        )
                        'Field "' +
                });
                        name +
 
                         '" is not used by the preload.'
            view.dispatch({
                     );
                effects:
                }
                    StateEffect.appendConfig.of(
                         syntaxField
                     )
             });
             });


             this.editor.syntaxField =
             if (!configured.includes('PAGE')) {
                 syntaxField;
                errors.push(
        },
                    'PAGE must always be configured.'
                 );
            }


        // CodeMirror mounting
            Object.entries(config.fields).forEach(([name, field]) => {
 
                if (
        async mountCodeMirror(textarea) {
                    !field ||
            return new Promise(
                     typeof field !== 'object' ||
                (resolve, reject) => {
                    Array.isArray(field)
                     let settled = false;
                ) {
                    errors.push(
                        'Field "' +
                        name +
                        '" must be an object.'
                    );


                     const cleanup = () => {
                     return;
                        mw.hook(
                }
                            'dev.CCM.ready'
                        ).remove(onReady);


                        mw.hook(
                if (!field.type) {
                            'dev.CCM.load'
                    warnings.push(
                         ).remove(onLoad);
                        'Field "' +
                     };
                        name +
                        '" has no type.'
                    );
                }
               
                if (
                    field.type === 'file'
                ) {
                    if (
                         field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                     }


                     const onReady = async cm => {
                     if (
                         if (
                         Array.isArray(field.accept) &&
                            settled ||
                        field.accept.some(
                             !cm ||
                             value =>
                            cm.textarea !==
                                !String(
                                textarea ||
                                    value || ''
                            !cm.view
                                ).trim()
                         ) {
                         )
                             return;
                    ) {
                        }
                        errors.push(
                            'File field "' +
                            name +
                             '" contains an empty accepted MIME type.'
                        );
                    }


                         settled = true;
                    if (
                         cleanup();
                         field.filename !== undefined &&
 
                        typeof field.filename !== 'string'
                         const view = cm.view;
                    ) {
                         errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                         );
                    }


                         const inputHandler =
                    if (
                            () => {
                         field.filetext !== undefined &&
                                this.state
                        typeof field.filetext !== 'string'
                                    .preloadContent =
                    ) {
                                    view.state.doc.toString();
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


                                this.state.dirty =
                    if (
                                    true;
                        !field.accept ||
 
                        !field.accept.length
                                this.reanalyze();
                    ) {
                                this.renderVariablesBySelector();
                        warnings.push(
                                this.renderVariableConfigurationBySelector();
                             'File field "' +
                                this.renderAnalysisBySelector();
                            name +
                                this.renderConfigPreviewBySelector();
                             '" has no accepted MIME types.'
                                this.updateEditorTools();
                             };
 
                        view.dom.addEventListener(
                             'input',
                            inputHandler
                         );
                         );
                    }


                         view.dom.classList.add(
                    if (
                             'preload-editor-codemirror'
                         !field.filename
                    ) {
                        warnings.push(
                             'File field "' +
                            name +
                            '" has no filename template.'
                         );
                         );
                    }
                }


                         const wrapper =
                if (
                            view.dom.closest(
                    (
                                '.ext-codemirror-wrapper'
                         field.type === 'select' ||
                            );
                        field.type === 'multiselect'
                    ) &&
                    !field.source &&
                    !Array.isArray(field.options)
                ) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                    );
                }


                        if (wrapper) {
                if (field.type === 'file') {
                            wrapper.classList.add(
                    if (
                                'preload-editor-codemirror-wrapper'
                        field.filename !== undefined &&
                             );
                        typeof field.filename !== 'string'
                        }
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                             '" has an invalid "filename" value.'
                        );
                    }


                         this.editor = {
                    if (
                            cm,
                        field.filetext !== undefined &&
                             view,
                         typeof field.filetext !== 'string'
                             textarea,
                    ) {
                             inputHandler
                        errors.push(
                         };
                             'File field "' +
                             name +
                             '" has an invalid "filetext" value.'
                         );
                    }


                         this.editorView = view;
                    if (
                         field.accept !== undefined &&
                        (
                            !Array.isArray(field.accept) ||
                            field.accept.some(
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                            )
                        )
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                    }
                }
            });


                        this.state.preloadContent =
            return {
                            view.state.doc.toString();
                valid: !errors.length,
                errors,
                warnings
            };
        },


                        try {
        // =========================================================
                            await this.installSyntaxHighlighting(
        // Transformation helpers
                                view
        // =========================================================
                            );


                            resolve(view);
        transformationObject(
                        } catch (error) {
            transform,
                            reject(error);
            prefix,
                        }
            suffix,
                    };
            from,
            to
        ) {
            if (!transform) {
                return null;
            }


                    const onLoad = loader => {
            switch (transform) {
                        if (
                case 'remove-prefix':
                            settled ||
                    return prefix
                            typeof loader !==
                         ? {
                                'function'
                             transform,
                         ) {
                            prefix
                             return;
                         }
                         }
                        : null;


                        try {
                case 'remove-suffix':
                            loader(textarea);
                    return suffix
                         } catch (error) {
                         ? {
                             settled = true;
                             transform,
                            cleanup();
                             suffix
                             reject(error);
                         }
                         }
                    };
                        : null;


                     mw.hook(
                case 'replace':
                         'dev.CCM.ready'
                     return from === ''
                    ).add(onReady);
                        ? null
                         : {
                            transform,
                            from,
                            to: to || ''
                        };


                    mw.hook(
                default:
                        'dev.CCM.load'
                     return null;
                     ).add(onLoad);
            }
                }
            );
         },
         },


         // Main UI
         // =========================================================
        // UI helpers
        // =========================================================


         init() {
         createSection(title, className) {
             const root =
             const section = $('<section>')
                 $('#mw-content-text');
                 .addClass('preload-editor-section');


             if (!root.length) return;
             if (className) {
                section.addClass(className);
            }


             this.root = $('<div>')
             $('<h2>')
                 .attr(
                 .addClass('preload-editor-section-title')
                    'id',
                 .text(title)
                    'preload-editor'
                 .appendTo(section);
                 )
                 .addClass(
                    'preload-editor'
                );


             root.append(this.root);
             return section;
        },


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


        renderShell() {
            if (className) {
            this.destroyEditor();
                button.addClass(className);
             this.root.empty();
             }


             const loader =
             if (callback) {
                 this.createSection(
                 button.on(
                     'Preload'
                     'click.preloadEditor',
                    callback
                 );
                 );
            }


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


             const loadButton =
        fieldRow(label, input, description) {
                 this.createButton(
             const row = $('<div>')
                    'Load',
                 .addClass('preload-editor-field');
                    'preload-editor-button-primary',
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                );


             const newButton =
             $('<label>')
                 this.createButton(
                 .addClass('preload-editor-label')
                    'New',
                .text(label)
                    '',
                 .appendTo(row);
                    () => this.startNew()
                 );


             const sampleButton =
             if (description) {
                this.createButton(
                    'Load Sample Page',
                    '',
                    () =>
                        this.loadSamplePage()
                );
 
            loader.append(
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass('preload-editor-help')
                        'preload-editor-toolbar'
                     .text(description)
                     )
                     .appendTo(row);
                     .append(
             }
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
             );


             this.root.append(loader);
             row.append(input);


             this.status =
             return row;
                $('<div>')
        },
                    .addClass(
                        'preload-editor-status'
                    );


             this.root.append(
        textInput(value, placeholder) {
                 this.status
             return $('<input>')
            );
                .attr({
                    type: 'text',
                    value: value == null ? '' : value,
                    placeholder: placeholder || ''
                })
                 .addClass('preload-editor-input');
        },


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


             this.root.append(
        checkbox(checked) {
                 this.workspace
             return $('<input>')
            );
                .attr('type', 'checkbox')
 
                 .prop('checked', !!checked)
            this.renderWelcome();
                .addClass('preload-editor-checkbox');
         },
         },


         renderWelcome() {
         select(options, value) {
             this.workspace.empty();
             const select = $('<select>')
                .addClass('preload-editor-select');


             const section =
             options.forEach(option => {
                 this.createSection(
                 $('<option>')
                     'Get started'
                    .attr('value', option.value)
                );
                     .text(option.label)
                    .prop(
                        'selected',
                        String(option.value) ===
                        String(value === undefined ? '' : value)
                    )
                    .appendTo(select);
            });


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


            const tips =
        // =========================================================
                $('<ul>')
        // In-wiki dialogs
                    .addClass(
        // =========================================================
                        'preload-editor-tips'
                    );


             [
        createConfirmDialog(
                'Existing preload: loads the preload and its config.json if available.',
             title,
                'New preload: starts with the standard Preload Template structure.',
            message,
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
            confirmLabel,
             ].forEach(text => {
            cancelLabel
                 $('<li>')
        ) {
                     .text(text)
             return new Promise(resolve => {
                    .appendTo(tips);
                 const overlay = $('<div>')
            });
                     .addClass('preload-editor-prompt-overlay');


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


        setStatus(message, type) {
                $('<h2>')
            if (!this.status) return;
                    .text(title)
                    .appendTo(box);


            this.status.removeClass(
                 const messageLines =
                 'is-error',
                    String(message || '').split('\n');
                'is-success',
                'is-warning',
                'is-loading'
            );


            if (type) {
                messageLines.forEach(line => {
                this.status.addClass(
                    if (line === '') {
                    'is-' + type
                        $('<div>')
                );
                            .addClass(
            }
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);
 
                        return;
                    }


            this.status.text(
                    $('<p>')
                message || ''
                        .text(line)
            );
                        .appendTo(box);
        },
                });


        // Load / create
                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


        async loadExisting(title) {
                const cancel = this.createButton(
            title =
                    cancelLabel || 'Cancel',
                String(title || '').trim();
                    '',
                    () => {
                        overlay.remove();
                        resolve(false);
                    }
                );


            if (!title) {
                 const confirm = this.createButton(
                 mw.notify(
                    confirmLabel || 'Confirm',
                     'Enter a preload page title first.',
                     'preload-editor-button-primary',
                     { type: 'warn' }
                     () => {
                        overlay.remove();
                        resolve(true);
                    }
                 );
                 );


                 return;
                 buttons.append(cancel, confirm);
            }
                box.append(buttons);
                overlay.append(box);


            this.setStatus(
                $(document.body).append(overlay);
                'Loading preload...',
                'loading'
            );


            try {
                 const close = value => {
                 const page =
                     if (value === 'Escape') {
                     await this.getPage(title);
                        cancel.trigger('click');
                    }
                };


                 if (!page) {
                 overlay.on(
                     const suggestions =
                    'keydown.preloadEditor',
                         await this.findSimilarPreloads(
                    event => {
                             title
                        close(event.key);
                         );
                    }
                );
 
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');
 
                overlay.on(
                    'click.preloadEditor',
                     event => {
                         if (event.target === overlay.get(0)) {
                             cancel.trigger('click');
                         }
                    }
                );
            });
        },


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


                     this.setStatus(
                const box = $('<div>')
                         'Preload not found.',
                     .addClass(
                        'warning'
                         'preload-editor-prompt'
                     );
                     );


                     return;
                $('<h2>')
                 }
                    .text(title)
                    .appendTo(box);
 
                $('<p>')
                     .text(message)
                    .appendTo(box);
 
                 const input = this.textInput();


                 await this.loadDefinition(
                 const buttons = $('<div>')
                     page.title,
                     .addClass(
                     page.content
                        'preload-editor-prompt-buttons'
                );
                     );


                 this.setStatus(
                 const cancel = this.createButton(
                     'Preload loaded.',
                     'Cancel',
                     'success'
                     '',
                );
                    () => {
            } catch (error) {
                        overlay.remove();
                console.error(
                        resolve(null);
                    'Preload Editor:',
                     }
                     error
                 );
                 );


                 this.setStatus(
                 const confirm = this.createButton(
                     error.message ||
                     'Load',
                        'Could not load preload.',
                    'preload-editor-button-primary',
                     'error'
                     () => {
                );
                        const value =
            }
                            String(
        },
                                input.val() || ''
                            ).trim();


        async findSimilarPreloads(title) {
                        if (!value) {
            let query =
                            return;
                title
                         }
                    .replace(
                         /\/Preload$/i,
                        ''
                    )
                    .trim();


            if (!query) {
                        overlay.remove();
                query = title;
                        resolve(value);
            }
                    }
                );


            try {
                 buttons.append(cancel, confirm);
                 const results =
                    await this.searchPages(
                        query
                    );


                 return results.filter(
                 box.append(
                     result =>
                     input,
                        /\/Preload$/i.test(
                     buttons
                            result.title
                        )
                );
            } catch (error) {
                console.error(
                    'Preload Editor search:',
                     error
                 );
                 );


                 return [];
                 overlay.append(box);
            }
        },


        renderMissingPage(
                $(document.body).append(overlay);
            title,
 
            suggestions
                input.trigger('focus');
        ) {
 
            this.workspace.empty();
                input.on(
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


            const section =
                        if (event.key === 'Escape') {
                this.createSection(
                            cancel.trigger('click');
                     'Preload not found'
                        }
                     }
                 );
                 );
            });
        },


             $('<p>')
        createConfigReviewDialog() {
                .text(
             return new Promise(resolve => {
                    'No preload exists at "' +
                const overlay = $('<div>')
                     title +
                    .addClass(
                    '".'
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                )
                     );
                .appendTo(section);
 
                const box = $('<div>')
                    .addClass(
                        'preload-editor-prompt preload-editor-code-review'
                    );


            if (suggestions.length) {
                 $('<h2>')
                 $('<h3>')
                     .text('Review config.json')
                     .text('Similar preloads')
                     .appendTo(box);
                     .appendTo(section);


                 const list =
                 $('<p>')
                    $('<div>')
                    .text(
                        .addClass(
                        'This is the config.json that will be saved for the current preload.'
                            'preload-editor-suggestions'
                    )
                        );
                    .appendTo(box);


                 suggestions.forEach(
                 const code = $('<pre>')
                     result => {
                    .addClass(
                         list.append(
                        'preload-editor-config-review'
                            this.createButton(
                    )
                                result.title,
                     .text(this.getConfigJSON());
                                'preload-editor-suggestion',
 
                                () =>
                const codeWrap = $('<div>')
                                    this.loadExisting(
                    .addClass(
                                        result.title
                         'preload-editor-config-review-wrap'
                                    )
                    )
                            )
                    .append(code);
                         );
 
                box.append(codeWrap);
 
                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );
 
                const close = this.createButton(
                    'Close',
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                         resolve();
                     }
                     }
                 );
                 );


                 section.append(list);
                 buttons.append(close);
            }
                box.append(buttons);
                overlay.append(box);


            section.append(
                $(document.body).append(overlay);
                this.createButton(
                    'Create this preload',
                    'preload-editor-button-primary',
                    () =>
                        this.startNew(title)
                )
            );


            this.workspace.append(section);
                overlay.attr('tabindex', '-1');
        },
                overlay.trigger('focus');


        async startNew(title) {
                overlay.on(
            title =
                    'keydown.preloadEditor',
                String(title || '').trim();
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                );


            this.state = {
                overlay.on(
                 preloadTitle: title,
                    'click.preloadEditor',
                preloadSource: '',
                    event => {
                 preloadContent:
                        if (event.target === overlay.get(0)) {
                    this.defaults.preload,
                            close.trigger('click');
                 config:
                        }
                    this.emptyConfig(),
                    }
                 variables: ['PAGE'],
                 );
                 conditions: [],
            });
                selectedVariable: 'PAGE',
        },
                 mode: 'new',
 
                dirty: true
        async confirmSave(mode, title) {
             };
            const configTitle =
                 title.replace(/\/+$/, '') +
                 '/config.json';
 
            let saveDescription;
 
            if (mode === 'preload') {
                 saveDescription =
                    'Save the preload page only?';
            } else if (mode === 'config') {
                 saveDescription =
                    'Save the config.json page only?';
            } else {
                 saveDescription =
                    'Save both the preload and config.json?';
            }
 
             const pages = [];


             this.renderEditor();
             if (mode === 'preload' || mode === 'both') {
                pages.push(
                    'Preload: ' +
                    title
                );
            }


             this.setStatus(
             if (mode === 'config' || mode === 'both') {
                 'Creating a new preload.',
                 pages.push(
                'success'
                    'Config: ' +
            );
                    configTitle
        },
                );


        async loadSamplePage() {
                 pages.push(
            const result =
                     'Config content model: JSON'
                 await this.createPromptDialog(
                     'Load Sample Page',
                    'Enter the title of a normal wiki page to use as the starting point.'
                 );
                 );
            }


             if (!result) return;
             const message =
                saveDescription +
                '\n\n' +
                pages.join('\n') +
                '\n\nThis will write the changes to the wiki.';


             this.setStatus(
             return this.createConfirmDialog(
                 'Loading sample page...',
                 'Confirm save',
                 'loading'
                message,
                'Save',
                 'Cancel'
             );
             );
        },


             try {
        // =========================================================
                 const page =
        // CodeMirror
                    await this.getPage(result);
        // =========================================================
                destroyEditor() {
             if (!this.editor) {
                 this.editorView = null;
                this.editorTools = null;
                return;
            }
 
            const {
                view,
                inputHandler
            } = this.editor;


                if (!page) {
            if (view && inputHandler) {
                    throw new Error(
                view.dom.removeEventListener(
                        'Sample page not found: ' +
                    'input',
                        result
                    inputHandler
                    );
                );
                }
            }


                 const sample =
            if (view) {
                    this.convertSampleToPreload(
                 view.destroy();
                        page.content
            }
                    );


                this.state = {
            this.editor = null;
                    preloadTitle: '',
            this.editorView = null;
                    preloadSource: '',
            this.editorTools = null;
                    preloadContent: sample,
        },
                    config:
                        this.emptyConfig(),
                    variables: ['PAGE'],
                    conditions: [],
                    selectedVariable: 'PAGE',
                    mode: 'new',
                    dirty: true
                };


                this.reanalyze();
        getEditorView() {
                this.renderEditor();
            return this.editorView;
        },


                 this.setStatus(
        getEditorContent() {
                    'Sample page loaded.',
            if (
                    'success'
                 this.editorView &&
                );
                this.editorView.state
             } catch (error) {
             ) {
                 console.error(
                 return this.editorView.state.doc.toString();
                    'Preload Editor sample:',
            }
                    error
                );


                this.setStatus(
            return this.state.preloadContent || '';
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
         },
         },


         convertSampleToPreload(source) {
         setEditorContent(content) {
             let content =
             content = String(content || '');
                String(source || '').trim();


             const include =
            if (!this.editorView) {
                 content.match(
                this.state.preloadContent = content;
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                return;
                );
            }
 
             const current =
                 this.editorView.state.doc.toString();


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


             content =
             this.editorView.dispatch({
                 content
                 changes: {
                     .replace(
                     from: 0,
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                     to: this.editorView.state.doc.length,
                        ''
                     insert: content
                     )
                 }
                     .trim();
             });
 
            return (
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                 '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
             );
         },
         },


         createPromptDialog(
         getEditorSelection() {
            title,
             if (
            message
                 !this.editorView ||
        ) {
                !this.editorView.state
             return new Promise(
            ) {
                 resolve => {
                return null;
                    const overlay =
            }
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                    const box =
            const selection =
                        $('<div>')
                this.editorView.state.selection.main;
                            .addClass(
                                'preload-editor-prompt'
                            );


                    $('<h2>')
            return {
                        .text(title)
                from: selection.from,
                        .appendTo(box);
                to: selection.to,
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
            };
        },


                    $('<p>')
        focusEditor() {
                        .text(message)
            if (this.editorView) {
                        .appendTo(box);
                this.editorView.focus();
            }
        },


                    const input =
        insertEditorText(
                        this.textInput();
            text,
            selectionFrom,
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }


                    const buttons =
            const view = this.editorView;
                        $('<div>')
            const selection = view.state.selection.main;
                            .addClass(
                                'preload-editor-prompt-buttons'
                            );


                    const cancel =
            const from =
                        this.createButton(
                selectionFrom === undefined
                            'Cancel',
                    ? selection.from
                            '',
                    : selectionFrom;
                            () => {
                                overlay.remove();
                                resolve(null);
                            }
                        );


                    const confirm =
            const to =
                        this.createButton(
                selectionTo === undefined
                            'Load',
                    ? selection.to
                            'preload-editor-button-primary',
                    : selectionTo;
                            () => {
                                const value =
                                    String(
                                        input.val() ||
                                        ''
                                    ).trim();


                                if (!value) return;
            const cursor =
                cursorPosition === undefined
                    ? from + text.length
                    : cursorPosition;


                                overlay.remove();
            view.dispatch({
                                resolve(value);
                changes: {
                            }
                    from,
                        );
                    to,
                    insert: text
                },
                selection: {
                    anchor: cursor
                }
            });


                    buttons.append(
            view.focus();
                        cancel,
        },
                        confirm
                    );


                    box.append(
        // =========================================================
                        input,
        // Editor tools
                        buttons
        // =========================================================
                    );


                    overlay.append(box);
        wrapSelectionWithVariable() {
                    $(document.body)
            const selected =
                        .append(overlay);
                this.getEditorSelection();


                    input.trigger('focus');
            if (
                !selected ||
                selected.from === selected.to
            ) {
                this.focusEditor();
                return;
            }


                    input.on(
            const replacement =
                        'keydown.preloadEditor',
                '%%' +
                        event => {
                selected.text +
                            if (
                '%%';
                                event.key ===
                                'Enter'
                            ) {
                                confirm.trigger(
                                    'click'
                                );
                            }


                            if (
            this.insertEditorText(
                                event.key ===
                replacement,
                                'Escape'
                selected.from,
                            ) {
                selected.to,
                                cancel.trigger(
                 selected.from + replacement.length
                                    'click'
                                );
                            }
                        }
                    );
                 }
             );
             );
         },
         },


         async loadDefinition(
         insertVariable(name) {
            title,
             name = String(name || '')
            source
                 .trim()
        ) {
                 .toUpperCase();
             const content =
                 this.extractIncludeonly(
                    source
                 );


             let config =
             if (!name) {
                 this.emptyConfig();
                 return;
            }


             const configTitle =
             const selected =
                 title.replace(/\/+$/, '') +
                 this.getEditorSelection();
                '/config.json';


             const configPage =
             if (!selected) {
                await this.getPage(
                 return;
                    configTitle
            }
                 );


             if (configPage) {
             this.insertEditorText(
                 try {
                 '%%' + name + '%%',
                    config =
                selected.from,
                        JSON.parse(
                selected.to
                            configPage.content
            );
                        );
        },
                } catch (error) {
 
                    throw new Error(
        insertCondition(
                        'The existing config.json contains invalid JSON: ' +
            type,
                        error.message
            variable
                    );
        ) {
                 }
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();
 
            const selected =
                 this.getEditorSelection();
 
            if (!selected) {
                return;
             }
             }


             const analysis =
             let text;
                this.analyzePreload(
            let cursorOffset;
                    content
                );


             config =
             switch (type) {
                 this.prepareConfigForVariables(
                 case 'if': {
                    config,
                    if (!variable) {
                     analysis
                        return;
                );
                     }


            this.state = {
                    const opening =
                preloadTitle: title,
                         '<!-- @if ' +
                preloadSource: source,
                         variable +
                preloadContent: source,
                         ' -->';
                config,
                variables:
                    analysis.variables,
                conditions:
                    analysis.conditions,
                selectedVariable:
                    analysis.variables.includes('PAGE')
                         ? 'PAGE'
                         : (
                            analysis.variables[0] ||
                            'PAGE'
                         ),
                mode: 'edit',
                dirty: false
            };


            this.renderEditor();
                    const closing =
        },
                        '<!-- @endif -->';


        // Editor
                    if (
                        selected.from !==
                        selected.to
                    ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


        renderEditor() {
                        cursorOffset = text.length;
            this.destroyEditor();
                    } else {
            this.workspace.empty();
                        text =
                            opening +
                            '\n\n' +
                            closing;
 
                        cursorOffset =
                            opening.length + 1;
                    }


            const layout =
                    break;
                 $('<div>')
                 }
                    .addClass(
                        'preload-editor-layout'
                    );


            const left =
                 case 'elseif':
                 $('<div>')
                     text =
                     .addClass(
                         '<!-- @elseif -->';
                         'preload-editor-left'
                    );


            const right =
                    cursorOffset =
                $('<div>')
                        text.length;
                    .addClass(
                        'preload-editor-right'
                    );


            const editorSection =
                     break;
                this.createSection(
                     'Preload',
                    'preload-editor-main-section'
                );


            const meta =
                 case 'else':
                 $('<div>')
                     text =
                     .addClass(
                         '<!-- @else -->';
                         'preload-editor-meta'
                    );


            $('<strong>')
                    cursorOffset =
                .text(
                        text.length;
                    this.state.preloadTitle ||
                    'New preload'
                )
                .appendTo(meta);


            if (
                     break;
                this.state.mode ===
                'new'
            ) {
                $('<span>')
                     .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
            }


            editorSection.append(meta);
                case 'endif':
                    text =
                        '<!-- @endif -->';


            editorSection.append(
                    cursorOffset =
                this.renderEditorTools()
                        text.length;
            );


            const textarea =
                     break;
                this.textarea(
                     this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


            const editorMount =
                 default:
                 $('<div>')
                     return;
                     .addClass(
            }
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);


             editorSection.append(
             this.insertEditorText(
                 editorMount
                 text,
                selected.from,
                selected.to,
                selected.from + cursorOffset
             );
             );
        },


             left.append(editorSection);
        getToolVariables() {
             const variables =
                new Set(['PAGE']);


             /*
             if (
            * RIGHT PANEL
                this.analysis &&
            *
                this.analysis.variables
            * Analysis is intentionally first.
            ) {
            * Variables are now only a live list.
                this.analysis.variables.forEach(
            * One configuration is displayed at a time.
                    name => {
            */
                        variables.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }


             const analysisSection =
             return Array.from(variables);
                this.createSection(
        },
                    'Analysis'
                );


             const analysisContainer =
        createToolSelect(
                 $('<div>')
            options,
            className
        ) {
             const select =
                 $('<select>')
                     .addClass(
                     .addClass(
                         'preload-editor-analysis'
                         'preload-editor-tool-select'
                     );
                     );


             analysisSection.append(
             if (className) {
                 analysisContainer
                select.addClass(className);
            }
 
            options.forEach(
                option => {
                    $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                 }
             );
             );


             const variablesSection =
             return select;
                this.createSection(
        },
                    'Variables'
                );


            const variableContainer =
        updateEditorToolVariables() {
                $('<div>')
            if (!this.editorTools) {
                    .addClass(
                return;
                        'preload-editor-variables'
            }
                    );


             variablesSection.append(
             const variables =
                variableContainer
                this.getToolVariables();
            );


             const configurationSection =
             const current =
                 this.createSection(
                 this.editorTools
                     'Variable configuration'
                     .variableSelect
                );
                    .val();


             const configurationContainer =
             const currentCondition =
                 $('<div>')
                 this.editorTools
                     .addClass(
                     .conditionVariableSelect
                        'preload-editor-variable-configuration'
                     .val();
                     );


             configurationSection.append(
             const populate = (
                 configurationContainer
                 select,
             );
                value
             ) => {
                select.empty();


            const configSection =
                variables.forEach(
                this.createSection(
                    name => {
                    'Generated configuration'
                        $('<option>')
                            .attr(
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                 );
                 );


            const configPreview =
                if (
                 $('<pre>')
                    value &&
                     .addClass(
                    variables.includes(value)
                         'preload-editor-config-preview'
                ) {
                    select.val(value);
                 } else if (
                    variables.length
                ) {
                     select.val(
                         variables[0]
                     );
                     );
                }
            };
            populate(
                this.editorTools.variableSelect,
                current
            );


             configSection.append(
             populate(
                 configPreview
                this.editorTools.conditionVariableSelect,
                 currentCondition
             );
             );
        },
        updateConditionVariableVisibility() {
            if (!this.editorTools) {
                return;
            }


             const actions =
             const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();
 
            this.editorTools
                .conditionVariableWrap
                .toggle(
                    type === 'if'
                );
        },
 
        renderEditorTools() {
            const tools =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-actions'
                         'preload-editor-tools'
                     );
                     );


             actions.append(
             const wrapGroup =
                 this.createButton(
                 $('<div>')
                    'Save Preload + Config',
                     .addClass(
                     'preload-editor-button-primary',
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                     () => this.saveAll()
                     );
                ),
 
            wrapGroup.append(
                 this.createButton(
                 this.createButton(
                     'Save Preload Only',
                     'Wrap selection',
                     '',
                     'preload-editor-tool-button',
                     () => this.savePreloadOnly()
                     () =>
                        this.wrapSelectionWithVariable()
                 )
                 )
             );
             );


             right.append(
             const variableGroup =
                 analysisSection,
                 $('<div>')
                variablesSection,
                    .addClass(
                configurationSection,
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                configSection,
                    );
                actions
            );


             layout.append(
             $('<span>')
                 left,
                .addClass(
                 right
                    'preload-editor-tool-label'
            );
                )
                 .text(
                    'Insert existing variable'
                 )
                .appendTo(variableGroup);


             this.workspace.append(
             const variableSelect =
                 layout
                this.createToolSelect(
            );
                    [],
                    'preload-editor-variable-select'
                 );


             this.reanalyze();
             variableGroup.append(
                variableSelect,


            this.renderVariables(
                this.createButton(
                 variableContainer
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                 )
             );
             );


             this.renderAnalysis(
             const conditionGroup =
                analysisContainer
                $('<div>')
            );
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


             this.renderVariableConfiguration(
             $('<span>')
                 configurationContainer
                .addClass(
            );
                    'preload-editor-tool-label'
                 )
                .text('Insert condition')
                .appendTo(conditionGroup);


             this.renderConfigPreview(
             const conditionTypeSelect =
                configPreview
                this.createToolSelect(
            );
                    [
 
                        {
            this.updateEditorTools();
                            value: 'if',
 
                            label: '@if'
            this.mountCodeMirror(
                        },
                textarea.get(0)
                        {
            ).catch(error => {
                            value: 'elseif',
                console.error(
                            label: '@elseif'
                    'Preload Editor CodeMirror:',
                        },
                    error
                        {
                );
                            value: 'else',
 
                            label: '@else'
                this.setStatus(
                        },
                     error.message ||
                        {
                        'Could not initialize CodeMirror.',
                            value: 'endif',
                     'error'
                            label: '@endif'
                        }
                     ],
                     'preload-editor-condition-type-select'
                 );
                 );
            });
        },


        reanalyze() {
             const conditionVariableSelect =
             const source =
                 this.createToolSelect(
                 this.getEditorContent();
                    [],
 
                     'preload-editor-condition-variable-select'
            const content =
                this.extractIncludeonly(
                     source
                 );
                 );


             const analysis =
             const conditionVariableWrap =
                 this.analyzePreload(
                 $('<span>')
                     content
                    .addClass(
                );
                        'preload-editor-condition-variable'
                     )
                    .append(
                        conditionVariableSelect
                    );


             this.state.preloadContent =
             const insertCondition =
                 source;
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                 );


             this.state.variables =
             conditionTypeSelect.on(
                analysis.variables;
                'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
            );


             this.state.conditions =
             conditionGroup.append(
                 analysis.conditions;
                conditionTypeSelect,
                conditionVariableWrap,
                 insertCondition
            );


             this.state.config =
             tools.append(
                 this.prepareConfigForVariables(
                 wrapGroup,
                    this.state.config ||
                variableGroup,
                        this.emptyConfig(),
                conditionGroup
                    analysis
            );
                );


             this.analysis =
             this.editorTools = {
                 analysis;
                 root: tools,
 
                variableSelect,
            /*
                conditionTypeSelect,
            * PAGE is always available.
                conditionVariableSelect,
            * If the selected variable disappears,
                conditionVariableWrap,
            * move the focus to PAGE or the first
                insertCondition
            * currently-used variable.
            };
            */
 
             const available =
             this.updateEditorToolVariables();
                ['PAGE'].concat(
            this.updateConditionVariableVisibility();
                    analysis.variables.filter(
                        name => name !== 'PAGE'
                    )
                );


             if (
             return tools;
                !available.includes(
                    this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] || 'PAGE';
            }
         },
         },


         renderAnalysis(container) {
         updateEditorTools() {
             container.empty();
             this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
        },


            const analysis =
        // =========================================================
                this.analysis ||
        // Syntax highlighting
                this.analyzePreload(
        // =========================================================
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


             const variableCount =
        getKnownVariables() {
                 analysis.variables.length;
             const known =
                 new Set(['PAGE']);


             const conditionCount =
             const fields =
                 analysis.conditions.length;
                 this.state.config &&
                this.state.config.fields;


             const configuredCount =
             if (
                 Object.keys(
                fields &&
                    this.state.config &&
                typeof fields === 'object'
                     this.state.config.fields
            ) {
                         ? this.state.config.fields
                 Object.keys(fields).forEach(
                         : {}
                     name => {
                 ).length;
                         known.add(
                            String(name).toUpperCase()
                         );
                    }
                 );
            }


             const summary =
             return known;
                $('<div>')
        },
                    .addClass(
                        'preload-editor-analysis-summary'
                    );


             const createMetric =
        createSyntaxDecorations(
                (value, label) =>
             state,
                    $('<div>')
            Decoration
                        .addClass(
        ) {
                            'preload-editor-analysis-metric'
            const decorations = [];
                        )
            const source =
                        .append(
                state.doc.toString();
                            $('<strong>')
 
                                .addClass(
            const knownVariables =
                                    'preload-editor-analysis-value'
                this.getKnownVariables();
                                )
                                .text(value),
                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                        );


             summary.append(
             const variablePattern =
                createMetric(
                 /%%([A-Za-z0-9_-]+)%%/g;
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                 ),
                createMetric(
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),
                createMetric(
                    configuredCount,
                    configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                )
            );


             container.append(
             let match;
                summary
            );


             if (
             while (
                 analysis.conditionVariables.length
                 (
                    match =
                        variablePattern.exec(source)
                ) !== null
             ) {
             ) {
                 container.append(
                 const name =
                     $('<div>')
                    match[1].toUpperCase();
                        .addClass(
 
                             'preload-editor-analysis-note'
                const known =
                        )
                     knownVariables.has(name);
                         .text(
 
                            'Condition variables: ' +
                decorations.push(
                            analysis.conditionVariables.join(
                    Decoration.mark({
                                ', '
                        class: [
                             )
                             'preload-editor-syntax-variable',
                        )
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                         ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                             match[0].length
                    )
                 );
                 );
             }
             }


             const validation =
             const conditionPattern =
                 this.validateConfig(
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    this.state.config,
                    analysis
                );


             if (
             while (
                 validation.errors.length
                 (
                    match =
                        conditionPattern.exec(source)
                ) !== null
             ) {
             ) {
                 const errors =
                 decorations.push(
                     $('<ul>')
                     Decoration.mark({
                         .addClass(
                         class:
                             'preload-editor-validation-errors'
                             'preload-editor-syntax-condition'
                         );
                    }).range(
                        match.index,
                         match.index +
                            match[0].length
                    )
                );


                 validation.errors.forEach(
                 const directiveStart =
                     error => {
                    match.index +
                        $('<li>')
                     match[0].indexOf('@');
                            .text(error)
                            .appendTo(errors);
                    }
                );


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


            if (
                 const type =
                validation.warnings.length
                     match[1].toLowerCase();
            ) {
                 const warnings =
                     $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );


                 validation.warnings.forEach(
                 if (
                     warning => {
                     type !== 'if' &&
                        $('<li>')
                    type !== 'elseif'
                            .text(warning)
                ) {
                            .appendTo(warnings);
                    continue;
                    }
                }
                 );
 
                 const expression =
                    match[2];


                 container.append(
                 const expressionStart =
                     warnings
                    match.index +
                );
                    match[0].indexOf(
            }
                        expression
                     );


            if (
                 const expressionPattern =
                 !validation.errors.length &&
                     /[A-Za-z0-9_-]+/g;
                !validation.warnings.length
            ) {
                container.append(
                     $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },


        renderAnalysisBySelector() {
                let expressionMatch;
            const container =
 
                this.root &&
                while (
                this.root.find(
                    (
                    '.preload-editor-analysis'
                        expressionMatch =
                );
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


            if (
                    if (
                container &&
                        !knownVariables.has(name)
                container.length
                    ) {
            ) {
                        continue;
                this.renderAnalysis(
                     }
                     container
                );
            }
        },


        /*
                    const start =
        * Variable list
                        expressionStart +
        *
                        expressionMatch.index;
        * This replaces the old behaviour where every
        * variable rendered its entire configuration card.
        */
        renderVariables(container) {
            container.empty();


            const analysis =
                     decorations.push(
                this.analysis ||
                         Decoration.mark({
                this.analyzePreload(
                            class:
                     this.extractIncludeonly(
                                'preload-editor-syntax-condition-variable'
                         this.getEditorContent()
                        }).range(
                    )
                            start,
                );
                            start +
 
                                expressionMatch[0].length
            const variables =
                        )
                analysis.variables.slice();
                     );
 
            const ordered = ['PAGE'];
 
            variables.forEach(name => {
                if (
                    name !== 'PAGE' &&
                    !ordered.includes(name)
                ) {
                     ordered.push(name);
                 }
                 }
             });
             }


             const list =
             return Decoration.set(
                 $('<div>')
                 decorations,
                    .addClass(
                true
                        'preload-editor-variable-list'
            );
                    );
        },


             ordered.forEach(name => {
        async installSyntaxHighlighting(view) {
                 const isSelected =
             await mw.loader.using(
                    name ===
                 'ext.CodeMirror.v6.lib'
                    this.state.selectedVariable;
            );


                const isUsed =
            const require =
                    analysis.variables.includes(
                mw.loader.require;
                        name
                    );


                const item =
            const {
                    $('<button>')
                StateField,
                        .attr({
                StateEffect,
                            type: 'button',
                EditorView,
                            'data-variable': name
                Decoration
                        })
            } = require(
                        .addClass(
                'ext.CodeMirror.v6.lib'
                            'preload-editor-variable-item'
            );
                        )
                        .toggleClass(
                            'is-selected',
                            isSelected
                        )
                        .on(
                            'click.preloadEditor',
                            () =>
                                this.selectVariable(
                                    name
                                )
                        );


                const nameLabel =
            const syntaxField =
                     $('<span>')
                StateField.define({
                         .addClass(
                     create: state =>
                             'preload-editor-variable-name'
                         this.createSyntaxDecorations(
                        )
                             state,
                         .text(name);
                            Decoration
                         ),


                item.append(
                    update: (
                    nameLabel
                        decorations,
                );
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                if (name === 'PAGE') {
                    provide: field =>
                    item.append(
                        EditorView.decorations.from(
                        $('<span>')
                             field
                            .addClass(
                        )
                                'preload-editor-badge'
                 });
                             )
                            .text('AUTOMATIC')
                    );
                 } else if (!isUsed) {
                    item.append(
                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text('UNUSED')
                    );
                }


                 list.append(item);
            view.dispatch({
                 effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
             });
             });


             container.append(list);
             this.editor.syntaxField =
 
                 syntaxField;
            if (!ordered.length) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                 );
            }
         },
         },


         renderVariablesBySelector() {
         async mountCodeMirror(textarea) {
             const container =
             return new Promise(
                 this.root &&
                 (
                this.root.find(
                    resolve,
                     '.preload-editor-variables'
                     reject
                 );
                 ) => {
                    let settled = false;


            if (
                    const cleanup = () => {
                container &&
                        mw.hook(
                container.length
                            'dev.CCM.ready'
            ) {
                        ).remove(onReady);
                this.renderVariables(
 
                    container
                        mw.hook(
                );
                            'dev.CCM.load'
            }
                        ).remove(onLoad);
        },
                    };


        /*
                    const onReady =
        * Select a variable from the list and display
                        async cm => {
        * only its configuration.
                            if (
        */
                                settled ||
        selectVariable(name) {
                                !cm ||
            name =
                                cm.textarea !== textarea ||
                String(name || '')
                                !cm.view
                    .trim()
                            ) {
                    .toUpperCase();
                                return;
                            }


            if (!name) return;
                            settled = true;
                            cleanup();


            const available =
                            const view =
                ['PAGE'].concat(
                                cm.view;
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );


            if (!available.includes(name)) {
                            const inputHandler =
                return;
                                () => {
            }
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();


            this.state.selectedVariable =
                                    this.markPreloadDirty();
                name;


            this.renderVariablesBySelector();
                                    this.reanalyze();
            this.renderVariableConfigurationBySelector();


            const configuration =
                                    this.renderVariablesBySelector();
                this.root &&
                                    this.renderVariableConfigurationBySelector();
                this.root.find(
                                    this.renderAnalysisBySelector();
                    '.preload-editor-variable-configuration'
                                    this.updateEditorTools();
                );
 
                                    this.saveDraft();
                                };


            if (
                            view.dom.addEventListener(
                configuration &&
                                'input',
                configuration.length
                                inputHandler
            ) {
                            );
                const element =
                    configuration.get(0);


                if (element) {
                            view.dom.classList.add(
                    element.scrollIntoView({
                                'preload-editor-codemirror'
                        behavior: 'smooth',
                            );
                        block: 'nearest'
                    });
                }
            }
        },


        renderVariableConfigurationBySelector() {
                            const wrapper =
            const container =
                                view.dom.closest(
                this.root &&
                                    '.ext-codemirror-wrapper'
                this.root.find(
                                );
                    '.preload-editor-variable-configuration'
                );


            if (
                            if (wrapper) {
                container &&
                                wrapper.classList.add(
                container.length
                                    'preload-editor-codemirror-wrapper'
            ) {
                                );
                this.renderVariableConfiguration(
                            }
                    container
                );
            }
        },


        renderVariableConfiguration(container) {
                            this.editor = {
            container.empty();
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


            const analysis =
                            this.editorView =
                this.analysis ||
                                view;
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


            const name =
                            this.state.preloadContent =
                this.state.selectedVariable ||
                                view.state.doc.toString();
                'PAGE';


            const fields =
                            try {
                this.state.config &&
                                await this.installSyntaxHighlighting(
                this.state.config.fields
                                    view
                    ? this.state.config.fields
                                );
                    : {};


            const field =
                                if (
                fields[name] ||
                                    this.state.dirty
                this.createDefaultField(
                                ) {
                    name,
                                    this.saveDraft();
                    analysis
                                }
                );


            if (name === 'PAGE') {
                                resolve(view);
                container.append(
                            } catch (error) {
                    this.createAutomaticPageCard(
                                reject(error);
                         field
                            }
                    )
                         };
                );


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


            container.append(
                            try {
                this.createVariableCard(
                                loader(textarea);
                    name,
                            } catch (error) {
                    field,
                                settled = true;
                    analysis
                                cleanup();
                )
                                reject(error);
            );
                            }
        },
                        };


        /*
                    mw.hook(
        * PAGE is precompiled/automatic.
                        'dev.CCM.ready'
        *
                    ).add(onReady);
        * It remains selectable so the user can inspect
 
        * what PAGE represents, but its configuration
                    mw.hook(
        * cannot be edited.
                        'dev.CCM.load'
        */
                    ).add(onLoad);
         createAutomaticPageCard(field) {
                }
             const card =
            );
        },
 
        // =========================================================
        // Main UI
        // =========================================================
 
         init() {
             const root =
                $('#mw-content-text');
 
            if (!root.length) {
                return;
            }
 
            this.root =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .attr(
                         'preload-editor-variable preload-editor-variable-automatic'
                        'id',
                         'preload-editor'
                     )
                     )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );
            const header =
                $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor'
                     );
                     );


             header.append(
             root.append(this.root);
                $('<h3>').text('PAGE'),
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
            );


             card.append(header);
             this.renderShell();
 
            this.restoreDraft();
 
            window.addEventListener(
                'beforeunload',
                () => {
                    if (this.state.dirty) {
                        this.saveDraft();
                    }
                }
            );
        },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


             $('<p>')
             const loader =
                 .addClass(
                 this.createSection('Preload');
                    '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 =
             const titleInput =
                 this.textInput(
                 this.textInput(
                     field.label || 'Page Name'
                     this.state.preloadTitle,
                 ).prop(
                    'Template:Example/Preload'
                     'disabled',
                 ).attr(
                     true
                     'id',
                     'preload-editor-title-input'
                 );
                 );


             const description =
             titleInput.on(
                this.textarea(
                'input.preloadEditor',
                    field.description || 'Name of the page.'
                () => {
                )
                    this.state.preloadTitle =
                     .addClass(
                        String(
                         'preload-editor-small-textarea'
                            titleInput.val() || ''
                     )
                        ).trim();
                    .prop(
 
                        'disabled',
                     if (
                        true
                        this.state.dirty &&
                    );
                         this.state.mode === 'new'
                     ) {
                        this.saveDraft();
                    }
                }
            );


             const type =
             const loadButton =
                 this.textInput(
                 this.createButton(
                     field.type || 'page'
                     'Load',
                ).prop(
                     'preload-editor-button-primary',
                     'disabled',
                     () =>
                     true
                        this.loadExisting(
                            titleInput.val()
                        )
                 );
                 );


             const required =
             const newButton =
                 this.checkbox(
                 this.createButton(
                     field.required !== false
                     'New',
                ).prop(
                     '',
                     'disabled',
                     () => this.startNew()
                     true
                 );
                 );


             const namespace =
             const sampleButton =
                 this.textInput(
                 this.createButton(
                     field.namespace || 'Main'
                     'Load Sample Page',
                ).prop(
                     '',
                     'disabled',
                     () => this.loadSamplePage()
                     true
                 );
                 );


             const allowNew =
             loader.append(
                 this.checkbox(
                 $('<div>')
                    field['allow-new'] === true
                    .addClass(
                 ).prop(
                        'preload-editor-toolbar'
                    'disabled',
                    )
                     true
                    .append(
                 );
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );
 
            this.root.append(loader);
 
            this.workspace =
                 $('<div>')
                    .addClass(
                        'preload-editor-workspace'
                     );
 
            this.root.append(
                 this.workspace
            );


             card.append(
             /*
                this.fieldRow(
            * Fixed footer
                    'Label',
            *
                    label
            * Local draft status, normal status messages,
                ),
            * and save actions live here.
                this.fieldRow(
            */
                    'Description',
            const footer =
                    description
                 $('<div>')
                ),
                     .addClass(
                this.fieldRow(
                        'preload-editor-footer'
                    'Type',
                     );
                    type
                ),
                 this.fieldRow(
                    'Required',
                    required
                ),
                this.fieldRow(
                    'Namespace',
                     namespace
                ),
                this.fieldRow(
                    'Allow new page',
                     allowNew
                )
            );
 
            return card;
        },


        createVariableCard(
             this.localDraftStatus =
             name,
            field,
            analysis
        ) {
            const card =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable'
                         'preload-editor-local-draft-status is-empty'
                     )
                     )
                     .attr(
                     .text(
                         'data-variable',
                         'No local draft'
                        name
                     );
                     );


             const header =
             this.status =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor-status'
                     );
                     );


             header.append(
             footer.append(
                 $('<h3>').text(name)
                 this.localDraftStatus,
                this.status
             );
             );


             if (name === 'PAGE') {
             this.root.append(
                header.append(
                 footer
                    $('<span>')
             );
                        .addClass(
                            'preload-editor-badge'
                        )
                        .text('AUTOMATIC')
                 );
            } else if (
                !analysis.variables.includes(name)
             ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }


             card.append(header);
             this.updateLocalDraftIndicator();


             const label =
             this.renderWelcome();
                this.textInput(
        },
                    field.label || ''
                );


            label.on(
        renderWelcome() {
                'input.preloadEditor',
            this.workspace.empty();
                () => {
                    field.label =
                        label.val();


                    this.markDirty();
            const section =
                    this.renderConfigPreviewBySelector();
                this.createSection('Get started');
                }
            );


             card.append(
             $('<p>')
                 this.fieldRow(
                 .text(
                     'Label',
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                    label
                 )
                 )
            );
                .appendTo(section);


             const description =
             const tips =
                 this.textarea(
                 $('<ul>')
                    field.description || ''
                    .addClass(
                ).addClass(
                        'preload-editor-tips'
                    'preload-editor-small-textarea'
                    );
                );


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


             card.append(
             section.append(tips);
                 this.fieldRow(
            this.workspace.append(section);
                    'Description',
        },
                    description
 
                 )
        setStatus(
            message,
            type
        ) {
            if (!this.status) {
                 return;
            }
 
            this.status.removeClass(
                'is-error',
                'is-success',
                'is-warning',
                 'is-loading'
             );
             );


             const types = [
             if (type) {
                ['text', 'Text'],
                 this.status.addClass(
                ['textarea', 'Textarea'],
                     'is-' + type
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                [
                    'multiselect',
                    'Multi-select'
                ],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date']
            ];
 
            const typeSelect =
                 this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                     field.type || 'text'
                 );
                 );
            }


             typeSelect.on(
             this.status.text(
                 'change.preloadEditor',
                 message || ''
                () => {
            );
                    field.type =
        },
                        typeSelect.val();


                    this.markDirty();
        // =========================================================
        // Load / create
        // =========================================================


                    this.renderVariableConfigurationBySelector();
        async loadExisting(title) {
                    this.renderConfigPreviewBySelector();
            title =
                }
                String(title || '').trim();
            );


             card.append(
             if (!title) {
                 this.fieldRow(
                 mw.notify(
                     'Type',
                     'Enter a preload page title first.',
                     typeSelect
                     {
                )
                        type: 'warn'
            );
                     }
 
            const required =
                this.checkbox(
                     field.required === true
                 );
                 );


            required.on(
                 return;
                 'change.preloadEditor',
            }
                () => {
                    field.required =
                        required.prop(
                            'checked'
                        );


                    this.markDirty();
            this.setStatus(
                    this.renderConfigPreviewBySelector();
                'Loading preload...',
                 }
                 'loading'
             );
             );


             card.append(
             try {
                 this.fieldRow(
                const page =
                     'Required',
                    await this.getPage(title);
                    required
 
                )
                 if (!page) {
            );
                     const suggestions =
                        await this.findSimilarPreloads(
                            title
                        );


            const placeholder =
                    this.renderMissingPage(
                this.textInput(
                        title,
                     field.placeholder || ''
                        suggestions
                );
                     );


            placeholder.on(
                    this.setStatus(
                'input.preloadEditor',
                        'Preload not found.',
                () => {
                        'warning'
                     const value =
                     );
                        placeholder.val();


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


            card.append(
                 await this.loadDefinition(
                 this.fieldRow(
                     page.title,
                     'Placeholder',
                     page.content
                     placeholder
                )
            );
 
            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                 );
                 );


            defaultInput.on(
                this.setStatus(
                'input.preloadEditor',
                    'Preload loaded.',
                 () => {
                    'success'
                     const value =
                 );
                        defaultInput.val();
            } catch (error) {
                console.error(
                     'Preload Editor:',
                    error
                );


                     if (value) {
                this.setStatus(
                         field.default =
                     error.message ||
                            value;
                         'Could not load preload.',
                    } else {
                    'error'
                        delete field.default;
                );
                    }
            }
        },


                     this.markDirty();
        async findSimilarPreloads(title) {
                     this.renderConfigPreviewBySelector();
            let query =
                }
                title
            );
                     .replace(
                        /\/Preload$/i,
                        ''
                    )
                     .trim();


             card.append(
             if (!query) {
                 this.fieldRow(
                 query = title;
                    'Default',
             }
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
             );


             if (
             try {
                field.type === 'textarea'
                 const results =
            ) {
                     await this.searchPages(query);
                 const maxRows =
                     this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );


                 maxRows.on(
                 return results.filter(
                     'input.preloadEditor',
                     result =>
                    () => {
                         /\/Preload$/i.test(
                         const value =
                             result.title
                             parseInt(
                        )
                                maxRows.val(),
                );
                                10
            } catch (error) {
                            );
                console.error(
                    'Preload Editor search:',
                    error
                );


                        if (
                return [];
                            Number.isFinite(
            }
                                value
        },
                            ) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }


                        this.markDirty();
        renderMissingPage(
                        this.renderConfigPreviewBySelector();
            title,
                    }
            suggestions
                );
        ) {
            this.workspace.empty();


                 card.append(
            const section =
                     this.fieldRow(
                 this.createSection(
                        'Maximum rows',
                     'Preload not found'
                        maxRows
                    )
                 );
                 );
            }


             if (
             $('<p>')
                 field.type === 'select' ||
                 .text(
                field.type === 'multiselect'
                    'No preload exists at "' +
            ) {
                    title +
                 this.renderSelectConfiguration(
                    '".'
                    card,
                )
                    field
                 .appendTo(section);
                );
            }


             return card;
             if (suggestions.length) {
        },
                $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);


        renderSelectConfiguration(
                const list =
            card,
                    $('<div>')
            field
                        .addClass(
        ) {
                            'preload-editor-suggestions'
            const source =
                        );
                this.textInput(
 
                    field.source || '',
                suggestions.forEach(
                     'category:Example'
                    result => {
                        list.append(
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                        );
                     }
                 );
                 );


            source.on(
                 section.append(list);
                 'input.preloadEditor',
            }
                () => {
                    const value =
                        source.val();


                    if (value) {
             section.append(
                        field.source = value;
                 this.createButton(
                    } else {
                     'Create this preload',
                        delete field.source;
                     'preload-editor-button-primary',
                    }
                     () =>
 
                        this.startNew(title)
                    this.markDirty();
                    this.renderConfigPreviewBySelector();
                }
            );
 
             card.append(
                 this.fieldRow(
                     'Source',
                     source,
                     'Currently supported source format: category:Category Name'
                 )
                 )
             );
             );


             const sourcePrefix =
             this.workspace.append(section);
                this.textInput(
        },
                    field['source-prefix'] || ''
                );


             sourcePrefix.on(
        async startNew(title) {
                 'input.preloadEditor',
             title =
                () => {
                 String(title || '').trim();
                    const value =
                        sourcePrefix.val();


                    if (value) {
            this.state = {
                        field['source-prefix'] =
                preloadTitle: title,
                            value;
                preloadSource: '',
                    } else {
                preloadContent:
                        delete field[
                     this.defaults.preload,
                            'source-prefix'
                        ];
                     }


                     this.markDirty();
                config:
                    this.renderConfigPreviewBySelector();
                     this.emptyConfig(),
                }
 
             );
                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };
 
            this.saveDraft();
             this.renderEditor();


             card.append(
             this.setStatus(
                 this.fieldRow(
                 'Creating a new preload.',
                    'Source prefix',
                'success'
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
             );
             );
        },


             const excludeCategory =
        async loadSamplePage() {
                 this.textInput(
             const result =
                     field.exclude &&
                 await this.createPromptDialog(
                     field.exclude.category ||
                     'Load Sample Page',
                    ''
                     'Enter the title of a normal wiki page to use as the starting point.'
                 );
                 );


             excludeCategory.on(
             if (!result) {
                'input.preloadEditor',
                return;
                () => {
            }
                    const value =
                        excludeCategory.val();


                    if (value) {
            this.setStatus(
                        field.exclude =
                'Loading sample page...',
                            Object.assign(
                'loading'
                                {},
            );
                                field.exclude || {},
                                {
                                    category:
                                        value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
            try {
                            !Object.keys(
                const page =
                                field.exclude
                    await this.getPage(result);
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }


                    this.markDirty();
                if (!page) {
                     this.renderConfigPreviewBySelector();
                     throw new Error(
                        'Sample page not found: ' +
                        result
                    );
                 }
                 }
            );


            card.append(
                const sample =
                this.fieldRow(
                    this.convertSampleToPreload(
                    'Exclude category',
                        page.content
                     excludeCategory
                     );
                )
            );


            card.append(
                 this.state = {
                 this.createTransformControls(
                     preloadTitle: '',
                    field,
                     preloadSource: '',
                     'value',
                     preloadContent: sample,
                     'Value transformation'
 
                ),
                     config:
                this.createTransformControls(
                        this.emptyConfig(),
                     field,
                    'label',
                     'Label transformation'
                )
            );


            const optionsValue =
                    variables: ['PAGE'],
                Array.isArray(field.options)
                    conditions: [],
                     ? field.options
                     selectedVariable: 'PAGE',
                        .map(option => {
                    deletedVariables: [],
                            if (
                    mode: 'new',
                                typeof option ===
                    dirty: true,
                                'string'
                    dirtyPreload: true,
                            ) {
                    dirtyConfig: true,
                                return option;
                            }


                            return (
                    localDraftSavedAt: null,
                                String(
                    localDraftAvailable: false
                                    option.value ||
                };
                                    ''
                                ) +
                                ' | ' +
                                String(
                                    option.label ||
                                    option.value ||
                                    ''
                                )
                            );
                        })
                        .join('\n')
                    : '';


            const options =
                 this.reanalyze();
                 this.textarea(
                 this.saveDraft();
                    optionsValue
                 this.renderEditor();
                 ).addClass(
                    'preload-editor-small-textarea'
                 );


            options.on(
                this.setStatus(
                'input.preloadEditor',
                    'Sample page loaded.',
                 () => {
                    'success'
                    const lines =
                 );
                        options
            } catch (error) {
                            .val()
                console.error(
                            .split('\n')
                    'Preload Editor sample:',
                            .map(
                    error
                                line =>
                );
                                    line.trim()
                            )
                            .filter(Boolean);


                     if (!lines.length) {
                this.setStatus(
                         delete field.options;
                     error.message ||
                     } else {
                         'Could not load sample page.',
                        field.options =
                     'error'
                            lines.map(line => {
                );
                                const parts =
            }
                                    line.split(
        },
                                        /\s*\|\s*/
                                    );


                                if (
        convertSampleToPreload(source) {
                                    parts.length ===
            let content =
                                    1
                String(source || '').trim();
                                ) {
                                    return parts[0];
                                }


                                return {
            const include =
                                    value:
                content.match(
                                        parts[0],
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                                    label:
                );
                                        parts
 
                                            .slice(1)
            if (include) {
                                            .join(
                content =
                                                ' | '
                    include[1].trim();
                                            )
            }
                                };
                            });
                    }


                     this.markDirty();
            content =
                     this.renderConfigPreviewBySelector();
                content
                }
                     .replace(
            );
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                     .trim();


             card.append(
             return (
                 this.fieldRow(
                 '<includeonly>\n' +
                    'Manual options',
                content +
                    options,
                '\n</includeonly>\n' +
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                 '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
                 )
             );
             );
         },
         },


         createTransformControls(
         async loadDefinition(
             field,
             title,
             property,
             source
            title
         ) {
         ) {
             const wrapper =
             const content =
                 $('<div>')
                 this.extractIncludeonly(source);
                    .addClass(
                        'preload-editor-transform'
                    );


             $('<h4>')
             let config =
                .text(title)
                 this.emptyConfig();
                 .appendTo(wrapper);


             const existing =
             const configTitle =
                 field[property] &&
                 title.replace(
                typeof field[property] ===
                    /\/+$/,
                     'object'
                     ''
                    ? field[property]
                ) +
                    : {};
                '/config.json';


             const transform =
             const configPage =
                 this.select(
                 await this.getPage(configTitle);
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label: 'Replace'
                        }
                    ],
                    existing.transform || ''
                );


             const prefix =
             if (configPage) {
                 this.textInput(
                try {
                     existing.prefix || ''
                    config =
                );
                        JSON.parse(
                            configPage.content
                        );
                 } catch (error) {
                     throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }


             const suffix =
             const analysis =
                 this.textInput(
                 this.analyzePreload(content);
                    existing.suffix || ''
                );


             const from =
             this.state.deletedVariables = [];
                this.textInput(
                    existing.from || ''
                );


             const to =
             config =
                 this.textInput(
                 this.prepareConfigForVariables(
                     existing.to || ''
                     config,
                    analysis
                 );
                 );


             const controls =
             this.state = {
                 $('<div>')
                 preloadTitle: title,
                    .addClass(
                preloadSource: source,
                        'preload-editor-transform-controls'
                preloadContent: source,
                    );
                config,


            const prefixRow =
                 variables:
                 this.fieldRow(
                     analysis.variables,
                     'Prefix',
                    prefix
                );


            const suffixRow =
                 conditions:
                 this.fieldRow(
                     analysis.conditions,
                     'Suffix',
                    suffix
                );


            const fromRow =
                selectedVariable:
                this.fieldRow(
                    analysis.variables.includes('PAGE')
                    'From',
                        ? 'PAGE'
                    from
                        : (
                );
                            analysis.variables[0] ||
                            'PAGE'
                        ),


            const toRow =
                 deletedVariables: [],
                 this.fieldRow(
                    'To',
                    to
                );


            const renderInputs =
                mode: 'edit',
                 () => {
                 dirty: false,
                    const type =
                dirtyPreload: false,
                        transform.val();
                dirtyConfig: false,


                    prefixRow.toggle(
                localDraftSavedAt: null,
                        type ===
                localDraftAvailable: false
                            'remove-prefix'
            };
                    );


                    suffixRow.toggle(
            this.clearDraft(title);
                        type ===
            this.renderEditor();
                            'remove-suffix'
        },
                    );


                     fromRow.toggle(
        // =========================================================
                         type === 'replace'
        // Editor
        // =========================================================
 
        renderEditor() {
            this.destroyEditor();
            this.workspace.empty();
 
            const layout =
                $('<div>')
                     .addClass(
                         'preload-editor-layout'
                     );
                     );


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


             const update =
             const right =
                 () => {
                 $('<div>')
                     const type =
                     .addClass(
                         transform.val();
                         'preload-editor-right'
                    );


                     let object = null;
            const editorSection =
                this.createSection(
                     'Preload',
                    'preload-editor-main-section'
                );


                    if (
            const meta =
                        type ===
                $('<div>')
                            'remove-prefix' &&
                     .addClass(
                        prefix.val()
                         'preload-editor-meta'
                     ) {
                     );
                        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) {
            $('<strong>')
                        field[property] =
                .text(
                            object;
                    this.state.preloadTitle ||
                     } else {
                     'New preload'
                        delete field[property];
                )
                    }
                .appendTo(meta);


                     this.markDirty();
            if (
                     this.renderConfigPreviewBySelector();
                this.state.mode === 'new'
                };
            ) {
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                     .text('NEW')
                     .appendTo(meta);
            }


             transform.on(
             editorSection.append(meta);
                'change.preloadEditor',
            editorSection.append(
                 () => {
                 this.renderEditorTools()
                    update();
                    renderInputs();
                }
             );
             );


             [
             const textarea =
                 prefix,
                 this.textarea(
                 suffix,
                    this.state.preloadContent
                from,
                 )
                to
                    .attr(
            ].forEach(input => {
                        'id',
                input.on(
                        'preload-editor-content'
                    'input.preloadEditor',
                    )
                     update
                    .addClass(
                );
                        'preload-editor-content'
            });
                    );
 
            const editorMount =
                $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                     )
                    .append(textarea);


             controls.append(
             editorSection.append(editorMount);
                this.fieldRow(
            left.append(editorSection);
                    'Transformation',
 
                    transform
            const analysisSection =
                ),
                 this.createSection('Analysis');
                prefixRow,
                suffixRow,
                 fromRow,
                toRow
            );


             renderInputs();
             const analysisContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis'
                    );


             wrapper.append(
             analysisSection.append(
                 controls
                 analysisContainer
             );
             );


             return wrapper;
             const variablesSection =
        },
                this.createSection('Variables');


        // Config output
            const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );


        getCleanConfig() {
             const detectHelp =
             const config =
                 $('<div>')
                 JSON.parse(
                     .addClass(
                     JSON.stringify(
                         'preload-editor-help preload-editor-detect-variables-help'
                         this.state.config
                     )
                     )
                );
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );


             const fields =
             variablesSection.append(
                 config.fields || {};
                 $('<div>')
                    .addClass(
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );


             const orderedFields = {};
             const variableContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variables'
                    );


             // PAGE is always first and automatic.
             variablesSection.append(
             orderedFields.PAGE =
                variableContainer
                this.getAutomaticPageField();
             );


             Object.keys(fields)
             const configurationSection =
                 .filter(
                 this.createSection(
                     name =>
                     'Variable configuration'
                        name.toUpperCase() !==
                 );
                        'PAGE'
                 )
                .forEach(name => {
                    orderedFields[name] =
                        fields[name];
                });


             config.fields =
             /*
                 orderedFields;
            * 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()
                 );


             return config;
             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.'
                    );


        getConfigJSON() {
             const importControls =
             return JSON.stringify(
                 $('<div>')
                 this.getCleanConfig(),
                    .addClass(
                null,
                        'preload-editor-import-definition-controls'
                4
                    )
            );
                    .append(
        },
                        importDefinitionsButton,
 
                        importHelp
        renderConfigPreview(container) {
                     );
            if (container) {
                container.text(
                     this.getConfigJSON()
                );
            }
        },


        renderConfigPreviewBySelector() {
             configurationSection.append(
             const preview =
                 importControls
                this.root &&
            );
                 this.root.find(
                    '.preload-editor-config-preview'
                );


             if (
             const configurationContainer =
                 preview &&
                 $('<div>')
                preview.length
                    .addClass(
            ) {
                        'preload-editor-variable-configuration'
                this.renderConfigPreview(
                     );
                     preview
                );
            }


             this.renderAnalysisBySelector();
             configurationSection.append(
        },
                configurationContainer
            );


        markDirty() {
            const configSection =
            this.state.dirty = true;
                this.createSection(
        },
                    'Configuration'
                );


        // Save
            const configHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );


        async savePreloadOnly() {
             const reviewConfigButton =
             let title =
                 this.createButton(
                 String(
                     'Review config.json',
                     this.state.preloadTitle ||
                     '',
                     ''
                    () =>
                ).trim();
                        this.createConfigReviewDialog()
                );


             if (!title) {
             configSection.append(
                 const result =
                 configHelp,
                    await this.createPromptDialog(
                reviewConfigButton
                        'Preload title',
            );
                        'Enter the full title for the preload.'
                    );


                 if (!result) return;
            right.append(
                 analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );


                 title = result;
            layout.append(
                 this.state.preloadTitle =
                 left,
                    title;
                 right
            }
            );


             this.state.preloadContent =
             const saveBar =
                 this.getEditorContent();
                 $('<div>')
                    .addClass(
                        'preload-editor-save-bar'
                    );


             const validation =
             saveBar.append(
                this.validateBeforeSave();
                this.createButton(
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),


            if (
                this.createButton(
                validation.errors.length
                    'Save Config',
            ) {
                    '',
                 this.showValidationErrors(
                    () =>
                     validation
                        this.saveConfigOnly()
                 );
                ),
 
                 this.createButton(
                     'Save',
                    'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                 )
            );


                 return;
            this.root
            }
                .find('.preload-editor-footer')
                 .append(saveBar);


             this.setStatus(
             this.workspace.append(
                 'Saving preload...',
                 layout
                'loading'
             );
             );


             try {
             this.reanalyze();
                const exists =
                    await this.pageExists(
                        title
                    );


                await this.savePage(
            this.renderVariables(
                    title,
                variableContainer
                    this.state.preloadContent,
            );
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );


                this.state.mode =
            this.renderAnalysis(
                    'edit';
                analysisContainer
            );


                this.state.dirty =
            this.renderVariableConfiguration(
                    false;
                configurationContainer
            );


                this.setStatus(
            this.updateEditorTools();
                    'Preload saved successfully.',
            this.updateLocalDraftIndicator();
                    'success'
 
                );
            this.mountCodeMirror(
 
                textarea.get(0)
                mw.notify(
            ).catch(
                    'Preload saved.',
                error => {
                    {
                    console.error(
                        type: 'success'
                        'Preload Editor CodeMirror:',
                    }
                        error
                );
                    );
             } catch (error) {
 
                 console.error(
                    this.setStatus(
                     'Preload Editor save:',
                        error.message ||
                     error
                            'Could not initialize CodeMirror.',
                 );
                        'error'
 
                    );
                 this.setStatus(
                }
                     error.message ||
            );
                         'Could not save preload.',
        },
                     'error'
 
                 );
        // =========================================================
 
        // Variable detection
                 mw.notify(
        // =========================================================
                     error.message ||
 
                         'Could not save preload.',
        detectVariables() {
                     {
            const source =
                         type: 'error'
                this.getEditorContent();
                     }
 
                 );
            this.state.preloadContent =
             }
                source;
         },
 
 
            const content =
         async saveAll() {
                this.extractIncludeonly(
             let title =
                    source
                 String(
                );
                     this.state.preloadTitle ||
 
                    ''
            const analysis =
                 ).trim();
                this.analyzePreload(
 
                    content
             if (!title) {
                );
                 const result =
 
                     await this.createPromptDialog(
            /*
                         'Preload title',
            * If a variable was previously deleted from
                         'Enter the full title for the preload.'
            * the configuration, detecting the current
                     );
            * preload again should allow it to come back.
 
            */
                 if (!result) return;
            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;
                 title = result;
Line 3,813: Line 5,943:
             this.state.preloadContent =
             this.state.preloadContent =
                 this.getEditorContent();
                 this.getEditorContent();
            this.reanalyze();


             const validation =
             const validation =
                 this.validateBeforeSave();
                 this.validateBeforeSave();


             if (
             if (validation.errors.length) {
                validation.errors.length
            ) {
                 this.showValidationErrors(
                 this.showValidationErrors(
                     validation
                     validation
                 );
                 );


                this.saveDraft();
                return;
            }
            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );
            if (!confirmed) {
                 return;
                 return;
             }
             }
Line 3,841: Line 5,982:
             try {
             try {
                 const preloadExists =
                 const preloadExists =
                     await this.pageExists(
                     await this.pageExists(title);
                        title
                    );


                 await this.savePage(
                 await this.savePage(
Line 3,854: Line 5,993:
                 );
                 );


                /*
                * 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 =
                 const configExists =
                     await this.pageExists(
                     await this.pageExists(
Line 3,859: Line 6,006:
                     );
                     );


                 await this.savePage(
                 await this.saveConfigPage(
                     configTitle,
                     configTitle,
                     this.getConfigJSON(),
                     this.getConfigJSON(),
                     configExists
                     configExists
                         ? 'Updated preload config with Preload Editor'
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor',
                         : 'Created preload config with Preload Editor'
                    !configExists
                 );
                 );


                 this.state.mode =
                 this.state.mode = 'edit';
                    'edit';
                this.state.dirtyPreload = false;
 
                this.state.dirtyConfig = false;
                 this.state.dirty =
                 this.state.dirty = false;
                    false;
                this.state.preloadTitle = title;


                 this.state.preloadTitle =
                 this.clearDraft(title);
                    title;


                 this.setStatus(
                 this.setStatus(
                     'Preload and config saved successfully.',
                     'Preload and JSON config saved successfully.',
                     'success'
                     'success'
                 );
                 );


                 mw.notify(
                 mw.notify(
                     'Preload and config saved.',
                     'Preload and config saved. config.json is using the JSON content model.',
                     {
                     {
                         type: 'success'
                         type: 'success'
Line 3,893: Line 6,038:
                     error
                     error
                 );
                 );
                this.saveDraft();


                 this.setStatus(
                 this.setStatus(
Line 3,909: Line 6,056:
             }
             }
         },
         },
        // =========================================================
        // Validation
        // =========================================================


         validateBeforeSave() {
         validateBeforeSave() {
Line 3,916: Line 6,067:
             const title =
             const title =
                 String(
                 String(
                     this.state.preloadTitle ||
                     this.state.preloadTitle || ''
                    ''
                 ).trim();
                 ).trim();


Line 3,948: Line 6,098:


             if (
             if (
                 !/<includeonly>/i.test(
                 !/<includeonly>/i.test(content)
                    content
                )
             ) {
             ) {
                 warnings.push(
                 warnings.push(
Line 3,958: Line 6,106:


             if (
             if (
                 !/<noinclude>/i.test(
                 !/<noinclude>/i.test(content)
                    content
                )
             ) {
             ) {
                 warnings.push(
                 warnings.push(
Line 3,972: Line 6,118:
                         content
                         content
                     )
                     )
                );
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                 );
                 );


Line 3,989: Line 6,142:


             let depth = 0;
             let depth = 0;
 
                        analysis.conditions.forEach(
            analysis.conditions.forEach(
                 condition => {
                 condition => {
                     if (
                     if (
                         condition.type ===
                         condition.type === 'if'
                        'if'
                     ) {
                     ) {
                         depth++;
                         depth++;
                     } else if (
                     } else if (
                         condition.type ===
                         condition.type === 'endif'
                        'endif'
                     ) {
                     ) {
                         depth--;
                         depth--;
Line 4,011: Line 6,161:
                         }
                         }
                     } else if (
                     } else if (
                         condition.type ===
                         condition.type === 'elseif' ||
                            'elseif' ||
                         condition.type === 'else'
                         condition.type ===
                            'else'
                     ) {
                     ) {
                         if (depth === 0) {
                         if (depth === 0) {
Line 4,041: Line 6,189:
         },
         },


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


             this.setStatus(
             this.setStatus(
Line 4,066: Line 6,214:
         if (
         if (
             mw.config.get('wgPageName') !==
             mw.config.get('wgPageName') !==
             'Petit_Planet:Preload_Editor'
             'Petit_Planet_Wiki:Preload_Editor'
         ) {
         ) {
             return;
             return;

Latest revision as of 22:07, 14 October 2026

(function (mw, $) {
    'use strict';

    const PreloadEditor = {
        version: '1.2.0',

        state: {
            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
        },

        editor: null,
        editorView: null,
        analysis: null,
        root: null,
        workspace: null,
        status: null,
        localDraftStatus: null,
        editorTools: null,

        draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',

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

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

        getDraftStorage() {
            try {
                const raw = window.localStorage.getItem(this.draftStorageKey);

                if (!raw) {
                    return {
                        active: null,
                        drafts: {}
                    };
                }

                const parsed = JSON.parse(raw);

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

                if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
                    parsed.drafts = {};
                }

                return parsed;
            } catch (error) {
                console.warn('Preload Editor: Could not read local drafts.', error);

                return {
                    active: null,
                    drafts: {}
                };
            }
        },

        setDraftStorage(storage) {
            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;
            }
        },

        getDraftId(title) {
            title = String(title || '').trim();
            return title ? title.toLowerCase() : '__untitled__';
        },

        getDraftSnapshot() {
            let content = this.getEditorContent();

            if (!this.editorView && !content) {
                content = this.state.preloadContent || '';
            }

            let config = null;

            try {
                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 {
                version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,

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

                conditions: Array.isArray(this.state.conditions)
                    ? this.state.conditions.slice()
                    : [],

                selectedVariable: String(this.state.selectedVariable || 'PAGE'),

                deletedVariables: Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.slice()
                    : [],

                mode: this.state.mode || 'edit',
                dirty: !!this.state.dirty,
                dirtyPreload: !!this.state.dirtyPreload,
                dirtyConfig: !!this.state.dirtyConfig,
                savedAt: Date.now()
            };
        },

        updateLocalDraftStatus(message, type) {
            if (!this.localDraftStatus) {
                return;
            }

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

            if (type) {
                this.localDraftStatus.addClass('is-' + type);
            }

            this.localDraftStatus.text(message || '');
        },

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

            try {
                return new Date(timestamp).toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            } catch (error) {
                return '';
            }
        },

        updateLocalDraftIndicator() {
            if (!this.localDraftStatus) {
                return;
            }

            if (this.state.localDraftSavedAt) {
                const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);

                this.updateLocalDraftStatus(
                    time ? 'Saved locally at ' + time : 'Saved locally',
                    'saved'
                );

                return;
            }

            this.updateLocalDraftStatus('No local draft', 'empty');
        },

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

            const snapshot = this.getDraftSnapshot();
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();

            storage.drafts[id] = snapshot;
            storage.active = id;

            const saved = this.setDraftStorage(storage);

            if (saved) {
                this.state.localDraftSavedAt = snapshot.savedAt;
                this.state.localDraftAvailable = true;
                this.updateLocalDraftIndicator();
            } else {
                this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
            }

            return saved;
        },

        clearDraft(title) {
            const storage = this.getDraftStorage();
            const id = this.getDraftId(title);

            if (storage.drafts && storage.drafts[id]) {
                delete storage.drafts[id];
            }

            if (storage.active === id) {
                storage.active = null;
            }

            this.setDraftStorage(storage);

            this.state.localDraftSavedAt = null;
            this.state.localDraftAvailable = false;

            this.updateLocalDraftIndicator();
        },

        getMostRecentDraft() {
            const storage = this.getDraftStorage();

            if (!storage.drafts || !Object.keys(storage.drafts).length) {
                return null;
            }

            if (storage.active && storage.drafts[storage.active]) {
                return {
                    id: storage.active,
                    draft: storage.drafts[storage.active]
                };
            }

            let latestId = null;
            let latestDraft = null;

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

                if (
                    !latestDraft ||
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                ) {
                    latestId = id;
                    latestDraft = draft;
                }
            });

            if (!latestDraft) {
                return null;
            }

            return {
                id: latestId,
                draft: latestDraft
            };
        },

        async restoreDraft() {
            const result = this.getMostRecentDraft();

            if (!result || !result.draft) {
                return false;
            }

            const draft = result.draft;
            const title = String(draft.preloadTitle || '').trim();
            const displayTitle = title || 'an untitled preload';

            const savedAt = draft.savedAt
                ? new Date(draft.savedAt).toLocaleString()
                : '';

            const message =
                'Preload Editor found unsaved local work for ' +
                displayTitle +
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                '\n\nRestore it?';

            const restore = await this.createConfirmDialog(
                'Restore unsaved work',
                message,
                'Restore',
                'Discard'
            );

            if (!restore) {
                this.clearDraft(title);
                return false;
            }

            let config = this.emptyConfig();

            if (
                draft.config &&
                typeof draft.config === 'object' &&
                !Array.isArray(draft.config)
            ) {
                try {
                    config = this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                    );
                } catch (error) {
                    console.warn(
                        'Preload Editor: Could not restore local config.',
                        error
                    );
                }
            }

            const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';

            this.state = {
                preloadTitle: title,
                preloadSource: String(draft.preloadSource || ''),
                preloadContent: String(draft.preloadContent || ''),
                config,

                variables: Array.isArray(draft.variables)
                    ? draft.variables.slice()
                    : [],

                conditions: Array.isArray(draft.conditions)
                    ? draft.conditions.slice()
                    : [],

                selectedVariable: String(draft.selectedVariable || 'PAGE'),

                deletedVariables: Array.isArray(draft.deletedVariables)
                    ? draft.deletedVariables
                        .map(name => String(name).toUpperCase())
                        .filter(name => name !== 'PAGE')
                    : [],

                mode: draft.mode || 'edit',

                dirty: hasDirtyFlags
                    ? !!(draft.dirtyPreload || draft.dirtyConfig)
                    : true,

                dirtyPreload: hasDirtyFlags
                    ? !!draft.dirtyPreload
                    : true,

                dirtyConfig: hasDirtyFlags
                    ? !!draft.dirtyConfig
                    : true,

                localDraftSavedAt: Number(draft.savedAt) || null,
                localDraftAvailable: true
            };

            this.reanalyze();
            this.renderEditor();
            this.updateLocalDraftIndicator();

            this.setStatus(
                'Restored unsaved local work from this browser.',
                'warning'
            );

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

            return true;
        },

        // =========================================================
        // API
        // =========================================================

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

            const page =
                response &&
                response.query &&
                response.query.pages &&
                response.query.pages[0];

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

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

            return {
                title: page.title || title,
                content: typeof content === 'string' ? content : '',
                contentmodel: page.contentmodel || 'wikitext'
            };
        },

        async pageExists(title) {
            return !!await this.getPage(title);
        },

        async searchPages(query) {
            const response = await new mw.Api().get({
                action: 'query',
                list: 'search',
                srsearch: query,
                srlimit: 10,
                srnamespace: 10,
                formatversion: 2
            });

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

        /*
         * Save a page.
         *
         * contentModel is mainly used when creating a page.
         *
         * 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 (createOnly) {
                params.createonly = true;
            }

            if (contentModel) {
                params.contentmodel = contentModel;
            }

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

        /*
         * Change the content model of an existing page.
         *
         * 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'
            });
        },

        /*
         * Save config.json and make sure its content model
         * is JSON.
         *
         * 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 (!page) {
                return this.savePage(
                    title,
                    content,
                    summary,
                    true,
                    'json'
                );
            }

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

            return this.savePage(
                title,
                content,
                summary,
                false
            );
        },

        // =========================================================
        // Config import helpers
        // =========================================================

        /*
         * Accept either:
         *
         *   Template:Example/Preload
         *
         * or:
         *
         *   Template:Example/Preload/config.json
         *
         * and always return the config.json title.
         */
        normalizeConfigTitle(title) {
            title = String(title || '').trim();
            title = title.replace(/\/+$/, '');

            if (/\/config\.json$/i.test(title)) {
                return title;
            }

            return title + '/config.json';
        },

        /*
         * Return a safe clone of a config field.
         *
         * 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
                );

                return null;
            }
        },

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

            if (
                !fields ||
                typeof fields !== 'object' ||
                Array.isArray(fields)
            ) {
                return {};
            }

            const result = {};

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

                if (!upper || upper === 'PAGE') {
                    return;
                }

                if (
                    !field ||
                    typeof field !== 'object' ||
                    Array.isArray(field)
                ) {
                    return;
                }

                const clone = this.cloneConfigField(field);

                if (!clone) {
                    return;
                }

                result[upper] = clone;
            });

            return result;
        },

        /*
         * 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));

                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );

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

                $('<h2>')
                    .text('Import variable definitions')
                    .appendTo(box);

                $('<p>')
                    .text(
                        'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                    )
                    .appendTo(box);

                if (!names.length) {
                    $('<div>')
                        .addClass(
                            'preload-editor-empty preload-editor-import-empty'
                        )
                        .text(
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);

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

                    const close = this.createButton(
                        'Close',
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );

                    emptyButtons.append(close);
                    box.append(emptyButtons);
                    overlay.append(box);

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

                    overlay.attr('tabindex', '-1');
                    overlay.trigger('focus');

                    return;
                }

                const search = this.textInput('', 'Search variables...')
                    .addClass('preload-editor-import-search');

                const searchWrap = $('<div>')
                    .addClass('preload-editor-import-search-wrap')
                    .append(search);

                box.append(searchWrap);

                const controls = $('<div>')
                    .addClass('preload-editor-import-controls');

                const selectAll = this.createButton(
                    'Select all',
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', true);

                        updateSummary();
                    }
                );

                const deselectAll = this.createButton(
                    'Deselect all',
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);

                        updateSummary();
                    }
                );

                controls.append(selectAll, deselectAll);
                box.append(controls);

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

                const localFields =
                    this.state.config && this.state.config.fields
                        ? this.state.config.fields
                        : {};

                names.forEach(name => {
                    const existing = !!localFields[name];
                    const field = fields[name];

                    const type = field && field.type
                        ? String(field.type)
                        : 'text';

                    const label = field && field.label
                        ? String(field.label)
                        : this.humanizeName(name);

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

                    const checkbox = this.checkbox(false)
                        .attr('data-import-variable', name)
                        .addClass('preload-editor-import-checkbox');

                    const content = $('<span>')
                        .addClass('preload-editor-import-content');

                    const header = $('<span>')
                        .addClass('preload-editor-import-header');

                    $('<strong>')
                        .text(name)
                        .appendTo(header);

                    $('<span>')
                        .addClass('preload-editor-import-type')
                        .text(type)
                        .appendTo(header);

                    const meta = $('<span>')
                        .addClass('preload-editor-import-meta');

                    $('<span>')
                        .text(label)
                        .appendTo(meta);

                    const status = $('<span>')
                        .addClass('preload-editor-import-status')
                        .toggleClass('is-existing', existing)
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');

                    content.append(header, meta, status);
                    row.append(checkbox, content);
                    list.append(row);
                });

                box.append(list);

                const summary = $('<div>')
                    .addClass('preload-editor-import-summary');

                const updateSummary = () => {
                    const selected = list.find(
                        'input[type="checkbox"]:checked'
                    ).length;

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

                            return !!localFields[name];
                        }).length;

                    let text =
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';

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

                    summary.text(text);

                    importButton.prop('disabled', selected === 0);
                };

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

                    list.find('.preload-editor-import-row').each(function () {
                        const row = $(this);
                        const haystack = String(
                            row.attr('data-search') || ''
                        );

                        row.toggle(!query || haystack.includes(query));
                    });
                };

                search.on(
                    'input.preloadEditor',
                    filterRows
                );

                list.on(
                    'change.preloadEditor',
                    'input[type="checkbox"]',
                    updateSummary
                );

                const buttons = $('<div>')
                    .addClass('preload-editor-prompt-buttons');

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

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

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

                        overlay.remove();
                        resolve(selected);
                    }
                );

                buttons.append(cancel, importButton);
                box.append(summary, buttons);
                overlay.append(box);

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

                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');

                updateSummary();
                search.trigger('focus');

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

                overlay.on(
                    'keydown.preloadEditor',
                    close
                );

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

        /*
         * Main import workflow.
         */
        async importVariableDefinitions() {
            const source = await this.createPromptDialog(
                'Import variable definitions',
                'Enter a preload title or its config.json title.'
            );

            if (!source) {
                return;
            }

            const configTitle = this.normalizeConfigTitle(source);

            this.setStatus(
                'Loading source config...',
                'loading'
            );

            try {
                const page = await this.getPage(configTitle);

                if (!page) {
                    throw new Error(
                        'No config.json was found at "' +
                        configTitle +
                        '".'
                    );
                }

                let sourceConfig;

                try {
                    sourceConfig = JSON.parse(page.content);
                } catch (error) {
                    throw new Error(
                        'The source config.json contains invalid JSON: ' +
                        error.message
                    );
                }

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

                if (
                    !sourceConfig.fields ||
                    typeof sourceConfig.fields !== 'object' ||
                    Array.isArray(sourceConfig.fields)
                ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }

                const fields = this.getImportableFields(sourceConfig);

                const selected =
                    await this.createImportDefinitionsDialog(
                        configTitle,
                        fields
                    );

                if (selected === null) {
                    this.setStatus(
                        'Variable import cancelled.',
                        'warning'
                    );

                    return;
                }

                if (!selected.length) {
                    this.setStatus(
                        'No variable definitions were imported.',
                        'warning'
                    );

                    return;
                }

                if (!this.state.config) {
                    this.state.config = this.emptyConfig();
                }

                if (!this.state.config.fields) {
                    this.state.config.fields = {};
                }

                const imported = [];
                const replaced = [];

                selected.forEach(name => {
                    if (name === 'PAGE') {
                        return;
                    }

                    const field = fields[name];

                    if (!field) {
                        return;
                    }

                    if (this.state.config.fields[name]) {
                        replaced.push(name);
                    } else {
                        imported.push(name);
                    }

                    const clone = this.cloneConfigField(field);

                    if (!clone) {
                        return;
                    }

                    this.state.config.fields[name] = clone;

                    /*
                     * If this variable was previously deleted,
                     * 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
                            );
                    }
                });

                /*
                 * Keep PAGE automatic regardless of what the
                 * imported config contained.
                 */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();

                this.markConfigDirty();

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

                if (
                    !selectedStillExists ||
                    this.state.selectedVariable === 'PAGE'
                ) {
                    this.state.selectedVariable =
                        selected[0] ||
                        'PAGE';
                }

                this.reanalyze();

                this.renderVariablesBySelector();
                this.renderVariableConfigurationBySelector();
                this.renderAnalysisBySelector();
                this.updateEditorTools();

                this.saveDraft();

                let status =
                    'Imported ' +
                    selected.length +
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                    '.';

                if (replaced.length) {
                    status +=
                        ' Replaced: ' +
                        replaced.join(', ') +
                        '.';
                }

                this.setStatus(status, 'success');

                mw.notify(status, {
                    type: 'success'
                });
            } catch (error) {
                console.error(
                    'Preload Editor variable import:',
                    error
                );

                this.setStatus(
                    error.message ||
                        'Could not import variable definitions.',
                    'error'
                );

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

        // =========================================================
        // Preload parsing
        // =========================================================

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

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

        findVariables(content) {
            const variables = [];
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;

            let match;

            while ((match = pattern.exec(content)) !== null) {
                const name = match[1].toUpperCase();

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

            return variables;
        },

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

            let match;

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

            return conditions;
        },

        findConditionVariables(content) {
            const variables = [];

            this.findConditions(content).forEach(condition => {
                if (
                    condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }

                const matches =
                    condition.expression.match(
                        /[A-Za-z0-9_-]+/g
                    ) || [];

                matches.forEach(name => {
                    name = name.toUpperCase();

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

            return variables;
        },

        analyzePreload(content) {
            return {
                variables: this.findVariables(content),
                conditions: this.findConditions(content),
                conditionVariables:
                    this.findConditionVariables(content)
            };
        },

        // =========================================================
        // Config
        // =========================================================

        getAutomaticPageField() {
            return {
                label: 'Page Name',
                description: 'Name of the page.',
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },

        emptyConfig() {
            return {
                settings: {
                    incomplete: 'add-stub'
                },

                fields: {
                    PAGE: this.getAutomaticPageField()
                }
            };
        },

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

            if (
                !config.settings ||
                typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
            ) {
                config.settings = {};
            }

            if (
                !config.fields ||
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
            ) {
                config.fields = {};
            }

            config.fields.PAGE =
                this.getAutomaticPageField();

            return config;
        },

        createDefaultField(name, analysis) {
            return {
                label: this.humanizeName(name),
                description: '',
                type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                    : 'text'
            };
        },

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

        prepareConfigForVariables(config, analysis) {
            config = this.normalizeConfig(config);

            const existing = config.fields || {};

            const deleted = new Set(
                Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.map(
                        name => String(name).toUpperCase()
                    )
                    : []
            );

            const fields = {};

            fields.PAGE =
                this.getAutomaticPageField();

            analysis.variables.forEach(name => {
                if (
                    name === 'PAGE' ||
                    deleted.has(name)
                ) {
                    return;
                }

                fields[name] =
                    existing[name] ||
                    this.createDefaultField(
                        name,
                        analysis
                    );
            });

            Object.keys(existing).forEach(name => {
                const upper = name.toUpperCase();

                if (
                    upper !== 'PAGE' &&
                    !fields[upper] &&
                    !deleted.has(upper)
                ) {
                    fields[upper] =
                        existing[name];
                }
            });

            config.fields = fields;

            return config;
        },

        validateConfig(config, analysis) {
            const errors = [];
            const warnings = [];

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

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

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

            analysis.variables.forEach(name => {
                if (!configured.includes(name)) {
                    errors.push(
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                }
            });

            configured.forEach(name => {
                if (!analysis.variables.includes(name)) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                    );
                }
            });

            if (!configured.includes('PAGE')) {
                errors.push(
                    'PAGE must always be configured.'
                );
            }

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

                    return;
                }

                if (!field.type) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" has no type.'
                    );
                }
                
                if (
                    field.type === 'file'
                ) {
                    if (
                        field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }

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

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

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

                    if (
                        !field.accept ||
                        !field.accept.length
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }

                    if (
                        !field.filename
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }

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

                if (field.type === 'file') {
                    if (
                        field.filename !== undefined &&
                        typeof field.filename !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filename" value.'
                        );
                    }

                    if (
                        field.filetext !== undefined &&
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }

                    if (
                        field.accept !== undefined &&
                        (
                            !Array.isArray(field.accept) ||
                            field.accept.some(
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                            )
                        )
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                    }
                }
            });

            return {
                valid: !errors.length,
                errors,
                warnings
            };
        },

        // =========================================================
        // Transformation helpers
        // =========================================================

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

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

                case 'remove-suffix':
                    return suffix
                        ? {
                            transform,
                            suffix
                        }
                        : null;

                case 'replace':
                    return from === ''
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };

                default:
                    return null;
            }
        },

        // =========================================================
        // UI helpers
        // =========================================================

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

            if (className) {
                section.addClass(className);
            }

            $('<h2>')
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);

            return section;
        },

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

            if (className) {
                button.addClass(className);
            }

            if (callback) {
                button.on(
                    'click.preloadEditor',
                    callback
                );
            }

            return button;
        },

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

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

            if (description) {
                $('<div>')
                    .addClass('preload-editor-help')
                    .text(description)
                    .appendTo(row);
            }

            row.append(input);

            return row;
        },

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

        textarea(value) {
            return $('<textarea>')
                .val(value == null ? '' : value)
                .addClass('preload-editor-textarea');
        },

        checkbox(checked) {
            return $('<input>')
                .attr('type', 'checkbox')
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },

        select(options, value) {
            const select = $('<select>')
                .addClass('preload-editor-select');

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

            return select;
        },

        // =========================================================
        // In-wiki dialogs
        // =========================================================

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

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

                $('<h2>')
                    .text(title)
                    .appendTo(box);

                const messageLines =
                    String(message || '').split('\n');

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

                        return;
                    }

                    $('<p>')
                        .text(line)
                        .appendTo(box);
                });

                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );

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

                const confirm = this.createButton(
                    confirmLabel || 'Confirm',
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                        resolve(true);
                    }
                );

                buttons.append(cancel, confirm);
                box.append(buttons);
                overlay.append(box);

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

                const close = value => {
                    if (value === 'Escape') {
                        cancel.trigger('click');
                    }
                };

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

                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');

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

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

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

                $('<h2>')
                    .text(title)
                    .appendTo(box);

                $('<p>')
                    .text(message)
                    .appendTo(box);

                const input = this.textInput();

                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );

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

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

                        if (!value) {
                            return;
                        }

                        overlay.remove();
                        resolve(value);
                    }
                );

                buttons.append(cancel, confirm);

                box.append(
                    input,
                    buttons
                );

                overlay.append(box);

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

                input.trigger('focus');

                input.on(
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }

                        if (event.key === 'Escape') {
                            cancel.trigger('click');
                        }
                    }
                );
            });
        },

        createConfigReviewDialog() {
            return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );

                const box = $('<div>')
                    .addClass(
                        'preload-editor-prompt preload-editor-code-review'
                    );

                $('<h2>')
                    .text('Review config.json')
                    .appendTo(box);

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

                const code = $('<pre>')
                    .addClass(
                        'preload-editor-config-review'
                    )
                    .text(this.getConfigJSON());

                const codeWrap = $('<div>')
                    .addClass(
                        'preload-editor-config-review-wrap'
                    )
                    .append(code);

                box.append(codeWrap);

                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );

                const close = this.createButton(
                    'Close',
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                        resolve();
                    }
                );

                buttons.append(close);
                box.append(buttons);
                overlay.append(box);

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

                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');

                overlay.on(
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                );

                overlay.on(
                    'click.preloadEditor',
                    event => {
                        if (event.target === overlay.get(0)) {
                            close.trigger('click');
                        }
                    }
                );
            });
        },

        async confirmSave(mode, title) {
            const configTitle =
                title.replace(/\/+$/, '') +
                '/config.json';

            let saveDescription;

            if (mode === 'preload') {
                saveDescription =
                    'Save the preload page only?';
            } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
            } else {
                saveDescription =
                    'Save both the preload and config.json?';
            }

            const pages = [];

            if (mode === 'preload' || mode === 'both') {
                pages.push(
                    'Preload: ' +
                    title
                );
            }

            if (mode === 'config' || mode === 'both') {
                pages.push(
                    'Config: ' +
                    configTitle
                );

                pages.push(
                    'Config content model: JSON'
                );
            }

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

            return this.createConfirmDialog(
                'Confirm save',
                message,
                'Save',
                'Cancel'
            );
        },

        // =========================================================
        // CodeMirror
        // =========================================================
                destroyEditor() {
            if (!this.editor) {
                this.editorView = null;
                this.editorTools = null;
                return;
            }

            const {
                view,
                inputHandler
            } = this.editor;

            if (view && inputHandler) {
                view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }

            if (view) {
                view.destroy();
            }

            this.editor = null;
            this.editorView = null;
            this.editorTools = null;
        },

        getEditorView() {
            return this.editorView;
        },

        getEditorContent() {
            if (
                this.editorView &&
                this.editorView.state
            ) {
                return this.editorView.state.doc.toString();
            }

            return this.state.preloadContent || '';
        },

        setEditorContent(content) {
            content = String(content || '');

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

            const current =
                this.editorView.state.doc.toString();

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

            this.editorView.dispatch({
                changes: {
                    from: 0,
                    to: this.editorView.state.doc.length,
                    insert: content
                }
            });
        },

        getEditorSelection() {
            if (
                !this.editorView ||
                !this.editorView.state
            ) {
                return null;
            }

            const selection =
                this.editorView.state.selection.main;

            return {
                from: selection.from,
                to: selection.to,
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
            };
        },

        focusEditor() {
            if (this.editorView) {
                this.editorView.focus();
            }
        },

        insertEditorText(
            text,
            selectionFrom,
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }

            const view = this.editorView;
            const selection = view.state.selection.main;

            const from =
                selectionFrom === undefined
                    ? selection.from
                    : selectionFrom;

            const to =
                selectionTo === undefined
                    ? selection.to
                    : selectionTo;

            const cursor =
                cursorPosition === undefined
                    ? from + text.length
                    : cursorPosition;

            view.dispatch({
                changes: {
                    from,
                    to,
                    insert: text
                },
                selection: {
                    anchor: cursor
                }
            });

            view.focus();
        },

        // =========================================================
        // Editor tools
        // =========================================================

        wrapSelectionWithVariable() {
            const selected =
                this.getEditorSelection();

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

            const replacement =
                '%%' +
                selected.text +
                '%%';

            this.insertEditorText(
                replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
            );
        },

        insertVariable(name) {
            name = String(name || '')
                .trim()
                .toUpperCase();

            if (!name) {
                return;
            }

            const selected =
                this.getEditorSelection();

            if (!selected) {
                return;
            }

            this.insertEditorText(
                '%%' + name + '%%',
                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 +
                        ' -->';

                    const closing =
                        '<!-- @endif -->';

                    if (
                        selected.from !==
                        selected.to
                    ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;

                        cursorOffset = text.length;
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;

                        cursorOffset =
                            opening.length + 1;
                    }

                    break;
                }

                case 'elseif':
                    text =
                        '<!-- @elseif -->';

                    cursorOffset =
                        text.length;

                    break;

                case 'else':
                    text =
                        '<!-- @else -->';

                    cursorOffset =
                        text.length;

                    break;

                case 'endif':
                    text =
                        '<!-- @endif -->';

                    cursorOffset =
                        text.length;

                    break;

                default:
                    return;
            }

            this.insertEditorText(
                text,
                selected.from,
                selected.to,
                selected.from + cursorOffset
            );
        },

        getToolVariables() {
            const variables =
                new Set(['PAGE']);

            if (
                this.analysis &&
                this.analysis.variables
            ) {
                this.analysis.variables.forEach(
                    name => {
                        variables.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }

            return Array.from(variables);
        },

        createToolSelect(
            options,
            className
        ) {
            const select =
                $('<select>')
                    .addClass(
                        'preload-editor-tool-select'
                    );

            if (className) {
                select.addClass(className);
            }

            options.forEach(
                option => {
                    $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                }
            );

            return select;
        },

        updateEditorToolVariables() {
            if (!this.editorTools) {
                return;
            }

            const variables =
                this.getToolVariables();

            const current =
                this.editorTools
                    .variableSelect
                    .val();

            const currentCondition =
                this.editorTools
                    .conditionVariableSelect
                    .val();

            const populate = (
                select,
                value
            ) => {
                select.empty();

                variables.forEach(
                    name => {
                        $('<option>')
                            .attr(
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                );

                if (
                    value &&
                    variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                        variables[0]
                    );
                }
            };

            populate(
                this.editorTools.variableSelect,
                current
            );

            populate(
                this.editorTools.conditionVariableSelect,
                currentCondition
            );
        },

        updateConditionVariableVisibility() {
            if (!this.editorTools) {
                return;
            }

            const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();

            this.editorTools
                .conditionVariableWrap
                .toggle(
                    type === 'if'
                );
        },

        renderEditorTools() {
            const tools =
                $('<div>')
                    .addClass(
                        'preload-editor-tools'
                    );

            const wrapGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );

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

            const variableGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                    );

            $('<span>')
                .addClass(
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);

            const variableSelect =
                this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );

            variableGroup.append(
                variableSelect,

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

            const conditionGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );

            $('<span>')
                .addClass(
                    'preload-editor-tool-label'
                )
                .text('Insert condition')
                .appendTo(conditionGroup);

            const conditionTypeSelect =
                this.createToolSelect(
                    [
                        {
                            value: 'if',
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                );

            const conditionVariableSelect =
                this.createToolSelect(
                    [],
                    'preload-editor-condition-variable-select'
                );

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

            const insertCondition =
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );

            conditionTypeSelect.on(
                'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
            );

            conditionGroup.append(
                conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );

            tools.append(
                wrapGroup,
                variableGroup,
                conditionGroup
            );

            this.editorTools = {
                root: tools,
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };

            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();

            return tools;
        },

        updateEditorTools() {
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
        },

        // =========================================================
        // Syntax highlighting
        // =========================================================

        getKnownVariables() {
            const known =
                new Set(['PAGE']);

            const fields =
                this.state.config &&
                this.state.config.fields;

            if (
                fields &&
                typeof fields === 'object'
            ) {
                Object.keys(fields).forEach(
                    name => {
                        known.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }

            return known;
        },

        createSyntaxDecorations(
            state,
            Decoration
        ) {
            const decorations = [];
            const source =
                state.doc.toString();

            const knownVariables =
                this.getKnownVariables();

            const variablePattern =
                /%%([A-Za-z0-9_-]+)%%/g;

            let match;

            while (
                (
                    match =
                        variablePattern.exec(source)
                ) !== null
            ) {
                const name =
                    match[1].toUpperCase();

                const known =
                    knownVariables.has(name);

                decorations.push(
                    Decoration.mark({
                        class: [
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );
            }

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

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

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

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

                const type =
                    match[1].toLowerCase();

                if (
                    type !== 'if' &&
                    type !== 'elseif'
                ) {
                    continue;
                }

                const expression =
                    match[2];

                const expressionStart =
                    match.index +
                    match[0].indexOf(
                        expression
                    );

                const expressionPattern =
                    /[A-Za-z0-9_-]+/g;

                let expressionMatch;

                while (
                    (
                        expressionMatch =
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();

                    if (
                        !knownVariables.has(name)
                    ) {
                        continue;
                    }

                    const start =
                        expressionStart +
                        expressionMatch.index;

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

            return Decoration.set(
                decorations,
                true
            );
        },

        async installSyntaxHighlighting(view) {
            await mw.loader.using(
                'ext.CodeMirror.v6.lib'
            );

            const require =
                mw.loader.require;

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

            const syntaxField =
                StateField.define({
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),

                    update: (
                        decorations,
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,

                    provide: field =>
                        EditorView.decorations.from(
                            field
                        )
                });

            view.dispatch({
                effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });

            this.editor.syntaxField =
                syntaxField;
        },

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

                    const cleanup = () => {
                        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;
                            cleanup();

                            const view =
                                cm.view;

                            const inputHandler =
                                () => {
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();

                                    this.markPreloadDirty();

                                    this.reanalyze();

                                    this.renderVariablesBySelector();
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();

                                    this.saveDraft();
                                };

                            view.dom.addEventListener(
                                'input',
                                inputHandler
                            );

                            view.dom.classList.add(
                                'preload-editor-codemirror'
                            );

                            const wrapper =
                                view.dom.closest(
                                    '.ext-codemirror-wrapper'
                                );

                            if (wrapper) {
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }

                            this.editor = {
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };

                            this.editorView =
                                view;

                            this.state.preloadContent =
                                view.state.doc.toString();

                            try {
                                await this.installSyntaxHighlighting(
                                    view
                                );

                                if (
                                    this.state.dirty
                                ) {
                                    this.saveDraft();
                                }

                                resolve(view);
                            } catch (error) {
                                reject(error);
                            }
                        };

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

                            try {
                                loader(textarea);
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };

                    mw.hook(
                        'dev.CCM.ready'
                    ).add(onReady);

                    mw.hook(
                        'dev.CCM.load'
                    ).add(onLoad);
                }
            );
        },

        // =========================================================
        // Main UI
        // =========================================================

        init() {
            const root =
                $('#mw-content-text');

            if (!root.length) {
                return;
            }

            this.root =
                $('<div>')
                    .attr(
                        'id',
                        'preload-editor'
                    )
                    .addClass(
                        'preload-editor'
                    );

            root.append(this.root);

            this.renderShell();

            this.restoreDraft();

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

            const loader =
                this.createSection('Preload');

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

            titleInput.on(
                'input.preloadEditor',
                () => {
                    this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();

                    if (
                        this.state.dirty &&
                        this.state.mode === 'new'
                    ) {
                        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();
    });

}(mediaWiki, jQuery));