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
 
(19 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
        // =========================================================


async getPage(title) {
        getDraftStorage() {
    const response = await new mw.Api().get({
            try {
        action: 'query',
                const raw = window.localStorage.getItem(this.draftStorageKey);
        prop: 'revisions',
        titles: title,
        rvprop: 'content',
        rvslots: 'main',
        formatversion: 2
    });
    const page =
        response &&
        response.query &&
        response.query.pages &&
        response.query.pages[0];
    if (!page || page.missing) return null;
    const content =
        page.revisions &&
        page.revisions[0] &&
        page.revisions[0].slots &&
        page.revisions[0].slots.main &&
        page.revisions[0].slots.main.content;
    return {
        title: page.title || title,
        content: typeof content === 'string' ? content : ''
    };
},


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


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


            return response?.query?.search || [];
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        },
                    return {
                        active: null,
                        drafts: {}
                    };
                }


        async savePage(title, content, summary, createOnly) {
                if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
            const params = {
                    parsed.drafts = {};
                 action: 'edit',
                 }
                title,
                text: content,
                summary: summary || 'Updated with Preload Editor',
                formatversion: 2
            };


             if (createOnly) params.createonly = true;
                return parsed;
             } catch (error) {
                console.warn('Preload Editor: Could not read local drafts.', error);


            return new mw.Api().postWithToken('csrf', params);
                return {
                    active: null,
                    drafts: {}
                };
            }
         },
         },


         // Preload parsing
         setDraftStorage(storage) {
            try {
                window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                return true;
            } catch (error) {
                console.warn('Preload Editor: Could not save local draft.', error);
                return false;
            }
        },


         extractIncludeonly(source) {
         getDraftId(title) {
             const match = String(source || '').match(
             title = String(title || '').trim();
                /<includeonly>([\s\S]*?)<\/includeonly>/i
             return title ? title.toLowerCase() : '__untitled__';
            );
             return match ? match[1].trim() : String(source || '').trim();
         },
         },


         findVariables(content) {
         getDraftSnapshot() {
             const variables = [];
             let content = this.getEditorContent();
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
            let match;


             while ((match = pattern.exec(content)) !== null) {
             if (!this.editorView && !content) {
                 const name = match[1].toUpperCase();
                 content = this.state.preloadContent || '';
                if (!variables.includes(name)) variables.push(name);
             }
             }


             return variables;
             let config = null;
        },


        findConditions(content) {
            try {
            const conditions = [];
                config = this.state.config
            const pattern =
                    ? JSON.parse(JSON.stringify(this.state.config))
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    : this.emptyConfig();
             let match;
             } catch (error) {
 
                 console.warn('Preload Editor: Could not clone config for local draft.', error);
            while ((match = pattern.exec(content)) !== null) {
                config = this.emptyConfig();
                 conditions.push({
                    type: match[1].toLowerCase(),
                    expression: match[2].trim(),
                    index: match.index
                });
             }
             }


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


        findConditionVariables(content) {
                variables: Array.isArray(this.state.variables)
            const variables = [];
                    ? this.state.variables.slice()
                    : [],


            this.findConditions(content).forEach(condition => {
                conditions: Array.isArray(this.state.conditions)
                if (condition.type !== 'if' &&
                     ? this.state.conditions.slice()
                     condition.type !== 'elseif') return;
                    : [],


                 const matches =
                 selectedVariable: String(this.state.selectedVariable || 'PAGE'),
                    condition.expression.match(/[A-Za-z0-9_-]+/g) || [];


                 matches.forEach(name => {
                 deletedVariables: Array.isArray(this.state.deletedVariables)
                    name = name.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()
             };
         },
         },


         analyzePreload(content) {
         updateLocalDraftStatus(message, type) {
             return {
             if (!this.localDraftStatus) {
                 variables: this.findVariables(content),
                 return;
                 conditions: this.findConditions(content),
            }
                 conditionVariables: this.findConditionVariables(content)
 
             };
            this.localDraftStatus.removeClass(
        },
                'is-saved',
                'is-warning',
                 'is-error',
                 'is-empty'
             );


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


        emptyConfig() {
             this.localDraftStatus.text(message || '');
             return {
                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) {
         formatLocalDraftTime(timestamp) {
             if (!config ||
             if (!timestamp) {
                 typeof config !== 'object' ||
                 return '';
                Array.isArray(config)) {
                config = this.emptyConfig();
             }
             }


             if (!config.settings ||
             try {
                typeof config.settings !== 'object' ||
                return new Date(timestamp).toLocaleTimeString([], {
                 Array.isArray(config.settings)) {
                    hour: '2-digit',
                 config.settings = {};
                    minute: '2-digit',
                    second: '2-digit'
                 });
            } catch (error) {
                 return '';
             }
             }
        },


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


             if (!config.fields.PAGE) {
             if (this.state.localDraftSavedAt) {
                 config.fields.PAGE = {
                 const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);
                    label: 'Page Name',
 
                    description: 'Name of the page.',
                this.updateLocalDraftStatus(
                     type: 'page',
                     time ? 'Saved locally at ' + time : 'Saved locally',
                    required: true,
                     'saved'
                    namespace: 'Main',
                 );
                     'allow-new': true
 
                 };
                return;
             }
             }


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


         createDefaultField(name, analysis) {
         saveDraft() {
             return {
             if (!this.state.dirty) {
                 label: this.humanizeName(name),
                 return false;
                description: '',
            }
                type: analysis.conditionVariables.includes(name)
 
                    ? 'boolean'
            const snapshot = this.getDraftSnapshot();
                    : 'text'
            const id = this.getDraftId(snapshot.preloadTitle);
             };
             const storage = this.getDraftStorage();
        },


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


        prepareConfigForVariables(config, analysis) {
             const saved = this.setDraftStorage(storage);
             config = this.normalizeConfig(config);


             const existing = config.fields || {};
             if (saved) {
             const fields = {};
                this.state.localDraftSavedAt = snapshot.savedAt;
                this.state.localDraftAvailable = true;
                this.updateLocalDraftIndicator();
            } else {
                this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
            }
 
            return saved;
        },
 
        clearDraft(title) {
            const storage = this.getDraftStorage();
             const id = this.getDraftId(title);
 
            if (storage.drafts && storage.drafts[id]) {
                delete storage.drafts[id];
            }


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


             analysis.variables.forEach(name => {
             this.setDraftStorage(storage);
                if (name === 'PAGE') return;
                fields[name] =
                    existing[name] ||
                    this.createDefaultField(name, analysis);
            });


             Object.keys(existing).forEach(name => {
             this.state.localDraftSavedAt = null;
                const upper = name.toUpperCase();
            this.state.localDraftAvailable = false;
                if (!fields[upper]) fields[upper] = existing[name];
            });


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


         validateConfig(config, analysis) {
         getMostRecentDraft() {
             const errors = [];
             const storage = this.getDraftStorage();
             const warnings = [];
 
             if (!storage.drafts || !Object.keys(storage.drafts).length) {
                return null;
            }


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


             if (!config.fields ||
             let latestId = null;
                typeof config.fields !== 'object' ||
             let latestDraft = null;
                Array.isArray(config.fields)) {
 
                return {
             Object.entries(storage.drafts).forEach(([id, draft]) => {
                    valid: false,
                 if (!draft || typeof draft !== 'object') {
                    errors: ['"fields" must be an object.'],
                     return;
                    warnings
                };
             }
 
             const configured =
                Object.keys(config.fields).map(name => name.toUpperCase());
 
            analysis.variables.forEach(name => {
                 if (!configured.includes(name)) {
                     errors.push(
                        'Variable "' + name + '" is not configured.'
                    );
                 }
                 }
            });


            configured.forEach(name => {
                 if (
                 if (!analysis.variables.includes(name)) {
                    !latestDraft ||
                     warnings.push(
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                        'Field "' + name + '" is not used by the preload.'
                ) {
                     );
                     latestId = id;
                     latestDraft = draft;
                 }
                 }
             });
             });


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


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


                if (!field.type) {
        async restoreDraft() {
                    warnings.push(
            const result = this.getMostRecentDraft();
                        'Field "' + name + '" has no type.'
                    );
                }


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


             return {
             const draft = result.draft;
                valid: !errors.length,
            const title = String(draft.preloadTitle || '').trim();
                errors,
             const displayTitle = title || 'an untitled preload';
                warnings
             };
        },


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


        transformationObject(transform, prefix, suffix, from, to) {
            const message =
            if (!transform) return null;
                'Preload Editor found unsaved local work for ' +
                displayTitle +
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                '\n\nRestore it?';


             switch (transform) {
             const restore = await this.createConfirmDialog(
                 case 'remove-prefix':
                 'Restore unsaved work',
                    return prefix
                message,
                        ? { transform, prefix }
                'Restore',
                        : null;
                'Discard'
            );


                case 'remove-suffix':
            if (!restore) {
                    return suffix
                 this.clearDraft(title);
                        ? { transform, suffix }
                 return false;
                        : null;
 
                 case 'replace':
                    return from === ''
                        ? null
                        : { transform, from, to: to || '' };
 
                 default:
                    return null;
             }
             }
        },


        // UI helpers
            let config = this.emptyConfig();


        createSection(title, className) {
            if (
             const section = $('<section>')
                draft.config &&
                 .addClass('preload-editor-section');
                typeof draft.config === 'object' &&
                !Array.isArray(draft.config)
            ) {
                try {
                    config = this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                    );
                } catch (error) {
                    console.warn(
                        'Preload Editor: Could not restore local config.',
                        error
                    );
                }
            }
 
             const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';
 
            this.state = {
                preloadTitle: title,
                preloadSource: String(draft.preloadSource || ''),
                 preloadContent: String(draft.preloadContent || ''),
                config,


            if (className) section.addClass(className);
                variables: Array.isArray(draft.variables)
                    ? draft.variables.slice()
                    : [],


            $('<h2>')
                 conditions: Array.isArray(draft.conditions)
                 .addClass('preload-editor-section-title')
                    ? draft.conditions.slice()
                .text(title)
                    : [],
                .appendTo(section);


            return section;
                selectedVariable: String(draft.selectedVariable || 'PAGE'),
        },


        createButton(label, className, callback) {
                deletedVariables: Array.isArray(draft.deletedVariables)
            const button = $('<button>')
                    ? draft.deletedVariables
                .attr('type', 'button')
                        .map(name => String(name).toUpperCase())
                .addClass('preload-editor-button')
                        .filter(name => name !== 'PAGE')
                .text(label);
                    : [],


            if (className) button.addClass(className);
                 mode: draft.mode || 'edit',
            if (callback) {
                 button.on('click.preloadEditor', callback);
            }


            return button;
                dirty: hasDirtyFlags
        },
                    ? !!(draft.dirtyPreload || draft.dirtyConfig)
                    : true,


        fieldRow(label, input, description) {
                dirtyPreload: hasDirtyFlags
            const row = $('<div>')
                    ? !!draft.dirtyPreload
                .addClass('preload-editor-field');
                    : true,


            $('<label>')
                 dirtyConfig: hasDirtyFlags
                 .addClass('preload-editor-label')
                    ? !!draft.dirtyConfig
                .text(label)
                    : true,
                .appendTo(row);


            if (description) {
                 localDraftSavedAt: Number(draft.savedAt) || null,
                 $('<div>')
                localDraftAvailable: true
                    .addClass('preload-editor-help')
             };
                    .text(description)
                    .appendTo(row);
             }


             row.append(input);
             this.reanalyze();
             return row;
             this.renderEditor();
        },
            this.updateLocalDraftIndicator();


        textInput(value, placeholder) {
             this.setStatus(
             return $('<input>')
                 'Restored unsaved local work from this browser.',
                 .attr({
                'warning'
                    type: 'text',
            );
                    value: value == null ? '' : value,
                    placeholder: placeholder || ''
                })
                .addClass('preload-editor-input');
        },


        textarea(value) {
             mw.notify('Unsaved Preload Editor work restored.', {
             return $('<textarea>')
                 type: 'success'
                 .val(value == null ? '' : value)
            });
                .addClass('preload-editor-textarea');
        },


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


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


             options.forEach(option => {
        async getPage(title) {
                 $('<option>')
             const response = await new mw.Api().get({
                    .attr('value', option.value)
                 action: 'query',
                    .text(option.label)
                prop: 'info|revisions',
                    .prop(
                titles: title,
                        'selected',
                rvprop: 'content',
                        String(option.value) === String(value === undefined ? '' : value)
                rvslots: 'main',
                    )
                formatversion: 2
                    .appendTo(select);
             });
             });


             return select;
             const page =
        },
                response &&
 
                response.query &&
        // CodeMirror
                response.query.pages &&
                response.query.pages[0];


        destroyEditor() {
             if (!page || page.missing) {
             if (!this.editor) {
                 return null;
                 this.editorView = null;
                this.editorTools = null;
                return;
             }
             }


             const { view, inputHandler } = this.editor;
             const content =
                page.revisions &&
                page.revisions[0] &&
                page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;


             if (view && inputHandler) {
             return {
                 view.dom.removeEventListener('input', inputHandler);
                 title: page.title || title,
            }
                content: typeof content === 'string' ? content : '',
 
                contentmodel: page.contentmodel || 'wikitext'
            if (view) view.destroy();
             };
 
             this.editor = null;
            this.editorView = null;
            this.editorTools = null;
         },
         },


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


         getEditorContent() {
         async searchPages(query) {
             if (this.editorView && this.editorView.state) {
             const response = await new mw.Api().get({
                 return this.editorView.state.doc.toString();
                 action: 'query',
             }
                list: 'search',
                srsearch: query,
                srlimit: 10,
                srnamespace: 10,
                formatversion: 2
             });


             return this.state.preloadContent || '';
             return (
                response &&
                response.query &&
                response.query.search
            ) || [];
         },
         },


         setEditorContent(content) {
         /*
             content = String(content || '');
        * Save a page.
        *
        * contentModel is mainly used when creating a page.
        *
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
        async savePage(title, content, summary, createOnly, contentModel) {
             const params = {
                action: 'edit',
                title,
                text: content,
                summary: summary || 'Updated with Preload Editor',
                formatversion: 2
            };


             if (!this.editorView) {
             if (createOnly) {
                 this.state.preloadContent = content;
                 params.createonly = true;
                return;
             }
             }


             const current = this.editorView.state.doc.toString();
             if (contentModel) {
             if (current === content) return;
                params.contentmodel = contentModel;
             }


             this.editorView.dispatch({
             return new mw.Api().postWithToken('csrf', params);
                changes: {
                    from: 0,
                    to: this.editorView.state.doc.length,
                    insert: content
                }
            });
         },
         },


         getEditorSelection() {
         /*
             if (!this.editorView?.state) return null;
        * Change the content model of an existing page.
        *
        * This is the API equivalent of using
        * Special:ChangeContentModel manually.
        *
        * The page must already exist.
        */
        async changeContentModel(title, model, summary) {
            return new mw.Api().postWithToken('csrf', {
                action: 'changecontentmodel',
                title,
                model,
                reason: summary || 'Changed content model with Preload Editor'
            });
        },
 
        /*
        * Save config.json and make sure its content model
        * is JSON.
        *
        * New page:
        *  create directly with contentmodel=json.
        *
        * Existing page:
        *  if not already JSON, change its model first,
        *  then save the JSON normally.
        */
        async saveConfigPage(title, content, summary) {
            const page = await this.getPage(title);
 
             if (!page) {
                return this.savePage(
                    title,
                    content,
                    summary,
                    true,
                    'json'
                );
            }


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


             return {
             return this.savePage(
                 from: selection.from,
                 title,
                 to: selection.to,
                 content,
                 text: this.editorView.state.doc.sliceString(
                 summary,
                    selection.from,
                 false
                    selection.to
             );
                 )
             };
         },
         },


         focusEditor() {
         // =========================================================
            if (this.editorView) this.editorView.focus();
        // Config import helpers
         },
         // =========================================================


         insertEditorText(
         /*
            text,
        * Accept either:
            selectionFrom,
        *
            selectionTo,
        *  Template:Example/Preload
            cursorPosition
        *
         ) {
        * or:
             if (!this.editorView) return;
        *
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
         normalizeConfigTitle(title) {
             title = String(title || '').trim();
            title = title.replace(/\/+$/, '');


             const view = this.editorView;
             if (/\/config\.json$/i.test(title)) {
             const selection = view.state.selection.main;
                return title;
             }


             const from =
             return title + '/config.json';
                selectionFrom === undefined
        },
                    ? selection.from
                    : selectionFrom;


             const to =
        /*
                 selectionTo === undefined
        * Return a safe clone of a config field.
                     ? selection.to
        *
                     : selectionTo;
        * 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
                );


            const cursor =
                 return null;
                 cursorPosition === undefined
            }
                    ? from + text.length
        },
                    : cursorPosition;


            view.dispatch({
        /*
                changes: { from, to, insert: text },
        * Normalize imported field names to the same uppercase
                selection: { anchor: cursor }
        * convention used throughout the editor.
             });
        */
        getImportableFields(sourceConfig) {
             const fields = sourceConfig && sourceConfig.fields;


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


        // V2.3 editor tools
            const result = {};


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


            if (!selected || selected.from === selected.to) {
                if (!upper || upper === 'PAGE') {
                this.focusEditor();
                    return;
                 return;
                 }
            }
 
            const replacement =
                '%%' + selected.text + '%%';


            this.insertEditorText(
                if (
                replacement,
                    !field ||
                selected.from,
                    typeof field !== 'object' ||
                selected.to,
                    Array.isArray(field)
                 selected.from + replacement.length
                 ) {
            );
                    return;
        },
                }


        insertVariable(name) {
                const clone = this.cloneConfigField(field);
            name = String(name || '').trim().toUpperCase();
            if (!name) return;


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


             const text = '%%' + name + '%%';
                result[upper] = clone;
             });


             this.insertEditorText(
             return result;
                text,
                selected.from,
                selected.to
            );
         },
         },


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


            const selected = this.getEditorSelection();
                const overlay = $('<div>')
            if (!selected) return;
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );


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


            switch (type) {
                $('<h2>')
                case 'if': {
                     .text('Import variable definitions')
                     const opening = '<!-- @if ' + variable + ' -->';
                     .appendTo(box);
                     const closing = '<!-- @endif -->';


                    if (selected.from !== selected.to) {
                $('<p>')
                        text =
                    .text(
                            opening +
                        'Choose which variable definitions to import from "' +
                            '\n' +
                        sourceTitle +
                            selected.text +
                        '". Existing local definitions can be replaced.'
                            '\n' +
                    )
                            closing;
                    .appendTo(box);
                        cursorOffset = text.length;
 
                     } else {
                if (!names.length) {
                         text =
                     $('<div>')
                             opening +
                         .addClass(
                             '\n\n' +
                             'preload-editor-empty preload-editor-import-empty'
                            closing;
                        )
                         cursorOffset = opening.length + 1;
                        .text(
                     }
                             'This config.json does not contain any importable variable definitions.'
                        )
                         .appendTo(box);
 
                     const emptyButtons = $('<div>')
                        .addClass('preload-editor-prompt-buttons');


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


                case 'elseif':
                     emptyButtons.append(close);
                     text = '<!-- @elseif -->';
                     box.append(emptyButtons);
                     cursorOffset = text.length;
                     overlay.append(box);
                     break;


                case 'else':
                     $(document.body).append(overlay);
                     text = '<!-- @else -->';
                    cursorOffset = text.length;
                    break;


                case 'endif':
                    overlay.attr('tabindex', '-1');
                    text = '<!-- @endif -->';
                     overlay.trigger('focus');
                     cursorOffset = text.length;
                    break;


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


            this.insertEditorText(
                const searchWrap = $('<div>')
                text,
                    .addClass('preload-editor-import-search-wrap')
                selected.from,
                    .append(search);
                selected.to,
 
                 selected.from + cursorOffset
                 box.append(searchWrap);
            );
        },


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


            if (this.analysis && this.analysis.variables) {
                const selectAll = this.createButton(
                this.analysis.variables.forEach(name => {
                    'Select all',
                    variables.add(String(name).toUpperCase());
                    '',
                });
                    () => {
            }
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', true);


            return Array.from(variables);
                        updateSummary();
        },
                    }
                );


        createToolSelect(options, className) {
                const deselectAll = this.createButton(
            const select = $('<select>')
                    'Deselect all',
                .addClass('preload-editor-tool-select');
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);


            if (className) select.addClass(className);
                        updateSummary();
                    }
                );


            options.forEach(option => {
                 controls.append(selectAll, deselectAll);
                 $('<option>')
                box.append(controls);
                    .attr('value', option.value)
                    .text(option.label)
                    .appendTo(select);
            });


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


        updateEditorToolVariables() {
                const localFields =
            if (!this.editorTools) return;
                    this.state.config && this.state.config.fields
                        ? this.state.config.fields
                        : {};


            const variables = this.getToolVariables();
                names.forEach(name => {
            const current =
                    const existing = !!localFields[name];
                this.editorTools.variableSelect.val();
                    const field = fields[name];
            const currentCondition =
                this.editorTools.conditionVariableSelect.val();


            const populate = (select, value) => {
                    const type = field && field.type
                select.empty();
                        ? String(field.type)
                        : 'text';


                variables.forEach(name => {
                    const label = field && field.label
                     $('<option>')
                        ? String(field.label)
                         .attr('value', name)
                        : this.humanizeName(name);
                         .text(name)
 
                        .appendTo(select);
                     const row = $('<label>')
                });
                        .addClass('preload-editor-import-row')
                         .attr('data-variable', name)
                         .attr(
                            'data-search',
                            (name + ' ' + label + ' ' + type).toLowerCase()
                        );


                if (value && variables.includes(value)) {
                    const checkbox = this.checkbox(false)
                    select.val(value);
                        .attr('data-import-variable', name)
                } else if (variables.length) {
                        .addClass('preload-editor-import-checkbox');
                    select.val(variables[0]);
                }
            };


            populate(
                    const content = $('<span>')
                this.editorTools.variableSelect,
                        .addClass('preload-editor-import-content');
                current
            );


            populate(
                    const header = $('<span>')
                this.editorTools.conditionVariableSelect,
                        .addClass('preload-editor-import-header');
                currentCondition
            );
        },


        updateConditionVariableVisibility() {
                    $('<strong>')
            if (!this.editorTools) return;
                        .text(name)
                        .appendTo(header);


            const type =
                    $('<span>')
                this.editorTools.conditionTypeSelect.val();
                        .addClass('preload-editor-import-type')
                        .text(type)
                        .appendTo(header);


            this.editorTools.conditionVariableWrap.toggle(
                    const meta = $('<span>')
                type === 'if'
                        .addClass('preload-editor-import-meta');
            );
        },


        renderEditorTools() {
                    $('<span>')
            const tools = $('<div>')
                        .text(label)
                .addClass('preload-editor-tools');
                        .appendTo(meta);


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


            const wrapGroup = $('<div>')
                    content.append(header, meta, status);
                .addClass(
                    row.append(checkbox, content);
                     'preload-editor-tool-group preload-editor-tool-group-wrap'
                     list.append(row);
                 );
                 });


            wrapGroup.append(
                box.append(list);
                this.createButton(
                    'Wrap selection with %%',
                    'preload-editor-tool-button',
                    () => this.wrapSelectionWithVariable()
                )
            );


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


            const variableGroup = $('<div>')
                const updateSummary = () => {
                .addClass(
                    const selected = list.find(
                    'preload-editor-tool-group preload-editor-tool-group-variable'
                        'input[type="checkbox"]:checked'
                );
                    ).length;


            $('<span>')
                    const existingSelected = list
                .addClass('preload-editor-tool-label')
                        .find('input[type="checkbox"]:checked')
                .text('Insert existing variable')
                        .filter(function () {
                .appendTo(variableGroup);
                            const name = $(this).attr(
                                'data-import-variable'
                            );


            const variableSelect = this.createToolSelect(
                            return !!localFields[name];
                [],
                        }).length;
                'preload-editor-variable-select'
            );


            variableGroup.append(
                    let text =
                variableSelect,
                        selected +
                this.createButton(
                        ' ' +
                    'Insert',
                        (selected === 1 ? 'variable' : 'variables') +
                    'preload-editor-tool-button',
                        ' selected.';
                    () => this.insertVariable(variableSelect.val())
                )
            );


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


            const conditionGroup = $('<div>')
                    summary.text(text);
                .addClass(
                    'preload-editor-tool-group preload-editor-tool-group-condition'
                );


            $('<span>')
                    importButton.prop('disabled', selected === 0);
                .addClass('preload-editor-tool-label')
                 };
                .text('Insert condition')
                 .appendTo(conditionGroup);


            const conditionTypeSelect = this.createToolSelect(
                const filterRows = () => {
                [
                     const query = String(search.val() || '')
                    { value: 'if', label: '@if' },
                        .trim()
                     { value: 'elseif', label: '@elseif' },
                        .toLowerCase();
                    { value: 'else', label: '@else' },
                    { value: 'endif', label: '@endif' }
                ],
                'preload-editor-condition-type-select'
            );


            const conditionVariableSelect = this.createToolSelect(
                    list.find('.preload-editor-import-row').each(function () {
                [],
                        const row = $(this);
                'preload-editor-condition-variable-select'
                        const haystack = String(
            );
                            row.attr('data-search') || ''
                        );


            const conditionVariableWrap = $('<span>')
                        row.toggle(!query || haystack.includes(query));
                .addClass(
                     });
                     'preload-editor-condition-variable'
                 };
                )
                 .append(conditionVariableSelect);


            const insertCondition = this.createButton(
                 search.on(
                'Insert',
                     'input.preloadEditor',
                'preload-editor-tool-button',
                     filterRows
                 () => this.insertCondition(
                 );
                     conditionTypeSelect.val(),
                     conditionVariableSelect.val()
                 )
            );


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


            conditionGroup.append(
                const buttons = $('<div>')
                conditionTypeSelect,
                    .addClass('preload-editor-prompt-buttons');
                conditionVariableWrap,
                insertCondition
            );


            tools.append(
                const cancel = this.createButton(
                wrapGroup,
                    'Cancel',
                variableGroup,
                    '',
                 conditionGroup
                    () => {
            );
                        overlay.remove();
                        resolve(null);
                    }
                 );


            this.editorTools = {
                const importButton = this.createButton(
                root: tools,
                    'Import selected',
                variableSelect,
                    'preload-editor-button-primary',
                conditionTypeSelect,
                    () => {
                conditionVariableSelect,
                        const selected = [];
                conditionVariableWrap,
                insertCondition
            };


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


            return tools;
                        overlay.remove();
        },
                        resolve(selected);
                    }
                );


        updateEditorTools() {
                buttons.append(cancel, importButton);
            this.updateEditorToolVariables();
                box.append(summary, buttons);
            this.updateConditionVariableVisibility();
                overlay.append(box);
        },
 
                $(document.body).append(overlay);
 
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');


        // Preload syntax highlighting
                updateSummary();
                search.trigger('focus');


        getKnownVariables() {
                const close = event => {
            const known = new Set(['PAGE']);
                    if (event.key === 'Escape') {
            const fields = this.state.config?.fields;
                        cancel.trigger('click');
                    }
                };


            if (fields && typeof fields === 'object') {
                 overlay.on(
                 Object.keys(fields).forEach(name => {
                    'keydown.preloadEditor',
                     known.add(String(name).toUpperCase());
                     close
                 });
                 );
            }


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


         createSyntaxDecorations(state, Decoration) {
         /*
             const decorations = [];
        * Main import workflow.
            const source = state.doc.toString();
        */
             const knownVariables = this.getKnownVariables();
        async importVariableDefinitions() {
             const source = await this.createPromptDialog(
                'Import variable definitions',
                'Enter a preload title or its config.json title.'
            );
 
             if (!source) {
                return;
            }


             const variablePattern = /%%([A-Za-z0-9_-]+)%%/g;
             const configTitle = this.normalizeConfigTitle(source);
            let match;


             while ((match = variablePattern.exec(source)) !== null) {
             this.setStatus(
                 const name = match[1].toUpperCase();
                 'Loading source config...',
                 const known = knownVariables.has(name);
                 'loading'
            );


                decorations.push(
            try {
                    Decoration.mark({
                const page = await this.getPage(configTitle);
                        class: [
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index + match[0].length
                    )
                );
            }


            const conditionPattern =
                 if (!page) {
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    throw new Error(
                        'No config.json was found at "' +
                        configTitle +
                        '".'
                    );
                }


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


                 const directiveStart =
                 try {
                     match.index + match[0].indexOf('@');
                     sourceConfig = JSON.parse(page.content);
                } catch (error) {
                    throw new Error(
                        'The source config.json contains invalid JSON: ' +
                        error.message
                    );
                }


                 decorations.push(
                 if (
                     Decoration.mark({
                     !sourceConfig ||
                        class: 'preload-editor-syntax-directive'
                    typeof sourceConfig !== 'object' ||
                     }).range(
                     Array.isArray(sourceConfig)
                        directiveStart,
                ) {
                         directiveStart + match[1].length + 1
                    throw new Error(
                     )
                         'The source config.json must contain a JSON object.'
                 );
                     );
                 }


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


                 if (type !== 'if' && type !== 'elseif') continue;
                 const fields = this.getImportableFields(sourceConfig);


                 const expression = match[2];
                 const selected =
                const expressionStart =
                     await this.createImportDefinitionsDialog(
                     match.index + match[0].indexOf(expression);
                        configTitle,
                        fields
                    );


                 const expressionPattern = /[A-Za-z0-9_-]+/g;
                 if (selected === null) {
                let expressionMatch;
                    this.setStatus(
                        'Variable import cancelled.',
                        'warning'
                    );


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


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


                     const start =
                     return;
                        expressionStart + expressionMatch.index;
                }


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


            return Decoration.set(decorations, true);
                if (!this.state.config.fields) {
        },
                    this.state.config.fields = {};
                }


        async installSyntaxHighlighting(view) {
                const imported = [];
            await mw.loader.using('ext.CodeMirror.v6.lib');
                const replaced = [];


            const require = mw.loader.require;
                selected.forEach(name => {
            const {
                    if (name === 'PAGE') {
                StateField,
                        return;
                StateEffect,
                    }
                EditorView,
                Decoration
            } = require('ext.CodeMirror.v6.lib');


            const syntaxField = StateField.define({
                    const field = fields[name];
                create: state =>
                    this.createSyntaxDecorations(state, Decoration),


                update: (decorations, transaction) =>
                    if (!field) {
                    transaction.docChanged
                         return;
                         ? this.createSyntaxDecorations(
                    }
                            transaction.state,
                            Decoration
                        )
                        : decorations,


                provide: field =>
                     if (this.state.config.fields[name]) {
                     EditorView.decorations.from(field)
                        replaced.push(name);
            });
                    } else {
                        imported.push(name);
                    }


            view.dispatch({
                    const clone = this.cloneConfigField(field);
                effects: StateEffect.appendConfig.of(syntaxField)
            });


            this.editor.syntaxField = syntaxField;
                    if (!clone) {
        },
                        return;
                    }


        // CodeMirror mounting
                    this.state.config.fields[name] = clone;


        async mountCodeMirror(textarea) {
                    /*
            return new Promise((resolve, reject) => {
                    * If this variable was previously deleted,
                 let settled = false;
                    * 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 cleanup = () => {
                 /*
                    mw.hook('dev.CCM.ready').remove(onReady);
                * Keep PAGE automatic regardless of what the
                     mw.hook('dev.CCM.load').remove(onLoad);
                * imported config contained.
                };
                */
                this.state.config.fields.PAGE =
                     this.getAutomaticPageField();


                 const onReady = async cm => {
                 this.markConfigDirty();
                    if (
                        settled ||
                        !cm ||
                        cm.textarea !== textarea ||
                        !cm.view
                    ) return;


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


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


                    const inputHandler = () => {
                this.reanalyze();
                        this.state.preloadContent =
                            view.state.doc.toString();


                        this.state.dirty = true;
                this.renderVariablesBySelector();
                        this.reanalyze();
                this.renderVariableConfigurationBySelector();
                        this.renderVariablesBySelector();
                this.renderAnalysisBySelector();
                        this.renderAnalysisBySelector();
                this.updateEditorTools();
                        this.renderConfigPreviewBySelector();
                        this.updateEditorTools();
                    };


                    view.dom.addEventListener(
                this.saveDraft();
                        'input',
                        inputHandler
                    );


                     view.dom.classList.add(
                let status =
                         'preload-editor-codemirror'
                    'Imported ' +
                     );
                     selected.length +
                    ' variable ' +
                    (selected.length === 1
                         ? 'definition'
                        : 'definitions') +
                     '.';


                     const wrapper =
                if (replaced.length) {
                         view.dom.closest(
                     status +=
                            '.ext-codemirror-wrapper'
                         ' Replaced: ' +
                        );
                        replaced.join(', ') +
                        '.';
                }


                    if (wrapper) {
                this.setStatus(status, 'success');
                        wrapper.classList.add(
                            'preload-editor-codemirror-wrapper'
                        );
                    }


                    this.editor = {
                mw.notify(status, {
                        cm,
                    type: 'success'
                        view,
                });
                        textarea,
            } catch (error) {
                        inputHandler
                console.error(
                    };
                    'Preload Editor variable import:',
                    error
                );


                    this.editorView = view;
                this.setStatus(
                     this.state.preloadContent =
                     error.message ||
                         view.state.doc.toString();
                         'Could not import variable definitions.',
                    'error'
                );


                     try {
                mw.notify(
                         await this.installSyntaxHighlighting(view);
                     error.message ||
                        resolve(view);
                         'Could not import variable definitions.',
                     } catch (error) {
                     {
                         reject(error);
                         type: 'error'
                     }
                     }
                 };
                 );
            }
        },


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


                    try {
        extractIncludeonly(source) {
                        loader(textarea);
            const match = String(source || '').match(
                    } catch (error) {
                /<includeonly>([\s\S]*?)<\/includeonly>/i
                        settled = true;
            );
                        cleanup();
                        reject(error);
                    }
                };


                 mw.hook('dev.CCM.ready').add(onReady);
            return match
                 mw.hook('dev.CCM.load').add(onLoad);
                 ? match[1].trim()
            });
                 : String(source || '').trim();
         },
         },


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


        init() {
             let match;
             const root = $('#mw-content-text');
            if (!root.length) return;


             this.root = $('<div>')
             while ((match = pattern.exec(content)) !== null) {
                .attr('id', 'preload-editor')
                 const name = match[1].toUpperCase();
                 .addClass('preload-editor');


            root.append(this.root);
                if (!variables.includes(name)) {
             this.renderShell();
                    variables.push(name);
                }
             }
 
            return variables;
         },
         },


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


             const loader = this.createSection('Preload');
             let match;


             const titleInput = this.textInput(
             while ((match = pattern.exec(content)) !== null) {
                 this.state.preloadTitle,
                 conditions.push({
                'Template:Example/Preload'
                    type: match[1].toLowerCase(),
            ).attr('id', 'preload-editor-title-input');
                    expression: match[2].trim(),
                    index: match.index
                });
            }


             const loadButton = this.createButton(
             return conditions;
                'Load',
        },
                'preload-editor-button-primary',
 
                () => this.loadExisting(titleInput.val())
        findConditionVariables(content) {
             );
             const variables = [];


             const newButton = this.createButton(
             this.findConditions(content).forEach(condition => {
                 'New',
                 if (
                '',
                    condition.type !== 'if' &&
                 () => this.startNew()
                    condition.type !== 'elseif'
            );
                 ) {
                    return;
                }


            const sampleButton = this.createButton(
                const matches =
                'Load Sample Page',
                    condition.expression.match(
                '',
                        /[A-Za-z0-9_-]+/g
                () => this.loadSamplePage()
                    ) || [];
            );


            loader.append(
                matches.forEach(name => {
                $('<div>')
                     name = name.toUpperCase();
                    .addClass('preload-editor-toolbar')
                     .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );


            this.root.append(loader);
                    if (!variables.includes(name)) {
                        variables.push(name);
                    }
                });
            });


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


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


            this.workspace = $('<div>')
        // =========================================================
                .addClass('preload-editor-workspace');
        // Config
        // =========================================================


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


         renderWelcome() {
         emptyConfig() {
             this.workspace.empty();
             return {
                settings: {
                    incomplete: 'add-stub'
                },


            const section = this.createSection('Get started');
                fields: {
 
                    PAGE: this.getAutomaticPageField()
             $('<p>')
                }
                .text(
             };
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
        },
                )
                .appendTo(section);


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


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


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


        setStatus(message, type) {
            config.fields.PAGE =
            if (!this.status) return;
                this.getAutomaticPageField();


             this.status.removeClass(
             return config;
                'is-error',
        },
                'is-success',
                'is-warning',
                'is-loading'
            );


            if (type) this.status.addClass('is-' + type);
        createDefaultField(name, analysis) {
            this.status.text(message || '');
            return {
                label: this.humanizeName(name),
                description: '',
                type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                    : 'text'
            };
         },
         },


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


         async loadExisting(title) {
         prepareConfigForVariables(config, analysis) {
             title = String(title || '').trim();
             config = this.normalizeConfig(config);


             if (!title) {
             const existing = config.fields || {};
                mw.notify(
                    'Enter a preload page title first.',
                    { type: 'warn' }
                );
                return;
            }


             this.setStatus('Loading preload...', 'loading');
             const deleted = new Set(
                Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.map(
                        name => String(name).toUpperCase()
                    )
                    : []
            );


             try {
             const fields = {};
                const page = await this.getPage(title);


                if (!page) {
            fields.PAGE =
                    const suggestions =
                this.getAutomaticPageField();
                        await this.findSimilarPreloads(title);


                    this.renderMissingPage(title, suggestions);
            analysis.variables.forEach(name => {
                    this.setStatus(
                if (
                        'Preload not found.',
                    name === 'PAGE' ||
                        'warning'
                     deleted.has(name)
                     );
                ) {
                     return;
                     return;
                 }
                 }


                 await this.loadDefinition(
                 fields[name] =
                    page.title,
                    existing[name] ||
                     page.content
                    this.createDefaultField(
                );
                        name,
                        analysis
                     );
            });


                this.setStatus(
            Object.keys(existing).forEach(name => {
                    'Preload loaded.',
                 const upper = name.toUpperCase();
                    'success'
                );
            } catch (error) {
                 console.error('Preload Editor:', error);
                this.setStatus(
                    error.message || 'Could not load preload.',
                    'error'
                );
            }
        },


        async findSimilarPreloads(title) {
                if (
            let query = title
                    upper !== 'PAGE' &&
                .replace(/\/Preload$/i, '')
                    !fields[upper] &&
                 .trim();
                    !deleted.has(upper)
                ) {
                    fields[upper] =
                        existing[name];
                 }
            });


             if (!query) query = title;
             config.fields = fields;


             try {
             return config;
                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) {
         validateConfig(config, analysis) {
             this.workspace.empty();
             const errors = [];
            const warnings = [];


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


             $('<p>')
             if (
                 .text('No preload exists at "' + title + '".')
                !config.fields ||
                 .appendTo(section);
                typeof config.fields !== 'object' ||
 
                 Array.isArray(config.fields)
             if (suggestions.length) {
            ) {
                 $('<h3>')
                return {
                    .text('Similar preloads')
                    valid: false,
                    .appendTo(section);
                    errors: [
                        '"fields" must be an object.'
                    ],
                    warnings
                 };
            }
 
             const configured =
                Object.keys(
                    config.fields
                 ).map(
                    name =>
                        name.toUpperCase()
                );


                 const list = $('<div>')
            analysis.variables.forEach(name => {
                     .addClass('preload-editor-suggestions');
                 if (!configured.includes(name)) {
                     errors.push(
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                }
            });


                suggestions.forEach(result => {
            configured.forEach(name => {
                    list.append(
                if (!analysis.variables.includes(name)) {
                        this.createButton(
                    warnings.push(
                            result.title,
                        'Field "' +
                            'preload-editor-suggestion',
                        name +
                            () => this.loadExisting(result.title)
                         '" is not used by the preload.'
                         )
                     );
                     );
                 });
                 }
            });


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


             section.append(
             Object.entries(config.fields).forEach(([name, field]) => {
                 this.createButton(
                 if (
                     'Create this preload',
                     !field ||
                     'preload-editor-button-primary',
                     typeof field !== 'object' ||
                     () => this.startNew(title)
                     Array.isArray(field)
                 )
                 ) {
            );
                    errors.push(
                        'Field "' +
                        name +
                        '" must be an object.'
                    );


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


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


            this.state = {
                    if (
                preloadTitle: title,
                        Array.isArray(field.accept) &&
                preloadSource: '',
                        field.accept.some(
                preloadContent: this.defaults.preload,
                            value =>
                config: this.emptyConfig(),
                                !String(
                variables: ['PAGE'],
                                    value || ''
                conditions: [],
                                ).trim()
                mode: 'new',
                        )
                dirty: true
                    ) {
            };
                        errors.push(
                            'File field "' +
                            name +
                            '" contains an empty accepted MIME type.'
                        );
                    }


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


            this.setStatus(
                    if (
                'Creating a new preload.',
                        field.filetext !== undefined &&
                'success'
                        typeof field.filetext !== 'string'
            );
                    ) {
        },
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


        async loadSamplePage() {
                    if (
            const result = await this.createPromptDialog(
                        !field.accept ||
                'Load Sample Page',
                        !field.accept.length
                'Enter the title of a normal wiki page to use as the starting point.'
                    ) {
            );
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


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


            this.setStatus(
                if (
                'Loading sample page...',
                    (
                'loading'
                        field.type === 'select' ||
            );
                        field.type === 'multiselect'
 
                    ) &&
            try {
                    !field.source &&
                const page = await this.getPage(result);
                    !Array.isArray(field.options)
 
                 ) {
                 if (!page) {
                     warnings.push(
                     throw new Error(
                         'Field "' +
                         'Sample page not found: ' + result
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                     );
                     );
                 }
                 }


                 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
        // =========================================================
                );
        // Transformation helpers
        // =========================================================


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


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


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


            if (include) content = include[1].trim();
                case 'replace':
 
                    return from === ''
            content = content
                        ? null
                .replace(
                        : {
                    /<noinclude>[\s\S]*?<\/noinclude>/gi,
                            transform,
                    ''
                            from,
                )
                            to: to || ''
                .trim();
                        };


            return (
                 default:
                 '<includeonly>\n' +
                    return null;
                content +
            }
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
         },
         },


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


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


                $('<h2>')
            if (className) {
                    .text(title)
                section.addClass(className);
                    .appendTo(box);
            }


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


                const input = this.textInput();
            return section;
        },


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


                 const cancel = this.createButton(
            if (callback) {
                     'Cancel',
                 button.on(
                     '',
                     'click.preloadEditor',
                    () => {
                     callback
                        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 =
        },
                 title.replace(/\/+$/, '') +
                '/config.json';


             const configPage =
        checkbox(checked) {
                 await this.getPage(configTitle);
             return $('<input>')
                .attr('type', 'checkbox')
                .prop('checked', !!checked)
                 .addClass('preload-editor-checkbox');
        },


            if (configPage) {
        select(options, value) {
                try {
            const select = $('<select>')
                    config = JSON.parse(configPage.content);
                 .addClass('preload-editor-select');
                 } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }


             const analysis =
             options.forEach(option => {
                 this.analyzePreload(content);
                 $('<option>')
 
                    .attr('value', option.value)
            config = this.prepareConfigForVariables(
                    .text(option.label)
                config,
                    .prop(
                analysis
                        'selected',
             );
                        String(option.value) ===
                        String(value === undefined ? '' : value)
                    )
                    .appendTo(select);
             });


             this.state = {
             return select;
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,
                variables: analysis.variables,
                conditions: analysis.conditions,
                mode: 'edit',
                dirty: false
            };
 
            this.renderEditor();
         },
         },


         // Editor
         // =========================================================
        // In-wiki dialogs
        // =========================================================


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


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


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


            const right = $('<div>')
                const messageLines =
                .addClass('preload-editor-right');
                    String(message || '').split('\n');


            const editorSection = this.createSection(
                messageLines.forEach(line => {
                'Preload',
                    if (line === '') {
                'preload-editor-main-section'
                        $('<div>')
            );
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);


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


            $('<strong>')
                    $('<p>')
                .text(this.state.preloadTitle || 'New preload')
                        .text(line)
                .appendTo(meta);
                        .appendTo(box);
                });


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


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


            editorSection.append(
                const confirm = this.createButton(
                this.renderEditorTools()
                    confirmLabel || 'Confirm',
            );
                    'preload-editor-button-primary',
                    () => {
                        overlay.remove();
                        resolve(true);
                    }
                );


            const textarea = this.textarea(
                buttons.append(cancel, confirm);
                this.state.preloadContent
                 box.append(buttons);
            )
                 overlay.append(box);
                 .attr('id', 'preload-editor-content')
                 .addClass('preload-editor-content');


            const editorMount = $('<div>')
                $(document.body).append(overlay);
                .addClass('preload-editor-codemirror-mount')
                .append(textarea);


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


            const analysisSection =
                 overlay.on(
                 this.createSection('Analysis');
                    'keydown.preloadEditor',
                    event => {
                        close(event.key);
                    }
                );


            const analysisContainer = $('<div>')
                overlay.attr('tabindex', '-1');
                 .addClass('preload-editor-analysis');
                 overlay.trigger('focus');


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


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


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


            variablesSection.append(variableContainer);
                $('<h2>')
                    .text(title)
                    .appendTo(box);


            const configSection =
                 $('<p>')
                 this.createSection('Generated configuration');
                    .text(message)
                    .appendTo(box);


            const configPreview = $('<pre>')
                const input = this.textInput();
                .addClass('preload-editor-config-preview');


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


            const actions = $('<div>')
                const cancel = this.createButton(
                .addClass('preload-editor-actions');
                     'Cancel',
 
            actions.append(
                this.createButton(
                    'Save Preload + Config',
                    'preload-editor-button-primary',
                    () => this.saveAll()
                ),
                this.createButton(
                     'Save Preload Only',
                     '',
                     '',
                     () => this.savePreloadOnly()
                     () => {
                )
                        overlay.remove();
            );
                        resolve(null);
                    }
                );


            right.append(
                const confirm = this.createButton(
                analysisSection,
                    'Load',
                variablesSection,
                    'preload-editor-button-primary',
                configSection,
                    () => {
                actions
                        const value =
            );
                            String(
                                input.val() || ''
                            ).trim();


            layout.append(left, right);
                        if (!value) {
            this.workspace.append(layout);
                            return;
                        }


            this.reanalyze();
                        overlay.remove();
            this.renderVariables(variableContainer);
                        resolve(value);
            this.renderAnalysis(analysisContainer);
                    }
            this.renderConfigPreview(configPreview);
                );
            this.updateEditorTools();


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


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


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


            this.state.preloadContent = source;
                $(document.body).append(overlay);
            this.state.variables = analysis.variables;
            this.state.conditions = analysis.conditions;


            this.state.config =
                 input.trigger('focus');
                 this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


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


        renderAnalysis(container) {
                        if (event.key === 'Escape') {
            container.empty();
                            cancel.trigger('click');
 
                         }
            const analysis =
                     }
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                         this.getEditorContent()
                     )
                 );
                 );
            });
        },


             const variableCount = analysis.variables.length;
        createConfigReviewDialog() {
            const conditionCount = analysis.conditions.length;
             return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );


            const summary = $('<div>')
                const box = $('<div>')
                .addClass('preload-editor-analysis-summary');
                    .addClass(
                        'preload-editor-prompt preload-editor-code-review'
                    );


            summary.append(
                 $('<h2>')
                 $('<span>').text(
                    .text('Review config.json')
                    variableCount +
                     .appendTo(box);
                    ' variable' +
 
                     (variableCount === 1 ? '' : 's')
                 $('<p>')
                ),
                    .text(
                 $('<span>').text(
                        'This is the config.json that will be saved for the current preload.'
                    conditionCount +
                     )
                    ' condition marker' +
                    .appendTo(box);
                     (conditionCount === 1 ? '' : 's')
                )
            );


            container.append(summary);
                const code = $('<pre>')
                    .addClass(
                        'preload-editor-config-review'
                    )
                    .text(this.getConfigJSON());


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


            const validation = this.validateConfig(
                box.append(codeWrap);
                this.state.config,
                analysis
            );


            if (validation.errors.length) {
                 const buttons = $('<div>')
                 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',
 
                    () => {
                 container.append(errors);
                        overlay.remove();
            }
                        resolve();
                    }
                 );
 
                 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;
            }


             header.append($('<h3>').text(name));
             const current =
                this.editorView.state.doc.toString();


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


             card.append(header);
             this.editorView.dispatch({
 
                changes: {
            const label = this.textInput(field.label || '');
                    from: 0,
 
                    to: this.editorView.state.doc.length,
            label.on('input.preloadEditor', () => {
                    insert: content
                field.label = label.val();
                 }
                this.markDirty();
                 this.renderConfigPreviewBySelector();
             });
             });
        },


             card.append(this.fieldRow('Label', label));
        getEditorSelection() {
             if (
                !this.editorView ||
                !this.editorView.state
            ) {
                return null;
            }


             const description = this.textarea(
             const selection =
                field.description || ''
                this.editorView.state.selection.main;
            ).addClass('preload-editor-small-textarea');


             description.on('input.preloadEditor', () => {
             return {
                 field.description = description.val();
                from: selection.from,
                this.markDirty();
                to: selection.to,
                 this.renderConfigPreviewBySelector();
                 text: this.editorView.state.doc.sliceString(
             });
                    selection.from,
                    selection.to
                 )
             };
        },


             card.append(
        focusEditor() {
                 this.fieldRow(
             if (this.editorView) {
                    'Description',
                 this.editorView.focus();
                    description
             }
                )
        },
             );


             const types = [
        insertEditorText(
                ['text', 'Text'],
             text,
                ['textarea', 'Textarea'],
            selectionFrom,
                ['number', 'Number'],
            selectionTo,
                ['boolean', 'Boolean'],
            cursorPosition
                ['select', 'Select'],
        ) {
                ['multiselect', 'Multi-select'],
            if (!this.editorView) {
                ['page', 'Page'],
                 return;
                 ['user', 'User'],
             }
                ['date', 'Date']
             ];


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


             typeSelect.on('change.preloadEditor', () => {
             const from =
                 field.type = typeSelect.val();
                 selectionFrom === undefined
                this.markDirty();
                     ? selection.from
 
                     : selectionFrom;
                card.replaceWith(
                     this.createVariableCard(
                        name,
                        field,
                        analysis
                     )
                );


                 this.renderConfigPreviewBySelector();
            const to =
            });
                 selectionTo === undefined
                    ? selection.to
                    : selectionTo;


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


             if (name === 'PAGE') {
             view.dispatch({
                 field.type = 'page';
                 changes: {
                    from,
                    to,
                    insert: text
                },
                selection: {
                    anchor: cursor
                }
            });


                const required = this.checkbox(
            view.focus();
                    field.required !== false
        },
                );


                required.on('change.preloadEditor', () => {
        // =========================================================
                    field.required =
        // Editor tools
                        required.prop('checked');
        // =========================================================


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


                 card.append(
            if (
                    this.fieldRow(
                !selected ||
                        'Required',
                 selected.from === selected.to
                        required
            ) {
                    )
                this.focusEditor();
                 );
                 return;
            }


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


                namespace.on('change.preloadEditor', () => {
            this.insertEditorText(
                    field.namespace = namespace.val();
                replacement,
                    this.markDirty();
                selected.from,
                    this.renderConfigPreviewBySelector();
                selected.to,
                });
                selected.from + replacement.length
            );
        },


                card.append(
        insertVariable(name) {
                    this.fieldRow(
            name = String(name || '')
                        'Namespace',
                .trim()
                        namespace
                 .toUpperCase();
                    )
                 );


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


                allowNew.on('change.preloadEditor', () => {
            const selected =
                    field['allow-new'] =
                this.getEditorSelection();
                        allowNew.prop('checked');


                    this.markDirty();
            if (!selected) {
                    this.renderConfigPreviewBySelector();
                 return;
                });
 
                card.append(
                    this.fieldRow(
                        'Allow new page',
                        allowNew
                    )
                );
 
                 return card;
             }
             }


             const required = this.checkbox(
             this.insertEditorText(
                 field.required === true
                 '%%' + name + '%%',
                selected.from,
                selected.to
             );
             );
        },


             required.on('change.preloadEditor', () => {
        insertCondition(
                 field.required =
            type,
                    required.prop('checked');
             variable
        ) {
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                 .trim()
                .toUpperCase();


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


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


             const placeholder = this.textInput(
             let text;
                field.placeholder || ''
             let cursorOffset;
             );


             placeholder.on('input.preloadEditor', () => {
             switch (type) {
                const value = placeholder.val();
                case 'if': {
                    if (!variable) {
                        return;
                    }


                if (value) field.placeholder = value;
                    const opening =
                else delete field.placeholder;
                        '<!-- @if ' +
                        variable +
                        ' -->';


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


            card.append(
                    if (
                this.fieldRow(
                        selected.from !==
                     'Placeholder',
                        selected.to
                    placeholder
                     ) {
                )
                        text =
            );
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


            const defaultInput = this.textInput(
                        cursorOffset = text.length;
                field.default === undefined
                    } else {
                    ? ''
                        text =
                    : field.default
                            opening +
            );
                            '\n\n' +
                            closing;


            defaultInput.on('input.preloadEditor', () => {
                        cursorOffset =
                const value = defaultInput.val();
                            opening.length + 1;
                    }


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


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


            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', () => {
                 case 'else':
                     const value =
                     text =
                         parseInt(maxRows.val(), 10);
                         '<!-- @else -->';


                     if (Number.isFinite(value) && value > 0) {
                     cursorOffset =
                        field.maxRows = value;
                         text.length;
                    } else {
                         delete field.maxRows;
                    }


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


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


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


             return card;
             this.insertEditorText(
                text,
                selected.from,
                selected.to,
                selected.from + cursorOffset
            );
         },
         },


         renderSelectConfiguration(card, field) {
         getToolVariables() {
             const source = this.textInput(
             const variables =
                field.source || '',
                 new Set(['PAGE']);
                 'category:Example'
            );


             source.on('input.preloadEditor', () => {
             if (
                const value = source.val();
                this.analysis &&
                this.analysis.variables
            ) {
                this.analysis.variables.forEach(
                    name => {
                        variables.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }


                if (value) field.source = value;
            return Array.from(variables);
                else delete field.source;
        },


                 this.markDirty();
        createToolSelect(
                this.renderConfigPreviewBySelector();
            options,
            });
            className
        ) {
            const select =
                 $('<select>')
                    .addClass(
                        'preload-editor-tool-select'
                    );


             card.append(
             if (className) {
                 this.fieldRow(
                 select.addClass(className);
                    'Source',
             }
                    source,
                    'Currently supported source format: category:Category Name'
                )
             );


             const sourcePrefix = this.textInput(
             options.forEach(
                 field['source-prefix'] || ''
                 option => {
                    $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                }
             );
             );


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


                if (value) {
        updateEditorToolVariables() {
                    field['source-prefix'] = value;
            if (!this.editorTools) {
                 } else {
                 return;
                    delete field['source-prefix'];
            }
                }


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


             card.append(
             const current =
                 this.fieldRow(
                 this.editorTools
                     'Source prefix',
                     .variableSelect
                     sourcePrefix,
                     .val();
                    'Only source values beginning with this text are included.'
                )
            );


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


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


                 if (value) {
                variables.forEach(
                     field.exclude = Object.assign(
                    name => {
                        {},
                        $('<option>')
                        field.exclude || {},
                            .attr(
                         { category: value }
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                );
 
                 if (
                    value &&
                    variables.includes(value)
                ) {
                     select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                         variables[0]
                     );
                     );
                } else if (field.exclude) {
                    delete field.exclude.category;
                    if (!Object.keys(field.exclude).length) {
                        delete field.exclude;
                    }
                 }
                 }
            };


                this.markDirty();
            populate(
                 this.renderConfigPreviewBySelector();
                 this.editorTools.variableSelect,
            });
                 current
 
            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                 )
             );
             );


             card.append(
             populate(
                 this.createTransformControls(
                 this.editorTools.conditionVariableSelect,
                    field,
                 currentCondition
                    'value',
                    'Value transformation'
                ),
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                 )
             );
             );
        },


            const optionsValue =
        updateConditionVariableVisibility() {
                Array.isArray(field.options)
            if (!this.editorTools) {
                    ? field.options.map(option => {
                return;
                        if (typeof option === 'string') {
            }
                            return option;
                        }


                        return (
            const type =
                            String(option.value || '') +
                this.editorTools
                            ' | ' +
                    .conditionTypeSelect
                            String(
                     .val();
                                option.label ||
                                option.value ||
                                ''
                            )
                        );
                     }).join('\n')
                    : '';


             const options = this.textarea(optionsValue)
             this.editorTools
                 .addClass('preload-editor-small-textarea');
                .conditionVariableWrap
                 .toggle(
                    type === 'if'
                );
        },


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


                 if (!lines.length) {
            const wrapGroup =
                     delete field.options;
                 $('<div>')
                } else {
                     .addClass(
                    field.options = lines.map(line => {
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                         const parts =
                    );
                            line.split(/\s*\|\s*/);


                        if (parts.length === 1) {
            wrapGroup.append(
                            return parts[0];
                this.createButton(
                        }
                    'Wrap selection',
                    'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                )
            );


                        return {
            const variableGroup =
                            value: parts[0],
                $('<div>')
                            label: parts.slice(1).join(' | ')
                    .addClass(
                        };
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                     });
                     );
                }


                 this.markDirty();
            $('<span>')
                 this.renderConfigPreviewBySelector();
                .addClass(
             });
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                 .appendTo(variableGroup);
 
            const variableSelect =
                 this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );
 
             variableGroup.append(
                variableSelect,


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


        createTransformControls(field, property, title) {
             const conditionGroup =
             const wrapper = $('<div>')
                $('<div>')
                .addClass('preload-editor-transform');
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


             $('<h4>')
             $('<span>')
                 .text(title)
                .addClass(
                 .appendTo(wrapper);
                    'preload-editor-tool-label'
                )
                 .text('Insert condition')
                 .appendTo(conditionGroup);


             const existing =
             const conditionTypeSelect =
                 field[property] &&
                 this.createToolSelect(
                 typeof field[property] === 'object'
                    [
                     ? field[property]
                        {
                     : {};
                            value: 'if',
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                 );
 
            const conditionVariableSelect =
                this.createToolSelect(
                     [],
                     'preload-editor-condition-variable-select'
                );


             const transform = this.select(
             const conditionVariableWrap =
                 [
                 $('<span>')
                    {
                     .addClass(
                        value: '',
                         'preload-editor-condition-variable'
                        label: 'No transformation'
                     )
                     },
                     .append(
                    {
                         conditionVariableSelect
                         value: 'remove-prefix',
                     );
                        label: 'Remove prefix'
                    },
                    {
                        value: 'remove-suffix',
                        label: 'Remove suffix'
                     },
                     {
                        value: 'replace',
                         label: 'Replace'
                     }
                ],
                existing.transform || ''
            );


             const prefix = this.textInput(
             const insertCondition =
                existing.prefix || ''
                this.createButton(
            );
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


             const suffix = this.textInput(
             conditionTypeSelect.on(
                 existing.suffix || ''
                 'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
             );
             );


             const from = this.textInput(
             conditionGroup.append(
                 existing.from || ''
                 conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
             );
             );


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


             const controls = $('<div>')
             this.editorTools = {
                .addClass(
                root: tools,
                    'preload-editor-transform-controls'
                variableSelect,
                );
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };
 
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();


             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,


            this.state.preloadContent =
                    provide: field =>
                 this.getEditorContent();
                        EditorView.decorations.from(
                            field
                        )
                 });


             const validation =
             view.dispatch({
                 this.validateBeforeSave();
                 effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });


             if (validation.errors.length) {
             this.editor.syntaxField =
                this.showValidationErrors(validation);
                 syntaxField;
                 return;
        },
            }


             this.setStatus(
        async mountCodeMirror(textarea) {
                 'Saving preload...',
             return new Promise(
                 'loading'
                 (
            );
                    resolve,
                    reject
                 ) => {
                    let settled = false;


            try {
                    const cleanup = () => {
                const exists =
                        mw.hook(
                    await this.pageExists(title);
                            'dev.CCM.ready'
                        ).remove(onReady);


                await this.savePage(
                        mw.hook(
                    title,
                            'dev.CCM.load'
                    this.state.preloadContent,
                         ).remove(onLoad);
                    exists
                     };
                        ? 'Updated preload with Preload Editor'
                         : 'Created preload with Preload Editor',
                     !exists
                );


                this.state.mode = 'edit';
                    const onReady =
                this.state.dirty = false;
                        async cm => {
                            if (
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                this.setStatus(
                            settled = true;
                    'Preload saved successfully.',
                            cleanup();
                    'success'
                );


                mw.notify(
                            const view =
                    'Preload saved.',
                                cm.view;
                    { type: 'success' }
 
                );
                            const inputHandler =
            } catch (error) {
                                () => {
                console.error(
                                    this.state
                    'Preload Editor save:',
                                        .preloadContent =
                    error
                                        view.state.doc.toString();
                );


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


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


        async saveAll() {
                                    this.renderVariablesBySelector();
            let title =
                                    this.renderVariableConfigurationBySelector();
                String(
                                    this.renderAnalysisBySelector();
                    this.state.preloadTitle || ''
                                    this.updateEditorTools();
                ).trim();


            if (!title) {
                                    this.saveDraft();
                const result =
                                };
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );


                if (!result) return;
                            view.dom.addEventListener(
                                'input',
                                inputHandler
                            );


                title = result;
                            view.dom.classList.add(
                this.state.preloadTitle = title;
                                'preload-editor-codemirror'
            }
                            );


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


            const validation =
                            if (wrapper) {
                this.validateBeforeSave();
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


            if (validation.errors.length) {
                            this.editor = {
                this.showValidationErrors(validation);
                                cm,
                return;
                                view,
            }
                                textarea,
                                inputHandler
                            };


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


            this.setStatus(
                            this.state.preloadContent =
                'Saving preload and config...',
                                view.state.doc.toString();
                'loading'
            );


            try {
                            try {
                const preloadExists =
                                await this.installSyntaxHighlighting(
                    await this.pageExists(title);
                                    view
                                );


                await this.savePage(
                                if (
                    title,
                                    this.state.dirty
                    this.state.preloadContent,
                                ) {
                    preloadExists
                                    this.saveDraft();
                        ? 'Updated preload with Preload Editor'
                                }
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );


                const configExists =
                                resolve(view);
                    await this.pageExists(configTitle);
                            } catch (error) {
                                reject(error);
                            }
                        };


                await this.savePage(
                    const onLoad =
                    configTitle,
                        loader => {
                    this.getConfigJSON(),
                            if (
                    configExists
                                settled ||
                        ? 'Updated preload config with Preload Editor'
                                typeof loader !==
                        : 'Created preload config with Preload Editor',
                                    'function'
                    !configExists
                            ) {
                );
                                return;
                            }


                this.state.mode = 'edit';
                            try {
                this.state.dirty = false;
                                loader(textarea);
                this.state.preloadTitle = title;
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };


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


                mw.notify(
        // =========================================================
                    'Preload and config saved.',
        // Main UI
                    { type: 'success' }
        // =========================================================
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );


                this.setStatus(
        init() {
                    error.message ||
            const root =
                        'Could not save preload/config.',
                $('#mw-content-text');
                    'error'
                );


                mw.notify(
            if (!root.length) {
                    error.message ||
                 return;
                        'Could not save preload/config.',
                    { type: 'error' }
                 );
             }
             }
        },


        validateBeforeSave() {
            this.root =
            const errors = [];
                $('<div>')
            const warnings = [];
                    .attr(
                        'id',
                        'preload-editor'
                    )
                    .addClass(
                        'preload-editor'
                    );


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


             if (!title) {
             this.state.config =
                errors.push(
                 this.prepareConfigForVariables(
                    'A preload title is required.'
                    this.state.config ||
                );
                        this.emptyConfig(),
            }
                     analysis
 
            if (
                title &&
                !/\/Preload$/i.test(title)
            ) {
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }
 
            const content =
                 this.getEditorContent();
 
            this.state.preloadContent = content;
 
            if (!content.trim()) {
                errors.push(
                     'The preload cannot be empty.'
                );
            }
 
            if (!/<includeonly>/i.test(content)) {
                warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }
 
            if (!/<noinclude>/i.test(content)) {
                warnings.push(
                    'The preload does not contain a <noinclude> section.'
                );
            }
 
            const analysis =
                this.analyzePreload(
                    this.extractIncludeonly(content)
                 );
                 );


Line 2,699: Line 6,133:
                 );
                 );


             errors.push(...configValidation.errors);
             errors.push(
             warnings.push(...configValidation.warnings);
                ...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,739: Line 6,184:
                 errors,
                 errors,
                 warnings,
                 warnings,
                 valid: errors.length === 0
                 valid:
                    errors.length === 0
             };
             };
         },
         },
Line 2,745: Line 6,191:
         showValidationErrors(validation) {
         showValidationErrors(validation) {
             this.renderAnalysisBySelector();
             this.renderAnalysisBySelector();
            this.saveDraft();


             this.setStatus(
             this.setStatus(
Line 2,753: 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;