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

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

MediaWiki interface page
ReisuDesign (talk | contribs)
No edit summary
ReisuDesign (talk | contribs)
No edit summary
 
(20 intermediate revisions by the same user not shown)
Line 3: Line 3:


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


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


Line 22: 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: {}
                    };
                }
 
                const parsed = JSON.parse(raw);


        async getPage(title) {
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            const response = await new mw.Api().get({
                    return {
                action: 'query',
                        active: null,
                prop: 'revisions',
                        drafts: {}
                titles: title,
                    };
                rvprop: 'content',
                 }
                rvslots: 'main',
                 formatversion: 2
            });


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


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


            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,
        getDraftSnapshot() {
                srnamespace: 10,
             let content = this.getEditorContent();
                formatversion: 2
             });


             return response?.query?.search || [];
             if (!this.editorView && !content) {
        },
                content = this.state.preloadContent || '';
            }


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


             if (createOnly) params.createonly = true;
             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 new mw.Api().postWithToken('csrf', params);
             return {
        },
                version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,


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


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


        findVariables(content) {
                selectedVariable: String(this.state.selectedVariable || 'PAGE'),
            const variables = [];
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
            let match;


            while ((match = pattern.exec(content)) !== null) {
                deletedVariables: Array.isArray(this.state.deletedVariables)
                const name = match[1].toUpperCase();
                    ? this.state.deletedVariables.slice()
                if (!variables.includes(name)) variables.push(name);
                    : [],
            }


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


         findConditions(content) {
         updateLocalDraftStatus(message, type) {
             const conditions = [];
             if (!this.localDraftStatus) {
             const pattern =
                return;
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
             }
             let match;
 
            this.localDraftStatus.removeClass(
                 'is-saved',
                'is-warning',
                'is-error',
                'is-empty'
             );


             while ((match = pattern.exec(content)) !== null) {
             if (type) {
                 conditions.push({
                 this.localDraftStatus.addClass('is-' + type);
                    type: match[1].toLowerCase(),
                    expression: match[2].trim(),
                    index: match.index
                });
             }
             }


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


         findConditionVariables(content) {
         formatLocalDraftTime(timestamp) {
             const variables = [];
             if (!timestamp) {
                return '';
            }


             this.findConditions(content).forEach(condition => {
             try {
                if (condition.type !== 'if' &&
                return new Date(timestamp).toLocaleTimeString([], {
                     condition.type !== 'elseif') return;
                    hour: '2-digit',
                    minute: '2-digit',
                     second: '2-digit'
                });
            } catch (error) {
                return '';
            }
        },


                 const matches =
        updateLocalDraftIndicator() {
                    condition.expression.match(/[A-Za-z0-9_-]+/g) || [];
            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'
                );


                 matches.forEach(name => {
                 return;
                    name = name.toUpperCase();
             }
                    if (!variables.includes(name)) variables.push(name);
                });
             });


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


         analyzePreload(content) {
         saveDraft() {
             return {
             if (!this.state.dirty) {
                variables: this.findVariables(content),
                 return false;
                conditions: this.findConditions(content),
             }
                 conditionVariables: this.findConditionVariables(content)
             };
        },


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


        emptyConfig() {
             storage.drafts[id] = snapshot;
             return {
             storage.active = id;
                settings: { incomplete: 'add-stub' },
                fields: {
                    PAGE: {
                        label: 'Page Name',
                        description: 'Name of the page.',
                        type: 'page',
                        required: true,
                        namespace: 'Main',
                        'allow-new': true
                    }
                }
             };
        },


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


             if (!config.settings ||
             if (saved) {
                 typeof config.settings !== 'object' ||
                this.state.localDraftSavedAt = snapshot.savedAt;
                 Array.isArray(config.settings)) {
                 this.state.localDraftAvailable = true;
                 config.settings = {};
                 this.updateLocalDraftIndicator();
            } else {
                 this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
             }
             }


             if (!config.fields ||
             return saved;
                typeof config.fields !== 'object' ||
        },
                Array.isArray(config.fields)) {
 
                 config.fields = {};
        clearDraft(title) {
            const storage = this.getDraftStorage();
            const id = this.getDraftId(title);
 
            if (storage.drafts && storage.drafts[id]) {
                 delete storage.drafts[id];
             }
             }


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


             return config;
             this.setDraftStorage(storage);
 
            this.state.localDraftSavedAt = null;
            this.state.localDraftAvailable = false;
 
            this.updateLocalDraftIndicator();
         },
         },


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


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


        prepareConfigForVariables(config, analysis) {
            if (storage.active && storage.drafts[storage.active]) {
            config = this.normalizeConfig(config);
                return {
                    id: storage.active,
                    draft: storage.drafts[storage.active]
                };
            }


             const existing = config.fields || {};
             let latestId = null;
             const fields = {};
             let latestDraft = null;


             fields.PAGE = existing.PAGE || {
             Object.entries(storage.drafts).forEach(([id, draft]) => {
                label: 'Page Name',
                 if (!draft || typeof draft !== 'object') {
                description: 'Name of the page.',
                    return;
                 type: 'page',
                 }
                required: true,
                namespace: 'Main',
                 'allow-new': true
            };


            analysis.variables.forEach(name => {
                 if (
                 if (name === 'PAGE') return;
                     !latestDraft ||
                fields[name] =
                     (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                     existing[name] ||
                ) {
                     this.createDefaultField(name, analysis);
                    latestId = id;
                    latestDraft = draft;
                }
             });
             });


             Object.keys(existing).forEach(name => {
             if (!latestDraft) {
                 const upper = name.toUpperCase();
                 return null;
                if (!fields[upper]) fields[upper] = existing[name];
             }
             });


             config.fields = fields;
             return {
             return config;
                id: latestId,
                draft: latestDraft
             };
         },
         },


         validateConfig(config, analysis) {
         async restoreDraft() {
             const errors = [];
             const result = this.getMostRecentDraft();
            const warnings = [];


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


             if (!config.fields ||
             const draft = result.draft;
                typeof config.fields !== 'object' ||
            const title = String(draft.preloadTitle || '').trim();
                Array.isArray(config.fields)) {
            const displayTitle = title || 'an untitled preload';
                return {
                    valid: false,
                    errors: ['"fields" must be an object.'],
                    warnings
                };
            }


             const configured =
             const savedAt = draft.savedAt
                 Object.keys(config.fields).map(name => name.toUpperCase());
                 ? new Date(draft.savedAt).toLocaleString()
                : '';


             analysis.variables.forEach(name => {
             const message =
                 if (!configured.includes(name)) {
                 'Preload Editor found unsaved local work for ' +
                    errors.push(
                displayTitle +
                        'Variable "' + name + '" is not configured.'
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                    );
                 '\n\nRestore it?';
                 }
            });


             configured.forEach(name => {
             const restore = await this.createConfirmDialog(
                 if (!analysis.variables.includes(name)) {
                 'Restore unsaved work',
                    warnings.push(
                message,
                        'Field "' + name + '" is not used by the preload.'
                'Restore',
                    );
                'Discard'
                }
             );
             });


             if (!configured.includes('PAGE')) {
             if (!restore) {
                 errors.push('PAGE must always be configured.');
                 this.clearDraft(title);
                return false;
             }
             }


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


                if (!field.type) {
            if (
                     warnings.push(
                draft.config &&
                         'Field "' + name + '" has no type.'
                typeof draft.config === 'object' &&
                !Array.isArray(draft.config)
            ) {
                try {
                     config = this.normalizeConfig(
                         JSON.parse(JSON.stringify(draft.config))
                     );
                     );
                 }
                 } catch (error) {
 
                     console.warn(
                if ((field.type === 'select' ||
                         'Preload Editor: Could not restore local config.',
                    field.type === 'multiselect') &&
                         error
                    !field.source &&
                    !Array.isArray(field.options)) {
                     warnings.push(
                         'Field "' + name + '" is a ' +
                        field.type +
                         ' without a source or manual options.'
                     );
                     );
                 }
                 }
             });
             }


             return {
             const hasDirtyFlags =
                 valid: !errors.length,
                 typeof draft.dirtyPreload === 'boolean' ||
                 errors,
                 typeof draft.dirtyConfig === 'boolean';
                warnings
            };
        },


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


        transformationObject(transform, prefix, suffix, from, to) {
                variables: Array.isArray(draft.variables)
            if (!transform) return null;
                    ? draft.variables.slice()
                    : [],


            switch (transform) {
                conditions: Array.isArray(draft.conditions)
                case 'remove-prefix':
                     ? draft.conditions.slice()
                     return prefix
                    : [],
                        ? { transform, prefix }
                        : null;


                 case 'remove-suffix':
                 selectedVariable: String(draft.selectedVariable || 'PAGE'),
                    return suffix
                        ? { transform, suffix }
                        : null;


                 case 'replace':
                 deletedVariables: Array.isArray(draft.deletedVariables)
                     return from === ''
                     ? draft.deletedVariables
                        ? null
                        .map(name => String(name).toUpperCase())
                        : { transform, from, to: to || '' };
                        .filter(name => name !== 'PAGE')
                    : [],


                 default:
                 mode: draft.mode || 'edit',
                    return null;
            }
        },


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


        createSection(title, className) {
                dirtyPreload: hasDirtyFlags
            const section = $('<section>')
                    ? !!draft.dirtyPreload
                .addClass('preload-editor-section');
                    : true,


            if (className) section.addClass(className);
                dirtyConfig: hasDirtyFlags
                    ? !!draft.dirtyConfig
                    : true,


            $('<h2>')
                localDraftSavedAt: Number(draft.savedAt) || null,
                .addClass('preload-editor-section-title')
                 localDraftAvailable: true
                 .text(title)
            };
                .appendTo(section);


             return section;
            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;
         },
         },


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


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


             return button;
             const page =
        },
                response &&
                response.query &&
                response.query.pages &&
                response.query.pages[0];


        fieldRow(label, input, description) {
            if (!page || page.missing) {
            const row = $('<div>')
                 return null;
                 .addClass('preload-editor-field');
            }


             $('<label>')
             const content =
                 .addClass('preload-editor-label')
                 page.revisions &&
                 .text(label)
                 page.revisions[0] &&
                 .appendTo(row);
                 page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;


             if (description) {
             return {
                 $('<div>')
                 title: page.title || title,
                    .addClass('preload-editor-help')
                content: typeof content === 'string' ? content : '',
                    .text(description)
                contentmodel: page.contentmodel || 'wikitext'
                    .appendTo(row);
            };
            }
        },


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


         textInput(value, placeholder) {
         async searchPages(query) {
             return $('<input>')
             const response = await new mw.Api().get({
                .attr({
                action: 'query',
                    type: 'text',
                list: 'search',
                    value: value == null ? '' : value,
                srsearch: query,
                    placeholder: placeholder || ''
                srlimit: 10,
                 })
                srnamespace: 10,
                 .addClass('preload-editor-input');
                 formatversion: 2
            });
 
            return (
                 response &&
                response.query &&
                response.query.search
            ) || [];
         },
         },


         textarea(value) {
         /*
             return $('<textarea>')
        * Save a page.
                 .val(value == null ? '' : value)
        *
                 .addClass('preload-editor-textarea');
        * 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;
            }


        checkbox(checked) {
             return new mw.Api().postWithToken('csrf', params);
             return $('<input>')
                .attr('type', 'checkbox')
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
         },
         },


         select(options, value) {
         /*
            const select = $('<select>')
        * Change the content model of an existing page.
                .addClass('preload-editor-select');
        *
 
        * This is the API equivalent of using
            options.forEach(option => {
        * Special:ChangeContentModel manually.
                $('<option>')
        *
                    .attr('value', option.value)
        * The page must already exist.
                    .text(option.label)
        */
                    .prop(
        async changeContentModel(title, model, summary) {
                        'selected',
            return new mw.Api().postWithToken('csrf', {
                        String(option.value) === String(value === undefined ? '' : value)
                action: 'changecontentmodel',
                    )
                title,
                    .appendTo(select);
                model,
                reason: summary || 'Changed content model with Preload Editor'
             });
             });
            return select;
         },
         },


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


        destroyEditor() {
             if (!page) {
             if (!this.editor) {
                 return this.savePage(
                 this.editorView = null;
                    title,
                this.editorTools = null;
                    content,
                 return;
                    summary,
                    true,
                    'json'
                 );
             }
             }


             const { view, inputHandler } = this.editor;
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
 
                 await this.changeContentModel(
            if (view && inputHandler) {
                    title,
                 view.dom.removeEventListener('input', inputHandler);
                    'json',
                    'Changed preload config content model to JSON'
                );
             }
             }


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


            this.editor = null;
        // =========================================================
            this.editorView = null;
        // Config import helpers
            this.editorTools = null;
         // =========================================================
         },


         getEditorView() {
         /*
             return this.editorView;
        * 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(/\/+$/, '');


        getEditorContent() {
             if (/\/config\.json$/i.test(title)) {
             if (this.editorView && this.editorView.state) {
                 return title;
                 return this.editorView.state.doc.toString();
             }
             }


             return this.state.preloadContent || '';
             return title + '/config.json';
         },
         },


         setEditorContent(content) {
         /*
             content = String(content || '');
        * 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
                );


            if (!this.editorView) {
                 return null;
                this.state.preloadContent = content;
                 return;
             }
             }
        },


            const current = this.editorView.state.doc.toString();
        /*
             if (current === content) return;
        * Normalize imported field names to the same uppercase
        * convention used throughout the editor.
        */
        getImportableFields(sourceConfig) {
             const fields = sourceConfig && sourceConfig.fields;


             this.editorView.dispatch({
             if (
                 changes: {
                !fields ||
                     from: 0,
                typeof fields !== 'object' ||
                     to: this.editorView.state.doc.length,
                Array.isArray(fields)
                     insert: content
            ) {
                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;
                 }
                 }
            });
        },


        getEditorSelection() {
                const clone = this.cloneConfigField(field);
            if (!this.editorView?.state) return null;


            const selection = this.editorView.state.selection.main;
                if (!clone) {
                    return;
                }


            return {
                 result[upper] = clone;
                 from: selection.from,
             });
                to: selection.to,
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
             };
        },


        focusEditor() {
             return result;
             if (this.editorView) this.editorView.focus();
         },
         },


         insertEditorText(
         /*
            text,
        * Show the variable-selection dialog after a source
            selectionFrom,
        * config has been loaded.
            selectionTo,
        *
            cursorPosition
        * Resolves:
         ) {
        *  null -> cancelled
             if (!this.editorView) return;
        *  []  -> 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 view = this.editorView;
                const overlay = $('<div>')
            const selection = view.state.selection.main;
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );


            const from =
                const box = $('<div>')
                selectionFrom === undefined
                     .addClass(
                     ? selection.from
                        'preload-editor-prompt preload-editor-import-dialog'
                     : selectionFrom;
                     );


            const to =
                 $('<h2>')
                 selectionTo === undefined
                     .text('Import variable definitions')
                     ? selection.to
                     .appendTo(box);
                     : selectionTo;


            const cursor =
                 $('<p>')
                 cursorPosition === undefined
                     .text(
                     ? from + text.length
                        'Choose which variable definitions to import from "' +
                     : cursorPosition;
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                    )
                     .appendTo(box);


            view.dispatch({
                if (!names.length) {
                changes: { from, to, insert: text },
                    $('<div>')
                selection: { anchor: cursor }
                        .addClass(
            });
                            'preload-editor-empty preload-editor-import-empty'
                        )
                        .text(
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);


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


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


        wrapSelectionWithVariable() {
                    emptyButtons.append(close);
            const selected = this.getEditorSelection();
                    box.append(emptyButtons);
                    overlay.append(box);


            if (!selected || selected.from === selected.to) {
                    $(document.body).append(overlay);
                this.focusEditor();
                return;
            }


            const replacement =
                    overlay.attr('tabindex', '-1');
                '%%' + selected.text + '%%';
                    overlay.trigger('focus');


            this.insertEditorText(
                    return;
                replacement,
                 }
                selected.from,
                selected.to,
                 selected.from + replacement.length
            );
        },


        insertVariable(name) {
                const search = this.textInput('', 'Search variables...')
            name = String(name || '').trim().toUpperCase();
                    .addClass('preload-editor-import-search');
            if (!name) return;


            const selected = this.getEditorSelection();
                const searchWrap = $('<div>')
            if (!selected) return;
                    .addClass('preload-editor-import-search-wrap')
                    .append(search);


            const text = '%%' + name + '%%';
                box.append(searchWrap);


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


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


            const selected = this.getEditorSelection();
                        updateSummary();
            if (!selected) return;
                    }
                );


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


            switch (type) {
                controls.append(selectAll, deselectAll);
                 case 'if': {
                 box.append(controls);
                    const opening = '<!-- @if ' + variable + ' -->';
                    const closing = '<!-- @endif -->';


                    if (selected.from !== selected.to) {
                const list = $('<div>')
                        text =
                    .addClass('preload-editor-import-list');
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;
                        cursorOffset = text.length;
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;
                        cursorOffset = opening.length + 1;
                    }


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


                 case 'elseif':
                 names.forEach(name => {
                     text = '<!-- @elseif -->';
                     const existing = !!localFields[name];
                     cursorOffset = text.length;
                     const field = fields[name];
                    break;


                case 'else':
                     const type = field && field.type
                     text = '<!-- @else -->';
                        ? String(field.type)
                    cursorOffset = text.length;
                        : 'text';
                    break;


                case 'endif':
                     const label = field && field.label
                     text = '<!-- @endif -->';
                        ? String(field.label)
                    cursorOffset = text.length;
                        : this.humanizeName(name);
                    break;


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


            this.insertEditorText(
                    const checkbox = this.checkbox(false)
                text,
                        .attr('data-import-variable', name)
                selected.from,
                        .addClass('preload-editor-import-checkbox');
                selected.to,
 
                selected.from + cursorOffset
                    const content = $('<span>')
            );
                        .addClass('preload-editor-import-content');
        },


        getToolVariables() {
                    const header = $('<span>')
            const variables = new Set(['PAGE']);
                        .addClass('preload-editor-import-header');


            if (this.analysis && this.analysis.variables) {
                    $('<strong>')
                this.analysis.variables.forEach(name => {
                        .text(name)
                    variables.add(String(name).toUpperCase());
                        .appendTo(header);
                });
            }


            return Array.from(variables);
                    $('<span>')
        },
                        .addClass('preload-editor-import-type')
                        .text(type)
                        .appendTo(header);


        createToolSelect(options, className) {
                    const meta = $('<span>')
            const select = $('<select>')
                        .addClass('preload-editor-import-meta');
                .addClass('preload-editor-tool-select');


            if (className) select.addClass(className);
                    $('<span>')
                        .text(label)
                        .appendTo(meta);


            options.forEach(option => {
                    const status = $('<span>')
                $('<option>')
                        .addClass('preload-editor-import-status')
                    .attr('value', option.value)
                        .toggleClass('is-existing', existing)
                    .text(option.label)
                        .toggleClass('is-new', !existing)
                    .appendTo(select);
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');
            });


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


        updateEditorToolVariables() {
                box.append(list);
            if (!this.editorTools) return;


            const variables = this.getToolVariables();
                const summary = $('<div>')
            const current =
                    .addClass('preload-editor-import-summary');
                this.editorTools.variableSelect.val();
            const currentCondition =
                this.editorTools.conditionVariableSelect.val();


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


                variables.forEach(name => {
                    const existingSelected = list
                    $('<option>')
                        .find('input[type="checkbox"]:checked')
                         .attr('value', name)
                         .filter(function () {
                        .text(name)
                            const name = $(this).attr(
                        .appendTo(select);
                                'data-import-variable'
                });
                            );


                if (value && variables.includes(value)) {
                            return !!localFields[name];
                    select.val(value);
                        }).length;
                } else if (variables.length) {
                    select.val(variables[0]);
                }
            };


            populate(
                    let text =
                this.editorTools.variableSelect,
                        selected +
                current
                        ' ' +
            );
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';


            populate(
                    if (existingSelected) {
                this.editorTools.conditionVariableSelect,
                        text +=
                currentCondition
                            ' ' +
            );
                            existingSelected +
        },
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


        updateConditionVariableVisibility() {
                    summary.text(text);
            if (!this.editorTools) return;


            const type =
                    importButton.prop('disabled', selected === 0);
                 this.editorTools.conditionTypeSelect.val();
                 };


            this.editorTools.conditionVariableWrap.toggle(
                 const filterRows = () => {
                 type === 'if'
                    const query = String(search.val() || '')
            );
                        .trim()
        },
                        .toLowerCase();


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


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


            const wrapGroup = $('<div>')
                 search.on(
                 .addClass(
                     'input.preloadEditor',
                     'preload-editor-tool-group preload-editor-tool-group-wrap'
                    filterRows
                 );
                 );


            wrapGroup.append(
                 list.on(
                 this.createButton(
                     'change.preloadEditor',
                     'Wrap selection with %%',
                     'input[type="checkbox"]',
                     'preload-editor-tool-button',
                     updateSummary
                     () => this.wrapSelectionWithVariable()
                )
            );
 
            // Insert existing variable
 
            const variableGroup = $('<div>')
                .addClass(
                    'preload-editor-tool-group preload-editor-tool-group-variable'
                 );
                 );


            $('<span>')
                const buttons = $('<div>')
                .addClass('preload-editor-tool-label')
                    .addClass('preload-editor-prompt-buttons');
                .text('Insert existing variable')
                .appendTo(variableGroup);


            const variableSelect = this.createToolSelect(
                const cancel = this.createButton(
                [],
                    'Cancel',
                'preload-editor-variable-select'
                    '',
            );
                    () => {
                        overlay.remove();
                        resolve(null);
                    }
                );


            variableGroup.append(
                 const importButton = this.createButton(
                variableSelect,
                     'Import selected',
                 this.createButton(
                     'preload-editor-button-primary',
                     'Insert',
                     () => {
                     'preload-editor-tool-button',
                        const selected = [];
                     () => this.insertVariable(variableSelect.val())
                )
            );


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


            const conditionGroup = $('<div>')
                        overlay.remove();
                .addClass(
                        resolve(selected);
                     'preload-editor-tool-group preload-editor-tool-group-condition'
                     }
                 );
                 );


            $('<span>')
                 buttons.append(cancel, importButton);
                 .addClass('preload-editor-tool-label')
                 box.append(summary, buttons);
                 .text('Insert condition')
                 overlay.append(box);
                 .appendTo(conditionGroup);


            const conditionTypeSelect = this.createToolSelect(
                $(document.body).append(overlay);
                [
                    { 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(
                overlay.attr('tabindex', '-1');
                [],
                 overlay.trigger('focus');
                 'preload-editor-condition-variable-select'
            );


            const conditionVariableWrap = $('<span>')
                updateSummary();
                 .addClass(
                 search.trigger('focus');
                    'preload-editor-condition-variable'
                )
                .append(conditionVariableSelect);


            const insertCondition = this.createButton(
                const close = event => {
                'Insert',
                    if (event.key === 'Escape') {
                'preload-editor-tool-button',
                        cancel.trigger('click');
                () => this.insertCondition(
                     }
                    conditionTypeSelect.val(),
                 };
                     conditionVariableSelect.val()
                 )
            );


            conditionTypeSelect.on(
                overlay.on(
                'change.preloadEditor',
                    'keydown.preloadEditor',
                 () => this.updateConditionVariableVisibility()
                    close
            );
                 );


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


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


             this.editorTools = {
             if (!source) {
                 root: tools,
                 return;
                variableSelect,
             }
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
             };


             this.updateEditorToolVariables();
             const configTitle = this.normalizeConfigTitle(source);
            this.updateConditionVariableVisibility();


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


        updateEditorTools() {
            try {
            this.updateEditorToolVariables();
                const page = await this.getPage(configTitle);
            this.updateConditionVariableVisibility();
        },


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


        getKnownVariables() {
                let sourceConfig;
            const known = new Set(['PAGE']);
            const fields = this.state.config?.fields;


            if (fields && typeof fields === 'object') {
                try {
                 Object.keys(fields).forEach(name => {
                    sourceConfig = JSON.parse(page.content);
                     known.add(String(name).toUpperCase());
                 } catch (error) {
                 });
                     throw new Error(
            }
                        'The source config.json contains invalid JSON: ' +
                        error.message
                    );
                 }


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


        createSyntaxDecorations(state, Decoration) {
                if (
            const decorations = [];
                    !sourceConfig.fields ||
            const source = state.doc.toString();
                    typeof sourceConfig.fields !== 'object' ||
            const knownVariables = this.getKnownVariables();
                    Array.isArray(sourceConfig.fields)
                ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }


            const variablePattern = /%%([A-Za-z0-9_-]+)%%/g;
                const fields = this.getImportableFields(sourceConfig);
            let match;


            while ((match = variablePattern.exec(source)) !== null) {
                 const selected =
                 const name = match[1].toUpperCase();
                    await this.createImportDefinitionsDialog(
                const known = knownVariables.has(name);
                        configTitle,
                        fields
                    );


                 decorations.push(
                 if (selected === null) {
                     Decoration.mark({
                     this.setStatus(
                         class: [
                         'Variable import cancelled.',
                            'preload-editor-syntax-variable',
                         'warning'
                            known
                     );
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                         ].join(' ')
                    }).range(
                        match.index,
                        match.index + match[0].length
                     )
                );
            }


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


            while ((match = conditionPattern.exec(source)) !== null) {
                if (!selected.length) {
                decorations.push(
                     this.setStatus(
                     Decoration.mark({
                         'No variable definitions were imported.',
                         class: 'preload-editor-syntax-condition'
                         'warning'
                    }).range(
                     );
                        match.index,
                         match.index + match[0].length
                     )
                );


                const directiveStart =
                     return;
                     match.index + match[0].indexOf('@');
                }


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


                 const type = match[1].toLowerCase();
                 if (!this.state.config.fields) {
                    this.state.config.fields = {};
                }


                 if (type !== 'if' && type !== 'elseif') continue;
                 const imported = [];
                const replaced = [];


                 const expression = match[2];
                 selected.forEach(name => {
                const expressionStart =
                     if (name === 'PAGE') {
                     match.index + match[0].indexOf(expression);
                        return;
                    }


                const expressionPattern = /[A-Za-z0-9_-]+/g;
                    const field = fields[name];
                let expressionMatch;


                while (
                     if (!field) {
                     (expressionMatch =
                         return;
                        expressionPattern.exec(expression)) !== null
                    }
                ) {
                    const name =
                         expressionMatch[0].toUpperCase();


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


                     const start =
                     const clone = this.cloneConfigField(field);
                        expressionStart + expressionMatch.index;


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


            return Decoration.set(decorations, true);
                    this.state.config.fields[name] = clone;
        },


        async installSyntaxHighlighting(view) {
                    /*
            await mw.loader.using('ext.CodeMirror.v6.lib');
                    * 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
                            );
                    }
                });


            const require = mw.loader.require;
                /*
            const {
                * Keep PAGE automatic regardless of what the
                StateField,
                * imported config contained.
                StateEffect,
                */
                 EditorView,
                 this.state.config.fields.PAGE =
                Decoration
                    this.getAutomaticPageField();
            } = require('ext.CodeMirror.v6.lib');


            const syntaxField = StateField.define({
                 this.markConfigDirty();
                 create: state =>
                    this.createSyntaxDecorations(state, Decoration),


                 update: (decorations, transaction) =>
                 /*
                     transaction.docChanged
                * Keep the current selection when possible.
                         ? this.createSyntaxDecorations(
                * Otherwise select the first imported definition.
                            transaction.state,
                */
                            Decoration
                const selectedStillExists = !!(
                        )
                     this.state.config.fields[
                        : decorations,
                         this.state.selectedVariable
                    ]
                );


                 provide: field =>
                 if (
                     EditorView.decorations.from(field)
                    !selectedStillExists ||
            });
                    this.state.selectedVariable === 'PAGE'
                ) {
                     this.state.selectedVariable =
                        selected[0] ||
                        'PAGE';
                }


            view.dispatch({
                 this.reanalyze();
                 effects: StateEffect.appendConfig.of(syntaxField)
            });


            this.editor.syntaxField = syntaxField;
                this.renderVariablesBySelector();
        },
                this.renderVariableConfigurationBySelector();
                this.renderAnalysisBySelector();
                this.updateEditorTools();


        // CodeMirror mounting
                this.saveDraft();


        async mountCodeMirror(textarea) {
                let status =
            return new Promise((resolve, reject) => {
                    'Imported ' +
                let settled = false;
                    selected.length +
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                    '.';


                 const cleanup = () => {
                 if (replaced.length) {
                     mw.hook('dev.CCM.ready').remove(onReady);
                     status +=
                    mw.hook('dev.CCM.load').remove(onLoad);
                        ' Replaced: ' +
                 };
                        replaced.join(', ') +
                        '.';
                 }


                 const onReady = async cm => {
                 this.setStatus(status, 'success');
                    if (
                        settled ||
                        !cm ||
                        cm.textarea !== textarea ||
                        !cm.view
                    ) return;


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


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


                     const inputHandler = () => {
                mw.notify(
                         this.state.preloadContent =
                    error.message ||
                            view.state.doc.toString();
                        'Could not import variable definitions.',
                     {
                         type: 'error'
                    }
                );
            }
        },


                        this.state.dirty = true;
        // =========================================================
                        this.reanalyze();
        // Preload parsing
                        this.renderVariablesBySelector();
        // =========================================================
                        this.renderAnalysisBySelector();
                        this.renderConfigPreviewBySelector();
                        this.updateEditorTools();
                    };


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


                    view.dom.classList.add(
            return match
                        'preload-editor-codemirror'
                ? match[1].trim()
                    );
                : String(source || '').trim();
        },


                    const wrapper =
        findVariables(content) {
                        view.dom.closest(
            const variables = [];
                            '.ext-codemirror-wrapper'
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                        );
 
            let match;


                    if (wrapper) {
            while ((match = pattern.exec(content)) !== null) {
                        wrapper.classList.add(
                const name = match[1].toUpperCase();
                            'preload-editor-codemirror-wrapper'
                        );
                    }


                    this.editor = {
                if (!variables.includes(name)) {
                        cm,
                    variables.push(name);
                        view,
                }
                        textarea,
            }
                        inputHandler
                    };


                    this.editorView = view;
            return variables;
                    this.state.preloadContent =
        },
                        view.state.doc.toString();


                    try {
        findConditions(content) {
                        await this.installSyntaxHighlighting(view);
            const conditions = [];
                        resolve(view);
            const pattern =
                    } catch (error) {
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                        reject(error);
                    }
                };


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


                    try {
            while ((match = pattern.exec(content)) !== null) {
                        loader(textarea);
                conditions.push({
                    } catch (error) {
                    type: match[1].toLowerCase(),
                        settled = true;
                    expression: match[2].trim(),
                        cleanup();
                     index: match.index
                        reject(error);
                 });
                     }
            }
                 };


                mw.hook('dev.CCM.ready').add(onReady);
             return conditions;
                mw.hook('dev.CCM.load').add(onLoad);
             });
         },
         },


         // Main UI
         findConditionVariables(content) {
            const variables = [];


        init() {
            this.findConditions(content).forEach(condition => {
            const root = $('#mw-content-text');
                if (
            if (!root.length) return;
                    condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }


            this.root = $('<div>')
                const matches =
                .attr('id', 'preload-editor')
                    condition.expression.match(
                .addClass('preload-editor');
                        /[A-Za-z0-9_-]+/g
                    ) || [];


            root.append(this.root);
                matches.forEach(name => {
            this.renderShell();
                    name = name.toUpperCase();
        },


        renderShell() {
                    if (!variables.includes(name)) {
            this.destroyEditor();
                        variables.push(name);
             this.root.empty();
                    }
                });
             });


             const loader = this.createSection('Preload');
             return variables;
        },


             const titleInput = this.textInput(
        analyzePreload(content) {
                 this.state.preloadTitle,
             return {
                 'Template:Example/Preload'
                variables: this.findVariables(content),
            ).attr('id', 'preload-editor-title-input');
                 conditions: this.findConditions(content),
                 conditionVariables:
                    this.findConditionVariables(content)
            };
        },


            const loadButton = this.createButton(
        // =========================================================
                'Load',
        // Config
                'preload-editor-button-primary',
        // =========================================================
                () => this.loadExisting(titleInput.val())
            );


             const newButton = this.createButton(
        getAutomaticPageField() {
                 'New',
             return {
                 '',
                 label: 'Page Name',
                 () => this.startNew()
                 description: 'Name of the page.',
            );
                 type: 'page',
 
                required: true,
            const sampleButton = this.createButton(
                 namespace: 'Main',
                 'Load Sample Page',
                 'allow-new': true
                 '',
             };
                () => this.loadSamplePage()
        },
             );


             loader.append(
        emptyConfig() {
                 $('<div>')
             return {
                     .addClass('preload-editor-toolbar')
                 settings: {
                    .append(
                     incomplete: 'add-stub'
                        titleInput,
                },
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );


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


             this.status = $('<div>')
        normalizeConfig(config) {
                 .addClass('preload-editor-status');
             if (
                !config ||
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                 config = this.emptyConfig();
            }


             this.root.append(this.status);
             if (
 
                !config.settings ||
            this.workspace = $('<div>')
                typeof config.settings !== 'object' ||
                 .addClass('preload-editor-workspace');
                 Array.isArray(config.settings)
            ) {
                config.settings = {};
            }


             this.root.append(this.workspace);
             if (
             this.renderWelcome();
                !config.fields ||
        },
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
             ) {
                config.fields = {};
            }


        renderWelcome() {
            config.fields.PAGE =
            this.workspace.empty();
                this.getAutomaticPageField();


             const section = this.createSection('Get started');
             return config;
        },


             $('<p>')
        createDefaultField(name, analysis) {
                 .text(
             return {
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                label: this.humanizeName(name),
                )
                description: '',
                .appendTo(section);
                 type: analysis.conditionVariables.includes(name)
                     ? 'boolean'
                    : 'text'
            };
        },


             const tips = $('<ul>')
        humanizeName(name) {
                 .addClass('preload-editor-tips');
             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) {
                'Existing preload: loads the preload and its config.json if available.',
             config = this.normalizeConfig(config);
                'New preload: starts with the standard Preload Template structure.',
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
             ].forEach(text => {
                $('<li>').text(text).appendTo(tips);
            });


             section.append(tips);
             const existing = config.fields || {};
            this.workspace.append(section);
        },


        setStatus(message, type) {
            const deleted = new Set(
            if (!this.status) return;
                Array.isArray(this.state.deletedVariables)
 
                    ? this.state.deletedVariables.map(
            this.status.removeClass(
                        name => String(name).toUpperCase()
                'is-error',
                    )
                'is-success',
                    : []
                'is-warning',
                'is-loading'
             );
             );


             if (type) this.status.addClass('is-' + type);
             const fields = {};
            this.status.text(message || '');
        },


        // Load / create
            fields.PAGE =
                this.getAutomaticPageField();


        async loadExisting(title) {
            analysis.variables.forEach(name => {
            title = String(title || '').trim();
                if (
                    name === 'PAGE' ||
                    deleted.has(name)
                ) {
                    return;
                }


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


             this.setStatus('Loading preload...', 'loading');
             Object.keys(existing).forEach(name => {
                const upper = name.toUpperCase();


            try {
                 if (
                 const page = await this.getPage(title);
                    upper !== 'PAGE' &&
 
                    !fields[upper] &&
                if (!page) {
                     !deleted.has(upper)
                     const suggestions =
                ) {
                        await this.findSimilarPreloads(title);
                     fields[upper] =
 
                         existing[name];
                    this.renderMissingPage(title, suggestions);
                     this.setStatus(
                         'Preload not found.',
                        'warning'
                    );
                    return;
                 }
                 }
            });


                await this.loadDefinition(
            config.fields = fields;
                    page.title,
                    page.content
                );


                this.setStatus(
             return config;
                    'Preload loaded.',
                    'success'
                );
             } catch (error) {
                console.error('Preload Editor:', error);
                this.setStatus(
                    error.message || 'Could not load preload.',
                    'error'
                );
            }
         },
         },


         async findSimilarPreloads(title) {
         validateConfig(config, analysis) {
             let query = title
             const errors = [];
                .replace(/\/Preload$/i, '')
            const warnings = [];
                .trim();


             if (!query) query = title;
             if (
 
                !config ||
             try {
                typeof config !== 'object' ||
                 const results = await this.searchPages(query);
                Array.isArray(config)
             ) {
                 return {
                    valid: false,
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                };
            }


                 return results.filter(result =>
            if (
                    /\/Preload$/i.test(result.title)
                 !config.fields ||
                );
                typeof config.fields !== 'object' ||
             } catch (error) {
                Array.isArray(config.fields)
                 console.error(
             ) {
                     'Preload Editor search:',
                 return {
                     error
                    valid: false,
                 );
                     errors: [
                return [];
                        '"fields" must be an object.'
                    ],
                     warnings
                 };
             }
             }
        },


        renderMissingPage(title, suggestions) {
            const configured =
            this.workspace.empty();
                Object.keys(
                    config.fields
                ).map(
                    name =>
                        name.toUpperCase()
                );


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


             $('<p>')
             configured.forEach(name => {
                .text('No preload exists at "' + title + '".')
                if (!analysis.variables.includes(name)) {
                 .appendTo(section);
                    warnings.push(
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                    );
                 }
            });


             if (suggestions.length) {
             if (!configured.includes('PAGE')) {
                 $('<h3>')
                 errors.push(
                     .text('Similar preloads')
                     'PAGE must always be configured.'
                    .appendTo(section);
                );
            }


                 const list = $('<div>')
            Object.entries(config.fields).forEach(([name, field]) => {
                     .addClass('preload-editor-suggestions');
                 if (
 
                    !field ||
                 suggestions.forEach(result => {
                    typeof field !== 'object' ||
                     list.append(
                     Array.isArray(field)
                         this.createButton(
                 ) {
                            result.title,
                     errors.push(
                            'preload-editor-suggestion',
                         'Field "' +
                            () => this.loadExisting(result.title)
                        name +
                         )
                         '" must be an object.'
                     );
                     );
                });


                section.append(list);
                    return;
            }
                }


            section.append(
                if (!field.type) {
                this.createButton(
                    warnings.push(
                    'Create this preload',
                        'Field "' +
                     'preload-editor-button-primary',
                        name +
                     () => this.startNew(title)
                        '" 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.'
                        );
                    }


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


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


            this.state = {
                    if (
                preloadTitle: title,
                        field.filetext !== undefined &&
                preloadSource: '',
                        typeof field.filetext !== 'string'
                preloadContent: this.defaults.preload,
                    ) {
                config: this.emptyConfig(),
                        errors.push(
                variables: ['PAGE'],
                            'File field "' +
                conditions: [],
                            name +
                mode: 'new',
                            '" must have "filetext" as a string.'
                dirty: true
                        );
            };
                    }


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


            this.setStatus(
                    if (
                'Creating a new preload.',
                        !field.filename
                'success'
                    ) {
            );
                        warnings.push(
        },
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


        async loadSamplePage() {
                if (
            const result = await this.createPromptDialog(
                    (
                'Load Sample Page',
                        field.type === 'select' ||
                'Enter the title of a normal wiki page to use as the starting point.'
                        field.type === 'multiselect'
            );
                    ) &&
 
                    !field.source &&
            if (!result) return;
                    !Array.isArray(field.options)
 
                ) {
            this.setStatus(
                    warnings.push(
                'Loading sample page...',
                        'Field "' +
                'loading'
                        name +
            );
                        '" is a ' +
 
                        field.type +
            try {
                         ' without a source or manual options.'
                const page = await this.getPage(result);
 
                if (!page) {
                    throw new Error(
                         'Sample page not found: ' + result
                     );
                     );
                 }
                 }


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


                this.state = {
                    if (
                    preloadTitle: '',
                        field.filetext !== undefined &&
                     preloadSource: '',
                        typeof field.filetext !== 'string'
                    preloadContent: sample,
                     ) {
                    config: this.emptyConfig(),
                        errors.push(
                    variables: ['PAGE'],
                            'File field "' +
                    conditions: [],
                            name +
                    mode: 'new',
                            '" has an invalid "filetext" value.'
                     dirty: true
                        );
                };
                     }


                this.reanalyze();
                    if (
                 this.renderEditor();
                        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.setStatus(
            return {
                    'Sample page loaded.',
                 valid: !errors.length,
                    'success'
                errors,
                 );
                 warnings
             } catch (error) {
             };
                console.error(
        },
                    'Preload Editor sample:',
                    error
                );


                this.setStatus(
        // =========================================================
                    error.message ||
        // Transformation helpers
                        'Could not load sample page.',
        // =========================================================
                    'error'
 
                 );
        transformationObject(
            transform,
            prefix,
            suffix,
            from,
            to
        ) {
            if (!transform) {
                 return null;
             }
             }
        },


        convertSampleToPreload(source) {
            switch (transform) {
            let content = String(source || '').trim();
                case 'remove-prefix':
                    return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;
 
                case 'remove-suffix':
                    return suffix
                        ? {
                            transform,
                            suffix
                        }
                        : null;


            const include = content.match(
                case 'replace':
                /<includeonly>([\s\S]*?)<\/includeonly>/i
                    return from === ''
            );
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


             if (include) content = include[1].trim();
                default:
                    return null;
             }
        },


            content = content
        // =========================================================
                .replace(
        // UI helpers
                    /<noinclude>[\s\S]*?<\/noinclude>/gi,
        // =========================================================
                    ''
                )
                .trim();


             return (
        createSection(title, className) {
                '<includeonly>\n' +
             const section = $('<section>')
                content +
                 .addClass('preload-editor-section');
                '\n</includeonly>\n' +
                 '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },


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


                const box = $('<div>')
            $('<h2>')
                    .addClass('preload-editor-prompt');
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);


                $('<h2>')
            return section;
                    .text(title)
        },
                    .appendTo(box);


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


                 const input = this.textInput();
            if (className) {
                 button.addClass(className);
            }


                const buttons = $('<div>')
            if (callback) {
                    .addClass('preload-editor-prompt-buttons');
                 button.on(
 
                     'click.preloadEditor',
                 const cancel = this.createButton(
                     callback
                     'Cancel',
                    '',
                     () => {
                        overlay.remove();
                        resolve(null);
                    }
                 );
                 );
            }


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


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


                        overlay.remove();
            $('<label>')
                        resolve(value);
                .addClass('preload-editor-label')
                    }
                .text(label)
                 );
                 .appendTo(row);


                buttons.append(cancel, confirm);
            if (description) {
                 box.append(input, buttons);
                 $('<div>')
                overlay.append(box);
                    .addClass('preload-editor-help')
                $(document.body).append(overlay);
                    .text(description)
                    .appendTo(row);
            }


                input.trigger('focus');
            row.append(input);


                input.on(
            return row;
                    'keydown.preloadEditor',
        },
                    event => {
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


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


         async loadDefinition(title, source) {
         textarea(value) {
             const content = this.extractIncludeonly(source);
             return $('<textarea>')
            let config = this.emptyConfig();
                .val(value == null ? '' : value)
                .addClass('preload-editor-textarea');
        },


             const configTitle =
        checkbox(checked) {
                 title.replace(/\/+$/, '') +
             return $('<input>')
                 '/config.json';
                 .attr('type', 'checkbox')
                 .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },
 
        select(options, value) {
            const select = $('<select>')
                .addClass('preload-editor-select');


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


             if (configPage) {
             return select;
                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);
        // In-wiki dialogs
        // =========================================================


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


            this.state = {
                const box = $('<div>')
                preloadTitle: title,
                    .addClass('preload-editor-prompt');
                preloadSource: source,
                preloadContent: source,
                config,
                variables: analysis.variables,
                conditions: analysis.conditions,
                mode: 'edit',
                dirty: false
            };


            this.renderEditor();
                $('<h2>')
        },
                    .text(title)
                    .appendTo(box);


        // Editor
                const messageLines =
                    String(message || '').split('\n');


        renderEditor() {
                messageLines.forEach(line => {
            this.destroyEditor();
                    if (line === '') {
            this.workspace.empty();
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);


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


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


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


            const editorSection = this.createSection(
                const cancel = this.createButton(
                'Preload',
                    cancelLabel || 'Cancel',
                'preload-editor-main-section'
                    '',
            );
                    () => {
 
                        overlay.remove();
            const meta = $('<div>')
                        resolve(false);
                 .addClass('preload-editor-meta');
                    }
                 );


            $('<strong>')
                 const confirm = this.createButton(
                 .text(this.state.preloadTitle || 'New preload')
                    confirmLabel || 'Confirm',
                .appendTo(meta);
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                        resolve(true);
                    }
                );


            if (this.state.mode === 'new') {
                 buttons.append(cancel, confirm);
                 $('<span>')
                box.append(buttons);
                    .addClass('preload-editor-badge')
                overlay.append(box);
                    .text('NEW')
                    .appendTo(meta);
            }


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


            editorSection.append(
                const close = value => {
                this.renderEditorTools()
                    if (value === 'Escape') {
            );
                        cancel.trigger('click');
                    }
                };


            const textarea = this.textarea(
                overlay.on(
                this.state.preloadContent
                    'keydown.preloadEditor',
            )
                    event => {
                .attr('id', 'preload-editor-content')
                        close(event.key);
                 .addClass('preload-editor-content');
                    }
                 );


            const editorMount = $('<div>')
                overlay.attr('tabindex', '-1');
                .addClass('preload-editor-codemirror-mount')
                 overlay.trigger('focus');
                 .append(textarea);


            editorSection.append(editorMount);
                overlay.on(
            left.append(editorSection);
                    'click.preloadEditor',
 
                    event => {
            const analysisSection =
                        if (event.target === overlay.get(0)) {
                 this.createSection('Analysis');
                            cancel.trigger('click');
                        }
                    }
                 );
            });
        },


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


            analysisSection.append(analysisContainer);
                const box = $('<div>')
                    .addClass(
                        'preload-editor-prompt'
                    );


            const variablesSection =
                 $('<h2>')
                 this.createSection('Variables');
                    .text(title)
                    .appendTo(box);


            const variableContainer = $('<div>')
                $('<p>')
                .addClass('preload-editor-variables');
                    .text(message)
                    .appendTo(box);


            variablesSection.append(variableContainer);
                const input = this.textInput();


            const configSection =
                const buttons = $('<div>')
                this.createSection('Generated configuration');
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


            const configPreview = $('<pre>')
                const cancel = this.createButton(
                .addClass('preload-editor-config-preview');
                    'Cancel',
                    '',
                    () => {
                        overlay.remove();
                        resolve(null);
                    }
                );


            configSection.append(configPreview);
                const confirm = this.createButton(
 
                     'Load',
            const actions = $('<div>')
                .addClass('preload-editor-actions');
 
            actions.append(
                this.createButton(
                     'Save Preload + Config',
                     'preload-editor-button-primary',
                     'preload-editor-button-primary',
                     () => this.saveAll()
                     () => {
                ),
                        const value =
                this.createButton(
                            String(
                    'Save Preload Only',
                                input.val() || ''
                    '',
                            ).trim();
                    () => this.savePreloadOnly()
                )
            );


            right.append(
                        if (!value) {
                analysisSection,
                            return;
                variablesSection,
                        }
                configSection,
                actions
            );


            layout.append(left, right);
                        overlay.remove();
            this.workspace.append(layout);
                        resolve(value);
                    }
                );


            this.reanalyze();
                buttons.append(cancel, confirm);
            this.renderVariables(variableContainer);
            this.renderAnalysis(analysisContainer);
            this.renderConfigPreview(configPreview);
            this.updateEditorTools();


            this.mountCodeMirror(textarea.get(0)).catch(error => {
                 box.append(
                 console.error(
                     input,
                     'Preload Editor CodeMirror:',
                     buttons
                     error
                 );
                 );


                 this.setStatus(
                 overlay.append(box);
                    error.message ||
                        'Could not initialize CodeMirror.',
                    'error'
                );
            });
        },


        reanalyze() {
                $(document.body).append(overlay);
            const source = this.getEditorContent();
            const content = this.extractIncludeonly(source);
            const analysis = this.analyzePreload(content);


            this.state.preloadContent = source;
                input.trigger('focus');
            this.state.variables = analysis.variables;
            this.state.conditions = analysis.conditions;


            this.state.config =
                input.on(
                this.prepareConfigForVariables(
                    'keydown.preloadEditor',
                    this.state.config ||
                    event => {
                        this.emptyConfig(),
                        if (event.key === 'Enter') {
                     analysis
                            confirm.trigger('click');
                        }
 
                        if (event.key === 'Escape') {
                            cancel.trigger('click');
                        }
                     }
                 );
                 );
 
             });
             this.analysis = analysis;
         },
         },


         renderAnalysis(container) {
         createConfigReviewDialog() {
             container.empty();
             return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );


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


            const variableCount = analysis.variables.length;
                $('<h2>')
            const conditionCount = analysis.conditions.length;
                    .text('Review config.json')
                    .appendTo(box);


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


            summary.append(
                 const code = $('<pre>')
                 $('<span>').text(
                    .addClass(
                    variableCount +
                        'preload-editor-config-review'
                    ' variable' +
                     )
                     (variableCount === 1 ? '' : 's')
                    .text(this.getConfigJSON());
                ),
                $('<span>').text(
                    conditionCount +
                    ' condition marker' +
                    (conditionCount === 1 ? '' : 's')
                )
            );


            container.append(summary);
                const codeWrap = $('<div>')
                    .addClass(
                        'preload-editor-config-review-wrap'
                    )
                    .append(code);


            if (analysis.conditionVariables.length) {
                 box.append(codeWrap);
                 container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }


            const validation = this.validateConfig(
                 const buttons = $('<div>')
                this.state.config,
                analysis
            );
 
            if (validation.errors.length) {
                 const errors = $('<ul>')
                     .addClass(
                     .addClass(
                         'preload-editor-validation-errors'
                         'preload-editor-prompt-buttons'
                     );
                     );


                 validation.errors.forEach(error => {
                 const close = this.createButton(
                     $('<li>').text(error).appendTo(errors);
                     'Close',
                 });
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                        resolve();
                    }
                 );


                 container.append(errors);
                 buttons.append(close);
            }
                box.append(buttons);
                overlay.append(box);


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


                 validation.warnings.forEach(warning => {
                 overlay.attr('tabindex', '-1');
                    $('<li>').text(warning).appendTo(warnings);
                 overlay.trigger('focus');
                 });


                 container.append(warnings);
                 overlay.on(
            }
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                );


            if (!validation.errors.length &&
                 overlay.on(
                 !validation.warnings.length) {
                    'click.preloadEditor',
                container.append(
                     event => {
                     $('<div>')
                         if (event.target === overlay.get(0)) {
                         .addClass(
                             close.trigger('click');
                             'preload-editor-validation-success'
                         }
                        )
                    }
                         .text(
                            'Preload and configuration are in sync.'
                        )
                 );
                 );
             }
             });
         },
         },


         renderAnalysisBySelector() {
         async confirmSave(mode, title) {
             const container =
             const configTitle =
                 this.root?.find(
                 title.replace(/\/+$/, '') +
                    '.preload-editor-analysis'
                '/config.json';
                );
 
            let saveDescription;


             if (container?.length) {
             if (mode === 'preload') {
                 this.renderAnalysis(container);
                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?';
             }
             }
        },


        renderVariables(container) {
             const pages = [];
             container.empty();


             const analysis =
             if (mode === 'preload' || mode === 'both') {
                this.analysis ||
                 pages.push(
                 this.analyzePreload(
                     'Preload: ' +
                     this.extractIncludeonly(
                     title
                        this.getEditorContent()
                     )
                 );
                 );
            }


             const variables = analysis.variables.slice();
             if (mode === 'config' || mode === 'both') {
            const ordered = ['PAGE'];
                pages.push(
                    'Config: ' +
                    configTitle
                );


            variables.forEach(name => {
                pages.push(
                if (name !== 'PAGE' &&
                    'Config content model: JSON'
                    !ordered.includes(name)) {
                );
                    ordered.push(name);
             }
                }
             });


             Object.keys(
             const message =
                 this.state.config.fields || {}
                saveDescription +
            ).forEach(name => {
                 '\n\n' +
                 const upper = name.toUpperCase();
                pages.join('\n') +
                 '\n\nThis will write the changes to the wiki.';


                if (!ordered.includes(upper)) {
            return this.createConfirmDialog(
                    ordered.push(upper);
                'Confirm save',
                 }
                message,
             });
                'Save',
                 'Cancel'
             );
        },


             ordered.forEach(name => {
        // =========================================================
                 const field =
        // CodeMirror
                    this.state.config.fields[name] ||
        // =========================================================
                    this.createDefaultField(name, analysis);
                destroyEditor() {
             if (!this.editor) {
                 this.editorView = null;
                this.editorTools = null;
                return;
            }


                 this.state.config.fields[name] = field;
            const {
                 view,
                inputHandler
            } = this.editor;


                 container.append(
            if (view && inputHandler) {
                     this.createVariableCard(
                 view.dom.removeEventListener(
                        name,
                     'input',
                        field,
                     inputHandler
                        analysis
                     )
                 );
                 );
             });
             }
 
            if (view) {
                view.destroy();
            }
 
            this.editor = null;
            this.editorView = null;
            this.editorTools = null;
         },
         },


         renderVariablesBySelector() {
         getEditorView() {
             const container =
             return this.editorView;
                this.root?.find(
        },
                    '.preload-editor-variables'
                );


             if (container?.length) {
        getEditorContent() {
                 this.renderVariables(container);
             if (
                this.editorView &&
                this.editorView.state
            ) {
                 return this.editorView.state.doc.toString();
             }
             }
            return this.state.preloadContent || '';
         },
         },


         createVariableCard(name, field, analysis) {
         setEditorContent(content) {
             const card = $('<div>')
             content = String(content || '');
                .addClass('preload-editor-variable')
                .attr('data-variable', name);


             const header = $('<div>')
            if (!this.editorView) {
                 .addClass('preload-editor-variable-header');
                this.state.preloadContent = content;
                return;
            }
 
             const current =
                 this.editorView.state.doc.toString();


             header.append($('<h3>').text(name));
             if (current === content) {
                return;
            }


             if (name === 'PAGE') {
             this.editorView.dispatch({
                 header.append(
                 changes: {
                     $('<span>')
                     from: 0,
                        .addClass('preload-editor-badge')
                    to: this.editorView.state.doc.length,
                        .text('AUTOMATIC')
                    insert: content
                 );
                 }
             } else if (!analysis.variables.includes(name)) {
            });
                 header.append(
        },
                    $('<span>')
 
                        .addClass(
        getEditorSelection() {
                            'preload-editor-badge is-warning'
             if (
                        )
                !this.editorView ||
                        .text('UNUSED')
                 !this.editorView.state
                 );
            ) {
                 return null;
             }
             }


             card.append(header);
             const selection =
                this.editorView.state.selection.main;


             const label = this.textInput(field.label || '');
             return {
                from: selection.from,
                to: selection.to,
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
            };
        },


            label.on('input.preloadEditor', () => {
        focusEditor() {
                field.label = label.val();
            if (this.editorView) {
                this.markDirty();
                 this.editorView.focus();
                 this.renderConfigPreviewBySelector();
             }
             });
        },


             card.append(this.fieldRow('Label', label));
        insertEditorText(
 
            text,
             const description = this.textarea(
            selectionFrom,
                 field.description || ''
             selectionTo,
             ).addClass('preload-editor-small-textarea');
            cursorPosition
        ) {
             if (!this.editorView) {
                 return;
             }


             description.on('input.preloadEditor', () => {
             const view = this.editorView;
                 field.description = description.val();
            const selection = view.state.selection.main;
                 this.markDirty();
 
                this.renderConfigPreviewBySelector();
            const from =
            });
                 selectionFrom === undefined
                    ? selection.from
                    : selectionFrom;
 
            const to =
                 selectionTo === undefined
                    ? selection.to
                    : selectionTo;


             card.append(
             const cursor =
                 this.fieldRow(
                 cursorPosition === undefined
                     'Description',
                     ? from + text.length
                     description
                     : cursorPosition;
                )
            );


             const types = [
             view.dispatch({
                 ['text', 'Text'],
                 changes: {
                ['textarea', 'Textarea'],
                    from,
                ['number', 'Number'],
                    to,
                ['boolean', 'Boolean'],
                    insert: text
                 ['select', 'Select'],
                 },
                 ['multiselect', 'Multi-select'],
                 selection: {
                ['page', 'Page'],
                    anchor: cursor
                 ['user', 'User'],
                 }
                ['date', 'Date']
             });
             ];


             const typeSelect = this.select(
             view.focus();
                types.map(([value, label]) => ({
        },
                    value,
                    label
                })),
                field.type || 'text'
            );


            typeSelect.on('change.preloadEditor', () => {
        // =========================================================
                field.type = typeSelect.val();
        // Editor tools
                this.markDirty();
        // =========================================================


                card.replaceWith(
        wrapSelectionWithVariable() {
                    this.createVariableCard(
            const selected =
                        name,
                this.getEditorSelection();
                        field,
                        analysis
                    )
                );


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


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


             if (name === 'PAGE') {
             this.insertEditorText(
                 field.type = 'page';
                 replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
            );
        },


                const required = this.checkbox(
        insertVariable(name) {
                    field.required !== false
            name = String(name || '')
                 );
                .trim()
                 .toUpperCase();


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


                    this.markDirty();
            const selected =
                    this.renderConfigPreviewBySelector();
                this.getEditorSelection();
                });


                card.append(
            if (!selected) {
                    this.fieldRow(
                 return;
                        'Required',
            }
                        required
                    )
                 );


                const namespace = this.select(
            this.insertEditorText(
                    [
                '%%' + name + '%%',
                        { value: 'Main', label: 'Main' },
                selected.from,
                        { value: 'Template', label: 'Template' },
                selected.to
                        { value: 'File', label: 'File' },
            );
                        { value: 'Category', label: 'Category' },
        },
                        { value: 'User', label: 'User' }
                    ],
                    field.namespace || 'Main'
                );


                namespace.on('change.preloadEditor', () => {
        insertCondition(
                    field.namespace = namespace.val();
            type,
                    this.markDirty();
            variable
                    this.renderConfigPreviewBySelector();
        ) {
                 });
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                 .toUpperCase();


                 card.append(
            const selected =
                    this.fieldRow(
                 this.getEditorSelection();
                        'Namespace',
                        namespace
                    )
                );


                const allowNew = this.checkbox(
            if (!selected) {
                    field['allow-new'] === true
                 return;
                 );
            }


                allowNew.on('change.preloadEditor', () => {
            let text;
                    field['allow-new'] =
            let cursorOffset;
                        allowNew.prop('checked');


                    this.markDirty();
            switch (type) {
                     this.renderConfigPreviewBySelector();
                case 'if': {
                });
                     if (!variable) {
                        return;
                    }


                card.append(
                     const opening =
                     this.fieldRow(
                         '<!-- @if ' +
                         'Allow new page',
                         variable +
                         allowNew
                        ' -->';
                    )
                );


                return card;
                    const closing =
            }
                        '<!-- @endif -->';


            const required = this.checkbox(
                    if (
                field.required === true
                        selected.from !==
            );
                        selected.to
                    ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


            required.on('change.preloadEditor', () => {
                        cursorOffset = text.length;
                field.required =
                     } else {
                     required.prop('checked');
                        text =
 
                            opening +
                this.markDirty();
                            '\n\n' +
                this.renderConfigPreviewBySelector();
                            closing;
            });
 
            card.append(
                this.fieldRow(
                    'Required',
                    required
                )
            );


            const placeholder = this.textInput(
                        cursorOffset =
                field.placeholder || ''
                            opening.length + 1;
            );
                    }


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


                 if (value) field.placeholder = value;
                 case 'elseif':
                else delete field.placeholder;
                    text =
                        '<!-- @elseif -->';


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


            card.append(
                     break;
                this.fieldRow(
                     'Placeholder',
                    placeholder
                )
            );


            const defaultInput = this.textInput(
                 case 'else':
                 field.default === undefined
                     text =
                    ? ''
                        '<!-- @else -->';
                     : field.default
            );


            defaultInput.on('input.preloadEditor', () => {
                    cursorOffset =
                const value = defaultInput.val();
                        text.length;


                if (value) field.default = value;
                    break;
                else delete field.default;


                 this.markDirty();
                 case 'endif':
                this.renderConfigPreviewBySelector();
                    text =
            });
                        '<!-- @endif -->';


            card.append(
                     cursorOffset =
                this.fieldRow(
                        text.length;
                    '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') {
                     break;
                const maxRows = this.textInput(
                     field.maxRows || ''
                ).attr('type', 'number');


                 maxRows.on('input.preloadEditor', () => {
                 default:
                     const value =
                     return;
                        parseInt(maxRows.val(), 10);
            }


                    if (Number.isFinite(value) && value > 0) {
            this.insertEditorText(
                        field.maxRows = value;
                text,
                    } else {
                selected.from,
                        delete field.maxRows;
                selected.to,
                    }
                selected.from + cursorOffset
            );
        },


                    this.markDirty();
        getToolVariables() {
                    this.renderConfigPreviewBySelector();
            const variables =
                 });
                 new Set(['PAGE']);


                 card.append(
            if (
                     this.fieldRow(
                this.analysis &&
                        'Maximum rows',
                this.analysis.variables
                         maxRows
            ) {
                     )
                 this.analysis.variables.forEach(
                     name => {
                        variables.add(
                            String(name).toUpperCase()
                         );
                     }
                 );
                 );
             }
             }


             if (field.type === 'select' ||
             return Array.from(variables);
                field.type === 'multiselect') {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }
 
            return card;
         },
         },


         renderSelectConfiguration(card, field) {
         createToolSelect(
             const source = this.textInput(
            options,
                 field.source || '',
            className
                 'category:Example'
        ) {
             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);
                 }
             );
             );


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


                if (value) field.source = value;
        updateEditorToolVariables() {
                 else delete field.source;
            if (!this.editorTools) {
                 return;
            }


                this.markDirty();
            const variables =
                 this.renderConfigPreviewBySelector();
                 this.getToolVariables();
            });


             card.append(
             const current =
                 this.fieldRow(
                 this.editorTools
                     'Source',
                     .variableSelect
                     source,
                     .val();
                    'Currently supported source format: category:Category Name'
                )
            );


             const sourcePrefix = this.textInput(
             const currentCondition =
                field['source-prefix'] || ''
                this.editorTools
            );
                    .conditionVariableSelect
                    .val();


             sourcePrefix.on('input.preloadEditor', () => {
             const populate = (
                 const value = sourcePrefix.val();
                select,
                value
            ) => {
                 select.empty();


                 if (value) {
                 variables.forEach(
                    field['source-prefix'] = value;
                    name => {
                } else {
                        $('<option>')
                    delete field['source-prefix'];
                            .attr(
                }
                                'value',
 
                                name
                this.markDirty();
                            )
                this.renderConfigPreviewBySelector();
                            .text(name)
            });
                            .appendTo(select);
                    }
                );


            card.append(
                if (
                 this.fieldRow(
                    value &&
                     'Source prefix',
                    variables.includes(value)
                     sourcePrefix,
                 ) {
                     'Only source values beginning with this text are included.'
                    select.val(value);
                 )
                } else if (
                     variables.length
                ) {
                     select.val(
                        variables[0]
                     );
                }
            };
 
            populate(
                this.editorTools.variableSelect,
                 current
             );
             );


             const excludeCategory = this.textInput(
             populate(
                 field.exclude && field.exclude.category || ''
                 this.editorTools.conditionVariableSelect,
                currentCondition
             );
             );
        },


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


                if (value) {
            const type =
                    field.exclude = Object.assign(
                this.editorTools
                        {},
                     .conditionTypeSelect
                        field.exclude || {},
                     .val();
                        { category: value }
                     );
                } else if (field.exclude) {
                     delete field.exclude.category;


                    if (!Object.keys(field.exclude).length) {
            this.editorTools
                        delete field.exclude;
                .conditionVariableWrap
                     }
                .toggle(
                 }
                     type === 'if'
                 );
        },


                 this.markDirty();
        renderEditorTools() {
                this.renderConfigPreviewBySelector();
            const tools =
            });
                 $('<div>')
                    .addClass(
                        'preload-editor-tools'
                    );


             card.append(
             const wrapGroup =
                 this.fieldRow(
                $('<div>')
                     'Exclude category',
                    .addClass(
                     excludeCategory
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );
 
            wrapGroup.append(
                 this.createButton(
                     'Wrap selection',
                     'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                 )
                 )
             );
             );


             card.append(
             const variableGroup =
                 this.createTransformControls(
                 $('<div>')
                     field,
                     .addClass(
                    'value',
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                     'Value transformation'
                     );
                ),
 
                 this.createTransformControls(
            $('<span>')
                    field,
                 .addClass(
                     'label',
                     'preload-editor-tool-label'
                     'Label transformation'
                )
                .text(
                     'Insert existing variable'
                 )
                 )
            );
                .appendTo(variableGroup);


             const optionsValue =
             const variableSelect =
                 Array.isArray(field.options)
                 this.createToolSelect(
                     ? field.options.map(option => {
                     [],
                        if (typeof option === 'string') {
                    'preload-editor-variable-select'
                            return option;
                );
                        }


                        return (
            variableGroup.append(
                            String(option.value || '') +
                variableSelect,
                            ' | ' +
                            String(
                                option.label ||
                                option.value ||
                                ''
                            )
                        );
                    }).join('\n')
                    : '';


            const options = this.textarea(optionsValue)
                this.createButton(
                .addClass('preload-editor-small-textarea');
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                )
            );


             options.on('input.preloadEditor', () => {
             const conditionGroup =
                const lines = options
                $('<div>')
                     .val()
                     .addClass(
                    .split('\n')
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                     .map(line => line.trim())
                     );
                    .filter(Boolean);


                 if (!lines.length) {
            $('<span>')
                     delete field.options;
                 .addClass(
                 } else {
                     'preload-editor-tool-label'
                    field.options = lines.map(line => {
                 )
                        const parts =
                .text('Insert condition')
                            line.split(/\s*\|\s*/);
                .appendTo(conditionGroup);


                         if (parts.length === 1) {
            const conditionTypeSelect =
                             return parts[0];
                this.createToolSelect(
                    [
                         {
                            value: 'if',
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                             value: 'endif',
                            label: '@endif'
                         }
                         }
                    ],
                    'preload-editor-condition-type-select'
                );


                        return {
            const conditionVariableSelect =
                            value: parts[0],
                this.createToolSelect(
                            label: parts.slice(1).join(' | ')
                    [],
                        };
                    'preload-editor-condition-variable-select'
                    });
                );
                }


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


             card.append(
             const insertCondition =
                 this.fieldRow(
                 this.createButton(
                     'Manual options',
                     'Insert',
                     options,
                     'preload-editor-tool-button',
                     'One per line. Optional label format: value | label. Leave empty when using a source.'
                     () =>
                )
                        this.insertCondition(
            );
                            conditionTypeSelect.val(),
        },
                            conditionVariableSelect.val()
                        )
                );


        createTransformControls(field, property, title) {
             conditionTypeSelect.on(
             const wrapper = $('<div>')
                 'change.preloadEditor',
                 .addClass('preload-editor-transform');
                 () =>
 
                     this.updateConditionVariableVisibility()
            $('<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(
             conditionGroup.append(
                 existing.prefix || ''
                 conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
             );
             );


             const suffix = this.textInput(
             tools.append(
                 existing.suffix || ''
                 wrapGroup,
            );
                variableGroup,
 
                 conditionGroup
            const from = this.textInput(
                 existing.from || ''
             );
             );


             const to = this.textInput(
             this.editorTools = {
                 existing.to || ''
                root: tools,
             );
                 variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
             };


             const controls = $('<div>')
             this.updateEditorToolVariables();
                .addClass(
            this.updateConditionVariableVisibility();
                    'preload-editor-transform-controls'
                );


             const prefixRow =
             return tools;
                this.fieldRow('Prefix', prefix);
        },


             const suffixRow =
        updateEditorTools() {
                this.fieldRow('Suffix', suffix);
             this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
        },


            const fromRow =
        // =========================================================
                this.fieldRow('From', from);
        // Syntax highlighting
        // =========================================================


             const toRow =
        getKnownVariables() {
                 this.fieldRow('To', to);
             const known =
                 new Set(['PAGE']);


             const renderInputs = () => {
             const fields =
                 const type = transform.val();
                 this.state.config &&
                this.state.config.fields;


                 prefixRow.toggle(
            if (
                    type === 'remove-prefix'
                 fields &&
                typeof fields === 'object'
            ) {
                Object.keys(fields).forEach(
                    name => {
                        known.add(
                            String(name).toUpperCase()
                        );
                    }
                 );
                 );
            }


                suffixRow.toggle(
            return known;
                    type === 'remove-suffix'
        },
                );


                fromRow.toggle(type === 'replace');
        createSyntaxDecorations(
                 toRow.toggle(type === 'replace');
            state,
            };
            Decoration
        ) {
            const decorations = [];
            const source =
                 state.doc.toString();


             const update = () => {
             const knownVariables =
                 const type = transform.val();
                 this.getKnownVariables();
                let object = null;


                if (type === 'remove-prefix' && prefix.val()) {
            const variablePattern =
                    object = {
                 /%%([A-Za-z0-9_-]+)%%/g;
                        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) {
            let match;
                    field[property] = object;
                } else {
                    delete field[property];
                }


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


            transform.on(
                 const known =
                 'change.preloadEditor',
                     knownVariables.has(name);
                () => {
                     update();
                    renderInputs();
                }
            );


            [prefix, suffix, from, to].forEach(input => {
                decorations.push(
                input.on(
                    Decoration.mark({
                    'input.preloadEditor',
                        class: [
                     update
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                     )
                 );
                 );
             });
             }


             controls.append(
             const conditionPattern =
                 this.fieldRow(
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    'Transformation',
                    transform
                ),
                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );


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


            return wrapper;
                const directiveStart =
        },
                    match.index +
                    match[0].indexOf('@');


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


        getCleanConfig() {
                const type =
            const config = JSON.parse(
                    match[1].toLowerCase();
                JSON.stringify(this.state.config)
            );


            const fields = config.fields || {};
                if (
            const orderedFields = {};
                    type !== 'if' &&
                    type !== 'elseif'
                ) {
                    continue;
                }


            if (fields.PAGE) {
                 const expression =
                 orderedFields.PAGE = fields.PAGE;
                    match[2];
            }


            Object.keys(fields)
                const expressionStart =
                .filter(
                    match.index +
                     name =>
                     match[0].indexOf(
                        name.toUpperCase() !== 'PAGE'
                        expression
                )
                     );
                .forEach(name => {
                     orderedFields[name] = fields[name];
                });


            config.fields = orderedFields;
                const expressionPattern =
            return config;
                    /[A-Za-z0-9_-]+/g;
        },


        getConfigJSON() {
                 let expressionMatch;
            return JSON.stringify(
                 this.getCleanConfig(),
                null,
                4
            );
        },


        renderConfigPreview(container) {
                while (
            if (container) {
                    (
                container.text(this.getConfigJSON());
                        expressionMatch =
            }
                            expressionPattern.exec(
        },
                                expression
                            )
                    ) !== null
                ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


        renderConfigPreviewBySelector() {
                    if (
            const preview =
                        !knownVariables.has(name)
                this.root?.find(
                     ) {
                     '.preload-editor-config-preview'
                        continue;
                );
                    }


            if (preview?.length) {
                    const start =
                this.renderConfigPreview(preview);
                        expressionStart +
            }
                        expressionMatch.index;


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


        markDirty() {
            return Decoration.set(
             this.state.dirty = true;
                decorations,
                true
             );
         },
         },


         // Save
         async installSyntaxHighlighting(view) {
            await mw.loader.using(
                'ext.CodeMirror.v6.lib'
            );


        async savePreloadOnly() {
             const require =
             let title =
                 mw.loader.require;
                 String(
                    this.state.preloadTitle || ''
                ).trim();


             if (!title) {
             const {
                 const result =
                 StateField,
                    await this.createPromptDialog(
                StateEffect,
                        'Preload title',
                EditorView,
                        'Enter the full title for the preload.'
                Decoration
                    );
            } = require(
                'ext.CodeMirror.v6.lib'
            );


                 if (!result) return;
            const syntaxField =
                 StateField.define({
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


                title = result;
                    update: (
                this.state.preloadTitle = title;
                        decorations,
            }
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,
 
                    provide: field =>
                        EditorView.decorations.from(
                            field
                        )
                });


             this.state.preloadContent =
             view.dispatch({
                 this.getEditorContent();
                 effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });


             const validation =
             this.editor.syntaxField =
                 this.validateBeforeSave();
                 syntaxField;
        },


            if (validation.errors.length) {
        async mountCodeMirror(textarea) {
                 this.showValidationErrors(validation);
            return new Promise(
                return;
                 (
            }
                    resolve,
                    reject
                ) => {
                    let settled = false;


            this.setStatus(
                    const cleanup = () => {
                'Saving preload...',
                        mw.hook(
                'loading'
                            'dev.CCM.ready'
            );
                        ).remove(onReady);


            try {
                        mw.hook(
                const exists =
                            'dev.CCM.load'
                    await this.pageExists(title);
                        ).remove(onLoad);
                    };


                await this.savePage(
                    const onReady =
                    title,
                        async cm => {
                    this.state.preloadContent,
                            if (
                    exists
                                settled ||
                        ? 'Updated preload with Preload Editor'
                                !cm ||
                        : 'Created preload with Preload Editor',
                                cm.textarea !== textarea ||
                    !exists
                                !cm.view
                );
                            ) {
                                return;
                            }


                this.state.mode = 'edit';
                            settled = true;
                this.state.dirty = false;
                            cleanup();
 
                            const view =
                                cm.view;


                this.setStatus(
                            const inputHandler =
                    'Preload saved successfully.',
                                () => {
                    'success'
                                    this.state
                );
                                        .preloadContent =
                                        view.state.doc.toString();


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


                this.setStatus(
                                    this.reanalyze();
                    error.message ||
                        'Could not save preload.',
                    'error'
                );


                mw.notify(
                                    this.renderVariablesBySelector();
                    error.message ||
                                    this.renderVariableConfigurationBySelector();
                        'Could not save preload.',
                                    this.renderAnalysisBySelector();
                    { type: 'error' }
                                    this.updateEditorTools();
                );
            }
        },


        async saveAll() {
                                    this.saveDraft();
            let title =
                                };
                String(
                    this.state.preloadTitle || ''
                ).trim();


            if (!title) {
                            view.dom.addEventListener(
                const result =
                                'input',
                    await this.createPromptDialog(
                                inputHandler
                        'Preload title',
                            );
                        'Enter the full title for the preload.'
                    );


                if (!result) return;
                            view.dom.classList.add(
                                'preload-editor-codemirror'
                            );


                title = result;
                            const wrapper =
                this.state.preloadTitle = title;
                                view.dom.closest(
            }
                                    '.ext-codemirror-wrapper'
                                );
 
                            if (wrapper) {
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }
 
                            this.editor = {
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


            this.state.preloadContent =
                            this.editorView =
                this.getEditorContent();
                                view;


            const validation =
                            this.state.preloadContent =
                this.validateBeforeSave();
                                view.state.doc.toString();


            if (validation.errors.length) {
                            try {
                this.showValidationErrors(validation);
                                await this.installSyntaxHighlighting(
                return;
                                    view
            }
                                );


            const configTitle =
                                if (
                title.replace(/\/+$/, '') +
                                    this.state.dirty
                '/config.json';
                                ) {
                                    this.saveDraft();
                                }


            this.setStatus(
                                resolve(view);
                'Saving preload and config...',
                            } catch (error) {
                'loading'
                                reject(error);
            );
                            }
                        };


            try {
                    const onLoad =
                const preloadExists =
                        loader => {
                    await this.pageExists(title);
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                await this.savePage(
                            try {
                    title,
                                loader(textarea);
                    this.state.preloadContent,
                            } catch (error) {
                    preloadExists
                                settled = true;
                        ? 'Updated preload with Preload Editor'
                                cleanup();
                         : 'Created preload with Preload Editor',
                                reject(error);
                    !preloadExists
                            }
                );
                         };


                const configExists =
                    mw.hook(
                     await this.pageExists(configTitle);
                        'dev.CCM.ready'
                     ).add(onReady);


                await this.savePage(
                     mw.hook(
                     configTitle,
                         'dev.CCM.load'
                    this.getConfigJSON(),
                     ).add(onLoad);
                    configExists
                 }
                         ? 'Updated preload config with Preload Editor'
            );
                        : 'Created preload config with Preload Editor',
        },
                     !configExists
                 );


                this.state.mode = 'edit';
        // =========================================================
                this.state.dirty = false;
        // Main UI
                this.state.preloadTitle = title;
        // =========================================================


                this.setStatus(
        init() {
                    'Preload and config saved successfully.',
            const root =
                    'success'
                $('#mw-content-text');
                );


                mw.notify(
            if (!root.length) {
                    'Preload and config saved.',
                 return;
                    { type: 'success' }
             }
                 );
             } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );


                this.setStatus(
            this.root =
                     error.message ||
                $('<div>')
                         'Could not save preload/config.',
                     .attr(
                     'error'
                        'id',
                );
                         'preload-editor'
                     )
                    .addClass(
                        'preload-editor'
                    );


                 mw.notify(
            root.append(this.root);
                     error.message ||
 
                         'Could not save preload/config.',
            this.renderShell();
                     { type: 'error' }
 
            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.'
                 );
                 );
             }
             }
        },


        validateBeforeSave() {
             const analysis =
             const errors = [];
                this.analyzePreload(
            const warnings = [];
                    this.extractIncludeonly(
                        content
                    )
                );


             const title =
             this.state.config =
                 String(
                 this.prepareConfigForVariables(
                     this.state.preloadTitle || ''
                     this.state.config ||
                ).trim();
                        this.emptyConfig(),
                    analysis
                );


             if (!title) {
             const configValidation =
                 errors.push(
                 this.validateConfig(
                     'A preload title is required.'
                     this.state.config,
                    analysis
                 );
                 );
            }


             if (
             errors.push(
                 title &&
                 ...configValidation.errors
                !/\/Preload$/i.test(title)
            );
            ) {
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }


             const content =
             warnings.push(
                this.getEditorContent();
                 ...configValidation.warnings
 
             );
            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)
                );
 
            const configValidation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );
 
            errors.push(...configValidation.errors);
             warnings.push(...configValidation.warnings);


             let depth = 0;
             let depth = 0;
                        analysis.conditions.forEach(
                condition => {
                    if (
                        condition.type === 'if'
                    ) {
                        depth++;
                    } else if (
                        condition.type === 'endif'
                    ) {
                        depth--;


            analysis.conditions.forEach(condition => {
                        if (depth < 0) {
                if (condition.type === 'if') {
                            errors.push(
                    depth++;
                                'Found @endif without a matching @if.'
                } else if (condition.type === 'endif') {
                            );
                    depth--;


                    if (depth < 0) {
                             depth = 0;
                        errors.push(
                        }
                             'Found @endif without a matching @if.'
                    } else if (
                        );
                        condition.type === 'elseif' ||
                        depth = 0;
                        condition.type === 'else'
                    }
                    ) {
                } else if (
                        if (depth === 0) {
                    condition.type === 'elseif' ||
                            errors.push(
                    condition.type === 'else'
                                '@' +
                ) {
                                condition.type +
                    if (depth === 0) {
                                ' exists outside an @if block.'
                        errors.push(
                            );
                            '@' +
                        }
                            condition.type +
                            ' exists outside an @if block.'
                        );
                     }
                     }
                 }
                 }
             });
             );


             if (depth > 0) {
             if (depth > 0) {
Line 2,734: Line 6,184:
                 errors,
                 errors,
                 warnings,
                 warnings,
                 valid: errors.length === 0
                 valid:
                    errors.length === 0
             };
             };
         },
         },
Line 2,740: Line 6,191:
         showValidationErrors(validation) {
         showValidationErrors(validation) {
             this.renderAnalysisBySelector();
             this.renderAnalysisBySelector();
            this.saveDraft();


             this.setStatus(
             this.setStatus(
Line 2,748: Line 6,201:
             mw.notify(
             mw.notify(
                 validation.errors.join('\n'),
                 validation.errors.join('\n'),
                 { type: 'error' }
                 {
                    type: 'error'
                }
             );
             );
         }
         }
     };
     };


     mw.PreloadEditor = PreloadEditor;
     mw.PreloadEditor =
        PreloadEditor;


     $(function () {
     $(function () {
         if (
         if (
             mw.config.get('wgPageName') !==
             mw.config.get('wgPageName') !==
             'Petit_Planet:Preload_Editor'
             'Petit_Planet_Wiki:Preload_Editor'
         ) {
         ) {
             return;
             return;