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
 
(18 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 =
                if (!raw) {
                response &&
                    return {
                response.query &&
                        active: null,
                response.query.pages &&
                        drafts: {}
                 response.query.pages[0];
                    };
                 }


            if (!page || page.missing) return null;
                const parsed = JSON.parse(raw);


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


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


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


         async searchPages(query) {
         setDraftStorage(storage) {
             const response = await new mw.Api().get({
             try {
                 action: 'query',
                window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                list: 'search',
                return true;
                 srsearch: query,
            } catch (error) {
                srlimit: 10,
                 console.warn('Preload Editor: Could not save local draft.', error);
                srnamespace: 10,
                 return false;
                formatversion: 2
            }
            });
        },


             return (
        getDraftId(title) {
                response &&
             title = String(title || '').trim();
                response.query &&
            return title ? title.toLowerCase() : '__untitled__';
                response.query.search
            ) || [];
         },
         },


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


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


             return new mw.Api().postWithToken('csrf', params);
             let config = null;
        },


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


        extractIncludeonly(source) {
            return {
            const match = String(source || '').match(
                version: 3,
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
                preloadTitle: String(this.state.preloadTitle || ''),
            );
                preloadSource: String(this.state.preloadSource || ''),
                 preloadContent: String(content || ''),
                config,


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


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


            while ((match = pattern.exec(content)) !== null) {
                selectedVariable: String(this.state.selectedVariable || 'PAGE'),
                const name = match[1].toUpperCase();


                 if (!variables.includes(name)) {
                 deletedVariables: Array.isArray(this.state.deletedVariables)
                     variables.push(name);
                     ? this.state.deletedVariables.slice()
                }
                    : [],
            }


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


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


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


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


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


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


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


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


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


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


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


         analyzePreload(content) {
         saveDraft() {
             return {
             if (!this.state.dirty) {
                 variables: this.findVariables(content),
                 return false;
                 conditions: this.findConditions(content),
            }
                 conditionVariables:
 
                    this.findConditionVariables(content)
            const snapshot = this.getDraftSnapshot();
             };
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();
 
            storage.drafts[id] = snapshot;
            storage.active = id;
 
            const saved = this.setDraftStorage(storage);
 
            if (saved) {
                this.state.localDraftSavedAt = snapshot.savedAt;
                this.state.localDraftAvailable = true;
                 this.updateLocalDraftIndicator();
            } else {
                 this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
             }
 
            return saved;
         },
         },


         // Config
         clearDraft(title) {
            const storage = this.getDraftStorage();
            const id = this.getDraftId(title);
 
            if (storage.drafts && storage.drafts[id]) {
                delete storage.drafts[id];
            }


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


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


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


             if (
             if (storage.active && storage.drafts[storage.active]) {
                !config.fields ||
                 return {
                typeof config.fields !== 'object' ||
                     id: storage.active,
                Array.isArray(config.fields)
                     draft: storage.drafts[storage.active]
            ) {
                config.fields = {};
            }
 
            if (!config.fields.PAGE) {
                 config.fields.PAGE = {
                     label: 'Page Name',
                     description: 'Name of the page.',
                    type: 'page',
                    required: true,
                    namespace: 'Main',
                    'allow-new': true
                 };
                 };
             }
             }


             return config;
             let latestId = null;
        },
            let latestDraft = null;


        createDefaultField(name, analysis) {
            Object.entries(storage.drafts).forEach(([id, draft]) => {
            return {
                if (!draft || typeof draft !== 'object') {
                 label: this.humanizeName(name),
                    return;
                 description: '',
                }
                 type:
 
                    analysis.conditionVariables.includes(name)
                 if (
                        ? 'boolean'
                    !latestDraft ||
                        : 'text'
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                 ) {
                    latestId = id;
                    latestDraft = draft;
                 }
            });
 
            if (!latestDraft) {
                return null;
            }
 
            return {
                id: latestId,
                draft: latestDraft
             };
             };
         },
         },


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


        prepareConfigForVariables(config, analysis) {
            if (!result || !result.draft) {
             config = this.normalizeConfig(config);
                return false;
             }


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


             fields.PAGE = existing.PAGE || {
             const savedAt = draft.savedAt
                 label: 'Page Name',
                 ? new Date(draft.savedAt).toLocaleString()
                description: 'Name of the page.',
                 : '';
                type: 'page',
                 required: true,
                namespace: 'Main',
                'allow-new': true
            };


             analysis.variables.forEach(name => {
             const message =
                 if (name === 'PAGE') return;
                 'Preload Editor found unsaved local work for ' +
                displayTitle +
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                '\n\nRestore it?';


                fields[name] =
            const restore = await this.createConfirmDialog(
                    existing[name] ||
                'Restore unsaved work',
                    this.createDefaultField(
                message,
                        name,
                'Restore',
                        analysis
                'Discard'
                    );
             );
             });


             Object.keys(existing).forEach(name => {
             if (!restore) {
                 const upper = name.toUpperCase();
                this.clearDraft(title);
                 return false;
            }
 
            let config = this.emptyConfig();


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


             if (className) {
            return (
                 section.addClass(className);
                response &&
                response.query &&
                response.query.search
            ) || [];
        },
 
        /*
        * Save a page.
        *
        * contentModel is mainly used when creating a page.
        *
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
        async savePage(title, content, summary, createOnly, contentModel) {
            const params = {
                action: 'edit',
                title,
                text: content,
                summary: summary || 'Updated with Preload Editor',
                formatversion: 2
            };
 
             if (createOnly) {
                 params.createonly = true;
             }
             }


             $('<h2>')
             if (contentModel) {
                 .addClass(
                 params.contentmodel = contentModel;
                    'preload-editor-section-title'
            }
                )
                .text(title)
                .appendTo(section);


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


         createButton(label, className, callback) {
         /*
             const button = $('<button>')
        * Change the content model of an existing page.
                .attr('type', 'button')
        *
                 .addClass('preload-editor-button')
        * This is the API equivalent of using
                .text(label);
        * 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'
            });
        },


            if (className) {
        /*
                button.addClass(className);
        * 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 (callback) {
             if (!page) {
                 button.on(
                 return this.savePage(
                     'click.preloadEditor',
                     title,
                     callback
                    content,
                    summary,
                    true,
                     'json'
                 );
                 );
             }
             }


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


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


            $('<label>')
        /*
                .addClass('preload-editor-label')
        * Accept either:
                .text(label)
        *
                .appendTo(row);
        *  Template:Example/Preload
        *
        * or:
        *
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
            title = String(title || '').trim();
            title = title.replace(/\/+$/, '');


             if (description) {
             if (/\/config\.json$/i.test(title)) {
                $('<div>')
                return title;
                    .addClass('preload-editor-help')
                    .text(description)
                    .appendTo(row);
             }
             }


             row.append(input);
             return title + '/config.json';
 
            return row;
         },
         },


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


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


         checkbox(checked) {
         /*
             return $('<input>')
        * Normalize imported field names to the same uppercase
                 .attr('type', 'checkbox')
        * convention used throughout the editor.
                 .prop('checked', !!checked)
        */
                 .addClass(
        getImportableFields(sourceConfig) {
                     'preload-editor-checkbox'
             const fields = sourceConfig && sourceConfig.fields;
                 );
 
        },
            if (
                !fields ||
                typeof fields !== 'object' ||
                Array.isArray(fields)
            ) {
                 return {};
            }
 
            const result = {};
 
            Object.entries(fields).forEach(([name, field]) => {
                const upper = String(name || '').trim().toUpperCase();
 
                 if (!upper || upper === 'PAGE') {
                    return;
                }
 
                 if (
                     !field ||
                    typeof field !== 'object' ||
                    Array.isArray(field)
                 ) {
                    return;
                }
 
                const clone = this.cloneConfigField(field);


        select(options, value) {
                if (!clone) {
            const select = $('<select>')
                     return;
                .addClass(
                 }
                     'preload-editor-select'
                 );


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


             return select;
             return result;
         },
         },


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


        destroyEditor() {
                const overlay = $('<div>')
            if (!this.editor) {
                    .addClass(
                this.editorView = null;
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                this.editorTools = null;
                    );
                return;
            }


            const {
                const box = $('<div>')
                view,
                    .addClass(
                inputHandler
                        'preload-editor-prompt preload-editor-import-dialog'
            } = this.editor;
                    );


            if (view && inputHandler) {
                $('<h2>')
                view.dom.removeEventListener(
                    .text('Import variable definitions')
                    'input',
                     .appendTo(box);
                     inputHandler
                );
            }


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


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


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


        getEditorContent() {
                    const close = this.createButton(
            if (
                        'Close',
                this.editorView &&
                        'preload-editor-button-primary',
                this.editorView.state
                        () => {
            ) {
                            overlay.remove();
                return this.editorView.state.doc.toString();
                            resolve(null);
            }
                        }
                    );
 
                    emptyButtons.append(close);
                    box.append(emptyButtons);
                    overlay.append(box);


            return this.state.preloadContent || '';
                    $(document.body).append(overlay);
        },


        setEditorContent(content) {
                    overlay.attr('tabindex', '-1');
            content = String(content || '');
                    overlay.trigger('focus');


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


            const current =
                const search = this.textInput('', 'Search variables...')
                this.editorView.state.doc.toString();
                    .addClass('preload-editor-import-search');


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


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


        getEditorSelection() {
                const controls = $('<div>')
            if (
                    .addClass('preload-editor-import-controls');
                !this.editorView ||
                !this.editorView.state
            ) {
                return null;
            }


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


            return {
                        updateSummary();
                 from: selection.from,
                    }
                 to: selection.to,
                 );
                text:
 
                     this.editorView.state.doc.sliceString(
                 const deselectAll = this.createButton(
                        selection.from,
                    'Deselect all',
                         selection.to
                    '',
                     )
                     () => {
            };
                        list
        },
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);
 
                         updateSummary();
                     }
                );


        focusEditor() {
                controls.append(selectAll, deselectAll);
            if (this.editorView) {
                 box.append(controls);
                 this.editorView.focus();
            }
        },


        insertEditorText(
                const list = $('<div>')
            text,
                    .addClass('preload-editor-import-list');
            selectionFrom,
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) return;


            const view = this.editorView;
                const localFields =
            const selection =
                    this.state.config && this.state.config.fields
                view.state.selection.main;
                        ? this.state.config.fields
                        : {};


            const from =
                 names.forEach(name => {
                 selectionFrom === undefined
                     const existing = !!localFields[name];
                     ? selection.from
                     const field = fields[name];
                     : selectionFrom;


            const to =
                    const type = field && field.type
                selectionTo === undefined
                        ? String(field.type)
                    ? selection.to
                        : 'text';
                    : selectionTo;


            const cursor =
                    const label = field && field.label
                cursorPosition === undefined
                        ? String(field.label)
                    ? from + text.length
                        : this.humanizeName(name);
                    : cursorPosition;


            view.dispatch({
                    const row = $('<label>')
                changes: {
                        .addClass('preload-editor-import-row')
                    from,
                        .attr('data-variable', name)
                    to,
                        .attr(
                    insert: text
                            'data-search',
                },
                            (name + ' ' + label + ' ' + type).toLowerCase()
                selection: {
                        );
                     anchor: cursor
 
                }
                     const checkbox = this.checkbox(false)
            });
                        .attr('data-import-variable', name)
                        .addClass('preload-editor-import-checkbox');


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


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


        wrapSelectionWithVariable() {
                    $('<strong>')
            const selected =
                        .text(name)
                this.getEditorSelection();
                        .appendTo(header);


            if (
                    $('<span>')
                !selected ||
                        .addClass('preload-editor-import-type')
                selected.from === selected.to
                        .text(type)
            ) {
                        .appendTo(header);
                this.focusEditor();
                return;
            }


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


            this.insertEditorText(
                    $('<span>')
                replacement,
                        .text(label)
                selected.from,
                        .appendTo(meta);
                selected.to,
                selected.from +
                    replacement.length
            );
        },


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


            if (!name) return;
                    content.append(header, meta, status);
                    row.append(checkbox, content);
                    list.append(row);
                });


            const selected =
                 box.append(list);
                 this.getEditorSelection();


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


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


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


        insertCondition(type, variable) {
                            return !!localFields[name];
            type =
                        }).length;
                String(type || '')
                    .toLowerCase();


            variable =
                    let text =
                String(variable || '')
                        selected +
                    .trim()
                        ' ' +
                    .toUpperCase();
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';


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


            if (!selected) return;
                    summary.text(text);


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


            switch (type) {
                const filterRows = () => {
                case 'if': {
                    const query = String(search.val() || '')
                    if (!variable) return;
                        .trim()
                        .toLowerCase();


                     const opening =
                     list.find('.preload-editor-import-row').each(function () {
                        '<!-- @if ' +
                         const row = $(this);
                         variable +
                         const haystack = String(
                         ' -->';
                            row.attr('data-search') || ''
                        );


                     const closing =
                        row.toggle(!query || haystack.includes(query));
                        '<!-- @endif -->';
                     });
                };


                    if (
                search.on(
                        selected.from !==
                     'input.preloadEditor',
                        selected.to
                    filterRows
                     ) {
                );
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                        cursorOffset =
                list.on(
                            text.length;
                    'change.preloadEditor',
                     } else {
                    'input[type="checkbox"]',
                        text =
                     updateSummary
                            opening +
                );
                            '\n\n' +
 
                            closing;
                const buttons = $('<div>')
                    .addClass('preload-editor-prompt-buttons');


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


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


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


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


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


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


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


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


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


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


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


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


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


        updateEditorToolVariables() {
            try {
            if (!this.editorTools) return;
                const page = await this.getPage(configTitle);


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


            const current =
                 let sourceConfig;
                 this.editorTools.variableSelect.val();


            const currentCondition =
                 try {
                 this.editorTools
                     sourceConfig = JSON.parse(page.content);
                     .conditionVariableSelect
                 } catch (error) {
                    .val();
                     throw new Error(
 
                         'The source config.json contains invalid JSON: ' +
            const populate = (
                         error.message
                 select,
                    );
                value
                 }
            ) => {
                select.empty();
 
                variables.forEach(name => {
                     $('<option>')
                         .attr(
                            'value',
                            name
                        )
                         .text(name)
                        .appendTo(select);
                 });


                 if (
                 if (
                     value &&
                     !sourceConfig ||
                     variables.includes(value)
                     typeof sourceConfig !== 'object' ||
                    Array.isArray(sourceConfig)
                 ) {
                 ) {
                     select.val(value);
                     throw new Error(
                } else if (variables.length) {
                        'The source config.json must contain a JSON object.'
                    select.val(
                        variables[0]
                     );
                     );
                 }
                 }
            };


            populate(
                if (
                 this.editorTools.variableSelect,
                    !sourceConfig.fields ||
                current
                    typeof sourceConfig.fields !== 'object' ||
            );
                    Array.isArray(sourceConfig.fields)
                 ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }
 
                const fields = this.getImportableFields(sourceConfig);
 
                const selected =
                    await this.createImportDefinitionsDialog(
                        configTitle,
                        fields
                    );


            populate(
                if (selected === null) {
                this.editorTools
                    this.setStatus(
                    .conditionVariableSelect,
                        'Variable import cancelled.',
                currentCondition
                        'warning'
            );
                    );
        },


        updateConditionVariableVisibility() {
                    return;
            if (!this.editorTools) return;
                }


            const type =
                if (!selected.length) {
                this.editorTools
                    this.setStatus(
                    .conditionTypeSelect
                        'No variable definitions were imported.',
                     .val();
                        'warning'
                     );


            this.editorTools
                    return;
                 .conditionVariableWrap
                 }
                .toggle(type === 'if');
        },


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


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


            const wrapGroup = $('<div>')
                const imported = [];
                 .addClass(
                 const replaced = [];
                    'preload-editor-tool-group ' +
                    'preload-editor-tool-group-wrap'
                );


            wrapGroup.append(
                 selected.forEach(name => {
                 this.createButton(
                     if (name === 'PAGE') {
                     'Wrap selection with %%',
                         return;
                    'preload-editor-tool-button',
                    }
                    () =>
                         this.wrapSelectionWithVariable()
                )
            );


            // Insert existing variable
                    const field = fields[name];


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


            $('<span>')
                    if (this.state.config.fields[name]) {
                .addClass(
                        replaced.push(name);
                    'preload-editor-tool-label'
                     } else {
                )
                        imported.push(name);
                .text(
                    }
                     'Insert existing variable'
                )
                .appendTo(variableGroup);


            const variableSelect =
                    const clone = this.cloneConfigField(field);
                this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );


            variableGroup.append(
                     if (!clone) {
                variableSelect,
                         return;
                this.createButton(
                    }
                    'Insert',
                    'preload-editor-tool-button',
                     () =>
                         this.insertVariable(
                            variableSelect.val()
                        )
                )
            );


            // Insert condition
                    this.state.config.fields[name] = clone;


            const conditionGroup = $('<div>')
                    /*
                .addClass(
                    * If this variable was previously deleted,
                    'preload-editor-tool-group ' +
                    * importing its definition explicitly should
                     'preload-editor-tool-group-condition'
                    * restore it.
                 );
                    */
                    if (Array.isArray(this.state.deletedVariables)) {
                        this.state.deletedVariables =
                            this.state.deletedVariables.filter(
                                deletedName =>
                                    String(deletedName).toUpperCase() !== name
                            );
                     }
                 });


            $('<span>')
                /*
                .addClass(
                * Keep PAGE automatic regardless of what the
                    'preload-editor-tool-label'
                * imported config contained.
                )
                */
                 .text('Insert condition')
                 this.state.config.fields.PAGE =
                .appendTo(conditionGroup);
                    this.getAutomaticPageField();


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


            const conditionVariableSelect =
                /*
                this.createToolSelect(
                * Keep the current selection when possible.
                     [],
                * Otherwise select the first imported definition.
                    'preload-editor-condition-variable-select'
                */
                const selectedStillExists = !!(
                    this.state.config.fields[
                        this.state.selectedVariable
                     ]
                 );
                 );


            const conditionVariableWrap =
                 if (
                 $('<span>')
                    !selectedStillExists ||
                     .addClass(
                    this.state.selectedVariable === 'PAGE'
                         'preload-editor-condition-variable'
                ) {
                    )
                     this.state.selectedVariable =
                    .append(
                        selected[0] ||
                        conditionVariableSelect
                         'PAGE';
                    );
                }
 
                this.reanalyze();


            const insertCondition =
                 this.renderVariablesBySelector();
                 this.createButton(
                this.renderVariableConfigurationBySelector();
                    'Insert',
                this.renderAnalysisBySelector();
                    'preload-editor-tool-button',
                this.updateEditorTools();
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


            conditionTypeSelect.on(
                 this.saveDraft();
                 'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
            );


            conditionGroup.append(
                let status =
                conditionTypeSelect,
                    'Imported ' +
                conditionVariableWrap,
                    selected.length +
                insertCondition
                    ' variable ' +
            );
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                    '.';


            tools.append(
                if (replaced.length) {
                wrapGroup,
                    status +=
                variableGroup,
                        ' Replaced: ' +
                 conditionGroup
                        replaced.join(', ') +
            );
                        '.';
                 }


            this.editorTools = {
                this.setStatus(status, 'success');
                root: tools,
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };


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


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


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


         // Preload syntax highlighting
        // =========================================================
         // Preload parsing
        // =========================================================


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


             const fields =
             return match
                 this.state.config &&
                 ? match[1].trim()
                 this.state.config.fields;
                 : String(source || '').trim();
        },


             if (
        findVariables(content) {
                fields &&
            const variables = [];
                typeof fields === 'object'
             const pattern = /%%([A-Za-z0-9_-]+)%%/g;
            ) {
 
                 Object.keys(fields).forEach(
            let match;
                    name => {
 
                        known.add(
            while ((match = pattern.exec(content)) !== null) {
                            String(name).toUpperCase()
                 const name = match[1].toUpperCase();
                        );
 
                    }
                if (!variables.includes(name)) {
                );
                    variables.push(name);
                }
             }
             }


             return known;
             return variables;
         },
         },


         createSyntaxDecorations(
         findConditions(content) {
            state,
             const conditions = [];
            Decoration
             const pattern =
        ) {
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
             const decorations = [];
             const source =
                 state.doc.toString();
 
            const knownVariables =
                this.getKnownVariables();
 
            const variablePattern =
                /%%([A-Za-z0-9_-]+)%%/g;


             let match;
             let match;


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


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


                decorations.push(
        findConditionVariables(content) {
                    Decoration.mark({
            const variables = [];
                        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 =
             this.findConditions(content).forEach(condition => {
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                 if (
                    condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }


            while (
                 const matches =
                 (match =
                     condition.expression.match(
                     conditionPattern.exec(source)) !==
                         /[A-Za-z0-9_-]+/g
                null
                     ) || [];
            ) {
                decorations.push(
                    Decoration.mark({
                         class:
                            'preload-editor-syntax-condition'
                     }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


                 const directiveStart =
                 matches.forEach(name => {
                     match.index +
                     name = name.toUpperCase();
                    match[0].indexOf('@');


                decorations.push(
                    if (!variables.includes(name)) {
                    Decoration.mark({
                         variables.push(name);
                         class:
                     }
                            'preload-editor-syntax-directive'
                });
                     }).range(
            });
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


                const type =
            return variables;
                    match[1].toLowerCase();
        },


                if (
        analyzePreload(content) {
                    type !== 'if' &&
            return {
                    type !== 'elseif'
                variables: this.findVariables(content),
                 ) {
                 conditions: this.findConditions(content),
                     continue;
                conditionVariables:
                }
                     this.findConditionVariables(content)
            };
        },


                const expression =
        // =========================================================
                    match[2];
        // Config
        // =========================================================


                 const expressionStart =
        getAutomaticPageField() {
                    match.index +
            return {
                    match[0].indexOf(
                 label: 'Page Name',
                        expression
                description: 'Name of the page.',
                    );
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


                 const expressionPattern =
        emptyConfig() {
                     /[A-Za-z0-9_-]+/g;
            return {
                 settings: {
                     incomplete: 'add-stub'
                },


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


                while (
        normalizeConfig(config) {
                    (
            if (
                        expressionMatch =
                !config ||
                            expressionPattern.exec(
                typeof config !== 'object' ||
                                expression
                Array.isArray(config)
                            )
            ) {
                    ) !== null
                 config = this.emptyConfig();
                 ) {
            }
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


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


                    const start =
            if (
                        expressionStart +
                !config.fields ||
                        expressionMatch.index;
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
            ) {
                config.fields = {};
            }


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


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


         async installSyntaxHighlighting(view) {
         humanizeName(name) {
             await mw.loader.using(
             return String(name || '')
                 'ext.CodeMirror.v6.lib'
                .replace(/[_-]+/g, ' ')
            );
                .replace(/([a-z])([A-Z])/g, '$1 $2')
                 .replace(/\s+/g, ' ')
                .trim()
                .replace(/\b\w/g, char => char.toUpperCase());
        },


             const require =
        prepareConfigForVariables(config, analysis) {
                mw.loader.require;
             config = this.normalizeConfig(config);


             const {
             const existing = config.fields || {};
                StateField,
 
                StateEffect,
             const deleted = new Set(
                EditorView,
                 Array.isArray(this.state.deletedVariables)
                Decoration
                    ? this.state.deletedVariables.map(
             } = require(
                        name => String(name).toUpperCase()
                 'ext.CodeMirror.v6.lib'
                    )
                    : []
             );
             );


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


                    update: (
            fields.PAGE =
                        decorations,
                this.getAutomaticPageField();
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                    provide: field =>
            analysis.variables.forEach(name => {
                        EditorView.decorations.from(
                if (
                            field
                    name === 'PAGE' ||
                        )
                    deleted.has(name)
                 });
                 ) {
                    return;
                }


            view.dispatch({
                fields[name] =
                effects:
                    existing[name] ||
                     StateEffect.appendConfig.of(
                     this.createDefaultField(
                         syntaxField
                         name,
                     )
                        analysis
                     );
             });
             });


             this.editor.syntaxField =
             Object.keys(existing).forEach(name => {
                 syntaxField;
                 const upper = name.toUpperCase();
        },


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


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


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


                        mw.hook(
        validateConfig(config, analysis) {
                            'dev.CCM.load'
            const errors = [];
                        ).remove(onLoad);
            const warnings = [];
                    };


                    const onReady = async cm => {
            if (
                        if (
                !config ||
                            settled ||
                typeof config !== 'object' ||
                            !cm ||
                Array.isArray(config)
                            cm.textarea !==
            ) {
                                textarea ||
                return {
                            !cm.view
                    valid: false,
                        ) {
                    errors: [
                            return;
                         'Config must be an object.'
                         }
                    ],
 
                    warnings: []
                        settled = true;
                };
                        cleanup();
            }


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


                        const inputHandler =
            const configured =
                            () => {
                Object.keys(
                                this.state
                    config.fields
                                    .preloadContent =
                ).map(
                                    view.state.doc.toString();
                    name =>
                        name.toUpperCase()
                );


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


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


                        view.dom.addEventListener(
            if (!configured.includes('PAGE')) {
                            'input',
                errors.push(
                            inputHandler
                    'PAGE must always be configured.'
                        );
                );
            }


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


                        const wrapper =
                    return;
                            view.dom.closest(
                }
                                '.ext-codemirror-wrapper'
                            );


                         if (wrapper) {
                if (!field.type) {
                            wrapper.classList.add(
                    warnings.push(
                                'preload-editor-codemirror-wrapper'
                         '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.editor = {
                    if (
                            cm,
                        Array.isArray(field.accept) &&
                             view,
                         field.accept.some(
                             textarea,
                            value =>
                             inputHandler
                                !String(
                         };
                                    value || ''
                                ).trim()
                        )
                    ) {
                        errors.push(
                             'File field "' +
                             name +
                             '" contains an empty accepted MIME type.'
                         );
                    }


                         this.editorView = view;
                    if (
 
                         field.filename !== undefined &&
                         this.state.preloadContent =
                         typeof field.filename !== 'string'
                            view.state.doc.toString();
                    ) {
 
                        errors.push(
                        try {
                            'File field "' +
                             await this.installSyntaxHighlighting(
                            name +
                                view
                             '" must have "filename" as a string.'
                            );
                        );
                    }


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


                     const onLoad = loader => {
                     if (
                         if (
                        !field.accept ||
                             settled ||
                        !field.accept.length
                             typeof loader !==
                    ) {
                                'function'
                         warnings.push(
                         ) {
                             'File field "' +
                            return;
                             name +
                        }
                            '" has no accepted MIME types.'
                         );
                    }


                         try {
                    if (
                            loader(textarea);
                         !field.filename
                         } catch (error) {
                    ) {
                             settled = true;
                         warnings.push(
                             cleanup();
                             'File field "' +
                             reject(error);
                             name +
                        }
                             '" has no filename template.'
                    };
                        );
                    }
                }


                     mw.hook(
                if (
                         'dev.CCM.ready'
                     (
                     ).add(onReady);
                         field.type === 'select' ||
 
                        field.type === 'multiselect'
                     mw.hook(
                     ) &&
                         'dev.CCM.load'
                    !field.source &&
                     ).add(onLoad);
                    !Array.isArray(field.options)
                ) {
                     warnings.push(
                         'Field "' +
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                     );
                 }
                 }
            );
        },


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


        init() {
                    if (
            const root =
                        field.filetext !== undefined &&
                $('#mw-content-text');
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }


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


             this.root = $('<div>')
             return {
                 .attr(
                 valid: !errors.length,
                    'id',
                 errors,
                    'preload-editor'
                 warnings
                 )
            };
                 .addClass(
        },
                    'preload-editor'
                );


            root.append(this.root);
        // =========================================================
        // Transformation helpers
        // =========================================================


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


        renderShell() {
            switch (transform) {
            this.destroyEditor();
                case 'remove-prefix':
            this.root.empty();
                    return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;


            const loader =
                 case 'remove-suffix':
                 this.createSection(
                     return suffix
                     'Preload'
                        ? {
                );
                            transform,
                            suffix
                        }
                        : null;


            const titleInput =
                 case 'replace':
                 this.textInput(
                     return from === ''
                     this.state.preloadTitle,
                        ? null
                    'Template:Example/Preload'
                        : {
                ).attr(
                            transform,
                    'id',
                            from,
                    'preload-editor-title-input'
                            to: to || ''
                );
                        };


            const loadButton =
                 default:
                 this.createButton(
                     return null;
                     'Load',
            }
                    'preload-editor-button-primary',
        },
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                );


            const newButton =
        // =========================================================
                this.createButton(
        // UI helpers
                    'New',
        // =========================================================
                    '',
                    () => this.startNew()
                );


             const sampleButton =
        createSection(title, className) {
                this.createButton(
             const section = $('<section>')
                    'Load Sample Page',
                .addClass('preload-editor-section');
                    '',
                    () =>
                        this.loadSamplePage()
                );


             loader.append(
             if (className) {
                 $('<div>')
                 section.addClass(className);
                    .addClass(
             }
                        'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
             );


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


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


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


             this.workspace =
             if (className) {
                $('<div>')
                button.addClass(className);
                    .addClass(
            }
                        'preload-editor-workspace'
                    );


             this.root.append(
             if (callback) {
                this.workspace
                button.on(
            );
                    'click.preloadEditor',
                    callback
                );
            }


             this.renderWelcome();
             return button;
         },
         },


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


             const section =
             $('<label>')
                 this.createSection(
                 .addClass('preload-editor-label')
                    'Get started'
                .text(label)
                 );
                 .appendTo(row);


             $('<p>')
             if (description) {
                .text(
                $('<div>')
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                    .addClass('preload-editor-help')
                )
                    .text(description)
                .appendTo(section);
                    .appendTo(row);
            }


             const tips =
             row.append(input);
                $('<ul>')
                    .addClass(
                        'preload-editor-tips'
                    );


             [
             return row;
                '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);
        textInput(value, placeholder) {
            this.workspace.append(section);
             return $('<input>')
                .attr({
                    type: 'text',
                    value: value == null ? '' : value,
                    placeholder: placeholder || ''
                })
                .addClass('preload-editor-input');
         },
         },


         setStatus(message, type) {
         textarea(value) {
             if (!this.status) return;
             return $('<textarea>')
                .val(value == null ? '' : value)
                .addClass('preload-editor-textarea');
        },


             this.status.removeClass(
        checkbox(checked) {
                'is-error',
             return $('<input>')
                 'is-success',
                 .attr('type', 'checkbox')
                'is-warning',
                 .prop('checked', !!checked)
                 'is-loading'
                 .addClass('preload-editor-checkbox');
            );
 
            if (type) {
                 this.status.addClass(
                    'is-' + type
                );
            }
 
            this.status.text(
                message || ''
            );
         },
         },


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


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


             if (!title) {
             return select;
                mw.notify(
        },
                    'Enter a preload page title first.',
                    { type: 'warn' }
                );


                return;
        // =========================================================
            }
        // In-wiki dialogs
        // =========================================================


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


            try {
                 const box = $('<div>')
                 const page =
                     .addClass('preload-editor-prompt');
                     await this.getPage(title);


                 if (!page) {
                 $('<h2>')
                     const suggestions =
                     .text(title)
                        await this.findSimilarPreloads(
                    .appendTo(box);
                            title
                        );


                     this.renderMissingPage(
                const messageLines =
                        title,
                     String(message || '').split('\n');
                        suggestions
                    );


                     this.setStatus(
                messageLines.forEach(line => {
                         'Preload not found.',
                     if (line === '') {
                         'warning'
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);
 
                         return;
                    }
 
                    $('<p>')
                        .text(line)
                        .appendTo(box);
                });
 
                const buttons = $('<div>')
                    .addClass(
                         'preload-editor-prompt-buttons'
                     );
                     );


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


                 await this.loadDefinition(
                 const confirm = this.createButton(
                     page.title,
                     confirmLabel || 'Confirm',
                     page.content
                    'preload-editor-button-primary',
                     () => {
                        overlay.remove();
                        resolve(true);
                    }
                 );
                 );


                 this.setStatus(
                 buttons.append(cancel, confirm);
                     'Preload loaded.',
                box.append(buttons);
                     'success'
                overlay.append(box);
 
                $(document.body).append(overlay);
 
                const close = value => {
                     if (value === 'Escape') {
                        cancel.trigger('click');
                    }
                };
 
                overlay.on(
                     'keydown.preloadEditor',
                    event => {
                        close(event.key);
                    }
                 );
                 );
            } catch (error) {
 
                 console.error(
                overlay.attr('tabindex', '-1');
                     'Preload Editor:',
                overlay.trigger('focus');
                     error
 
                 overlay.on(
                     'click.preloadEditor',
                     event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                    }
                 );
                 );
            });
        },


                 this.setStatus(
        createPromptDialog(title, message) {
                     error.message ||
            return new Promise(resolve => {
                         'Could not load preload.',
                 const overlay = $('<div>')
                     'error'
                     .addClass(
                 );
                         'preload-editor-prompt-overlay'
            }
                    );
        },
 
                const box = $('<div>')
                     .addClass(
                        'preload-editor-prompt'
                    );
 
                 $('<h2>')
                    .text(title)
                    .appendTo(box);


        async findSimilarPreloads(title) {
                $('<p>')
            let query =
                     .text(message)
                title
                     .appendTo(box);
                     .replace(
                        /\/Preload$/i,
                        ''
                    )
                     .trim();


            if (!query) {
                const input = this.textInput();
                query = title;
            }


            try {
                 const buttons = $('<div>')
                 const results =
                     .addClass(
                     await this.searchPages(
                         'preload-editor-prompt-buttons'
                         query
                     );
                     );


                 return results.filter(
                 const cancel = this.createButton(
                     result =>
                     'Cancel',
                         /\/Preload$/i.test(
                    '',
                            result.title
                    () => {
                        )
                         overlay.remove();
                );
                        resolve(null);
            } catch (error) {
                     }
                console.error(
                     'Preload Editor search:',
                    error
                 );
                 );


                 return [];
                 const confirm = this.createButton(
            }
                    'Load',
        },
                    'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();
 
                        if (!value) {
                            return;
                        }
 
                        overlay.remove();
                        resolve(value);
                    }
                );


        renderMissingPage(
                buttons.append(cancel, confirm);
            title,
            suggestions
        ) {
            this.workspace.empty();


            const section =
                 box.append(
                 this.createSection(
                     input,
                     'Preload not found'
                    buttons
                 );
                 );


            $('<p>')
                 overlay.append(box);
                .text(
                    'No preload exists at "' +
                    title +
                    '".'
                )
                 .appendTo(section);


            if (suggestions.length) {
                 $(document.body).append(overlay);
                 $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);


                 const list =
                 input.trigger('focus');
                    $('<div>')
                        .addClass(
                            'preload-editor-suggestions'
                        );


                 suggestions.forEach(
                 input.on(
                     result => {
                     'keydown.preloadEditor',
                         list.append(
                    event => {
                             this.createButton(
                         if (event.key === 'Enter') {
                                result.title,
                             confirm.trigger('click');
                                'preload-editor-suggestion',
                        }
                                () =>
 
                                    this.loadExisting(
                        if (event.key === 'Escape') {
                                        result.title
                             cancel.trigger('click');
                                    )
                         }
                             )
                         );
                     }
                     }
                 );
                 );
            });
        },
        createConfigReviewDialog() {
            return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );


                 section.append(list);
                 const box = $('<div>')
            }
                    .addClass(
                        'preload-editor-prompt preload-editor-code-review'
                    );


            section.append(
                 $('<h2>')
                 this.createButton(
                     .text('Review config.json')
                    'Create this preload',
                     .appendTo(box);
                     'preload-editor-button-primary',
                     () =>
                        this.startNew(title)
                )
            );


            this.workspace.append(section);
                $('<p>')
        },
                    .text(
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);


        async startNew(title) {
                const code = $('<pre>')
            title =
                    .addClass(
                String(title || '').trim();
                        'preload-editor-config-review'
                    )
                    .text(this.getConfigJSON());


            this.state = {
                const codeWrap = $('<div>')
                preloadTitle: title,
                     .addClass(
                preloadSource: '',
                        'preload-editor-config-review-wrap'
                preloadContent:
                    )
                     this.defaults.preload,
                     .append(code);
                config:
                     this.emptyConfig(),
                variables: ['PAGE'],
                conditions: [],
                mode: 'new',
                dirty: true
            };


            this.renderEditor();
                box.append(codeWrap);


            this.setStatus(
                const buttons = $('<div>')
                'Creating a new preload.',
                    .addClass(
                'success'
                        'preload-editor-prompt-buttons'
            );
                    );
        },


        async loadSamplePage() {
                const close = this.createButton(
            const result =
                     'Close',
                await this.createPromptDialog(
                     'preload-editor-button-primary',
                     'Load Sample Page',
                    () => {
                     'Enter the title of a normal wiki page to use as the starting point.'
                        overlay.remove();
                        resolve();
                    }
                 );
                 );


            if (!result) return;
                buttons.append(close);
                box.append(buttons);
                overlay.append(box);


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


            try {
                overlay.attr('tabindex', '-1');
                 const page =
                 overlay.trigger('focus');
                    await this.getPage(result);


                 if (!page) {
                 overlay.on(
                    throw new Error(
                    'keydown.preloadEditor',
                        'Sample page not found: ' +
                    event => {
                         result
                        if (event.key === 'Escape') {
                     );
                            close.trigger('click');
                }
                         }
                     }
                );


                 const sample =
                 overlay.on(
                    this.convertSampleToPreload(
                    'click.preloadEditor',
                         page.content
                    event => {
                     );
                        if (event.target === overlay.get(0)) {
                            close.trigger('click');
                         }
                     }
                );
            });
        },
 
        async confirmSave(mode, title) {
            const configTitle =
                title.replace(/\/+$/, '') +
                '/config.json';
 
            let saveDescription;


                 this.state = {
            if (mode === 'preload') {
                     preloadTitle: '',
                 saveDescription =
                    preloadSource: '',
                     'Save the preload page only?';
                    preloadContent: sample,
            } else if (mode === 'config') {
                     config:
                saveDescription =
                        this.emptyConfig(),
                     'Save the config.json page only?';
                    variables: ['PAGE'],
            } else {
                    conditions: [],
                saveDescription =
                     mode: 'new',
                     'Save both the preload and config.json?';
                    dirty: true
            }
                };


                this.reanalyze();
            const pages = [];
                this.renderEditor();


                 this.setStatus(
            if (mode === 'preload' || mode === 'both') {
                     'Sample page loaded.',
                 pages.push(
                     'success'
                     'Preload: ' +
                     title
                 );
                 );
             } catch (error) {
             }
                 console.error(
 
                     'Preload Editor sample:',
            if (mode === 'config' || mode === 'both') {
                     error
                 pages.push(
                     'Config: ' +
                     configTitle
                 );
                 );


                 this.setStatus(
                 pages.push(
                    error.message ||
                     'Config content model: JSON'
                        'Could not load sample page.',
                     'error'
                 );
                 );
             }
             }
            const message =
                saveDescription +
                '\n\n' +
                pages.join('\n') +
                '\n\nThis will write the changes to the wiki.';
            return this.createConfirmDialog(
                'Confirm save',
                message,
                'Save',
                'Cancel'
            );
         },
         },


         convertSampleToPreload(source) {
         // =========================================================
             let content =
        // CodeMirror
                 String(source || '').trim();
        // =========================================================
                destroyEditor() {
             if (!this.editor) {
                this.editorView = null;
                this.editorTools = null;
                return;
            }
 
            const {
                view,
                 inputHandler
            } = this.editor;


             const include =
             if (view && inputHandler) {
                 content.match(
                 view.dom.removeEventListener(
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                     'input',
                    inputHandler
                 );
                 );
            }


             if (include) {
             if (view) {
                 content =
                 view.destroy();
                    include[1].trim();
             }
             }


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


            return (
        getEditorView() {
                '<includeonly>\n' +
             return this.editorView;
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
             );
         },
         },


         createPromptDialog(
         getEditorContent() {
            title,
             if (
            message
                 this.editorView &&
        ) {
                this.editorView.state
             return new Promise(
            ) {
                 resolve => {
                return this.editorView.state.doc.toString();
                    const overlay =
            }
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


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


                    $('<h2>')
        setEditorContent(content) {
                        .text(title)
            content = String(content || '');
                        .appendTo(box);


                    $('<p>')
            if (!this.editorView) {
                        .text(message)
                this.state.preloadContent = content;
                        .appendTo(box);
                return;
            }


                    const input =
            const current =
                        this.textInput();
                this.editorView.state.doc.toString();


                    const buttons =
            if (current === content) {
                        $('<div>')
                return;
                            .addClass(
            }
                                'preload-editor-prompt-buttons'
                            );


                    const cancel =
            this.editorView.dispatch({
                        this.createButton(
                changes: {
                            'Cancel',
                    from: 0,
                            '',
                    to: this.editorView.state.doc.length,
                            () => {
                    insert: content
                                overlay.remove();
                }
                                resolve(null);
            });
                            }
        },
                        );


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


                                if (!value) return;
            const selection =
                this.editorView.state.selection.main;


                                overlay.remove();
            return {
                                resolve(value);
                from: selection.from,
                            }
                to: selection.to,
                        );
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                )
            };
        },


                    buttons.append(
        focusEditor() {
                        cancel,
            if (this.editorView) {
                        confirm
                this.editorView.focus();
                    );
            }
        },


                    box.append(
        insertEditorText(
                        input,
            text,
                        buttons
            selectionFrom,
                    );
            selectionTo,
 
            cursorPosition
                    overlay.append(box);
        ) {
                    $(document.body)
            if (!this.editorView) {
                        .append(overlay);
                return;
            }


                    input.trigger('focus');
            const view = this.editorView;
            const selection = view.state.selection.main;


                     input.on(
            const from =
                        'keydown.preloadEditor',
                selectionFrom === undefined
                        event => {
                     ? selection.from
                            if (
                    : selectionFrom;
                                event.key ===
 
                                'Enter'
            const to =
                            ) {
                selectionTo === undefined
                                confirm.trigger(
                    ? selection.to
                                    'click'
                    : selectionTo;
                                );
                            }


                            if (
            const cursor =
                                event.key ===
                cursorPosition === undefined
                                'Escape'
                    ? from + text.length
                            ) {
                     : cursorPosition;
                                cancel.trigger(
                                    'click'
                                );
                            }
                        }
                     );
                }
            );
        },


        async loadDefinition(
            view.dispatch({
            title,
                changes: {
            source
                    from,
        ) {
                    to,
            const content =
                    insert: text
                 this.extractIncludeonly(
                },
                     source
                 selection: {
                 );
                     anchor: cursor
                 }
            });
 
            view.focus();
        },


            let config =
        // =========================================================
                this.emptyConfig();
        // Editor tools
        // =========================================================


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


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


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


             const analysis =
             const selected =
                 this.analyzePreload(
                 this.getEditorSelection();
                    content
                );


             config =
             if (!selected) {
                this.prepareConfigForVariables(
                 return;
                    config,
            }
                    analysis
                 );


             this.state = {
             this.insertEditorText(
                 preloadTitle: title,
                 '%%' + name + '%%',
                preloadSource: source,
                 selected.from,
                 preloadContent: source,
                 selected.to
                config,
             );
                variables:
                    analysis.variables,
                 conditions:
                    analysis.conditions,
                mode: 'edit',
                dirty: false
             };
 
            this.renderEditor();
         },
         },


         // Editor
         insertCondition(
            type,
            variable
        ) {
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();


        renderEditor() {
             const selected =
             this.destroyEditor();
                this.getEditorSelection();
            this.workspace.empty();


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


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


             const right =
             switch (type) {
                 $('<div>')
                 case 'if': {
                     .addClass(
                     if (!variable) {
                         'preload-editor-right'
                         return;
                     );
                     }


            const editorSection =
                    const opening =
                this.createSection(
                        '<!-- @if ' +
                    'Preload',
                        variable +
                    'preload-editor-main-section'
                        ' -->';
                );


            const meta =
                    const closing =
                $('<div>')
                        '<!-- @endif -->';
                    .addClass(
                        'preload-editor-meta'
                    );


            $('<strong>')
                    if (
                .text(
                        selected.from !==
                    this.state.preloadTitle ||
                        selected.to
                     'New preload'
                     ) {
                )
                        text =
                .appendTo(meta);
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


            if (
                        cursorOffset = text.length;
                this.state.mode ===
                    } else {
                'new'
                        text =
            ) {
                            opening +
                $('<span>')
                            '\n\n' +
                    .addClass(
                            closing;
                        'preload-editor-badge'
 
                    )
                        cursorOffset =
                    .text('NEW')
                            opening.length + 1;
                    .appendTo(meta);
                    }
            }


            editorSection.append(meta);
                    break;
                }


            editorSection.append(
                case 'elseif':
                this.renderEditorTools()
                    text =
            );
                        '<!-- @elseif -->';


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


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


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


            left.append(editorSection);
                    cursorOffset =
                        text.length;


            const analysisSection =
                     break;
                this.createSection(
                     'Analysis'
                );


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


            analysisSection.append(
                    cursorOffset =
                analysisContainer
                        text.length;
            );


            const variablesSection =
                     break;
                this.createSection(
                     'Variables'
                );


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


             variablesSection.append(
             this.insertEditorText(
                 variableContainer
                 text,
                selected.from,
                selected.to,
                selected.from + cursorOffset
             );
             );
        },


             const configSection =
        getToolVariables() {
                 this.createSection(
             const variables =
                    'Generated configuration'
                 new Set(['PAGE']);
                );


             const configPreview =
             if (
                 $('<pre>')
                this.analysis &&
                    .addClass(
                this.analysis.variables
                         'preload-editor-config-preview'
            ) {
                     );
                 this.analysis.variables.forEach(
                    name => {
                        variables.add(
                            String(name).toUpperCase()
                         );
                     }
                );
            }


             configSection.append(
             return Array.from(variables);
                configPreview
        },
            );


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


             actions.append(
             if (className) {
                 this.createButton(
                 select.addClass(className);
                    'Save Preload + Config',
            }
                    'preload-editor-button-primary',
 
                    () => this.saveAll()
            options.forEach(
                ),
                option => {
                this.createButton(
                    $('<option>')
                    'Save Preload Only',
                        .attr(
                    '',
                            'value',
                    () => this.savePreloadOnly()
                            option.value
                 )
                        )
                        .text(option.label)
                        .appendTo(select);
                 }
             );
             );


             right.append(
             return select;
                analysisSection,
        },
                variablesSection,
                configSection,
                actions
            );


             layout.append(
        updateEditorToolVariables() {
                 left,
             if (!this.editorTools) {
                right
                 return;
             );
             }


             this.workspace.append(
             const variables =
                layout
                this.getToolVariables();
            );


             this.reanalyze();
             const current =
                this.editorTools
                    .variableSelect
                    .val();


             this.renderVariables(
             const currentCondition =
                variableContainer
                this.editorTools
            );
                    .conditionVariableSelect
                    .val();


             this.renderAnalysis(
             const populate = (
                 analysisContainer
                 select,
             );
                value
             ) => {
                select.empty();


            this.renderConfigPreview(
                variables.forEach(
                configPreview
                    name => {
            );
                        $('<option>')
 
                            .attr(
            this.updateEditorTools();
                                'value',
 
                                name
            this.mountCodeMirror(
                            )
                textarea.get(0)
                            .text(name)
            ).catch(error => {
                            .appendTo(select);
                console.error(
                     }
                     'Preload Editor CodeMirror:',
                    error
                 );
                 );


                 this.setStatus(
                 if (
                     error.message ||
                    value &&
                         'Could not initialize CodeMirror.',
                    variables.includes(value)
                    'error'
                ) {
                );
                    select.val(value);
             });
                } else if (
                     variables.length
                ) {
                    select.val(
                         variables[0]
                    );
                }
            };
 
            populate(
                this.editorTools.variableSelect,
                current
            );
 
            populate(
                this.editorTools.conditionVariableSelect,
                currentCondition
             );
         },
         },


         reanalyze() {
         updateConditionVariableVisibility() {
             const source =
            if (!this.editorTools) {
                 this.getEditorContent();
                return;
            }
 
             const type =
                 this.editorTools
                    .conditionTypeSelect
                    .val();


             const content =
             this.editorTools
                 this.extractIncludeonly(
                .conditionVariableWrap
                     source
                 .toggle(
                     type === 'if'
                 );
                 );
        },


             const analysis =
        renderEditorTools() {
                 this.analyzePreload(
             const tools =
                     content
                 $('<div>')
                );
                    .addClass(
                        'preload-editor-tools'
                     );


             this.state.preloadContent =
             const wrapGroup =
                 source;
                 $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );


             this.state.variables =
             wrapGroup.append(
                 analysis.variables;
                this.createButton(
                    'Wrap selection',
                    'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                 )
            );


             this.state.conditions =
             const variableGroup =
                 analysis.conditions;
                 $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                    );


             this.state.config =
             $('<span>')
                 this.prepareConfigForVariables(
                 .addClass(
                     this.state.config ||
                     'preload-editor-tool-label'
                        this.emptyConfig(),
                )
                     analysis
                .text(
                 );
                     'Insert existing variable'
                )
                 .appendTo(variableGroup);


            this.analysis =
             const variableSelect =
                analysis;
                 this.createToolSelect(
        },
                     [],
 
                     'preload-editor-variable-select'
        renderAnalysis(container) {
            container.empty();
 
             const analysis =
                 this.analysis ||
                this.analyzePreload(
                     this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );
                 );


             const variableCount =
             variableGroup.append(
                 analysis.variables.length;
                 variableSelect,


            const conditionCount =
                this.createButton(
                analysis.conditions.length;
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                )
            );


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


             summary.append(
             $('<span>')
                $('<span>').text(
                .addClass(
                    variableCount +
                     'preload-editor-tool-label'
                     ' variable' +
                 )
                    (
                 .text('Insert condition')
                        variableCount === 1
                 .appendTo(conditionGroup);
                            ? ''
                            : 's'
                    )
                 ),
                 $('<span>').text(
                    conditionCount +
                    ' condition marker' +
                    (
                        conditionCount === 1
                            ? ''
                            : 's'
                    )
                 )
            );


             container.append(
             const conditionTypeSelect =
                 summary
                this.createToolSelect(
            );
                    [
                        {
                            value: 'if',
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                 );


             if (
             const conditionVariableSelect =
                 analysis.conditionVariables.length
                this.createToolSelect(
             ) {
                    [],
                 container.append(
                    'preload-editor-condition-variable-select'
                    $('<div>')
                 );
                        .addClass(
 
                            'preload-editor-analysis-note'
             const conditionVariableWrap =
                         )
                 $('<span>')
                        .text(
                    .addClass(
                            'Condition variables: ' +
                        'preload-editor-condition-variable'
                             analysis.conditionVariables.join(
                    )
                                ', '
                    .append(
                             )
                         conditionVariableSelect
                    );
 
            const insertCondition =
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                             conditionTypeSelect.val(),
                             conditionVariableSelect.val()
                         )
                         )
                 );
                 );
            }


             const validation =
             conditionTypeSelect.on(
                 this.validateConfig(
                 'change.preloadEditor',
                     this.state.config,
                () =>
                    analysis
                     this.updateConditionVariableVisibility()
                );
            );


             if (
             conditionGroup.append(
                 validation.errors.length
                 conditionTypeSelect,
            ) {
                conditionVariableWrap,
                 const errors =
                 insertCondition
                    $('<ul>')
            );
                        .addClass(
                            'preload-editor-validation-errors'
                        );


                validation.errors.forEach(
            tools.append(
                    error => {
                wrapGroup,
                        $('<li>')
                variableGroup,
                            .text(error)
                conditionGroup
                            .appendTo(errors);
            );
                    }
                );


                 container.append(
            this.editorTools = {
                    errors
                 root: tools,
                 );
                variableSelect,
             }
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                 insertCondition
             };


             if (
             this.updateEditorToolVariables();
                validation.warnings.length
            this.updateConditionVariableVisibility();
            ) {
                const warnings =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );


                validation.warnings.forEach(
            return tools;
                    warning => {
        },
                        $('<li>')
 
                            .text(warning)
        updateEditorTools() {
                            .appendTo(warnings);
            this.updateEditorToolVariables();
                    }
            this.updateConditionVariableVisibility();
                 );
        },
 
        // =========================================================
        // Syntax highlighting
        // =========================================================
 
        getKnownVariables() {
            const known =
                 new Set(['PAGE']);


                 container.append(
            const fields =
                    warnings
                 this.state.config &&
                 );
                 this.state.config.fields;
            }


             if (
             if (
                 !validation.errors.length &&
                 fields &&
                 !validation.warnings.length
                 typeof fields === 'object'
             ) {
             ) {
                 container.append(
                 Object.keys(fields).forEach(
                     $('<div>')
                     name => {
                         .addClass(
                         known.add(
                             'preload-editor-validation-success'
                             String(name).toUpperCase()
                        )
                         );
                        .text(
                    }
                            'Preload and configuration are in sync.'
                         )
                 );
                 );
             }
             }
        },


        renderAnalysisBySelector() {
             return known;
             const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderAnalysis(
                    container
                );
            }
         },
         },


         renderVariables(container) {
         createSyntaxDecorations(
             container.empty();
            state,
            Decoration
        ) {
             const decorations = [];
            const source =
                state.doc.toString();


             const analysis =
             const knownVariables =
                 this.analysis ||
                 this.getKnownVariables();
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


             const variables =
             const variablePattern =
                 analysis.variables.slice();
                 /%%([A-Za-z0-9_-]+)%%/g;


             const ordered = ['PAGE'];
             let match;


             variables.forEach(name => {
             while (
                 if (
                 (
                     name !== 'PAGE' &&
                     match =
                    !ordered.includes(name)
                        variablePattern.exec(source)
                 ) {
                 ) !== null
                     ordered.push(name);
            ) {
                }
                const name =
            });
                     match[1].toUpperCase();


            Object.keys(
                 const known =
                this.state.config.fields || {}
                     knownVariables.has(name);
            ).forEach(name => {
                 const upper =
                     name.toUpperCase();


                 if (
                 decorations.push(
                    !ordered.includes(upper)
                     Decoration.mark({
                ) {
                        class: [
                     ordered.push(upper);
                            'preload-editor-syntax-variable',
                }
                            known
            });
                                ? 'preload-editor-syntax-variable-known'
 
                                : 'preload-editor-syntax-variable-unknown'
            ordered.forEach(name => {
                        ].join(' ')
                const field =
                     }).range(
                    this.state.config.fields[name] ||
                         match.index,
                    this.createDefaultField(
                         match.index +
                        name,
                            match[0].length
                        analysis
                    );
 
                this.state.config.fields[name] =
                    field;
 
                container.append(
                     this.createVariableCard(
                         name,
                         field,
                        analysis
                     )
                     )
                 );
                 );
             });
             }
        },


        renderVariablesBySelector() {
             const conditionPattern =
             const container =
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                 this.root &&
                this.root.find(
                    '.preload-editor-variables'
                );


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


        createVariableCard(
                const directiveStart =
            name,
                     match.index +
            field,
                     match[0].indexOf('@');
            analysis
        ) {
            const card =
                $('<div>')
                     .addClass(
                        'preload-editor-variable'
                    )
                     .attr(
                        'data-variable',
                        name
                    );


            const header =
                 decorations.push(
                 $('<div>')
                     Decoration.mark({
                     .addClass(
                         class:
                         'preload-editor-variable-header'
                            'preload-editor-syntax-directive'
                     );
                     }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


            header.append(
                const type =
                $('<h3>').text(name)
                    match[1].toLowerCase();
            );


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


            card.append(header);
                const expression =
                    match[2];


            const label =
                const expressionStart =
                this.textInput(
                    match.index +
                     field.label || ''
                     match[0].indexOf(
                );
                        expression
                    );


            label.on(
                 const expressionPattern =
                 'input.preloadEditor',
                     /[A-Za-z0-9_-]+/g;
                () => {
                     field.label =
                        label.val();


                    this.markDirty();
                 let expressionMatch;
                    this.renderConfigPreviewBySelector();
                 }
            );


            card.append(
                while (
                this.fieldRow(
                    (
                    'Label',
                        expressionMatch =
                     label
                            expressionPattern.exec(
                 )
                                expression
            );
                            )
                     ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


            const description =
                    if (
                this.textarea(
                        !knownVariables.has(name)
                     field.description || ''
                     ) {
                ).addClass(
                        continue;
                     'preload-editor-small-textarea'
                     }
                );


            description.on(
                    const start =
                'input.preloadEditor',
                        expressionStart +
                () => {
                         expressionMatch.index;
                    field.description =
                         description.val();


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


             card.append(
        async installSyntaxHighlighting(view) {
                 this.fieldRow(
             await mw.loader.using(
                    'Description',
                 'ext.CodeMirror.v6.lib'
                    description
                )
             );
             );


             const types = [
             const require =
                 ['text', 'Text'],
                 mw.loader.require;
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                [
                    'multiselect',
                    'Multi-select'
                ],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date']
            ];


             const typeSelect =
             const {
                 this.select(
                 StateField,
                    types.map(
                StateEffect,
                        ([value, label]) => ({
                EditorView,
                            value,
                Decoration
                            label
            } = require(
                        })
                'ext.CodeMirror.v6.lib'
                    ),
            );
                    field.type || 'text'
                );


             typeSelect.on(
             const syntaxField =
                 'change.preloadEditor',
                 StateField.define({
                () => {
                     create: state =>
                     field.type =
                         this.createSyntaxDecorations(
                         typeSelect.val();
                            state,
                            Decoration
                        ),


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


                     card.replaceWith(
                     provide: field =>
                         this.createVariableCard(
                         EditorView.decorations.from(
                            name,
                             field
                             field,
                            analysis
                         )
                         )
                    );
                });


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


             card.append(
             this.editor.syntaxField =
                 this.fieldRow(
                 syntaxField;
                    'Type',
        },
                    typeSelect
                )
            );


             if (name === 'PAGE') {
        async mountCodeMirror(textarea) {
                field.type = 'page';
             return new Promise(
                (
                    resolve,
                    reject
                ) => {
                    let settled = false;


                const required =
                    const cleanup = () => {
                    this.checkbox(
                        mw.hook(
                         field.required !== false
                            'dev.CCM.ready'
                    );
                         ).remove(onReady);


                required.on(
                        mw.hook(
                    'change.preloadEditor',
                            'dev.CCM.load'
                    () => {
                        ).remove(onLoad);
                         field.required =
                    };
                             required.prop(
 
                                 'checked'
                    const onReady =
                             );
                         async cm => {
                             if (
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                 !cm.view
                             ) {
                                return;
                            }


                        this.markDirty();
                            settled = true;
                        this.renderConfigPreviewBySelector();
                            cleanup();
                    }
                );


                card.append(
                            const view =
                    this.fieldRow(
                                cm.view;
                        'Required',
                        required
                    )
                );


                const namespace =
                            const inputHandler =
                    this.select(
                                () => {
                        [
                                    this.state
                            {
                                        .preloadContent =
                                value: 'Main',
                                        view.state.doc.toString();
                                label: 'Main'
                            },
                            {
                                value: 'Template',
                                label: 'Template'
                            },
                            {
                                value: 'File',
                                label: 'File'
                            },
                            {
                                value: 'Category',
                                label: 'Category'
                            },
                            {
                                value: 'User',
                                label: 'User'
                            }
                        ],
                        field.namespace || 'Main'
                    );


                namespace.on(
                                    this.markPreloadDirty();
                    'change.preloadEditor',
                    () => {
                        field.namespace =
                            namespace.val();


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


                card.append(
                                    this.renderVariablesBySelector();
                    this.fieldRow(
                                    this.renderVariableConfigurationBySelector();
                        'Namespace',
                                    this.renderAnalysisBySelector();
                        namespace
                                    this.updateEditorTools();
                    )
                );


                const allowNew =
                                    this.saveDraft();
                    this.checkbox(
                                };
                        field['allow-new'] === true
                    );


                allowNew.on(
                            view.dom.addEventListener(
                    'change.preloadEditor',
                                'input',
                    () => {
                                 inputHandler
                        field['allow-new'] =
                            allowNew.prop(
                                 'checked'
                             );
                             );


                        this.markDirty();
                            view.dom.classList.add(
                        this.renderConfigPreviewBySelector();
                                'preload-editor-codemirror'
                    }
                            );
                );


                card.append(
                            const wrapper =
                    this.fieldRow(
                                view.dom.closest(
                        'Allow new page',
                                    '.ext-codemirror-wrapper'
                        allowNew
                                );
                    )
                );


                return card;
                            if (wrapper) {
            }
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


            const required =
                            this.editor = {
                this.checkbox(
                                cm,
                    field.required === true
                                view,
                );
                                textarea,
                                inputHandler
                            };


            required.on(
                            this.editorView =
                'change.preloadEditor',
                                view;
                () => {
                    field.required =
                        required.prop(
                            'checked'
                        );


                    this.markDirty();
                            this.state.preloadContent =
                    this.renderConfigPreviewBySelector();
                                view.state.doc.toString();
                }
            );


            card.append(
                            try {
                this.fieldRow(
                                await this.installSyntaxHighlighting(
                    'Required',
                                    view
                    required
                                );
                )
            );


            const placeholder =
                                if (
                this.textInput(
                                    this.state.dirty
                    field.placeholder || ''
                                ) {
                );
                                    this.saveDraft();
                                }


            placeholder.on(
                                resolve(view);
                'input.preloadEditor',
                            } catch (error) {
                () => {
                                reject(error);
                    const value =
                            }
                         placeholder.val();
                         };


                     if (value) {
                     const onLoad =
                        field.placeholder =
                        loader => {
                             value;
                            if (
                     } else {
                                settled ||
                         delete field.placeholder;
                                typeof loader !==
                     }
                                    'function'
                            ) {
                                return;
                            }
 
                            try {
                                loader(textarea);
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                             }
                        };
 
                     mw.hook(
                         'dev.CCM.ready'
                     ).add(onReady);


                     this.markDirty();
                     mw.hook(
                     this.renderConfigPreviewBySelector();
                        'dev.CCM.load'
                     ).add(onLoad);
                 }
                 }
             );
             );
        },


            card.append(
        // =========================================================
                this.fieldRow(
        // Main UI
                    'Placeholder',
        // =========================================================
                    placeholder
 
                )
        init() {
             );
             const root =
                $('#mw-content-text');


             const defaultInput =
             if (!root.length) {
                this.textInput(
                 return;
                    field.default === undefined
            }
                        ? ''
                        : field.default
                 );


             defaultInput.on(
             this.root =
                 'input.preloadEditor',
                $('<div>')
                    .attr(
                        'id',
                        'preload-editor'
                    )
                    .addClass(
                        'preload-editor'
                    );
 
            root.append(this.root);
 
            this.renderShell();
 
            this.restoreDraft();
 
            window.addEventListener(
                 'beforeunload',
                 () => {
                 () => {
                    const value =
                     if (this.state.dirty) {
                        defaultInput.val();
                         this.saveDraft();
 
                     if (value) {
                         field.default =
                            value;
                    } else {
                        delete field.default;
                     }
                     }
                    this.markDirty();
                    this.renderConfigPreviewBySelector();
                 }
                 }
             );
             );
        },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


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


             if (
             const titleInput =
                field.type === 'textarea'
                 this.textInput(
            ) {
                    this.state.preloadTitle,
                 const maxRows =
                    'Template:Example/Preload'
                    this.textInput(
                ).attr(
                        field.maxRows || ''
                    'id',
                    ).attr(
                    'preload-editor-title-input'
                        'type',
                );
                        'number'
                    );


                maxRows.on(
            titleInput.on(
                    'input.preloadEditor',
                'input.preloadEditor',
                    () => {
                () => {
                        const value =
                    this.state.preloadTitle =
                            parseInt(
                        String(
                                maxRows.val(),
                            titleInput.val() || ''
                                10
                        ).trim();
                            );


                        if (
                    if (
                            Number.isFinite(
                        this.state.dirty &&
                                value
                         this.state.mode === 'new'
                            ) &&
                    ) {
                            value > 0
                         this.saveDraft();
                         ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }
 
                        this.markDirty();
                         this.renderConfigPreviewBySelector();
                     }
                     }
                 );
                 }
            );


                 card.append(
            const loadButton =
                     this.fieldRow(
                 this.createButton(
                        'Maximum rows',
                     'Load',
                         maxRows
                    'preload-editor-button-primary',
                    )
                    () =>
                         this.loadExisting(
                            titleInput.val()
                        )
                 );
                 );
            }


             if (
             const newButton =
                 field.type === 'select' ||
                 this.createButton(
                field.type === 'multiselect'
                    'New',
            ) {
                    '',
                this.renderSelectConfiguration(
                    () => this.startNew()
                    card,
                    field
                 );
                 );
            }


            return card;
             const sampleButton =
        },
                 this.createButton(
 
                     'Load Sample Page',
        renderSelectConfiguration(
                     '',
            card,
                    () => this.loadSamplePage()
            field
        ) {
             const source =
                 this.textInput(
                     field.source || '',
                     'category:Example'
                 );
                 );


             source.on(
             loader.append(
                 'input.preloadEditor',
                 $('<div>')
                () => {
                    .addClass(
                     const value =
                        'preload-editor-toolbar'
                         source.val();
                    )
                     .append(
                        titleInput,
                        loadButton,
                        newButton,
                         sampleButton
                    )
            );


                    if (value) {
            this.root.append(loader);
                        field.source = value;
                    } else {
                        delete field.source;
                    }


                    this.markDirty();
            this.workspace =
                     this.renderConfigPreviewBySelector();
                $('<div>')
                }
                     .addClass(
            );
                        'preload-editor-workspace'
                    );


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


             const sourcePrefix =
            /*
                 this.textInput(
            * Fixed footer
                    field['source-prefix'] || ''
            *
                );
            * Local draft status, normal status messages,
            * and save actions live here.
            */
             const footer =
                 $('<div>')
                    .addClass(
                        'preload-editor-footer'
                    );


             sourcePrefix.on(
             this.localDraftStatus =
                 'input.preloadEditor',
                 $('<div>')
                () => {
                    .addClass(
                     const value =
                        'preload-editor-local-draft-status is-empty'
                         sourcePrefix.val();
                    )
                     .text(
                         'No local draft'
                    );


                    if (value) {
            this.status =
                        field['source-prefix'] =
                $('<div>')
                            value;
                     .addClass(
                     } else {
                         'preload-editor-status'
                         delete field[
                    );
                            'source-prefix'
                        ];
                    }


                    this.markDirty();
            footer.append(
                    this.renderConfigPreviewBySelector();
                this.localDraftStatus,
                 }
                 this.status
             );
             );


             card.append(
             this.root.append(
                 this.fieldRow(
                 footer
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
             );
             );


             const excludeCategory =
             this.updateLocalDraftIndicator();
                this.textInput(
 
                    field.exclude &&
            this.renderWelcome();
                    field.exclude.category ||
        },
                    ''
                );


            excludeCategory.on(
        renderWelcome() {
                'input.preloadEditor',
            this.workspace.empty();
                () => {
                    const value =
                        excludeCategory.val();


                    if (value) {
            const section =
                        field.exclude =
                this.createSection('Get started');
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category:
                                        value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
            $('<p>')
                            !Object.keys(
                .text(
                                field.exclude
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                            ).length
                )
                        ) {
                .appendTo(section);
                            delete field.exclude;
                        }
                    }


                    this.markDirty();
            const tips =
                     this.renderConfigPreviewBySelector();
                $('<ul>')
                }
                     .addClass(
            );
                        'preload-editor-tips'
                    );


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


             card.append(
             section.append(tips);
                this.createTransformControls(
            this.workspace.append(section);
                    field,
        },
                    'value',
 
                    'Value transformation'
        setStatus(
                ),
            message,
                 this.createTransformControls(
            type
                    field,
        ) {
                    'label',
            if (!this.status) {
                    'Label transformation'
                 return;
                 )
            }
 
            this.status.removeClass(
                'is-error',
                'is-success',
                'is-warning',
                 'is-loading'
             );
             );


             const optionsValue =
             if (type) {
                Array.isArray(field.options)
                 this.status.addClass(
                    ? field.options
                     'is-' + type
                        .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(
             this.status.text(
                 'input.preloadEditor',
                 message || ''
                () => {
            );
                    const lines =
        },
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                    if (!lines.length) {
        // =========================================================
                        delete field.options;
        // Load / create
                    } else {
        // =========================================================
                        field.options =
                            lines.map(line => {
                                const parts =
                                    line.split(
                                        /\s*\|\s*/
                                    );


                                if (
        async loadExisting(title) {
                                    parts.length ===
            title =
                                    1
                String(title || '').trim();
                                ) {
                                    return parts[0];
                                }


                                return {
            if (!title) {
                                    value:
                mw.notify(
                                        parts[0],
                    'Enter a preload page title first.',
                                    label:
                    {
                                        parts
                        type: 'warn'
                                            .slice(1)
                                            .join(
                                                ' | '
                                            )
                                };
                            });
                     }
                     }
                );


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


             card.append(
             this.setStatus(
                 this.fieldRow(
                 'Loading preload...',
                    'Manual options',
                 'loading'
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                 )
             );
             );
        },


        createTransformControls(
             try {
             field,
                const page =
            property,
                     await this.getPage(title);
            title
        ) {
            const wrapper =
                $('<div>')
                     .addClass(
                        'preload-editor-transform'
                    );


            $('<h4>')
                if (!page) {
                .text(title)
                    const suggestions =
                .appendTo(wrapper);
                        await this.findSimilarPreloads(
                            title
                        );


            const existing =
                    this.renderMissingPage(
                field[property] &&
                        title,
                typeof field[property] ===
                        suggestions
                    'object'
                     );
                    ? field[property]
                     : {};


            const transform =
                    this.setStatus(
                this.select(
                         'Preload not found.',
                    [
                         'warning'
                         {
                     );
                            value: '',
                            label:
                                'No transformation'
                        },
                         {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label: 'Replace'
                        }
                     ],
                    existing.transform || ''
                );


            const prefix =
                     return;
                this.textInput(
                 }
                     existing.prefix || ''
                 );


            const suffix =
                 await this.loadDefinition(
                 this.textInput(
                     page.title,
                     existing.suffix || ''
                    page.content
                 );
                 );


            const from =
                 this.setStatus(
                 this.textInput(
                     'Preload loaded.',
                     existing.from || ''
                    'success'
                 );
                 );
 
             } catch (error) {
             const to =
                 console.error(
                 this.textInput(
                     'Preload Editor:',
                     existing.to || ''
                    error
                 );
                 );


            const controls =
                 this.setStatus(
                 $('<div>')
                     error.message ||
                     .addClass(
                         'Could not load preload.',
                         'preload-editor-transform-controls'
                     'error'
                    );
 
            const prefixRow =
                this.fieldRow(
                     'Prefix',
                    prefix
                 );
                 );
            }
        },


             const suffixRow =
        async findSimilarPreloads(title) {
                 this.fieldRow(
             let query =
                    'Suffix',
                 title
                     suffix
                    .replace(
                 );
                        /\/Preload$/i,
                        ''
                     )
                    .trim();
 
            if (!query) {
                query = title;
            }
 
            try {
                 const results =
                    await this.searchPages(query);


            const fromRow =
                return results.filter(
                this.fieldRow(
                    result =>
                    'From',
                        /\/Preload$/i.test(
                    from
                            result.title
                        )
                 );
                 );
 
             } catch (error) {
             const toRow =
                 console.error(
                 this.fieldRow(
                     'Preload Editor search:',
                     'To',
                     error
                     to
                 );
                 );


            const renderInputs =
                 return [];
                 () => {
            }
                    const type =
        },
                        transform.val();


                    prefixRow.toggle(
        renderMissingPage(
                        type ===
            title,
                            'remove-prefix'
            suggestions
                    );
        ) {
            this.workspace.empty();


                    suffixRow.toggle(
            const section =
                        type ===
                this.createSection(
                            'remove-suffix'
                    'Preload not found'
                    );
                );


                    fromRow.toggle(
            $('<p>')
                        type === 'replace'
                .text(
                     );
                    'No preload exists at "' +
                    title +
                     '".'
                )
                .appendTo(section);


                     toRow.toggle(
            if (suggestions.length) {
                        type === 'replace'
                $('<h3>')
                     );
                     .text('Similar preloads')
                };
                     .appendTo(section);


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


                    let object = null;
                suggestions.forEach(
 
                     result => {
                     if (
                         list.append(
                        type ===
                             this.createButton(
                            'remove-prefix' &&
                                 result.title,
                         prefix.val()
                                'preload-editor-suggestion',
                    ) {
                                 () =>
                        object = {
                                    this.loadExisting(
                             transform: type,
                                        result.title
                            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) {
                section.append(list);
                        field[property] =
            }
                            object;
                    } else {
                        delete field[property];
                    }


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


             transform.on(
             this.workspace.append(section);
                'change.preloadEditor',
        },
                () => {
                    update();
                    renderInputs();
                }
            );


            [
        async startNew(title) {
                prefix,
             title =
                suffix,
                 String(title || '').trim();
                from,
                to
             ].forEach(input => {
                 input.on(
                    'input.preloadEditor',
                    update
                );
            });


             controls.append(
             this.state = {
                 this.fieldRow(
                preloadTitle: title,
                    'Transformation',
                preloadSource: '',
                    transform
                preloadContent:
                 ),
                    this.defaults.preload,
                 prefixRow,
 
                 suffixRow,
                 config:
                 fromRow,
                    this.emptyConfig(),
                 toRow
 
             );
                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                 dirty: true,
                 dirtyPreload: true,
                 dirtyConfig: true,
 
                 localDraftSavedAt: null,
                 localDraftAvailable: false
             };


             renderInputs();
             this.saveDraft();
            this.renderEditor();


             wrapper.append(
             this.setStatus(
                 controls
                 'Creating a new preload.',
                'success'
             );
             );
            return wrapper;
         },
         },


         // Config output
         async loadSamplePage() {
 
             const result =
        getCleanConfig() {
                 await this.createPromptDialog(
             const config =
                     'Load Sample Page',
                 JSON.parse(
                    'Enter the title of a normal wiki page to use as the starting point.'
                     JSON.stringify(
                        this.state.config
                    )
                 );
                 );


             const fields =
             if (!result) {
                 config.fields || {};
                 return;
            }


             const orderedFields = {};
             this.setStatus(
                'Loading sample page...',
                'loading'
            );


             if (fields.PAGE) {
             try {
                 orderedFields.PAGE =
                 const page =
                     fields.PAGE;
                     await this.getPage(result);
            }


            Object.keys(fields)
                if (!page) {
                .filter(
                     throw new Error(
                     name =>
                         'Sample page not found: ' +
                        name.toUpperCase() !==
                        result
                         'PAGE'
                     );
                )
                 }
                .forEach(name => {
                     orderedFields[name] =
                        fields[name];
                 });


            config.fields =
                const sample =
                orderedFields;
                    this.convertSampleToPreload(
                        page.content
                    );


            return config;
                this.state = {
        },
                    preloadTitle: '',
                    preloadSource: '',
                    preloadContent: sample,


        getConfigJSON() {
                    config:
            return JSON.stringify(
                        this.emptyConfig(),
                 this.getCleanConfig(),
 
                 null,
                    variables: ['PAGE'],
                4
                    conditions: [],
            );
                    selectedVariable: 'PAGE',
        },
                    deletedVariables: [],
                    mode: 'new',
                    dirty: true,
                    dirtyPreload: true,
                    dirtyConfig: true,
 
                    localDraftSavedAt: null,
                    localDraftAvailable: false
                };
 
                this.reanalyze();
                 this.saveDraft();
                 this.renderEditor();


        renderConfigPreview(container) {
                 this.setStatus(
            if (container) {
                     'Sample page loaded.',
                 container.text(
                    'success'
                     this.getConfigJSON()
                 );
                 );
             }
             } catch (error) {
        },
                 console.error(
 
                     'Preload Editor sample:',
        renderConfigPreviewBySelector() {
                    error
            const preview =
                 this.root &&
                this.root.find(
                     '.preload-editor-config-preview'
                 );
                 );


            if (
                this.setStatus(
                preview &&
                    error.message ||
                preview.length
                        'Could not load sample page.',
            ) {
                     'error'
                this.renderConfigPreview(
                     preview
                 );
                 );
             }
             }
            this.renderAnalysisBySelector();
         },
         },


         markDirty() {
         convertSampleToPreload(source) {
             this.state.dirty = true;
             let content =
        },
                String(source || '').trim();


        // Save
            const include =
                content.match(
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                );


        async savePreloadOnly() {
             if (include) {
            let title =
                 content =
                String(
                     include[1].trim();
                    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 =
             content =
                 this.getEditorContent();
                 content
                    .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();


             const validation =
             return (
                this.validateBeforeSave();
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },


            if (
        async loadDefinition(
                validation.errors.length
            title,
             ) {
             source
                 this.showValidationErrors(
        ) {
                    validation
            const content =
                );
                 this.extractIncludeonly(source);


                 return;
            let config =
            }
                 this.emptyConfig();


             this.setStatus(
             const configTitle =
                'Saving preload...',
                title.replace(
                 'loading'
                    /\/+$/,
            );
                    ''
                ) +
                 '/config.json';


             try {
             const configPage =
                const exists =
                await this.getPage(configTitle);
                    await this.pageExists(
                        title
                    );


                 await this.savePage(
            if (configPage) {
                     title,
                 try {
                    this.state.preloadContent,
                     config =
                     exists
                        JSON.parse(
                         ? 'Updated preload with Preload Editor'
                            configPage.content
                         : 'Created preload with Preload Editor',
                        );
                     !exists
                } catch (error) {
                 );
                     throw new Error(
                         'The existing config.json contains invalid JSON: ' +
                         error.message
                     );
                 }
            }


                 this.state.mode =
            const analysis =
                    'edit';
                 this.analyzePreload(content);


                this.state.dirty =
            this.state.deletedVariables = [];
                    false;


                 this.setStatus(
            config =
                     'Preload saved successfully.',
                 this.prepareConfigForVariables(
                     'success'
                     config,
                     analysis
                 );
                 );


                mw.notify(
            this.state = {
                    'Preload saved.',
                preloadTitle: title,
                    {
                preloadSource: source,
                        type: 'success'
                preloadContent: source,
                    }
                 config,
                 );
 
            } catch (error) {
                 variables:
                 console.error(
                     analysis.variables,
                     'Preload Editor save:',
                    error
                );


                 this.setStatus(
                 conditions:
                     error.message ||
                     analysis.conditions,
                        'Could not save preload.',
                    'error'
                );


                 mw.notify(
                 selectedVariable:
                     error.message ||
                     analysis.variables.includes('PAGE')
                         'Could not save preload.',
                         ? 'PAGE'
                    {
                         : (
                         type: 'error'
                            analysis.variables[0] ||
                    }
                            'PAGE'
                );
                        ),
            }
        },


        async saveAll() {
                 deletedVariables: [],
            let title =
                 String(
                    this.state.preloadTitle ||
                    ''
                ).trim();


            if (!title) {
                 mode: 'edit',
                 const result =
                dirty: false,
                    await this.createPromptDialog(
                dirtyPreload: false,
                        'Preload title',
                dirtyConfig: false,
                        'Enter the full title for the preload.'
                    );


                 if (!result) return;
                 localDraftSavedAt: null,
                localDraftAvailable: false
            };


                title = result;
            this.clearDraft(title);
                this.state.preloadTitle =
            this.renderEditor();
                    title;
        },
            }


            this.state.preloadContent =
        // =========================================================
                this.getEditorContent();
        // Editor
        // =========================================================


             const validation =
        renderEditor() {
                 this.validateBeforeSave();
            this.destroyEditor();
 
            this.workspace.empty();
             if (
 
                 validation.errors.length
            const layout =
             ) {
                $('<div>')
                 this.showValidationErrors(
                    .addClass(
                     validation
                        'preload-editor-layout'
                 );
                    );
 
 
                 return;
            const left =
             }
                $('<div>')
 
                    .addClass(
             const configTitle =
                        'preload-editor-left'
                 title.replace(
                    );
                     /\/+$/,
 
                     ''
            const right =
                 ) +
                $('<div>')
                 '/config.json';
                    .addClass(
 
                        'preload-editor-right'
             this.setStatus(
                    );
                 'Saving preload and config...',
 
                 'loading'
            const editorSection =
             );
                this.createSection(
 
                    'Preload',
             try {
                    'preload-editor-main-section'
                 const preloadExists =
                );
                     await this.pageExists(
 
                         title
            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.savePage(
                 await this.saveConfigPage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );
 
                const configExists =
                    await this.pageExists(
                        configTitle
                    );
 
                await this.savePage(
                     configTitle,
                     configTitle,
                     this.getConfigJSON(),
                     this.getConfigJSON(),
                     configExists
                     configExists
                         ? 'Updated preload config with Preload Editor'
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor',
                         : 'Created preload config with Preload Editor'
                    !configExists
                 );
                 );


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


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


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


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


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


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


Line 3,676: Line 6,098:


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


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


Line 3,717: Line 6,142:


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


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


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