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)
Created page with "(function (mw, $) { 'use strict'; const PreloadEditor = { version: '0.1.0', state: { preloadTitle: '', preloadSource: '', preloadContent: '', config: null, variables: [], conditions: [], mode: 'idle', dirty: false }, defaults: { preload: '<includeonly>\n' + '<!-- preload here -->\n' +..."
 
ReisuDesign (talk | contribs)
No edit summary
 
(26 intermediate revisions by the same user not shown)
Line 3: Line 3:


     const PreloadEditor = {
     const PreloadEditor = {
         version: '0.1.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
         },
         },
        editor: null,
        editorView: null,
        analysis: null,
        root: null,
        workspace: null,
        status: null,
        localDraftStatus: 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>' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
         },
         },


         /* =========================================================
         // =========================================================
        * API
        // Browser-local draft storage
        * ========================================================= */
        // =========================================================
 
        getDraftStorage() {
            try {
                const raw = window.localStorage.getItem(this.draftStorageKey);


        async getPage(title) {
                if (!raw) {
            const api = new mw.Api();
                    return {
                        active: null,
                        drafts: {}
                    };
                }
 
                const parsed = JSON.parse(raw);
 
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
                    return {
                        active: null,
                        drafts: {}
                    };
                }


            const response = await api.get({
                if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
                action: 'query',
                    parsed.drafts = {};
                 prop: 'revisions',
                 }
                titles: title,
                rvprop: 'content',
                rvslots: 'main',
                formatversion: 2
            });


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


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


             const content =
        setDraftStorage(storage) {
                 page.revisions &&
             try {
                page.revisions[0] &&
                 window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                page.revisions[0].slots &&
                 return true;
                 page.revisions[0].slots.main &&
             } catch (error) {
                page.revisions[0].slots.main.content;
                 console.warn('Preload Editor: Could not save local draft.', error);
 
                 return false;
             return {
             }
                 title: page.title || title,
                 content:
                    typeof content === 'string'
                        ? content
                        : ''
             };
         },
         },


         async pageExists(title) {
         getDraftId(title) {
             const page = await this.getPage(title);
             title = String(title || '').trim();
             return !!page;
             return title ? title.toLowerCase() : '__untitled__';
         },
         },


         async searchPages(query) {
         getDraftSnapshot() {
             const api = new mw.Api();
             let content = this.getEditorContent();


             const response = await api.get({
             if (!this.editorView && !content) {
                 action: 'query',
                 content = this.state.preloadContent || '';
                list: 'search',
             }
                srsearch: query,
                srlimit: 10,
                srnamespace: 10,
                formatversion: 2
             });


             return (
             let config = null;
                response &&
                response.query &&
                response.query.search
                    ? response.query.search
                    : []
            );
        },


        async savePage(title, content, summary, createOnly) {
            try {
            const api = new mw.Api();
                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();
            }


             const params = {
             return {
                 action: 'edit',
                 version: 3,
                 title: title,
                 preloadTitle: String(this.state.preloadTitle || ''),
                 text: content,
                 preloadSource: String(this.state.preloadSource || ''),
                 summary:
                 preloadContent: String(content || ''),
                    summary ||
                 config,
                    'Updated with Preload Editor',
                 formatversion: 2
            };


             if (createOnly) {
                variables: Array.isArray(this.state.variables)
                 params.createonly = true;
                    ? this.state.variables.slice()
                    : [],
 
                conditions: Array.isArray(this.state.conditions)
                    ? this.state.conditions.slice()
                    : [],
 
                selectedVariable: String(this.state.selectedVariable || 'PAGE'),
 
                deletedVariables: Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.slice()
                    : [],
 
                mode: this.state.mode || 'edit',
                dirty: !!this.state.dirty,
                dirtyPreload: !!this.state.dirtyPreload,
                dirtyConfig: !!this.state.dirtyConfig,
                savedAt: Date.now()
            };
        },
 
        updateLocalDraftStatus(message, type) {
             if (!this.localDraftStatus) {
                 return;
             }
             }


             return api.postWithToken(
             this.localDraftStatus.removeClass(
                 'csrf',
                 'is-saved',
                 params
                 'is-warning',
                'is-error',
                'is-empty'
             );
             );
        },


        /* =========================================================
            if (type) {
        * PRELOAD PARSING
                this.localDraftStatus.addClass('is-' + type);
        * ========================================================= */
            }


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


             if (!match) {
        formatLocalDraftTime(timestamp) {
                 return String(source || '').trim();
             if (!timestamp) {
                 return '';
             }
             }


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


         findVariables(content) {
         updateLocalDraftIndicator() {
             const variables = [];
             if (!this.localDraftStatus) {
             const pattern =
                return;
                /%%([A-Za-z0-9_-]+)%%/g;
             }


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


            while (
                 this.updateLocalDraftStatus(
                 (match = pattern.exec(content)) !== null
                    time ? 'Saved locally at ' + time : 'Saved locally',
            ) {
                    'saved'
                 const name =
                 );
                    match[1].toUpperCase();


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


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


         findConditions(content) {
         saveDraft() {
             const conditions = [];
            if (!this.state.dirty) {
             const pattern =
                return false;
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
            }
 
             const snapshot = this.getDraftSnapshot();
             const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();
 
            storage.drafts[id] = snapshot;
            storage.active = id;


             let match;
             const saved = this.setDraftStorage(storage);


             while (
             if (saved) {
                 (match = pattern.exec(content)) !== null
                 this.state.localDraftSavedAt = snapshot.savedAt;
             ) {
                this.state.localDraftAvailable = true;
                 conditions.push({
                this.updateLocalDraftIndicator();
                    type:
             } else {
                        match[1].toLowerCase(),
                 this.state.localDraftAvailable = false;
                    expression:
                this.updateLocalDraftStatus('Could not save local draft', 'error');
                        match[2].trim(),
                    index:
                        match.index
                });
             }
             }


             return conditions;
             return saved;
         },
         },


         findConditionVariables(content) {
         clearDraft(title) {
             const variables = [];
             const storage = this.getDraftStorage();
             const conditions =
             const id = this.getDraftId(title);
                this.findConditions(content);


             conditions.forEach(condition => {
             if (storage.drafts && storage.drafts[id]) {
                if (
                delete storage.drafts[id];
                    condition.type !== 'if' &&
            }
                    condition.type !== 'elseif'
                ) {
                    return;
                }


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


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


                    if (
            this.state.localDraftSavedAt = null;
                        !variables.includes(upper)
             this.state.localDraftAvailable = false;
                    ) {
                        variables.push(upper);
                    }
                });
             });


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


         analyzePreload(content) {
         getMostRecentDraft() {
             const variables =
             const storage = this.getDraftStorage();
                this.findVariables(content);
 
            if (!storage.drafts || !Object.keys(storage.drafts).length) {
                return null;
            }


             const conditions =
             if (storage.active && storage.drafts[storage.active]) {
                 this.findConditions(content);
                 return {
                    id: storage.active,
                    draft: storage.drafts[storage.active]
                };
            }


             const conditionVariables =
             let latestId = null;
                this.findConditionVariables(content);
            let latestDraft = null;


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


        /* =========================================================
                if (
        * CONFIG
                    !latestDraft ||
        * ========================================================= */
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                ) {
                    latestId = id;
                    latestDraft = draft;
                }
            });
 
            if (!latestDraft) {
                return null;
            }


        emptyConfig() {
             return {
             return {
                 settings: {
                 id: latestId,
                    incomplete: 'add-stub'
                 draft: latestDraft
                },
                 fields: {
                    PAGE: {
                        label: 'Page Name',
                        description:
                            'Name of the page.',
                        type: 'page',
                        required: true,
                        namespace: 'Main',
                        'allow-new': true
                    }
                }
             };
             };
         },
         },


         normalizeConfig(config) {
         async restoreDraft() {
             if (
            const result = this.getMostRecentDraft();
                !config ||
 
                typeof config !== 'object' ||
             if (!result || !result.draft) {
                Array.isArray(config)
                 return false;
            ) {
                 config =
                    this.emptyConfig();
             }
             }


             if (
             const draft = result.draft;
                !config.settings ||
            const title = String(draft.preloadTitle || '').trim();
                 typeof config.settings !== 'object' ||
            const displayTitle = title || 'an untitled preload';
                 Array.isArray(config.settings)
 
             ) {
            const savedAt = draft.savedAt
                 config.settings = {};
                 ? new Date(draft.savedAt).toLocaleString()
                : '';
 
            const message =
                'Preload Editor found unsaved local work for ' +
                displayTitle +
                (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                 '\n\nRestore it?';
 
            const restore = await this.createConfirmDialog(
                'Restore unsaved work',
                message,
                'Restore',
                'Discard'
            );
 
             if (!restore) {
                 this.clearDraft(title);
                return false;
             }
             }
            let config = this.emptyConfig();


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


             /*
             const hasDirtyFlags =
            * PAGE is always present.
                typeof draft.dirtyPreload === 'boolean' ||
            *
                typeof draft.dirtyConfig === 'boolean';
            * Existing PAGE configuration is preserved.
 
            */
             this.state = {
             if (!config.fields.PAGE) {
                 preloadTitle: title,
                 config.fields.PAGE = {
                preloadSource: String(draft.preloadSource || ''),
                    label: 'Page Name',
                preloadContent: String(draft.preloadContent || ''),
                    description:
                config,
                        'Name of the page.',
 
                    type: 'page',
                variables: Array.isArray(draft.variables)
                    required: true,
                     ? draft.variables.slice()
                     namespace: 'Main',
                     : [],
                     'allow-new': true
                };
            }


            return config;
                conditions: Array.isArray(draft.conditions)
        },
                    ? draft.conditions.slice()
                    : [],


        createDefaultField(name, analysis) {
                selectedVariable: String(draft.selectedVariable || 'PAGE'),
            const isConditionVariable =
                analysis.conditionVariables.includes(
                    name
                );


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


            /*
                mode: draft.mode || 'edit',
            * Variables used directly as conditions
            * are most commonly booleans.
            *
            * This is only a suggestion; the editor
            * can change it.
            */
            if (isConditionVariable) {
                type = 'boolean';
            }


            return {
                 dirty: hasDirtyFlags
                 label: this.humanizeName(name),
                    ? !!(draft.dirtyPreload || draft.dirtyConfig)
                description: '',
                    : true,
                type: type
            };
        },


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


        prepareConfigForVariables(
                dirtyConfig: hasDirtyFlags
            config,
                    ? !!draft.dirtyConfig
            analysis
                    : true,
        ) {
            config =
                this.normalizeConfig(config);


            const existing =
                 localDraftSavedAt: Number(draft.savedAt) || null,
                 config.fields || {};
                localDraftAvailable: true
            };


             const fields = {};
             this.reanalyze();
            this.renderEditor();
            this.updateLocalDraftIndicator();


             /*
             this.setStatus(
            * PAGE is deliberately first.
                 'Restored unsaved local work from this browser.',
            */
                'warning'
            fields.PAGE =
             );
                 existing.PAGE || {
                    label: 'Page Name',
                    description:
                        'Name of the page.',
                    type: 'page',
                    required: true,
                    namespace: 'Main',
                    'allow-new': true
                };
 
             analysis.variables.forEach(name => {
                if (name === 'PAGE') {
                    return;
                }


                fields[name] =
            mw.notify('Unsaved Preload Editor work restored.', {
                    existing[name] ||
                type: 'success'
                    this.createDefaultField(
                        name,
                        analysis
                    );
             });
             });


             /*
             return true;
            * Preserve fields that exist in the config
        },
            * but are no longer present in the preload.
 
            *
        // =========================================================
            * They are shown as unused rather than deleted.
        // API
            */
        // =========================================================
            Object.keys(existing).forEach(name => {
                const upper =
                    name.toUpperCase();


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


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


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


        validateConfig(config, analysis) {
             const content =
             const errors = [];
                page.revisions &&
            const warnings = [];
                page.revisions[0] &&
                page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;


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


            if (
        async pageExists(title) {
                !config.fields ||
            return !!await this.getPage(title);
                typeof config.fields !== 'object' ||
        },
                Array.isArray(config.fields)
            ) {
                errors.push(
                    '"fields" must be an object.'
                );


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


             const configured =
            return (
                 Object.keys(config.fields)
                response &&
                    .map(name =>
                response.query &&
                        name.toUpperCase()
                response.query.search
                    );
            ) || [];
        },
 
        /*
        * Save a page.
        *
        * contentModel is mainly used when creating a page.
        *
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
        async savePage(title, content, summary, createOnly, contentModel) {
             const params = {
                 action: 'edit',
                title,
                text: content,
                summary: summary || 'Updated with Preload Editor',
                formatversion: 2
            };
 
            if (createOnly) {
                params.createonly = true;
            }
 
            if (contentModel) {
                params.contentmodel = contentModel;
            }
 
            return new mw.Api().postWithToken('csrf', params);
        },


            analysis.variables.forEach(name => {
        /*
                if (
        * Change the content model of an existing page.
                    !configured.includes(name)
        *
                ) {
        * This is the API equivalent of using
                    errors.push(
        * Special:ChangeContentModel manually.
                        'Variable "' +
        *
                        name +
        * The page must already exist.
                        '" is not configured.'
        */
                    );
        async changeContentModel(title, model, summary) {
                 }
            return new mw.Api().postWithToken('csrf', {
                action: 'changecontentmodel',
                title,
                model,
                 reason: summary || 'Changed content model with Preload Editor'
             });
             });
        },


            configured.forEach(name => {
        /*
                if (
        * Save config.json and make sure its content model
                    !analysis.variables.includes(
        * is JSON.
                        name
        *
                    )
        * New page:
                 ) {
        *  create directly with contentmodel=json.
                     warnings.push(
        *
                        'Field "' +
        * Existing page:
                        name +
        *  if not already JSON, change its model first,
                        '" is not used by the preload.'
        *  then save the JSON normally.
                    );
        */
                }
        async saveConfigPage(title, content, summary) {
             });
            const page = await this.getPage(title);
 
            if (!page) {
                 return this.savePage(
                    title,
                     content,
                    summary,
                    true,
                    'json'
                );
             }


             if (
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                !configured.includes('PAGE')
                 await this.changeContentModel(
            ) {
                    title,
                 errors.push(
                     'json',
                     'PAGE must always be configured.'
                    'Changed preload config content model to JSON'
                 );
                 );
             }
             }


             Object.entries(
             return this.savePage(
                 config.fields
                 title,
            ).forEach(
                content,
                ([name, field]) => {
                summary,
                    if (
                false
                        !field ||
            );
                        typeof field !== 'object' ||
        },
                        Array.isArray(field)
 
                    ) {
        // =========================================================
                        errors.push(
        // Config import helpers
                            'Field "' +
        // =========================================================
                            name +
 
                            '" must be an object.'
        /*
                        );
        * Accept either:
        *
        *  Template:Example/Preload
        *
        * or:
        *
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
            title = String(title || '').trim();
            title = title.replace(/\/+$/, '');


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


                    if (!field.type) {
            return title + '/config.json';
                        warnings.push(
        },
                            'Field "' +
                            name +
                            '" has no type.'
                        );
                    }


                    if (
        /*
                        (
        * Return a safe clone of a config field.
                            field.type === 'select' ||
        *
                            field.type === 'multiselect'
        * This is deliberately JSON-based because config
                        ) &&
        * definitions are JSON-compatible objects.
                        !field.source &&
        */
                        !Array.isArray(
        cloneConfigField(field) {
                            field.options
            try {
                        )
                return JSON.parse(JSON.stringify(field));
                    ) {
            } catch (error) {
                        warnings.push(
                console.warn(
                            'Field "' +
                    'Preload Editor: Could not clone imported field.',
                            name +
                     error
                            '" is a ' +
                 );
                            field.type +
                            ' without a source or manual options.'
                        );
                     }
                 }
            );


            return {
                return null;
                valid:
             }
                    errors.length === 0,
                errors: errors,
                warnings: warnings
             };
         },
         },


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


        transformationObject(
            if (
            transform,
                !fields ||
            prefix,
                typeof fields !== 'object' ||
            suffix,
                Array.isArray(fields)
            from,
             ) {
            to
                 return {};
        ) {
             if (!transform) {
                 return null;
             }
             }


             switch (transform) {
             const result = {};
                case 'remove-prefix':
                    if (!prefix) {
                        return null;
                    }


                    return {
            Object.entries(fields).forEach(([name, field]) => {
                        transform:
                const upper = String(name || '').trim().toUpperCase();
                            'remove-prefix',
                        prefix: prefix
                    };


                 case 'remove-suffix':
                 if (!upper || upper === 'PAGE') {
                    if (!suffix) {
                    return;
                        return null;
                }
                    }


                     return {
                if (
                        transform:
                     !field ||
                            'remove-suffix',
                    typeof field !== 'object' ||
                        suffix: suffix
                    Array.isArray(field)
                     };
                ) {
                     return;
                }
 
                const clone = this.cloneConfigField(field);


                 case 'replace':
                 if (!clone) {
                    if (from === '') {
                    return;
                        return null;
                }
                    }


                    return {
                result[upper] = clone;
                        transform: 'replace',
            });
                        from: from,
                        to: to || ''
                    };


                default:
            return result;
                    return null;
            }
         },
         },


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


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


            if (className) {
                const box = $('<div>')
                section.addClass(className);
                    .addClass(
            }
                        'preload-editor-prompt preload-editor-import-dialog'
                    );


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


            return section;
                 $('<p>')
        },
                     .text(
 
                        'Choose which variable definitions to import from "' +
        createButton(
                        sourceTitle +
            label,
                         '". Existing local definitions can be replaced.'
            className,
            callback
        ) {
            const button =
                 $('<button>')
                     .attr('type', 'button')
                    .addClass(
                         'preload-editor-button'
                     )
                     )
                     .text(label);
                     .appendTo(box);


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


            if (callback) {
                    const emptyButtons = $('<div>')
                button.on(
                        .addClass('preload-editor-prompt-buttons');
                    'click.preloadEditor',
                    callback
                );
            }


            return button;
                    const close = this.createButton(
        },
                        'Close',
 
                        'preload-editor-button-primary',
        fieldRow(
                        () => {
            label,
                            overlay.remove();
            input,
                            resolve(null);
            description
                         }
        ) {
            const row =
                $('<div>')
                    .addClass(
                         'preload-editor-field'
                     );
                     );


            const labelElement =
                    emptyButtons.append(close);
                $('<label>')
                     box.append(emptyButtons);
                     .addClass(
                     overlay.append(box);
                        'preload-editor-label'
                    )
                     .text(label);


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


            if (description) {
                    overlay.attr('tabindex', '-1');
                $('<div>')
                     overlay.trigger('focus');
                    .addClass(
                        'preload-editor-help'
                    )
                     .text(description)
                    .appendTo(row);
            }


            row.append(input);
                    return;
                }
 
                const search = this.textInput('', 'Search variables...')
                    .addClass('preload-editor-import-search');
 
                const searchWrap = $('<div>')
                    .addClass('preload-editor-import-search-wrap')
                    .append(search);
 
                box.append(searchWrap);
 
                const controls = $('<div>')
                    .addClass('preload-editor-import-controls');


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


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


        textarea(value) {
                const deselectAll = this.createButton(
            return $('<textarea>')
                    'Deselect all',
                .val(
                     '',
                     value === undefined ||
                     () => {
                     value === null
                         list
                         ? ''
                            .find('input[type="checkbox"]:visible')
                        : value
                            .prop('checked', false);
                )
 
                .addClass(
                        updateSummary();
                     'preload-editor-textarea'
                     }
                 );
                 );
        },


        checkbox(checked) {
                 controls.append(selectAll, deselectAll);
            return $('<input>')
                 box.append(controls);
                .attr({
                    type: 'checkbox'
                })
                 .prop(
                    'checked',
                    !!checked
                )
                 .addClass(
                    'preload-editor-checkbox'
                );
        },


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


            options.forEach(option => {
                const localFields =
                $('<option>')
                     this.state.config && this.state.config.fields
                     .attr(
                         ? this.state.config.fields
                        'value',
                         : {};
                        option.value
                    )
                    .text(option.label)
                    .prop(
                         'selected',
                        String(
                            option.value
                         ) ===
                            String(
                                value === undefined
                                    ? ''
                                    : value
                            )
                    )
                    .appendTo(select);
            });


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


        /* =========================================================
                    const type = field && field.type
        * MAIN UI
                        ? String(field.type)
        * ========================================================= */
                        : 'text';


        init() {
                    const label = field && field.label
            const root =
                        ? String(field.label)
                $('#mw-content-text');
                        : this.humanizeName(name);


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


            this.root =
                    const checkbox = this.checkbox(false)
                $('<div>')
                        .attr('data-import-variable', name)
                    .attr(
                         .addClass('preload-editor-import-checkbox');
                        'id',
                         'preload-editor'
                    )
                    .addClass(
                        'preload-editor'
                    );


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


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


        renderShell() {
                    $('<strong>')
            this.root.empty();
                        .text(name)
                        .appendTo(header);


            $('<h1>')
                    $('<span>')
                .addClass(
                        .addClass('preload-editor-import-type')
                    'preload-editor-title'
                        .text(type)
                )
                        .appendTo(header);
                .text(
                    'Petit Planet Wiki: Preload Editor'
                )
                .appendTo(this.root);


            $('<p>')
                    const meta = $('<span>')
                .addClass(
                        .addClass('preload-editor-import-meta');
                    'preload-editor-intro'
                )
                .text(
                    'Create and edit wiki preloads and their configuration from one place.'
                )
                .appendTo(this.root);


            /*
                    $('<span>')
            * Loader.
                        .text(label)
            */
                        .appendTo(meta);
            const loader =
                this.createSection(
                    'Preload'
                );


            const titleInput =
                    const status = $('<span>')
                this.textInput(
                        .addClass('preload-editor-import-status')
                    this.state.preloadTitle,
                        .toggleClass('is-existing', existing)
                    'Template:Example/Preload'
                        .toggleClass('is-new', !existing)
                )
                         .text(existing ? 'REPLACE EXISTING' : 'NEW');
                    .attr(
                        'id',
                         'preload-editor-title-input'
                    );


            const loadButton =
                    content.append(header, meta, status);
                this.createButton(
                     row.append(checkbox, content);
                    'Load',
                    list.append(row);
                    'preload-editor-button-primary',
                 });
                     () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                 );


            const newButton =
                 box.append(list);
                 this.createButton(
 
                    'New',
                const summary = $('<div>')
                     '',
                     .addClass('preload-editor-import-summary');
                    () =>
 
                        this.startNew()
                const updateSummary = () => {
                );
                    const selected = list.find(
                        'input[type="checkbox"]:checked'
                    ).length;


            const sampleButton =
                    const existingSelected = list
                this.createButton(
                        .find('input[type="checkbox"]:checked')
                    'Load Sample Page',
                        .filter(function () {
                    '',
                            const name = $(this).attr(
                    () =>
                                'data-import-variable'
                        this.loadSamplePage()
                            );
                );


            const loadRow =
                            return !!localFields[name];
                $('<div>')
                        }).length;
                    .addClass(
                        'preload-editor-toolbar'
                    );


            loadRow.append(
                    let text =
                titleInput,
                        selected +
                loadButton,
                        ' ' +
                newButton,
                        (selected === 1 ? 'variable' : 'variables') +
                sampleButton
                        ' selected.';
            );


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


            this.root.append(loader);
                    summary.text(text);


            /*
                    importButton.prop('disabled', selected === 0);
            * Status area.
                };
            */
            this.status =
                $('<div>')
                    .addClass(
                        'preload-editor-status'
                    );


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


            /*
                    list.find('.preload-editor-import-row').each(function () {
            * Workspace.
                        const row = $(this);
            */
                        const haystack = String(
            this.workspace =
                            row.attr('data-search') || ''
                $('<div>')
                        );
                    .addClass(
 
                        'preload-editor-workspace'
                        row.toggle(!query || haystack.includes(query));
                     );
                     });
                };


            this.root.append(
                search.on(
                this.workspace
                    'input.preloadEditor',
            );
                    filterRows
                );


            /*
                list.on(
            * Initially show instructions.
                    'change.preloadEditor',
            */
                    'input[type="checkbox"]',
            this.renderWelcome();
                    updateSummary
        },
                );


        renderWelcome() {
                const buttons = $('<div>')
            this.workspace.empty();
                    .addClass('preload-editor-prompt-buttons');


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


            $('<p>')
                const importButton = this.createButton(
                .text(
                    'Import selected',
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                     'preload-editor-button-primary',
                )
                    () => {
                .appendTo(section);
                        const selected = [];


            const tips =
                        list
                $('<ul>')
                            .find('input[type="checkbox"]:checked')
                    .addClass(
                            .each(function () {
                        'preload-editor-tips'
                                selected.push(
                     );
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });
 
                        overlay.remove();
                        resolve(selected);
                     }
                );
 
                buttons.append(cancel, importButton);
                box.append(summary, buttons);
                overlay.append(box);


            [
                 $(document.body).append(overlay);
                '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);
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');


            this.workspace.append(
                updateSummary();
                 section
                 search.trigger('focus');
            );
        },


        setStatus(message, type) {
                const close = event => {
            if (!this.status) {
                    if (event.key === 'Escape') {
                return;
                        cancel.trigger('click');
            }
                    }
                };


            this.status
                 overlay.on(
                 .removeClass(
                     'keydown.preloadEditor',
                     'is-error',
                     close
                    'is-success',
                     'is-warning',
                    'is-loading'
                 );
                 );


            if (type) {
                overlay.on(
                this.status.addClass(
                    'click.preloadEditor',
                     'is-' + type
                    event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                     }
                 );
                 );
             }
             });
        },


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


        /* =========================================================
            if (!source) {
        * LOAD / CREATE
                 return;
        * ========================================================= */
            }
 
 
        async loadExisting(title) {
             const configTitle = this.normalizeConfigTitle(source);
            title =
                 String(title || '').trim();
 
             if (!title) {
                mw.notify(
                    'Enter a preload page title first.',
                    {
                        type: 'warn'
                    }
                );
 
                return;
            }


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


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


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


                    this.renderMissingPage(
                let sourceConfig;
                        title,
                        suggestions
                    );


                     this.setStatus(
                try {
                         'Preload not found.',
                     sourceConfig = JSON.parse(page.content);
                         'warning'
                } catch (error) {
                    throw new Error(
                         'The source config.json contains invalid JSON: ' +
                         error.message
                     );
                     );
                    return;
                 }
                 }


                 await this.loadDefinition(
                 if (
                     page.title,
                     !sourceConfig ||
                     page.content
                    typeof sourceConfig !== 'object' ||
                );
                    Array.isArray(sourceConfig)
                ) {
                     throw new Error(
                        'The source config.json must contain a JSON object.'
                    );
                }


                 this.setStatus(
                 if (
                     'Preload loaded.',
                     !sourceConfig.fields ||
                     'success'
                     typeof sourceConfig.fields !== 'object' ||
                );
                    Array.isArray(sourceConfig.fields)
            } catch (error) {
                ) {
                console.error(
                    throw new Error(
                    'Preload Editor:',
                        'The source config.json does not contain a valid "fields" object.'
                     error
                     );
                 );
                 }


                 this.setStatus(
                 const fields = this.getImportableFields(sourceConfig);
                    error.message ||
                        'Could not load preload.',
                    'error'
                );
            }
        },


        async findSimilarPreloads(title) {
                const selected =
            let query =
                     await this.createImportDefinitionsDialog(
                title
                         configTitle,
                     .replace(
                         fields
                         /\/Preload$/i,
                     );
                         ''
                     )
                    .trim();


            if (!query) {
                if (selected === null) {
                query = title;
                    this.setStatus(
            }
                        'Variable import cancelled.',
                        'warning'
                    );
 
                    return;
                }


            try {
                if (!selected.length) {
                const results =
                     this.setStatus(
                     await this.searchPages(
                         'No variable definitions were imported.',
                         query
                        'warning'
                     );
                     );


                return results.filter(
                    return;
                    result =>
                }
                        /\/Preload$/i.test(
 
                            result.title
                 if (!this.state.config) {
                        )
                    this.state.config = this.emptyConfig();
                 );
                 }
            } catch (error) {
                console.error(
                    'Preload Editor search:',
                    error
                 );


                 return [];
                 if (!this.state.config.fields) {
            }
                    this.state.config.fields = {};
        },
                }


        renderMissingPage(
                const imported = [];
            title,
                const replaced = [];
            suggestions
        ) {
            this.workspace.empty();


            const section =
                 selected.forEach(name => {
                 this.createSection(
                     if (name === 'PAGE') {
                     'Preload not found'
                        return;
                );
                    }


            $('<p>')
                     const field = fields[name];
                .text(
                     'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


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


                const list =
                     if (this.state.config.fields[name]) {
                     $('<div>')
                         replaced.push(name);
                         .addClass(
                    } else {
                            'preload-editor-suggestions'
                         imported.push(name);
                         );
                    }


                suggestions.forEach(
                     const clone = this.cloneConfigField(field);
                     result => {
                        const button =
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            );


                         list.append(button);
                    if (!clone) {
                        return;
                    }
 
                    this.state.config.fields[name] = clone;
 
                    /*
                    * If this variable was previously deleted,
                    * importing its definition explicitly should
                    * restore it.
                    */
                    if (Array.isArray(this.state.deletedVariables)) {
                         this.state.deletedVariables =
                            this.state.deletedVariables.filter(
                                deletedName =>
                                    String(deletedName).toUpperCase() !== name
                            );
                     }
                     }
                });
                /*
                * Keep PAGE automatic regardless of what the
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();
                this.markConfigDirty();
                /*
                * Keep the current selection when possible.
                * Otherwise select the first imported definition.
                */
                const selectedStillExists = !!(
                    this.state.config.fields[
                        this.state.selectedVariable
                    ]
                 );
                 );


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


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


            this.workspace.append(
                this.renderVariablesBySelector();
                 section
                this.renderVariableConfigurationBySelector();
            );
                 this.renderAnalysisBySelector();
        },
                this.updateEditorTools();


        async startNew(title) {
                 this.saveDraft();
            title =
                 String(
                    title ||
                    ''
                ).trim();


            this.state = {
                let status =
                preloadTitle: title,
                    'Imported ' +
                preloadSource: '',
                     selected.length +
                preloadContent:
                    ' variable ' +
                     this.defaults.preload,
                     (selected.length === 1
                config:
                        ? 'definition'
                     this.emptyConfig(),
                        : 'definitions') +
                variables: ['PAGE'],
                    '.';
                conditions: [],
                mode: 'new',
                dirty: true
            };


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


            this.setStatus(
                this.setStatus(status, 'success');
                'Creating a new preload.',
                'success'
            );
        },


        async loadSamplePage() {
                mw.notify(status, {
             const dialog =
                    type: 'success'
                 this.createPromptDialog(
                });
                     'Load Sample Page',
             } catch (error) {
                     'Enter the title of a normal wiki page to use as the starting point.'
                 console.error(
                     'Preload Editor variable import:',
                     error
                 );
                 );


            const result =
                this.setStatus(
                 await dialog;
                    error.message ||
                        'Could not import variable definitions.',
                    'error'
                 );


            if (!result) {
                mw.notify(
                 return;
                    error.message ||
             }
                        'Could not import variable definitions.',
                    {
                        type: 'error'
                    }
                 );
             }
        },
 
        // =========================================================
        // Preload parsing
        // =========================================================


             this.setStatus(
        extractIncludeonly(source) {
                'Loading sample page...',
             const match = String(source || '').match(
                 'loading'
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
             );
             );


             try {
             return match
                const page =
                ? match[1].trim()
                    await this.getPage(
                : String(source || '').trim();
                        result
        },
                    );
 
        findVariables(content) {
            const variables = [];
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
 
            let match;
 
            while ((match = pattern.exec(content)) !== null) {
                const name = match[1].toUpperCase();


                 if (!page) {
                 if (!variables.includes(name)) {
                     throw new Error(
                     variables.push(name);
                        'Sample page not found: ' +
                        result
                    );
                 }
                 }
            }


                const sample =
            return variables;
                    this.convertSampleToPreload(
        },
                        page.content
                    );


                this.state = {
        findConditions(content) {
                    preloadTitle: '',
            const conditions = [];
                    preloadSource: '',
            const pattern =
                    preloadContent:
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                        sample,
                    config:
                        this.emptyConfig(),
                    variables:
                        ['PAGE'],
                    conditions: [],
                    mode: 'new',
                    dirty: true
                 };


                this.reanalyze();
            let match;


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


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


         convertSampleToPreload(source) {
         findConditionVariables(content) {
             let content =
             const variables = [];
                String(source || '').trim();


             /*
             this.findConditions(content).forEach(condition => {
            * If the sample itself contains includeonly,
                if (
            * use only its included content.
                    condition.type !== 'if' &&
            *
                    condition.type !== 'elseif'
            * Otherwise use the complete page.
                 ) {
            */
                     return;
            const include =
                 }
                 content.match(
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                 );


            if (include) {
                 const matches =
                 content =
                     condition.expression.match(
                     include[1].trim();
                        /[A-Za-z0-9_-]+/g
            }
                    ) || [];


            /*
                 matches.forEach(name => {
            * Remove documentation/noinclude blocks
                     name = name.toUpperCase();
            * from a normal sample page.
            */
            content =
                 content.replace(
                    /<noinclude>[\s\S]*?<\/noinclude>/gi,
                     ''
                ).trim();


            return (
                    if (!variables.includes(name)) {
                '<includeonly>\n' +
                        variables.push(name);
                content +
                    }
                 '\n</includeonly>\n' +
                 });
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
             });
             );
        },


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


                 const box =
        analyzePreload(content) {
                    $('<div>')
            return {
                        .addClass(
                 variables: this.findVariables(content),
                            'preload-editor-prompt'
                conditions: this.findConditions(content),
                        );
                conditionVariables:
                    this.findConditionVariables(content)
            };
        },


                $('<h2>')
        // =========================================================
                    .text(title)
        // Config
                    .appendTo(box);
        // =========================================================


                 $('<p>')
        getAutomaticPageField() {
                    .text(message)
            return {
                    .appendTo(box);
                 label: 'Page Name',
                description: 'Name of the page.',
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


                 const input =
        emptyConfig() {
                     this.textInput();
            return {
                 settings: {
                     incomplete: 'add-stub'
                },


                 const buttons =
                 fields: {
                     $('<div>')
                     PAGE: this.getAutomaticPageField()
                        .addClass(
                }
                            'preload-editor-prompt-buttons'
            };
                        );
        },


                const cancel =
        normalizeConfig(config) {
                    this.createButton(
            if (
                        'Cancel',
                !config ||
                        '',
                typeof config !== 'object' ||
                        () => {
                Array.isArray(config)
                            overlay.remove();
            ) {
                            resolve(null);
                config = this.emptyConfig();
                        }
            }
                    );


                 const confirm =
            if (
                    this.createButton(
                 !config.settings ||
                        'Load',
                typeof config.settings !== 'object' ||
                        'preload-editor-button-primary',
                Array.isArray(config.settings)
                        () => {
            ) {
                            const value =
                config.settings = {};
                                String(
            }
                                    input.val() ||
                                    ''
                                ).trim();


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


                            overlay.remove();
            config.fields.PAGE =
                            resolve(value);
                this.getAutomaticPageField();
                        }
                    );


                buttons.append(
            return config;
                    cancel,
        },
                    confirm
                );


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


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


                $(document.body).append(
        prepareConfigForVariables(config, analysis) {
                    overlay
            config = this.normalizeConfig(config);
                );


                input.trigger('focus');
            const existing = config.fields || {};


                 input.on(
            const deleted = new Set(
                     'keydown.preloadEditor',
                 Array.isArray(this.state.deletedVariables)
                    event => {
                     ? this.state.deletedVariables.map(
                        if (
                        name => String(name).toUpperCase()
                            event.key ===
                    )
                            'Enter'
                    : []
                        ) {
            );
                            confirm.trigger(
                                'click'
                            );
                        }


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


        async loadDefinition(
             fields.PAGE =
             title,
                 this.getAutomaticPageField();
            source
        ) {
            const content =
                 this.extractIncludeonly(
                    source
                );


             let config =
             analysis.variables.forEach(name => {
                this.emptyConfig();
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            try {
                const configPage =
                    await this.getPage(
                        configTitle
                    );
 
                if (configPage) {
                    try {
                        config =
                            JSON.parse(
                                configPage.content
                            );
                    } catch (error) {
                        throw new Error(
                            'The existing config.json contains invalid JSON: ' +
                            error.message
                        );
                    }
                }
            } catch (error) {
                /*
                * A missing config is allowed.
                * Other errors are re-thrown.
                */
                 if (
                 if (
                     error &&
                     name === 'PAGE' ||
                    error.message &&
                     deleted.has(name)
                     error.message.indexOf(
                        'invalid JSON'
                    ) !== -1
                 ) {
                 ) {
                     throw error;
                     return;
                 }
                 }
            }


            const analysis =
                fields[name] =
                this.analyzePreload(
                    existing[name] ||
                     content
                    this.createDefaultField(
                 );
                        name,
                        analysis
                     );
            });
 
            Object.keys(existing).forEach(name => {
                 const upper = name.toUpperCase();


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


             this.state = {
             config.fields = fields;
                preloadTitle: title,
                preloadSource: source,
                preloadContent: content,
                config: config,
                variables:
                    analysis.variables,
                conditions:
                    analysis.conditions,
                mode: 'edit',
                dirty: false
            };


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


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


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


             const editor =
             const configured =
                 this.createSection(
                 Object.keys(
                     'Preload editor',
                     config.fields
                     'preload-editor-main-section'
                ).map(
                     name =>
                        name.toUpperCase()
                 );
                 );


             const meta =
             analysis.variables.forEach(name => {
                 $('<div>')
                 if (!configured.includes(name)) {
                     .addClass(
                     errors.push(
                         'preload-editor-meta'
                         'Variable "' +
                     );
                        name +
 
                        '" is not configured.'
             const title =
                     );
                 this.state.preloadTitle ||
                }
                'New preload';
            });
 
 
            $('<strong>')
             configured.forEach(name => {
                 .text(title)
                 if (!analysis.variables.includes(name)) {
                .appendTo(meta);
                    warnings.push(
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                    );
                 }
            });


             if (
             if (!configured.includes('PAGE')) {
                this.state.mode === 'new'
                 errors.push(
            ) {
                     'PAGE must always be configured.'
                 $('<span>')
                );
                     .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
             }
             }


             editor.append(meta);
             Object.entries(config.fields).forEach(([name, field]) => {
 
                 if (
            const textarea =
                     !field ||
                 this.textarea(
                    typeof field !== 'object' ||
                     this.state.preloadContent
                    Array.isArray(field)
                 )
                 ) {
                     .attr(
                     errors.push(
                         'id',
                         'Field "' +
                         'preload-editor-content'
                         name +
                    )
                         '" must be an object.'
                    .addClass(
                         'preload-editor-content'
                     );
                     );


            textarea.on(
                    return;
                'input.preloadEditor',
                 }
                 () => {
                    this.state.preloadContent =
                        textarea.val();


                    this.state.dirty =
                if (!field.type) {
                        true;
                     warnings.push(
 
                         'Field "' +
                    this.reanalyze();
                        name +
 
                         '" has no type.'
                     this.renderVariables(
                         variableContainer
                    );
 
                    this.renderAnalysis(
                         analysisContainer
                    );
 
                    this.renderConfigPreview(
                        configPreview
                     );
                     );
                 }
                 }
            );
               
                if (
                    field.type === 'file'
                ) {
                    if (
                        field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }


            editor.append(
                    if (
                this.fieldRow(
                        Array.isArray(field.accept) &&
                     'Preload wikitext',
                        field.accept.some(
                    textarea,
                            value =>
                    'This is the actual preload. Variables use %%VARIABLE%% syntax.'
                                !String(
                )
                                    value || ''
            );
                                ).trim()
                        )
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" contains an empty accepted MIME type.'
                        );
                    }


            /*
                    if (
            * Analysis.
                        field.filename !== undefined &&
            */
                        typeof field.filename !== 'string'
            const analysisSection =
                    ) {
                this.createSection(
                        errors.push(
                    'Analysis'
                            'File field "' +
                );
                            name +
                            '" must have "filename" as a string.'
                        );
                    }


            const analysisContainer =
                    if (
                $('<div>')
                        field.filetext !== undefined &&
                    .addClass(
                        typeof field.filetext !== 'string'
                        'preload-editor-analysis'
                    ) {
                    );
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


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


            /*
                    if (
            * Variables.
                        !field.filename
            */
                    ) {
            const variablesSection =
                        warnings.push(
                this.createSection(
                            'File field "' +
                    'Variables'
                            name +
                );
                            '" has no filename template.'
                        );
                    }
                }


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


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


            /*
                    if (
            * Config preview.
                        field.filetext !== undefined &&
            */
                        typeof field.filetext !== 'string'
            const configSection =
                    ) {
                this.createSection(
                        errors.push(
                    'Generated configuration'
                            'File field "' +
                );
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }


            const configPreview =
                    if (
                $('<pre>')
                        field.accept !== undefined &&
                     .addClass(
                        (
                        'preload-editor-config-preview'
                            !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.'
                        );
                     }
                }
            });


             configSection.append(
             return {
                 configPreview
                valid: !errors.length,
             );
                 errors,
                warnings
             };
        },


            /*
        // =========================================================
            * Actions.
        // Transformation helpers
            */
        // =========================================================
            const actions =
                $('<div>')
                    .addClass(
                        'preload-editor-actions'
                    );


             const save =
        transformationObject(
                this.createButton(
             transform,
                    'Save Preload + Config',
            prefix,
                    'preload-editor-button-primary',
            suffix,
                    () =>
            from,
                        this.saveAll()
            to
                 );
        ) {
            if (!transform) {
                 return null;
            }


             const savePreload =
             switch (transform) {
                 this.createButton(
                 case 'remove-prefix':
                    'Save Preload Only',
                     return prefix
                     '',
                        ? {
                    () =>
                            transform,
                         this.savePreloadOnly()
                            prefix
                );
                         }
                        : null;


            actions.append(
                case 'remove-suffix':
                save,
                    return suffix
                savePreload
                        ? {
            );
                            transform,
                            suffix
                        }
                        : null;


            this.workspace.append(
                case 'replace':
                editor,
                    return from === ''
                analysisSection,
                        ? null
                variablesSection,
                        : {
                configSection,
                            transform,
                actions
                            from,
            );
                            to: to || ''
                        };


             this.reanalyze();
                default:
                    return null;
             }
        },


            this.renderVariables(
        // =========================================================
                variableContainer
        // UI helpers
            );
        // =========================================================


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


             this.renderConfigPreview(
             if (className) {
                 configPreview
                section.addClass(className);
             );
            }
 
            $('<h2>')
                 .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);
 
             return section;
         },
         },


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


             this.state.variables =
             if (className) {
                 analysis.variables;
                 button.addClass(className);
            }


             this.state.conditions =
             if (callback) {
                analysis.conditions;
                 button.on(
 
                     'click.preloadEditor',
            this.state.config =
                     callback
                 this.prepareConfigForVariables(
                     this.state.config ||
                        this.emptyConfig(),
                     analysis
                 );
                 );
            }


             this.analysis =
             return button;
                analysis;
         },
         },


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


             const analysis =
             if (description) {
                 this.analysis ||
                 $('<div>')
                this.analyzePreload(
                    .addClass('preload-editor-help')
                     this.state.preloadContent
                    .text(description)
                );
                     .appendTo(row);
            }


             const variableCount =
             row.append(input);
                analysis.variables.length;


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


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


            summary.append(
        textarea(value) {
                $('<span>')
            return $('<textarea>')
                    .text(
                .val(value == null ? '' : value)
                        variableCount +
                .addClass('preload-editor-textarea');
                        ' variable' +
        },
                        (
                            variableCount === 1
                                ? ''
                                : 's'
                        )
                    )
            );


             summary.append(
        checkbox(checked) {
                 $('<span>')
             return $('<input>')
                     .text(
                .attr('type', 'checkbox')
                        conditionCount +
                .prop('checked', !!checked)
                         ' condition marker' +
                 .addClass('preload-editor-checkbox');
                         (
        },
                            conditionCount === 1
 
                                ? ''
        select(options, value) {
                                : 's'
            const select = $('<select>')
                        )
                .addClass('preload-editor-select');
 
            options.forEach(option => {
                $('<option>')
                    .attr('value', option.value)
                     .text(option.label)
                    .prop(
                         'selected',
                         String(option.value) ===
                        String(value === undefined ? '' : value)
                     )
                     )
             );
                    .appendTo(select);
             });


             container.append(summary);
             return select;
        },


            if (
        // =========================================================
                analysis.conditionVariables.length
        // In-wiki dialogs
            ) {
        // =========================================================
                const note =
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(
                                ', '
                            )
                        );


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


            const validation =
                const box = $('<div>')
                 this.validateConfig(
                    .addClass('preload-editor-prompt');
                     this.state.config,
 
                    analysis
                 $('<h2>')
                 );
                    .text(title)
                     .appendTo(box);
 
                 const messageLines =
                    String(message || '').split('\n');


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


                validation.errors.forEach(
                         return;
                    error => {
                         $('<li>')
                            .text(error)
                            .appendTo(errors);
                     }
                     }
                );


                container.append(errors);
                    $('<p>')
            }
                        .text(line)
                        .appendTo(box);
                });


            if (
                 const buttons = $('<div>')
                validation.warnings.length
                    .addClass(
            ) {
                        'preload-editor-prompt-buttons'
                 const warnings =
                    );
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );


                 validation.warnings.forEach(
                 const cancel = this.createButton(
                     warning => {
                     cancelLabel || 'Cancel',
                         $('<li>')
                    '',
                            .text(warning)
                    () => {
                            .appendTo(warnings);
                         overlay.remove();
                        resolve(false);
                     }
                     }
                 );
                 );


                 container.append(warnings);
                 const confirm = this.createButton(
            }
                     confirmLabel || 'Confirm',
 
                    'preload-editor-button-primary',
            if (
                    () => {
                !validation.errors.length &&
                         overlay.remove();
                !validation.warnings.length
                         resolve(true);
            ) {
                    }
                container.append(
                     $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                         .text(
                            'Preload and configuration are in sync.'
                         )
                 );
                 );
            }
        },


        /* =========================================================
                buttons.append(cancel, confirm);
        * VARIABLE CARDS
                box.append(buttons);
        * ========================================================= */
                overlay.append(box);


        renderVariables(container) {
                $(document.body).append(overlay);
            container.empty();


            const analysis =
                const close = value => {
                this.analysis ||
                    if (value === 'Escape') {
                this.analyzePreload(
                        cancel.trigger('click');
                     this.state.preloadContent
                     }
                 );
                 };


            const variables =
                 overlay.on(
                 analysis.variables.slice();
                    'keydown.preloadEditor',
                    event => {
                        close(event.key);
                    }
                );


            /*
                overlay.attr('tabindex', '-1');
            * PAGE always comes first.
                overlay.trigger('focus');
            */
            const ordered = [];


            ordered.push('PAGE');
                overlay.on(
 
                    'click.preloadEditor',
            variables.forEach(name => {
                    event => {
                if (
                        if (event.target === overlay.get(0)) {
                    name !== 'PAGE' &&
                            cancel.trigger('click');
                    !ordered.includes(name)
                        }
                ) {
                    }
                    ordered.push(name);
                 );
                 }
             });
             });
        },


            /*
        createPromptDialog(title, message) {
            * Preserve unused config fields after
             return new Promise(resolve => {
            * actual variables.
                 const overlay = $('<div>')
            */
                     .addClass(
            Object.keys(
                        'preload-editor-prompt-overlay'
                this.state.config.fields || {}
                    );
             ).forEach(name => {
                 const upper =
                     name.toUpperCase();


                 if (
                 const box = $('<div>')
                    !ordered.includes(upper)
                     .addClass(
                ) {
                         'preload-editor-prompt'
                     ordered.push(upper);
                }
            });
 
            ordered.forEach(name => {
                const field =
                    this.state.config.fields[name] ||
                    this.createDefaultField(
                        name,
                         analysis
                     );
                     );


                 this.state.config.fields[name] =
                 $('<h2>')
                     field;
                    .text(title)
                     .appendTo(box);


                 const card =
                 $('<p>')
                     this.createVariableCard(
                     .text(message)
                        name,
                     .appendTo(box);
                        field,
                        analysis
                     );


                 container.append(card);
                 const input = this.textInput();
            });
        },


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


            const header =
                const cancel = this.createButton(
                $('<div>')
                    'Cancel',
                    .addClass(
                    '',
                         'preload-editor-variable-header'
                    () => {
                     );
                        overlay.remove();
                         resolve(null);
                     }
                );


            const heading =
                const confirm = this.createButton(
                $('<h3>')
                    'Load',
                    .text(name);
                    'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();


            header.append(heading);
                        if (!value) {
                            return;
                        }


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


            card.append(header);
                buttons.append(cancel, confirm);


            /*
                 box.append(
            * Existing field object is mutated by
                     input,
            * the controls below.
                    buttons
            */
 
            const label =
                 this.textInput(
                     field.label || ''
                 );
                 );


            label.on(
                 overlay.append(box);
                'input.preloadEditor',
                 () => {
                    field.label =
                        label.val();


                    this.markDirty();
                $(document.body).append(overlay);
                    this.renderConfigPreviewBySelector();
                }
            );


            card.append(
                 input.trigger('focus');
                 this.fieldRow(
                    'Label',
                    label
                )
            );


            const description =
                 input.on(
                 this.textarea(
                     'keydown.preloadEditor',
                     field.description || ''
                    event => {
                );
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


            description
                        if (event.key === 'Escape') {
                .addClass(
                             cancel.trigger('click');
                    'preload-editor-small-textarea'
                         }
                )
                .on(
                    'input.preloadEditor',
                    () => {
                        field.description =
                             description.val();
 
                         this.markDirty();
                        this.renderConfigPreviewBySelector();
                     }
                     }
                 );
                 );
            });
        },


             card.append(
        createConfigReviewDialog() {
                 this.fieldRow(
             return new Promise(resolve => {
                    'Description',
                 const overlay = $('<div>')
                     description
                    .addClass(
                )
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
            );
                     );


            const types = [
                const box = $('<div>')
                ['text', 'Text'],
                    .addClass(
                ['textarea', 'Textarea'],
                        'preload-editor-prompt preload-editor-code-review'
                ['number', 'Number'],
                    );
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date']
            ];


            const typeSelect =
                 $('<h2>')
                 this.select(
                     .text('Review config.json')
                     types.map(
                     .appendTo(box);
                        ([value, label]) => ({
                            value: value,
                            label: label
                        })
                     ),
                    field.type || 'text'
                );


            typeSelect.on(
                $('<p>')
                'change.preloadEditor',
                    .text(
                () => {
                        'This is the config.json that will be saved for the current preload.'
                     field.type =
                    )
                        typeSelect.val();
                     .appendTo(box);


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


                     /*
                const codeWrap = $('<div>')
                    * Re-render the whole card so
                     .addClass(
                    * type-specific controls appear.
                        'preload-editor-config-review-wrap'
                    */
                    )
                     const newCard =
                     .append(code);
                        this.createVariableCard(
                            name,
                            field,
                            analysis
                        );


                    card.replaceWith(
                box.append(codeWrap);
                        newCard
                    );


                    this.renderConfigPreviewBySelector();
                 const buttons = $('<div>')
                 }
                     .addClass(
            );
                        'preload-editor-prompt-buttons'
 
            card.append(
                this.fieldRow(
                    'Type',
                     typeSelect
                )
            );
 
            /*
            * PAGE has special controls.
            */
            if (name === 'PAGE') {
                field.type = 'page';
 
                const required =
                    this.checkbox(
                        field.required !== false
                     );
                     );


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


                 card.append(
                 buttons.append(close);
                    this.fieldRow(
                box.append(buttons);
                        'Required',
                 overlay.append(box);
                        required
                    )
                 );


                 const namespace =
                 $(document.body).append(overlay);
                    this.select(
                        [
                            {
                                value: 'Main',
                                label: 'Main'
                            },
                            {
                                value: 'Template',
                                label: 'Template'
                            },
                            {
                                value: 'File',
                                label: 'File'
                            },
                            {
                                value: 'Category',
                                label: 'Category'
                            },
                            {
                                value: 'User',
                                label: 'User'
                            }
                        ],
                        field.namespace ||
                            'Main'
                    );


                 namespace.on(
                 overlay.attr('tabindex', '-1');
                    'change.preloadEditor',
                overlay.trigger('focus');
                    () => {
                        field.namespace =
                            namespace.val();


                         this.markDirty();
                overlay.on(
                        this.renderConfigPreviewBySelector();
                    'keydown.preloadEditor',
                    event => {
                         if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                     }
                     }
                 );
                 );


                 card.append(
                 overlay.on(
                     this.fieldRow(
                     'click.preloadEditor',
                        'Namespace',
                    event => {
                         namespace
                        if (event.target === overlay.get(0)) {
                     )
                            close.trigger('click');
                         }
                     }
                 );
                 );
            });
        },


                const allowNew =
        async confirmSave(mode, title) {
                    this.checkbox(
            const configTitle =
                        field['allow-new'] ===
                title.replace(/\/+$/, '') +
                            true
                '/config.json';
                     );
 
            let saveDescription;
 
            if (mode === 'preload') {
                saveDescription =
                     'Save the preload page only?';
            } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
            } else {
                saveDescription =
                    'Save both the preload and config.json?';
            }


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


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


                 card.append(
            if (mode === 'config' || mode === 'both') {
                     this.fieldRow(
                 pages.push(
                        'Allow new page',
                     'Config: ' +
                        allowNew
                     configTitle
                     )
                 );
                 );


                 return card;
                 pages.push(
                    'Config content model: JSON'
                );
             }
             }


            /*
             const message =
            * Required.
                 saveDescription +
            */
                '\n\n' +
             const required =
                 pages.join('\n') +
                 this.checkbox(
                 '\n\nThis will write the changes to the wiki.';
                    field.required === true
                 );
 
            required.on(
                'change.preloadEditor',
                 () => {
                    field.required =
                        required.prop(
                            'checked'
                        );


                    this.markDirty();
            return this.createConfirmDialog(
                    this.renderConfigPreviewBySelector();
                'Confirm save',
                 }
                message,
                'Save',
                 'Cancel'
             );
             );
        },


             card.append(
        // =========================================================
                 this.fieldRow(
        // CodeMirror
                    'Required',
        // =========================================================
                    required
                destroyEditor() {
                 )
             if (!this.editor) {
             );
                this.editorView = null;
                 this.editorTools = null;
                return;
            }
 
            const {
                view,
                 inputHandler
             } = this.editor;


             /*
             if (view && inputHandler) {
            * Placeholder.
                view.dom.removeEventListener(
            */
                     'input',
            const placeholder =
                    inputHandler
                this.textInput(
                     field.placeholder || ''
                 );
                 );
            }


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


                    if (value) {
            this.editor = null;
                        field.placeholder =
            this.editorView = null;
                            value;
            this.editorTools = null;
                    } else {
        },
                        delete field.placeholder;
                    }


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


             card.append(
        getEditorContent() {
                 this.fieldRow(
             if (
                    'Placeholder',
                this.editorView &&
                    placeholder
                this.editorView.state
                )
            ) {
             );
                 return this.editorView.state.doc.toString();
            }
 
            return this.state.preloadContent || '';
        },
 
        setEditorContent(content) {
             content = String(content || '');


             /*
             if (!this.editorView) {
            * Default.
                 this.state.preloadContent = content;
            */
                 return;
            const defaultInput =
            }
                 this.textInput(
                    field.default ===
                        undefined
                        ? ''
                        : field.default
                 );


             defaultInput.on(
             const current =
                 'input.preloadEditor',
                 this.editorView.state.doc.toString();
                () => {
                    const value =
                        defaultInput.val();


                    if (value) {
            if (current === content) {
                        field.default =
                return;
                            value;
            }
                    } else {
                        delete field.default;
                    }


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


             card.append(
        getEditorSelection() {
                 this.fieldRow(
             if (
                    'Default',
                !this.editorView ||
                    defaultInput,
                !this.editorView.state
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
            ) {
                return null;
            }
 
            const selection =
                 this.editorView.state.selection.main;
 
            return {
                from: selection.from,
                to: selection.to,
                text: this.editorView.state.doc.sliceString(
                    selection.from,
                    selection.to
                 )
                 )
             );
             };
        },
 
        focusEditor() {
            if (this.editorView) {
                this.editorView.focus();
            }
        },
 
        insertEditorText(
            text,
            selectionFrom,
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }


             /*
             const view = this.editorView;
            * Textarea-specific maxRows.
             const selection = view.state.selection.main;
            */
            if (
                field.type === 'textarea'
             ) {
                const maxRows =
                    this.textInput(
                        field.maxRows ||
                            ''
                    )
                        .attr(
                            'type',
                            'number'
                        );


                 maxRows.on(
            const from =
                     'input.preloadEditor',
                 selectionFrom === undefined
                     () => {
                     ? selection.from
                        const value =
                     : selectionFrom;
                            parseInt(
                                maxRows.val(),
                                10
                            );


                        if (
            const to =
                            Number.isFinite(
                selectionTo === undefined
                                value
                    ? selection.to
                            ) &&
                    : selectionTo;
                            value > 0
 
                        ) {
            const cursor =
                            field.maxRows =
                cursorPosition === undefined
                                value;
                    ? from + text.length
                        } else {
                    : cursorPosition;
                            delete field.maxRows;
 
                        }
            view.dispatch({
                changes: {
                    from,
                    to,
                    insert: text
                },
                selection: {
                    anchor: cursor
                }
            });
 
            view.focus();
        },


                        this.markDirty();
        // =========================================================
                        this.renderConfigPreviewBySelector();
        // Editor tools
                    }
        // =========================================================
                );


                card.append(
        wrapSelectionWithVariable() {
                    this.fieldRow(
            const selected =
                        'Maximum rows',
                this.getEditorSelection();
                        maxRows
                    )
                );
            }


            /*
            * Select/multiselect source.
            */
             if (
             if (
                 field.type === 'select' ||
                 !selected ||
                 field.type === 'multiselect'
                 selected.from === selected.to
             ) {
             ) {
                 this.renderSelectConfiguration(
                 this.focusEditor();
                    card,
                 return;
                    field
                 );
             }
             }


             return card;
             const replacement =
                '%%' +
                selected.text +
                '%%';
 
            this.insertEditorText(
                replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
            );
         },
         },


         renderSelectConfiguration(
         insertVariable(name) {
            card,
             name = String(name || '')
            field
                .trim()
        ) {
                 .toUpperCase();
             const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                 );


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


                    if (value) {
            const selected =
                        field.source =
                this.getEditorSelection();
                            value;
                    } else {
                        delete field.source;
                    }


                    this.markDirty();
            if (!selected) {
                    this.renderConfigPreviewBySelector();
                return;
                }
            }
            );


             card.append(
             this.insertEditorText(
                 this.fieldRow(
                 '%%' + name + '%%',
                    'Source',
                selected.from,
                    source,
                 selected.to
                    'Currently supported source format: category:Category Name'
                 )
             );
             );
        },


             const sourcePrefix =
        insertCondition(
                 this.textInput(
            type,
                     field['source-prefix'] ||
            variable
                         ''
        ) {
                );
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();
 
             const selected =
                 this.getEditorSelection();
 
            if (!selected) {
                return;
            }
 
            let text;
            let cursorOffset;
 
            switch (type) {
                case 'if': {
                    if (!variable) {
                        return;
                    }
 
                     const opening =
                        '<!-- @if ' +
                        variable +
                         ' -->';
 
                    const closing =
                        '<!-- @endif -->';


            sourcePrefix.on(
                    if (
                'input.preloadEditor',
                        selected.from !==
                () => {
                        selected.to
                    const value =
                    ) {
                        sourcePrefix.val();
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                    if (value) {
                         cursorOffset = text.length;
                         field['source-prefix'] =
                            value;
                     } else {
                     } else {
                         delete field[
                         text =
                             'source-prefix'
                            opening +
                         ];
                             '\n\n' +
                            closing;
 
                         cursorOffset =
                            opening.length + 1;
                     }
                     }


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


            card.append(
                 case 'elseif':
                 this.fieldRow(
                     text =
                    'Source prefix',
                        '<!-- @elseif -->';
                     sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );


            const excludeCategory =
                    cursorOffset =
                this.textInput(
                         text.length;
                    field.exclude &&
                    field.exclude.category
                         ? field.exclude.category
                        : ''
                );


            excludeCategory.on(
                    break;
                 'input.preloadEditor',
 
                () => {
                 case 'else':
                     const value =
                    text =
                         excludeCategory.val();
                        '<!-- @else -->';
 
                     cursorOffset =
                         text.length;


                     if (value) {
                     break;
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category:
                                        value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
                case 'endif':
                            !Object.keys(
                    text =
                                field.exclude
                         '<!-- @endif -->';
                            ).length
                         ) {
                            delete field.exclude;
                        }
                    }


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


            card.append(
                     break;
                this.fieldRow(
                     'Exclude category',
                    excludeCategory
                )
            );


            /*
                 default:
            * Value transformation.
                     return;
            */
             }
            card.append(
                 this.createTransformControls(
                     field,
                    'value',
                    'Value transformation'
                )
             );


             /*
             this.insertEditorText(
            * Label transformation.
                text,
            */
                selected.from,
            card.append(
                 selected.to,
                 this.createTransformControls(
                 selected.from + cursorOffset
                    field,
                    'label',
                    'Label transformation'
                 )
             );
             );
        },


            /*
        getToolVariables() {
            * Manual options.
             const variables =
            */
                 new Set(['PAGE']);
             const optionsValue =
                 Array.isArray(
                    field.options
                )
                    ? field.options
                        .map(option => {
                            if (
                                typeof option ===
                                'string'
                            ) {
                                return option;
                            }


                            return (
            if (
                                String(
                this.analysis &&
                                    option.value ||
                this.analysis.variables
                                    ''
            ) {
                                ) +
                this.analysis.variables.forEach(
                                ' | ' +
                    name => {
                                String(
                        variables.add(
                                    option.label ||
                            String(name).toUpperCase()
                                    option.value ||
                        );
                                    ''
                    }
                                )
                );
                            );
            }
                        })
 
                        .join('\n')
            return Array.from(variables);
                    : '';
        },


             const options =
        createToolSelect(
                 this.textarea(
            options,
                    optionsValue
            className
                )
        ) {
             const select =
                 $('<select>')
                     .addClass(
                     .addClass(
                         'preload-editor-small-textarea'
                         'preload-editor-tool-select'
                     );
                     );


             options.on(
             if (className) {
                'input.preloadEditor',
                select.addClass(className);
                () => {
            }
                    const lines =
                        options.val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                     if (!lines.length) {
            options.forEach(
                         delete field.options;
                option => {
                    } else {
                     $('<option>')
                         field.options =
                         .attr(
                            lines.map(line => {
                            'value',
                                const parts =
                            option.value
                                    line.split(
                         )
                                        /\s*\|\s*/
                        .text(option.label)
                                    );
                        .appendTo(select);
                }
            );


                                if (
            return select;
                                    parts.length ===
        },
                                    1
 
                                ) {
        updateEditorToolVariables() {
                                    return parts[0];
            if (!this.editorTools) {
                                }
                return;
            }
 
            const variables =
                this.getToolVariables();
 
            const current =
                this.editorTools
                    .variableSelect
                    .val();
 
            const currentCondition =
                this.editorTools
                    .conditionVariableSelect
                    .val();
 
            const populate = (
                select,
                value
            ) => {
                select.empty();


                                return {
                variables.forEach(
                                    value:
                    name => {
                                        parts[0],
                        $('<option>')
                                    label:
                            .attr(
                                        parts
                                'value',
                                            .slice(1)
                                name
                                            .join(
                            )
                                                ' | '
                            .text(name)
                                            )
                             .appendTo(select);
                                };
                             });
                     }
                     }
                );


                     this.markDirty();
                if (
                     this.renderConfigPreviewBySelector();
                    value &&
                     variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                     select.val(
                        variables[0]
                    );
                 }
                 }
            };
            populate(
                this.editorTools.variableSelect,
                current
             );
             );


             card.append(
             populate(
                 this.fieldRow(
                 this.editorTools.conditionVariableSelect,
                    'Manual options',
                 currentCondition
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                 )
             );
             );
         },
         },


         createTransformControls(
         updateConditionVariableVisibility() {
             field,
             if (!this.editorTools) {
             property,
                return;
            title
            }
         ) {
 
             const wrapper =
            const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();
 
             this.editorTools
                .conditionVariableWrap
                .toggle(
                    type === 'if'
                );
        },
 
         renderEditorTools() {
             const tools =
                $('<div>')
                    .addClass(
                        'preload-editor-tools'
                    );
 
            const wrapGroup =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-transform'
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                     );
                     );


             $('<h4>')
             wrapGroup.append(
                .text(title)
                this.createButton(
                 .appendTo(wrapper);
                    'Wrap selection',
                    'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                 )
            );
 
            const variableGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                    );


             const existing =
             $('<span>')
                 field[property] &&
                .addClass(
                 typeof field[property] ===
                    'preload-editor-tool-label'
                     'object'
                 )
                    ? field[property]
                 .text(
                    : {};
                     'Insert existing variable'
                )
                .appendTo(variableGroup);


             const transform =
             const variableSelect =
                 this.select(
                 this.createToolSelect(
                     [
                     [],
                        {
                    'preload-editor-variable-select'
                            value: '',
                );
                            label: 'No transformation'
 
                         },
            variableGroup.append(
                         {
                variableSelect,
                            value: 'remove-prefix',
 
                            label: 'Remove prefix'
                this.createButton(
                        },
                    'Insert',
                         {
                    'preload-editor-tool-button',
                             value: 'remove-suffix',
                    () =>
                             label: 'Remove suffix'
                         this.insertVariable(
                            variableSelect.val()
                         )
                )
            );
 
            const conditionGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );
 
            $('<span>')
                .addClass(
                    'preload-editor-tool-label'
                )
                .text('Insert condition')
                .appendTo(conditionGroup);
 
            const conditionTypeSelect =
                this.createToolSelect(
                    [
                         {
                             value: 'if',
                             label: '@if'
                         },
                         },
                         {
                         {
                             value: 'replace',
                             value: 'elseif',
                             label: 'Replace'
                             label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                         }
                         }
                     ],
                     ],
                     existing.transform || ''
                     'preload-editor-condition-type-select'
                 );
                 );


             const prefix =
             const conditionVariableSelect =
                 this.textInput(
                 this.createToolSelect(
                     existing.prefix || ''
                     [],
                    'preload-editor-condition-variable-select'
                 );
                 );


             const suffix =
             const conditionVariableWrap =
                 this.textInput(
                 $('<span>')
                     existing.suffix || ''
                     .addClass(
                );
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


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


             const to =
             conditionTypeSelect.on(
                 this.textInput(
                'change.preloadEditor',
                    existing.to || ''
                () =>
                );
                    this.updateConditionVariableVisibility()
            );
 
            conditionGroup.append(
                conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );
 
            tools.append(
                wrapGroup,
                variableGroup,
                conditionGroup
            );
 
            this.editorTools = {
                root: tools,
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                 insertCondition
            };
 
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
 
            return tools;
        },
 
        updateEditorTools() {
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
        },
 
        // =========================================================
        // Syntax highlighting
        // =========================================================


            const update =
        getKnownVariables() {
                () => {
            const known =
                    const type =
                new Set(['PAGE']);
                        transform.val();


                    let object = null;
            const fields =
                this.state.config &&
                this.state.config.fields;


                    if (
            if (
                        type ===
                fields &&
                        'remove-prefix'
                typeof fields === 'object'
                    ) {
            ) {
                        if (
                Object.keys(fields).forEach(
                            prefix.val()
                     name => {
                        ) {
                         known.add(
                            object = {
                             String(name).toUpperCase()
                                transform:
                         );
                                    type,
                                prefix:
                                    prefix.val()
                            };
                        }
                     } else if (
                        type ===
                        'remove-suffix'
                    ) {
                         if (
                            suffix.val()
                        ) {
                             object = {
                                transform:
                                    type,
                                suffix:
                                    suffix.val()
                            };
                        }
                    } else if (
                        type === 'replace'
                    ) {
                        if (
                            from.val()
                         ) {
                            object = {
                                transform:
                                    type,
                                from:
                                    from.val(),
                                to:
                                    to.val()
                            };
                        }
                     }
                     }
                );
            }


                    if (object) {
            return known;
                        field[property] =
        },
                            object;
 
                    } else {
        createSyntaxDecorations(
                        delete field[property];
            state,
                    }
            Decoration
        ) {
            const decorations = [];
            const source =
                state.doc.toString();


                    this.markDirty();
            const knownVariables =
                    this.renderConfigPreviewBySelector();
                this.getKnownVariables();
                };


             transform.on(
             const variablePattern =
                'change.preloadEditor',
                 /%%([A-Za-z0-9_-]+)%%/g;
                 () => {
                    update();
                    renderInputs();
                }
            );


             [
             let match;
                prefix,
                suffix,
                from,
                to
            ].forEach(input => {
                input.on(
                    'input.preloadEditor',
                    update
                );
            });


             const controls =
             while (
                 $('<div>')
                 (
                     .addClass(
                     match =
                        'preload-editor-transform-controls'
                        variablePattern.exec(source)
                     );
                ) !== null
            ) {
                const name =
                     match[1].toUpperCase();


            controls.append(
                const known =
                this.fieldRow(
                    knownVariables.has(name);
                    'Transformation',
                    transform
                )
            );


            const prefixRow =
                 decorations.push(
                 this.fieldRow(
                     Decoration.mark({
                     'Prefix',
                        class: [
                     prefix
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                     )
                 );
                 );
            }
            const conditionPattern =
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


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


            const fromRow =
                const directiveStart =
                 this.fieldRow(
                    match.index +
                     'From',
                    match[0].indexOf('@');
                     from
 
                 decorations.push(
                     Decoration.mark({
                        class:
                            'preload-editor-syntax-directive'
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                     )
                 );
                 );


            const toRow =
                const type =
                this.fieldRow(
                    match[1].toLowerCase();
                    'To',
                    to
                );


            controls.append(
                if (
                prefixRow,
                    type !== 'if' &&
                 suffixRow,
                    type !== 'elseif'
                fromRow,
                 ) {
                 toRow
                    continue;
            );
                 }


            const renderInputs =
                const expression =
                () => {
                     match[2];
                     const type =
                        transform.val();


                     prefixRow.toggle(
                const expressionStart =
                         type ===
                     match.index +
                            'remove-prefix'
                    match[0].indexOf(
                         expression
                     );
                     );


                    suffixRow.toggle(
                const expressionPattern =
                        type ===
                    /[A-Za-z0-9_-]+/g;
                            'remove-suffix'
                    );


                    fromRow.toggle(
                let expressionMatch;
                        type === 'replace'
                    );


                     toRow.toggle(
                while (
                         type === 'replace'
                     (
                     );
                         expressionMatch =
                };
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                ) {
                     const name =
                        expressionMatch[0]
                            .toUpperCase();


            renderInputs();
                    if (
                        !knownVariables.has(name)
                    ) {
                        continue;
                    }
 
                    const start =
                        expressionStart +
                        expressionMatch.index;
 
                    decorations.push(
                        Decoration.mark({
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                }
            }


             wrapper.append(
             return Decoration.set(
                 controls
                 decorations,
                true
             );
             );
            return wrapper;
         },
         },


         /* =========================================================
         async installSyntaxHighlighting(view) {
        * CONFIG OUTPUT
            await mw.loader.using(
        * ========================================================= */
                'ext.CodeMirror.v6.lib'
            );


        getCleanConfig() {
             const require =
             const config =
                 mw.loader.require;
                 JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );


             /*
             const {
            * Keep PAGE first.
                StateField,
            */
                StateEffect,
             const fields =
                EditorView,
                 config.fields || {};
                Decoration
             } = require(
                 'ext.CodeMirror.v6.lib'
            );


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


            if (fields.PAGE) {
                    update: (
                orderedFields.PAGE =
                        decorations,
                    fields.PAGE;
                        transaction
            }
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


            Object.keys(fields)
                     provide: field =>
                .filter(
                         EditorView.decorations.from(
                     name =>
                            field
                         name.toUpperCase() !==
                         )
                        'PAGE'
                )
                .forEach(name => {
                    orderedFields[name] =
                         fields[name];
                 });
                 });


             config.fields =
             view.dispatch({
                 orderedFields;
                 effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });


             return config;
             this.editor.syntaxField =
                syntaxField;
         },
         },


         getConfigJSON() {
         async mountCodeMirror(textarea) {
             return JSON.stringify(
             return new Promise(
                 this.getCleanConfig(),
                 (
                 null,
                    resolve,
                4
                    reject
            );
                 ) => {
        },
                    let settled = false;
 
                    const cleanup = () => {
                        mw.hook(
                            'dev.CCM.ready'
                        ).remove(onReady);


        renderConfigPreview(container) {
                        mw.hook(
            if (!container) {
                            'dev.CCM.load'
                return;
                        ).remove(onLoad);
            }
                    };


            container.text(
                    const onReady =
                this.getConfigJSON()
                        async cm => {
            );
                            if (
        },
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


        renderConfigPreviewBySelector() {
                            settled = true;
            const preview =
                            cleanup();
                this.root &&
                this.root.find(
                    '.preload-editor-config-preview'
                );


            if (preview && preview.length) {
                            const view =
                this.renderConfigPreview(
                                cm.view;
                    preview
                );
            }


            const analysis =
                            const inputHandler =
                this.root &&
                                () => {
                this.root.find(
                                    this.state
                    '.preload-editor-analysis'
                                        .preloadContent =
                );
                                        view.state.doc.toString();


            if (
                                    this.markPreloadDirty();
                analysis &&
                analysis.length
            ) {
                this.renderAnalysis(
                    analysis
                );
            }
        },


        markDirty() {
                                    this.reanalyze();
            this.state.dirty = true;
        },


        /* =========================================================
                                    this.renderVariablesBySelector();
        * SAVE
                                    this.renderVariableConfigurationBySelector();
        * ========================================================= */
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


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


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


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


                title = result;
                            const wrapper =
                                view.dom.closest(
                                    '.ext-codemirror-wrapper'
                                );


                this.state.preloadTitle =
                            if (wrapper) {
                    title;
                                wrapper.classList.add(
            }
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


            const validation =
                            this.editor = {
                this.validateBeforeSave();
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


            if (
                            this.editorView =
                validation.errors.length
                                view;
            ) {
                this.showValidationErrors(
                    validation
                );


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


            this.setStatus(
                            try {
                'Saving preload...',
                                await this.installSyntaxHighlighting(
                'loading'
                                    view
            );
                                );


            try {
                                if (
                const exists =
                                    this.state.dirty
                    await this.pageExists(
                                ) {
                        title
                                    this.saveDraft();
                    );
                                }


                await this.savePage(
                                resolve(view);
                    title,
                            } catch (error) {
                    this.state.preloadContent,
                                reject(error);
                    exists
                            }
                        ? 'Updated preload with Preload Editor'
                         };
                         : 'Created preload with Preload Editor',
                    !exists
                );


                this.state.mode = 'edit';
                    const onLoad =
                this.state.dirty = false;
                        loader => {
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                this.setStatus(
                            try {
                    'Preload saved successfully.',
                                loader(textarea);
                    'success'
                            } catch (error) {
                );
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };


                mw.notify(
                    mw.hook(
                    'Preload saved.',
                        'dev.CCM.ready'
                     {
                     ).add(onReady);
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );


                this.setStatus(
                    mw.hook(
                    error.message ||
                         'dev.CCM.load'
                         'Could not save preload.',
                     ).add(onLoad);
                     'error'
                 }
                );
            );
 
                 mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
         },
         },


         async saveAll() {
         // =========================================================
            let title =
        // Main UI
                String(
        // =========================================================
                    this.state.preloadTitle ||
                    ''
                ).trim();


            if (!title) {
        init() {
                const result =
            const root =
                    await this.createPromptDialog(
                $('#mw-content-text');
                        'Preload title',
                        'Enter the full title for the preload.'
                    );


                if (!result) {
            if (!root.length) {
                    return;
                return;
                }
            }


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


                this.state.preloadTitle =
            root.append(this.root);
                    title;
            }


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


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


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


             const configTitle =
             const loader =
                 title.replace(
                 this.createSection('Preload');
                    /\/+$/,
                    ''
                ) +
                '/config.json';


             this.setStatus(
             const titleInput =
                 'Saving preload and config...',
                this.textInput(
                 'loading'
                    this.state.preloadTitle,
                    'Template:Example/Preload'
                 ).attr(
                    'id',
                    'preload-editor-title-input'
                );
 
            titleInput.on(
                'input.preloadEditor',
                 () => {
                    this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();
 
                    if (
                        this.state.dirty &&
                        this.state.mode === 'new'
                    ) {
                        this.saveDraft();
                    }
                }
             );
             );


             try {
             const loadButton =
                const preloadExists =
                 this.createButton(
                    await this.pageExists(
                     'Load',
                        title
                     'preload-editor-button-primary',
                    );
                     () =>
 
                         this.loadExisting(
                 await this.savePage(
                            titleInput.val()
                     title,
                         )
                     this.state.preloadContent,
                     preloadExists
                         ? 'Updated preload with Preload Editor'
                         : 'Created preload with Preload Editor',
                    !preloadExists
                 );
                 );


                const configExists =
            const newButton =
                    await this.pageExists(
                this.createButton(
                        configTitle
                    'New',
                     );
                     '',
                    () => this.startNew()
                );


                 await this.savePage(
            const sampleButton =
                     configTitle,
                 this.createButton(
                    this.getConfigJSON(),
                     'Load Sample Page',
                     configExists
                     '',
                        ? 'Updated preload config with Preload Editor'
                     () => this.loadSamplePage()
                        : 'Created preload config with Preload Editor',
                     !configExists
                 );
                 );


                 this.state.mode = 'edit';
            loader.append(
                this.state.dirty = false;
                 $('<div>')
                this.state.preloadTitle =
                    .addClass(
                     title;
                        'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                     )
            );


                this.setStatus(
            this.root.append(loader);
                    'Preload and config saved successfully.',
                    'success'
                );


                 mw.notify(
            this.workspace =
                    'Preload and config saved.',
                 $('<div>')
                    {
                     .addClass(
                        type: 'success'
                        'preload-editor-workspace'
                     }
                     );
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                     error
                );


                this.setStatus(
            this.root.append(
                    error.message ||
                this.workspace
                        'Could not save preload/config.',
            );
                    'error'
                );


                mw.notify(
            /*
                    error.message ||
            * Fixed footer
                        'Could not save preload/config.',
            *
                     {
            * Local draft status, normal status messages,
                         type: 'error'
            * and save actions live here.
                     }
            */
                );
            const footer =
            }
                $('<div>')
        },
                     .addClass(
                         'preload-editor-footer'
                     );


        validateBeforeSave() {
            this.localDraftStatus =
            const errors = [];
                $('<div>')
            const warnings = [];
                    .addClass(
                        'preload-editor-local-draft-status is-empty'
                    )
                    .text(
                        'No local draft'
                    );


             const title =
             this.status =
                 String(
                 $('<div>')
                     this.state.preloadTitle ||
                     .addClass(
                    ''
                        'preload-editor-status'
                ).trim();
                    );


             if (!title) {
             footer.append(
                 errors.push(
                 this.localDraftStatus,
                    'A preload title is required.'
                this.status
                );
            );
            }


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


             const content =
             this.updateLocalDraftIndicator();
                String(
                    this.state.preloadContent ||
                    ''
                );


             if (!content.trim()) {
             this.renderWelcome();
                errors.push(
        },
                    'The preload cannot be empty.'
 
                );
        renderWelcome() {
            }
            this.workspace.empty();


             if (
             const section =
                !/<includeonly>/i.test(
                 this.createSection('Get started');
                    content
                )
            ) {
                 warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }


             if (
             $('<p>')
                 !/<noinclude>/i.test(
                 .text(
                     content
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                 )
                 )
            ) {
                 .appendTo(section);
                 warnings.push(
                    'The preload does not contain a <noinclude> section.'
                );
            }


             const analysis =
             const tips =
                 this.analyzePreload(
                 $('<ul>')
                     content
                    .addClass(
                );
                        'preload-editor-tips'
                     );


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


             errors.push(
             this.status.removeClass(
                 ...configValidation.errors
                 'is-error',
                'is-success',
                'is-warning',
                'is-loading'
             );
             );


             warnings.push(
             if (type) {
                 ...configValidation.warnings
                 this.status.addClass(
                    'is-' + type
                );
            }
 
            this.status.text(
                message || ''
             );
             );
        },


            /*
        // =========================================================
            * Basic conditional marker validation.
        // Load / create
            */
        // =========================================================
            let depth = 0;


             analysis.conditions.forEach(
        async loadExisting(title) {
                condition => {
             title =
                    if (
                String(title || '').trim();
                        condition.type ===
 
                         'if'
            if (!title) {
                     ) {
                mw.notify(
                        depth++;
                    'Enter a preload page title first.',
                    } else if (
                    {
                        condition.type ===
                         type: 'warn'
                        'endif'
                     }
                     ) {
                );
                         depth--;
 
                return;
            }
 
            this.setStatus(
                'Loading preload...',
                'loading'
            );
 
            try {
                const page =
                     await this.getPage(title);
 
                if (!page) {
                    const suggestions =
                         await this.findSimilarPreloads(
                            title
                        );


                         if (depth < 0) {
                    this.renderMissingPage(
                             errors.push(
                        title,
                                 'Found @endif without a matching @if.'
                        suggestions
                    );
 
                    this.setStatus(
                        'Preload not found.',
                        'warning'
                    );
 
                    return;
                }
 
                await this.loadDefinition(
                    page.title,
                    page.content
                );
 
                this.setStatus(
                    'Preload loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not load preload.',
                    'error'
                );
            }
        },
 
        async findSimilarPreloads(title) {
            let query =
                title
                    .replace(
                        /\/Preload$/i,
                        ''
                    )
                    .trim();
 
            if (!query) {
                query = title;
            }
 
            try {
                const results =
                    await this.searchPages(query);
 
                return results.filter(
                    result =>
                        /\/Preload$/i.test(
                            result.title
                        )
                );
            } catch (error) {
                console.error(
                    'Preload Editor search:',
                    error
                );
 
                return [];
            }
        },
 
        renderMissingPage(
            title,
            suggestions
        ) {
            this.workspace.empty();
 
            const section =
                this.createSection(
                    'Preload not found'
                );
 
            $('<p>')
                .text(
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);
 
            if (suggestions.length) {
                $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);
 
                const list =
                    $('<div>')
                        .addClass(
                            'preload-editor-suggestions'
                        );
 
                suggestions.forEach(
                    result => {
                        list.append(
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                        );
                    }
                );
 
                section.append(list);
            }
 
            section.append(
                this.createButton(
                    'Create this preload',
                    'preload-editor-button-primary',
                    () =>
                        this.startNew(title)
                )
            );
 
            this.workspace.append(section);
        },
 
        async startNew(title) {
            title =
                String(title || '').trim();
 
            this.state = {
                preloadTitle: title,
                preloadSource: '',
                preloadContent:
                    this.defaults.preload,
 
                config:
                    this.emptyConfig(),
 
                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };
 
            this.saveDraft();
            this.renderEditor();
 
            this.setStatus(
                'Creating a new preload.',
                'success'
            );
        },
 
        async loadSamplePage() {
            const result =
                await this.createPromptDialog(
                    'Load Sample Page',
                    'Enter the title of a normal wiki page to use as the starting point.'
                );
 
            if (!result) {
                return;
            }
 
            this.setStatus(
                'Loading sample page...',
                'loading'
            );
 
            try {
                const page =
                    await this.getPage(result);
 
                if (!page) {
                    throw new Error(
                         'Sample page not found: ' +
                        result
                    );
                }
 
                const sample =
                    this.convertSampleToPreload(
                        page.content
                    );
 
                this.state = {
                    preloadTitle: '',
                    preloadSource: '',
                    preloadContent: sample,
 
                    config:
                        this.emptyConfig(),
 
                    variables: ['PAGE'],
                    conditions: [],
                    selectedVariable: 'PAGE',
                    deletedVariables: [],
                    mode: 'new',
                    dirty: true,
                    dirtyPreload: true,
                    dirtyConfig: true,
 
                    localDraftSavedAt: null,
                    localDraftAvailable: false
                };
 
                this.reanalyze();
                this.saveDraft();
                this.renderEditor();
 
                this.setStatus(
                    'Sample page loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
        },
 
        convertSampleToPreload(source) {
            let content =
                String(source || '').trim();
 
            const include =
                content.match(
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                );
 
            if (include) {
                content =
                    include[1].trim();
            }
 
            content =
                content
                    .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();
 
            return (
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },
 
        async loadDefinition(
            title,
            source
        ) {
            const content =
                this.extractIncludeonly(source);
 
            let config =
                this.emptyConfig();
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            const configPage =
                await this.getPage(configTitle);
 
            if (configPage) {
                try {
                    config =
                        JSON.parse(
                            configPage.content
                        );
                } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }
 
            const analysis =
                this.analyzePreload(content);
 
            this.state.deletedVariables = [];
 
            config =
                this.prepareConfigForVariables(
                    config,
                    analysis
                );
 
            this.state = {
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,
 
                variables:
                    analysis.variables,
 
                conditions:
                    analysis.conditions,
 
                selectedVariable:
                    analysis.variables.includes('PAGE')
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),
 
                deletedVariables: [],
 
                mode: 'edit',
                dirty: false,
                dirtyPreload: false,
                dirtyConfig: false,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };
 
            this.clearDraft(title);
            this.renderEditor();
        },
 
        // =========================================================
        // Editor
        // =========================================================
 
        renderEditor() {
            this.destroyEditor();
            this.workspace.empty();
 
            const layout =
                $('<div>')
                    .addClass(
                        'preload-editor-layout'
                    );
 
            const left =
                $('<div>')
                    .addClass(
                        'preload-editor-left'
                    );
 
            const right =
                $('<div>')
                    .addClass(
                        'preload-editor-right'
                    );
 
            const editorSection =
                this.createSection(
                    'Preload',
                    'preload-editor-main-section'
                );
 
            const meta =
                $('<div>')
                    .addClass(
                        'preload-editor-meta'
                    );
 
            $('<strong>')
                .text(
                    this.state.preloadTitle ||
                    'New preload'
                )
                .appendTo(meta);
 
            if (
                this.state.mode === 'new'
            ) {
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
            }
 
            editorSection.append(meta);
            editorSection.append(
                this.renderEditorTools()
            );
 
            const textarea =
                this.textarea(
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );
 
            const editorMount =
                $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);
 
            editorSection.append(editorMount);
            left.append(editorSection);
 
            const analysisSection =
                this.createSection('Analysis');
 
            const analysisContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis'
                    );
 
            analysisSection.append(
                analysisContainer
            );
 
            const variablesSection =
                this.createSection('Variables');
 
            const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );
 
            const detectHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );
 
            variablesSection.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );
 
            const variableContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variables'
                    );
 
            variablesSection.append(
                variableContainer
            );
 
            const configurationSection =
                this.createSection(
                    'Variable configuration'
                );
 
            /*
            * Import button lives at the top of the
            * variable configuration section so the
            * workflow is always easy to find.
            */
            const importDefinitionsButton =
                this.createButton(
                    'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                        this.importVariableDefinitions()
                );
 
            const importHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-import-definitions-help'
                    )
                    .text(
                        'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );
 
            const importControls =
                $('<div>')
                    .addClass(
                        'preload-editor-import-definition-controls'
                    )
                    .append(
                        importDefinitionsButton,
                        importHelp
                    );
 
            configurationSection.append(
                importControls
            );
 
            const configurationContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-configuration'
                    );
 
            configurationSection.append(
                configurationContainer
            );
 
            const configSection =
                this.createSection(
                    'Configuration'
                );
 
            const configHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );
 
            const reviewConfigButton =
                this.createButton(
                    'Review config.json',
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );
 
            configSection.append(
                configHelp,
                reviewConfigButton
            );
 
            right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );
 
            layout.append(
                left,
                right
            );
 
            const saveBar =
                $('<div>')
                    .addClass(
                        'preload-editor-save-bar'
                    );
 
            saveBar.append(
                this.createButton(
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),
 
                this.createButton(
                    'Save Config',
                    '',
                    () =>
                        this.saveConfigOnly()
                ),
 
                this.createButton(
                    'Save',
                    'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                )
            );
 
            this.root
                .find('.preload-editor-footer')
                .append(saveBar);
 
            this.workspace.append(
                layout
            );
 
            this.reanalyze();
 
            this.renderVariables(
                variableContainer
            );
 
            this.renderAnalysis(
                analysisContainer
            );
 
            this.renderVariableConfiguration(
                configurationContainer
            );
 
            this.updateEditorTools();
            this.updateLocalDraftIndicator();
 
            this.mountCodeMirror(
                textarea.get(0)
            ).catch(
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                    );
 
                    this.setStatus(
                        error.message ||
                            'Could not initialize CodeMirror.',
                        'error'
                    );
                }
            );
        },
 
        // =========================================================
        // Variable detection
        // =========================================================
 
        detectVariables() {
            const source =
                this.getEditorContent();
 
            this.state.preloadContent =
                source;
 
            const content =
                this.extractIncludeonly(
                    source
                );
 
            const analysis =
                this.analyzePreload(
                    content
                );
 
            /*
            * If a variable was previously deleted from
            * the configuration, detecting the current
            * preload again should allow it to come back.
            */
            if (
                Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                const detected =
                    new Set(
                        analysis.variables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                    );
 
                this.state.deletedVariables =
                    this.state.deletedVariables
                        .filter(
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                this.state.deletedVariables = [];
            }
 
            this.markDirty();
 
            this.reanalyze();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.updateEditorTools();
 
            this.saveDraft();
 
            this.setStatus(
                'Variables detected from the current preload.',
                'success'
            );
        },
 
        reanalyze() {
            const source =
                this.getEditorContent();
 
            const content =
                this.extractIncludeonly(source);
 
            const analysis =
                this.analyzePreload(
                    content
                );
 
            this.state.preloadContent =
                source;
 
            this.state.variables =
                analysis.variables;
 
            this.state.conditions =
                analysis.conditions;
 
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );
 
            this.analysis =
                analysis;
 
            const available =
                ['PAGE'].concat(
                    analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );
 
            if (
                !available.includes(
                    this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },
 
        // =========================================================
        // Analysis
        // =========================================================
 
        renderAnalysis(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const variableCount =
                analysis.variables.length;
 
            const conditionCount =
                analysis.conditions.length;
 
            const configuredCount =
                Object.keys(
                    this.state.config &&
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;
 
            const summary =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis-summary'
                    );
 
            const createMetric =
                (
                    value,
                    label
                ) =>
                    $('<div>')
                        .addClass(
                             'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),
 
                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                        );
 
            summary.append(
                createMetric(
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),
 
                createMetric(
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),
 
                createMetric(
                    configuredCount,
                    configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                )
            );
 
            container.append(summary);
 
            if (
                analysis.conditionVariables.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }
 
            const validation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );
 
            if (validation.errors.length) {
                const errors =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-errors'
                        );
 
                validation.errors.forEach(
                    error => {
                        $('<li>')
                            .text(error)
                            .appendTo(errors);
                    }
                );
 
                container.append(errors);
            }
 
            if (validation.warnings.length) {
                const warnings =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );
 
                validation.warnings.forEach(
                    warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                );
 
                container.append(warnings);
            }
 
            if (
                !validation.errors.length &&
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },
 
        renderAnalysisBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderAnalysis(container);
            }
        },
 
        // =========================================================
        // Variables
        // =========================================================
 
        renderVariables(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const variables =
                analysis.variables.slice();
 
            const ordered =
                ['PAGE'];
 
            variables.forEach(
                name => {
                    if (
                        name !== 'PAGE' &&
                        !ordered.includes(name)
                    ) {
                        ordered.push(name);
                    }
                }
            );
 
            const configuredFields =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];
 
            configuredFields.forEach(
                name => {
                    const upper =
                        name.toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );
 
            const deleted =
                Array.isArray(
                    this.state.deletedVariables
                )
                    ? this.state.deletedVariables
                    : [];
 
            deleted.forEach(
                name => {
                    const upper =
                        String(name).toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );
 
            const list =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-list'
                    );
 
            ordered.forEach(
                name => {
                    const isSelected =
                        name ===
                        this.state.selectedVariable;
 
                    const isUsed =
                        analysis.variables.includes(
                            name
                        );
 
                    const isConfigured =
                        !!(
                            this.state.config &&
                            this.state.config.fields &&
                            this.state.config.fields[name]
                        );
 
                    const item =
                        $('<button>')
                            .attr({
                                type: 'button',
                                'data-variable':
                                    name
                            })
                            .addClass(
                                 'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                             );
                             );


                             depth = 0;
                    $('<span>')
                         }
                        .addClass(
                     } else if (
                            'preload-editor-variable-name'
                         condition.type ===
                        )
                         'elseif' ||
                        .text(name)
                         condition.type ===
                        .appendTo(item);
                        'else'
 
                     ) {
                    if (name === 'PAGE') {
                         if (depth === 0) {
                        item.append(
                             errors.push(
                            $('<span>')
                                 '@' +
                                .addClass(
                                 condition.type +
                                    'preload-editor-badge'
                                 ' exists outside an @if block.'
                                )
                             );
                                .text('AUTOMATIC')
                         }
                        );
                     }
                    } else if (!isConfigured) {
                 }
                        item.append(
             );
                            $('<span>')
 
                                .addClass(
             if (depth > 0) {
                                    'preload-editor-badge is-warning'
                 errors.push(
                                )
                     'One or more @if blocks are missing @endif.'
                                .text(
                 );
                                    isUsed
             }
                                        ? 'NOT CONFIGURED'
 
                                        : 'DELETED'
             return {
                                )
                 errors: errors,
                        );
                 warnings: warnings,
                    } else if (!isUsed) {
                 valid:
                        item.append(
                     errors.length === 0
                            $('<span>')
             };
                                .addClass(
         },
                                    'preload-editor-badge is-warning'
 
                                )
         showValidationErrors(validation) {
                                .text('UNUSED')
             this.renderAnalysis(
                        );
                this.root.find(
                    }
                    '.preload-editor-analysis'
 
                )
                    list.append(item);
            );
                }
            );
 
            container.append(list);
 
            if (!ordered.length) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                );
            }
        },
 
        renderVariablesBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variables'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderVariables(container);
            }
        },
 
        selectVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();
 
            if (!name) {
                return;
            }
 
            const available =
                ['PAGE'].concat(
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );
 
            const configuredUnused =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];
 
            configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                }
            );
 
            if (!available.includes(name)) {
                return;
            }
 
            this.state.selectedVariable =
                name;
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },
 
        renderVariableConfigurationBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variable-configuration'
                );
 
            if (
                container &&
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
            }
        },
 
        renderVariableConfiguration(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );
 
            const name =
                this.state.selectedVariable ||
                'PAGE';
 
            const fields =
                this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};
 
            const field =
                fields[name];
 
            if (name === 'PAGE') {
                container.append(
                    this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                );
 
                return;
            }
 
            if (!field) {
                const missing =
                    $('<div>')
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );
 
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    )
                    .append(
                        $('<h3>')
                            .text(name),
 
                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);
 
                $('<p>')
                    .addClass(
                        'preload-editor-analysis-note'
                    )
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);
 
                container.append(missing);
                return;
            }
 
            container.append(
                this.createVariableCard(
                    name,
                    field,
                    analysis
                )
            );
        },
 
        createAutomaticPageCard(field) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );
 
            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );
 
            header.append(
                $('<h3>').text('PAGE'),
 
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
            );
 
            card.append(header);
 
            $('<p>')
                .addClass(
                    'preload-editor-analysis-note'
                )
                .text(
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);
 
            const label =
                this.textInput(
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                );
 
            const description =
                this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                    .addClass(
                        'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                    );
 
            const type =
                this.textInput(
                    field.type || 'page'
                ).prop(
                    'disabled',
                    true
                );
 
            const required =
                this.checkbox(
                    field.required !== false
                ).prop(
                    'disabled',
                    true
                );
 
            const namespace =
                this.textInput(
                    field.namespace || 'Main'
                ).prop(
                    'disabled',
                    true
                );
 
            const allowNew =
                this.checkbox(
                    field['allow-new'] === true
                ).prop(
                    'disabled',
                    true
                );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                ),
 
                this.fieldRow(
                    'Description',
                    description
                ),
 
                this.fieldRow(
                    'Type',
                    type
                ),
 
                this.fieldRow(
                    'Required',
                    required
                ),
 
                this.fieldRow(
                    'Namespace',
                    namespace
                ),
 
                this.fieldRow(
                    'Allow new page',
                    allowNew
                )
            );
 
            return card;
        },
 
        createVariableCard(
            name,
            field,
            analysis
        ) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );
 
            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );
 
            header.append(
                $('<h3>').text(name)
            );
 
            if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }
 
            card.append(header);
 
            const label =
                this.textInput(
                    field.label || ''
                );
 
            label.on(
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                )
            );
 
            const description =
                this.textarea(
                    field.description || ''
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            description.on(
                'input.preloadEditor',
                () => {
                    field.description =
                        description.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Description',
                    description
                )
            );
 
            const types = [
                ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];
 
            const typeSelect =
                this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                );
 
            typeSelect.on(
                'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();
 
                    this.markDirty();
 
                    this.renderVariableConfigurationBySelector();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );
 
            const required =
                this.checkbox(
                    field.required === true
                );
 
            required.on(
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Required',
                    required
                )
            );
 
            const placeholder =
                this.textInput(
                    field.placeholder || ''
                );
 
            placeholder.on(
                'input.preloadEditor',
                () => {
                    const value =
                        placeholder.val();
 
                    if (value) {
                        field.placeholder =
                            value;
                    } else {
                        delete field.placeholder;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );
 
            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                );
 
            defaultInput.on(
                'input.preloadEditor',
                () => {
                    const value =
                        defaultInput.val();
 
                    if (value) {
                        field.default =
                            value;
                    } else {
                        delete field.default;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Default',
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
            );
 
            if (
                field.type === 'textarea'
            ) {
                const maxRows =
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );
 
                maxRows.on(
                    'input.preloadEditor',
                    () => {
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );
 
                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }
 
                        this.markDirty();
                        this.renderConfigReviewAvailability();
                    }
                );
 
                card.append(
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                );
            }
 
            if (
                field.type === 'select' ||
                field.type === 'multiselect'
            ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }
 
            if (
                field.type === 'file'
            ) {
                this.renderFileConfiguration(
                    card,
                    field
                );
            }
 
            const deleteButton =
                this.createButton(
                    'Delete variable',
                    'preload-editor-button-danger preload-editor-delete-variable',
                    async () => {
                        const confirmed =
                            await this.createConfirmDialog(
                                'Delete variable',
                                'Delete "' +
                                name +
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                                'Delete variable',
                                'Cancel'
                            );
 
                        if (!confirmed) {
                            return;
                        }
 
                        this.deleteVariable(name);
                    }
                );
 
            card.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );
 
            return card;
        },
 
        async deleteVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();
 
            if (
                !name ||
                name === 'PAGE'
            ) {
                return;
            }
 
            if (
                !this.state.config ||
                !this.state.config.fields
            ) {
                return;
            }
 
            delete this.state.config.fields[name];
 
            if (
                !Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                this.state.deletedVariables = [];
            }
 
            if (
                !this.state.deletedVariables.includes(
                    name
                )
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }
 
            this.state.selectedVariable =
                name;
 
            this.markDirty();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();
 
            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },
 
        // =========================================================
        // Select configuration
        // =========================================================
 
        renderSelectConfiguration(
            card,
            field
        ) {
            const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                );
 
            source.on(
                'input.preloadEditor',
                () => {
                    const value =
                        source.val();
 
                    if (value) {
                        field.source = value;
                    } else {
                        delete field.source;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source',
                    source,
                    'Currently supported source format: category:Category Name'
                )
            );
 
            const sourcePrefix =
                this.textInput(
                    field['source-prefix'] || ''
                );
 
            sourcePrefix.on(
                'input.preloadEditor',
                () => {
                    const value =
                        sourcePrefix.val();
 
                    if (value) {
                        field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );
 
            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );
 
            excludeCategory.on(
                'input.preloadEditor',
                () => {
                    const value =
                        excludeCategory.val();
 
                    if (value) {
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;
 
                        if (
                            !Object.keys(
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                )
            );
 
            card.append(
                this.createTransformControls(
                    field,
                    'value',
                    'Value transformation'
                ),
 
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );
 
            const optionsValue =
                Array.isArray(field.options)
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }
 
                                return (
                                    String(
                                        option.value || ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';
 
            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            options.on(
                'input.preloadEditor',
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);
 
                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );
 
                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }
 
                                    return {
                                        value:
                                            parts[0],
 
                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                             );
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
       
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);
 
                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );
 
            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );
 
            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();
 
                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );
 
            const filetext =
                this.textarea(
                    field.filetext || ''
                );
 
            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();
 
                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },
 
        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                $('<div>')
                    .addClass(
                        'preload-editor-transform'
                    );
 
            $('<h4>')
                .text(title)
                .appendTo(wrapper);
 
            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );
 
            const prefix =
                this.textInput(
                    existing.prefix || ''
                );
 
            const suffix =
                this.textInput(
                    existing.suffix || ''
                );
 
            const from =
                this.textInput(
                    existing.from || ''
                );
 
            const to =
                this.textInput(
                    existing.to || ''
                );
 
            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );
 
            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );
 
            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );
 
            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );
 
            const toRow =
                this.fieldRow(
                    'To',
                    to
                );
 
            const renderInputs =
                () => {
                    const type =
                        transform.val();
 
                    prefixRow.toggle(
                        type === 'remove-prefix'
                    );
 
                    suffixRow.toggle(
                        type === 'remove-suffix'
                    );
 
                    fromRow.toggle(
                        type === 'replace'
                    );
 
                    toRow.toggle(
                        type === 'replace'
                    );
                };
 
            const update =
                () => {
                    const type =
                        transform.val();
 
                    let object = null;
 
                    if (
                        type === 'remove-prefix' &&
                        prefix.val()
                    ) {
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                    ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }
 
                    if (object) {
                        field[property] = object;
                    } else {
                        delete field[property];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                };
 
            transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );
 
            controls.append(
                this.fieldRow(
                    'Transformation',
                    transform
                ),
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );
 
            renderInputs();
 
            wrapper.append(controls);
 
            return wrapper;
        },
 
        // =========================================================
        // Config output
        // =========================================================
 
        getCleanConfig() {
            const config =
                JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );
 
            const fields =
                config.fields || {};
 
            const orderedFields = {};
 
            orderedFields.PAGE =
                this.getAutomaticPageField();
 
            Object.keys(fields)
                .filter(
                    name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );
 
            config.fields =
                orderedFields;
 
            return config;
        },
 
        getConfigJSON() {
            return JSON.stringify(
                this.getCleanConfig(),
                null,
                4
            );
        },
 
        renderConfigPreview(container) {
            if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },
 
        renderConfigPreviewBySelector() {
            this.renderAnalysisBySelector();
        },
 
        renderConfigReviewAvailability() {
            this.renderAnalysisBySelector();
        },
 
        // =========================================================
        // Dirty state
        // =========================================================
 
        updateDirtyState() {
            this.state.dirty =
                !!(
                    this.state.dirtyPreload ||
                    this.state.dirtyConfig
                );
        },
 
        markPreloadDirty() {
            this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markConfigDirty() {
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markDirty() {
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        // =========================================================
        // Save
        // =========================================================
 
        async savePreloadOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'preload',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            this.setStatus(
                'Saving preload...',
                'loading'
            );
 
            try {
                const exists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyPreload = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveConfigOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'config',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving config...',
                'loading'
            );
 
            try {
                /*
                * This now automatically creates or converts
                * config.json to the JSON content model.
                */
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    (
                        await this.pageExists(
                            configTitle
                        )
                    )
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyConfig = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor config save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveAll() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving preload and config...',
                'loading'
            );
 
            try {
                const preloadExists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );
 
                /*
                * Config is saved through the JSON-aware
                * helper. This means:
                *
                * - new config -> created as JSON
                * - old wikitext config -> converted to JSON
                * - existing JSON config -> simply updated
                */
                const configExists =
                    await this.pageExists(
                        configTitle
                    );
 
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.dirtyPreload = false;
                this.state.dirtyConfig = false;
                this.state.dirty = false;
                this.state.preloadTitle = title;
 
                this.clearDraft(title);
 
                this.setStatus(
                    'Preload and JSON config saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload and config saved. config.json is using the JSON content model.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        // =========================================================
        // Validation
        // =========================================================
 
        validateBeforeSave() {
            const errors = [];
            const warnings = [];
 
            const title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                errors.push(
                    'A preload title is required.'
                );
            }
 
            if (
                title &&
                !/\/Preload$/i.test(title)
            ) {
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }
 
            const content =
                this.getEditorContent();
 
            this.state.preloadContent =
                content;
 
            if (!content.trim()) {
                errors.push(
                    'The preload cannot be empty.'
                );
            }
 
            if (
                !/<includeonly>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }
 
            if (
                !/<noinclude>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain a <noinclude> section.'
                );
            }
 
            const analysis =
                this.analyzePreload(
                    this.extractIncludeonly(
                        content
                    )
                );
 
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );
 
            const configValidation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );
 
            errors.push(
                ...configValidation.errors
            );
 
            warnings.push(
                ...configValidation.warnings
            );
 
            let depth = 0;
                         analysis.conditions.forEach(
                condition => {
                    if (
                        condition.type === 'if'
                    ) {
                        depth++;
                     } else if (
                         condition.type === 'endif'
                    ) {
                        depth--;
 
                        if (depth < 0) {
                            errors.push(
                                'Found @endif without a matching @if.'
                            );
 
                            depth = 0;
                        }
                    } else if (
                         condition.type === 'elseif' ||
                         condition.type === 'else'
                     ) {
                         if (depth === 0) {
                             errors.push(
                                 '@' +
                                 condition.type +
                                 ' exists outside an @if block.'
                             );
                         }
                     }
                 }
             );
 
             if (depth > 0) {
                 errors.push(
                     'One or more @if blocks are missing @endif.'
                 );
             }
 
             return {
                 errors,
                 warnings,
                 valid:
                     errors.length === 0
             };
         },
 
         showValidationErrors(validation) {
             this.renderAnalysisBySelector();
 
            this.saveDraft();


             this.setStatus(
             this.setStatus(
                 validation.errors.join(
                 validation.errors.join(' '),
                    ' '
                ),
                 'error'
                 'error'
             );
             );


             mw.notify(
             mw.notify(
                 validation.errors.join(
                 validation.errors.join('\n'),
                    '\n'
                ),
                 {
                 {
                     type: 'error'
                     type: 'error'
Line 3,217: Line 6,208:
     };
     };


    /*
    * Expose globally.
    */
     mw.PreloadEditor =
     mw.PreloadEditor =
         PreloadEditor;
         PreloadEditor;


    /*
    * Initialise only on the project page.
    */
     $(function () {
     $(function () {
        const title =
            mw.config.get(
                'wgPageName'
            );
         if (
         if (
             title !==
             mw.config.get('wgPageName') !==
             'Petit_Planet:Preload_Editor'
             'Petit_Planet_Wiki:Preload_Editor'
         ) {
         ) {
             return;
             return;