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

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

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


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


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


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


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


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


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


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


             if (!page || page.missing) return null;
                return parsed;
             } catch (error) {
                console.warn('Preload Editor: Could not read local drafts.', error);


            const content =
                return {
                page.revisions &&
                    active: null,
                page.revisions[0] &&
                    drafts: {}
                 page.revisions[0].slots &&
                 };
                page.revisions[0].slots.main &&
            }
                page.revisions[0].slots.main.content;
        },


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


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


         async searchPages(query) {
         getDraftSnapshot() {
             const response = await new mw.Api().get({
             let content = this.getEditorContent();
                 action: 'query',
 
                 list: 'search',
            if (!this.editorView && !content) {
                 srsearch: query,
                content = this.state.preloadContent || '';
                 srlimit: 10,
            }
                 srnamespace: 10,
 
                 formatversion: 2
            let config = null;
            });
 
            try {
                config = this.state.config
                    ? JSON.parse(JSON.stringify(this.state.config))
                    : this.emptyConfig();
            } catch (error) {
                console.warn('Preload Editor: Could not clone config for local draft.', error);
                config = this.emptyConfig();
            }
 
            return {
                 version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                 preloadSource: String(this.state.preloadSource || ''),
                 preloadContent: String(content || ''),
                 config,
 
                variables: Array.isArray(this.state.variables)
                    ? this.state.variables.slice()
                    : [],
 
                 conditions: Array.isArray(this.state.conditions)
                    ? this.state.conditions.slice()
                    : [],
 
                 selectedVariable: String(this.state.selectedVariable || 'PAGE'),


            return (
                deletedVariables: Array.isArray(this.state.deletedVariables)
                response &&
                    ? this.state.deletedVariables.slice()
                response.query &&
                    : [],
                response.query.search
            ) || [];
        },


        async savePage(
                 mode: this.state.mode || 'edit',
            title,
                 dirty: !!this.state.dirty,
            content,
                 dirtyPreload: !!this.state.dirtyPreload,
            summary,
                 dirtyConfig: !!this.state.dirtyConfig,
            createOnly
                 savedAt: Date.now()
        ) {
            const params = {
                 action: 'edit',
                 title,
                 text: content,
                 summary:
                    summary ||
                    'Updated with Preload Editor',
                 formatversion: 2
             };
             };
        },


             if (createOnly) {
        updateLocalDraftStatus(message, type) {
                 params.createonly = true;
             if (!this.localDraftStatus) {
                 return;
             }
             }


             return new mw.Api().postWithToken(
             this.localDraftStatus.removeClass(
                 'csrf',
                 'is-saved',
                 params
                 'is-warning',
                'is-error',
                'is-empty'
             );
             );
            if (type) {
                this.localDraftStatus.addClass('is-' + type);
            }
            this.localDraftStatus.text(message || '');
         },
         },


         // =========================================================
         formatLocalDraftTime(timestamp) {
        // Preload parsing
            if (!timestamp) {
        // =========================================================
                return '';
            }


        extractIncludeonly(source) {
            try {
            const match =
                return new Date(timestamp).toLocaleTimeString([], {
                String(source || '').match(
                    hour: '2-digit',
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                    minute: '2-digit',
                 );
                     second: '2-digit'
 
                 });
             return match
             } catch (error) {
                ? match[1].trim()
                 return '';
                 : String(source || '').trim();
            }
         },
         },


         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)) !==
                    time ? 'Saved locally at ' + time : 'Saved locally',
                null
                    '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) {
                return false;
            }
 
             const snapshot = this.getDraftSnapshot();
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();


             const pattern =
             storage.drafts[id] = snapshot;
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
            storage.active = id;


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


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


             return conditions;
             return saved;
         },
         },


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


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


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


                    matches.forEach(name => {
            this.state.localDraftSavedAt = null;
                        name =
            this.state.localDraftAvailable = false;
                            name.toUpperCase();


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


             return variables;
        getMostRecentDraft() {
        },
             const storage = this.getDraftStorage();


        analyzePreload(content) {
            if (!storage.drafts || !Object.keys(storage.drafts).length) {
            return {
                return null;
                variables:
            }
                    this.findVariables(content),


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


                conditionVariables:
            let latestId = null;
                    this.findConditionVariables(
             let latestDraft = null;
                        content
                    )
             };
        },


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


        getAutomaticPageField() {
                if (
            return {
                    !latestDraft ||
                label: 'Page Name',
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                 description:
                 ) {
                     'Name of the page.',
                     latestId = id;
                type: 'page',
                    latestDraft = draft;
                 required: true,
                 }
                namespace: 'Main',
            });
                'allow-new': true
 
             };
             if (!latestDraft) {
        },
                return null;
            }


        emptyConfig() {
             return {
             return {
                 settings: {
                 id: latestId,
                    incomplete: 'add-stub'
                 draft: latestDraft
                },
 
                 fields: {
                    PAGE:
                        this.getAutomaticPageField()
                }
             };
             };
         },
         },


         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 !==
            const displayTitle = title || 'an untitled preload';
                    'object' ||
 
                 Array.isArray(config.settings)
            const savedAt = draft.savedAt
             ) {
                 ? new Date(draft.savedAt).toLocaleString()
                 config.settings = {};
                : '';
 
            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 !==
                 typeof draft.config === 'object' &&
                    'object' ||
                 !Array.isArray(draft.config)
                 Array.isArray(config.fields)
             ) {
             ) {
                 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 a special automatic field.
                typeof draft.dirtyPreload === 'boolean' ||
            */
                typeof draft.dirtyConfig === 'boolean';
             config.fields.PAGE =
 
                 this.getAutomaticPageField();
             this.state = {
                preloadTitle: title,
                 preloadSource: String(draft.preloadSource || ''),
                preloadContent: String(draft.preloadContent || ''),
                config,


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


        createDefaultField(
                conditions: Array.isArray(draft.conditions)
            name,
                     ? draft.conditions.slice()
            analysis
                    : [],
        ) {
            return {
                label:
                     this.humanizeName(name),


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


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


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


        /*
                dirty: hasDirtyFlags
        * Makes sure every variable currently used
                    ? !!(draft.dirtyPreload || draft.dirtyConfig)
        * by the preload has a configuration field.
                     : true,
        *
        * This is the important part for newly typed
        * variables such as %%ZHS%%.
        */
        prepareConfigForVariables(
            config,
            analysis
        ) {
            config =
                this.normalizeConfig(
                     config
                );


            const existing =
                dirtyPreload: hasDirtyFlags
                config.fields || {};
                    ? !!draft.dirtyPreload
                    : true,


            const fields = {};
                dirtyConfig: hasDirtyFlags
                    ? !!draft.dirtyConfig
                    : true,


            /*
                localDraftSavedAt: Number(draft.savedAt) || null,
            * PAGE is always automatic/precompiled.
                localDraftAvailable: true
            */
             };
             fields.PAGE =
                this.getAutomaticPageField();


             /*
             this.reanalyze();
            * Add every variable currently found
            this.renderEditor();
            * in the preload.
             this.updateLocalDraftIndicator();
            *
            * Existing configuration is preserved.
            * New variables receive a default field.
            */
             analysis.variables.forEach(
                name => {
                    if (name === 'PAGE') {
                        return;
                    }


                    const existingField =
            this.setStatus(
                        existing[name];
                'Restored unsaved local work from this browser.',
 
                 'warning'
                    fields[name] =
                        existingField ||
                        this.createDefaultField(
                            name,
                            analysis
                        );
                 }
             );
             );


             /*
             mw.notify('Unsaved Preload Editor work restored.', {
            * Preserve existing fields which are no
                 type: 'success'
            * longer used. These are shown as UNUSED
            });
            * rather than silently deleted.
            */
            Object.keys(existing).forEach(
                 name => {
                    const upper =
                        name.toUpperCase();


                    if (
             return true;
                        upper !== 'PAGE' &&
                        !fields[upper]
                    ) {
                        fields[upper] =
                            existing[name];
                    }
                }
            );
 
            config.fields = fields;
 
             return config;
         },
         },


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


             if (
        async getPage(title) {
                 !config ||
             const response = await new mw.Api().get({
                 typeof config !== 'object' ||
                 action: 'query',
                 Array.isArray(config)
                 prop: 'info|revisions',
            ) {
                 titles: title,
                 return {
                 rvprop: 'content',
                    valid: false,
                rvslots: 'main',
                    errors: [
                formatversion: 2
                        'Config must be an object.'
            });
                    ],
 
                    warnings: []
             const page =
                };
                response &&
             }
                response.query &&
                response.query.pages &&
                response.query.pages[0];


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


             const configured =
             const content =
                 Object.keys(
                 page.revisions &&
                    config.fields
                page.revisions[0] &&
                 ).map(
                 page.revisions[0].slots &&
                    name =>
                page.revisions[0].slots.main &&
                        name.toUpperCase()
                 page.revisions[0].slots.main.content;
                 );


             analysis.variables.forEach(
             return {
                 name => {
                title: page.title || title,
                    if (
                 content: typeof content === 'string' ? content : '',
                        !configured.includes(
                contentmodel: page.contentmodel || 'wikitext'
                            name
            };
                        )
        },
                    ) {
                        errors.push(
                            'Variable "' +
                            name +
                            '" is not configured.'
                        );
                    }
                }
            );


            configured.forEach(
        async pageExists(title) {
                name => {
            return !!await this.getPage(title);
                    if (
        },
                        !analysis.variables.includes(
                            name
                        )
                    ) {
                        warnings.push(
                            'Field "' +
                            name +
                            '" is not used by the preload.'
                        );
                    }
                }
            );


             if (
        async searchPages(query) {
                 !configured.includes(
             const response = await new mw.Api().get({
                    'PAGE'
                 action: 'query',
                 )
                list: 'search',
             ) {
                srsearch: query,
                 errors.push(
                 srlimit: 10,
                    'PAGE must always be configured.'
                srnamespace: 10,
                 );
                formatversion: 2
            });
 
             return (
                response &&
                response.query &&
                response.query.search
            ) || [];
        },
 
        /*
        * Save a page.
        *
        * contentModel is mainly used when creating a page.
        *
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
        async savePage(title, content, summary, createOnly, contentModel) {
            const params = {
                 action: 'edit',
                title,
                text: content,
                summary: summary || 'Updated with Preload Editor',
                 formatversion: 2
            };
 
            if (createOnly) {
                params.createonly = true;
             }
             }


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


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


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


                    if (
            if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                        (
                await this.changeContentModel(
                            field.type ===
                    title,
                                'select' ||
                    'json',
                            field.type ===
                    'Changed preload config content model to JSON'
                                'multiselect'
                );
                        ) &&
            }
                        !field.source &&
 
                        !Array.isArray(
            return this.savePage(
                            field.options
                 title,
                        )
                content,
                    ) {
                summary,
                        warnings.push(
                false
                            'Field "' +
                            name +
                            '" is a ' +
                            field.type +
                            ' without a source or manual options.'
                        );
                    }
                 }
             );
             );
            return {
                valid:
                    !errors.length,
                errors,
                warnings
            };
         },
         },


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


         transformationObject(
         /*
             transform,
        * Accept either:
             prefix,
        *
             suffix,
        *  Template:Example/Preload
             from,
        *
            to
        * or:
         ) {
        *
             if (!transform) {
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
             title = String(title || '').trim();
            title = title.replace(/\/+$/, '');
 
             if (/\/config\.json$/i.test(title)) {
                return title;
             }
 
             return title + '/config.json';
        },
 
         /*
        * Return a safe clone of a config field.
        *
        * This is deliberately JSON-based because config
        * definitions are JSON-compatible objects.
        */
        cloneConfigField(field) {
             try {
                return JSON.parse(JSON.stringify(field));
            } catch (error) {
                console.warn(
                    'Preload Editor: Could not clone imported field.',
                    error
                );
 
                 return null;
                 return null;
             }
             }
        },


            switch (transform) {
        /*
                 case 'remove-prefix':
        * Normalize imported field names to the same uppercase
                    return prefix
        * convention used throughout the editor.
                        ? {
        */
                            transform,
        getImportableFields(sourceConfig) {
                            prefix
            const fields = sourceConfig && sourceConfig.fields;
                        }
 
                        : null;
            if (
                 !fields ||
                typeof fields !== 'object' ||
                Array.isArray(fields)
            ) {
                return {};
            }


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


                case 'replace':
            Object.entries(fields).forEach(([name, field]) => {
                    return from === ''
                const upper = String(name || '').trim().toUpperCase();
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


                 default:
                 if (!upper || upper === 'PAGE') {
                     return null;
                     return;
            }
                }
        },


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


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


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


            $('<h2>')
                 result[upper] = clone;
                 .addClass(
            });
                    'preload-editor-section-title'
                )
                .text(title)
                .appendTo(section);


             return section;
             return result;
         },
         },


         createButton(
         /*
            label,
        * Show the variable-selection dialog after a source
            className,
        * config has been loaded.
            callback
        *
         ) {
        * Resolves:
             const button =
        *  null -> cancelled
                 $('<button>')
        *  []  -> confirmed with no selections
                     .attr(
        *  [...] -> selected field names
                         'type',
        */
                        'button'
         createImportDefinitionsDialog(sourceTitle, fields) {
                    )
             return new Promise(resolve => {
                const names = Object.keys(fields).sort((a, b) => a.localeCompare(b));
 
                 const overlay = $('<div>')
                     .addClass(
                         'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );
 
                const box = $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-button'
                         'preload-editor-prompt preload-editor-import-dialog'
                    );
 
                $('<h2>')
                    .text('Import variable definitions')
                    .appendTo(box);
 
                $('<p>')
                    .text(
                        'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                     )
                     )
                     .text(label);
                     .appendTo(box);
 
                if (!names.length) {
                    $('<div>')
                        .addClass(
                            'preload-editor-empty preload-editor-import-empty'
                        )
                        .text(
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);


            if (className) {
                    const emptyButtons = $('<div>')
                button.addClass(
                        .addClass('preload-editor-prompt-buttons');
                    className
                );
            }


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


            return button;
                    emptyButtons.append(close);
        },
                    box.append(emptyButtons);
                    overlay.append(box);


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


            $('<label>')
                    overlay.attr('tabindex', '-1');
                .addClass(
                    overlay.trigger('focus');
                    'preload-editor-label'
                )
                .text(label)
                .appendTo(row);


            if (description) {
                    return;
                 $('<div>')
                }
                     .addClass(
 
                        'preload-editor-help'
                const search = this.textInput('', 'Search variables...')
                    )
                    .addClass('preload-editor-import-search');
                     .text(description)
 
                    .appendTo(row);
                 const searchWrap = $('<div>')
            }
                     .addClass('preload-editor-import-search-wrap')
                     .append(search);
 
                box.append(searchWrap);


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


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


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


        select(
                const localFields =
            options,
                    this.state.config && this.state.config.fields
            value
                        ? this.state.config.fields
        ) {
                        : {};
            const select =
 
                 $('<select>')
                 names.forEach(name => {
                     .addClass(
                    const existing = !!localFields[name];
                         'preload-editor-select'
                    const field = fields[name];
                     );
 
                     const type = field && field.type
                        ? String(field.type)
                         : 'text';
 
                     const label = field && field.label
                        ? String(field.label)
                        : this.humanizeName(name);


            options.forEach(
                    const row = $('<label>')
                option => {
                        .addClass('preload-editor-import-row')
                    $('<option>')
                        .attr('data-variable', name)
                         .attr(
                         .attr(
                             'value',
                             'data-search',
                             option.value
                             (name + ' ' + label + ' ' + type).toLowerCase()
                         )
                         );
                        .text(
 
                            option.label
                    const checkbox = this.checkbox(false)
                        )
                         .attr('data-import-variable', name)
                         .prop(
                        .addClass('preload-editor-import-checkbox');
                            'selected',
 
                            String(
                    const content = $('<span>')
                                option.value
                         .addClass('preload-editor-import-content');
                            ) ===
                                String(
                                    value ===
                                        undefined
                                        ? ''
                                        : value
                                )
                        )
                         .appendTo(select);
                }
            );


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


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


        destroyEditor() {
                    $('<span>')
            if (!this.editor) {
                        .addClass('preload-editor-import-type')
                this.editorView = null;
                        .text(type)
                this.editorTools = null;
                        .appendTo(header);
                return;
            }


            const {
                    const meta = $('<span>')
                view,
                        .addClass('preload-editor-import-meta');
                inputHandler
            } = this.editor;


            if (
                    $('<span>')
                view &&
                        .text(label)
                inputHandler
                        .appendTo(meta);
            ) {
 
                view.dom.removeEventListener(
                    const status = $('<span>')
                    'input',
                        .addClass('preload-editor-import-status')
                     inputHandler
                        .toggleClass('is-existing', existing)
                );
                        .toggleClass('is-new', !existing)
            }
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');
 
                    content.append(header, meta, status);
                     row.append(checkbox, content);
                    list.append(row);
                });


            if (view) {
                 box.append(list);
                 view.destroy();
            }


            this.editor = null;
                const summary = $('<div>')
            this.editorView = null;
                    .addClass('preload-editor-import-summary');
            this.editorTools = null;
        },


        getEditorView() {
                const updateSummary = () => {
            return this.editorView;
                    const selected = list.find(
        },
                        'input[type="checkbox"]:checked'
                    ).length;


        getEditorContent() {
                    const existingSelected = list
            if (
                        .find('input[type="checkbox"]:checked')
                this.editorView &&
                        .filter(function () {
                this.editorView.state
                            const name = $(this).attr(
            ) {
                                'data-import-variable'
                return this.editorView.state.doc.toString();
                            );
            }


            return (
                            return !!localFields[name];
                this.state.preloadContent ||
                        }).length;
                ''
            );
        },


        setEditorContent(content) {
                    let text =
            content =
                        selected +
                String(content || '');
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';


            if (!this.editorView) {
                    if (existingSelected) {
                this.state.preloadContent =
                        text +=
                     content;
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                     }


                return;
                    summary.text(text);
            }


            const current =
                    importButton.prop('disabled', selected === 0);
                 this.editorView.state.doc.toString();
                 };


            if (current === content) {
                const filterRows = () => {
                return;
                    const query = String(search.val() || '')
            }
                        .trim()
                        .toLowerCase();


            this.editorView.dispatch({
                    list.find('.preload-editor-import-row').each(function () {
                changes: {
                        const row = $(this);
                    from: 0,
                        const haystack = String(
                    to:
                            row.attr('data-search') || ''
                         this.editorView.state
                         );
                            .doc.length,
 
                     insert: content
                        row.toggle(!query || haystack.includes(query));
                }
                     });
            });
                };
        },


        getEditorSelection() {
                 search.on(
            if (
                    'input.preloadEditor',
                 !this.editorView ||
                    filterRows
                !this.editorView.state
                 );
            ) {
                 return null;
            }


            const selection =
                 list.on(
                 this.editorView.state
                    'change.preloadEditor',
                     .selection.main;
                     'input[type="checkbox"]',
                    updateSummary
                );


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


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


        insertEditorText(
                const importButton = this.createButton(
            text,
                    'Import selected',
            selectionFrom,
                    'preload-editor-button-primary',
            selectionTo,
                    () => {
            cursorPosition
                        const selected = [];
        ) {
 
            if (!this.editorView) {
                        list
                return;
                            .find('input[type="checkbox"]:checked')
            }
                            .each(function () {
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });
 
                        overlay.remove();
                        resolve(selected);
                    }
                );


            const view =
                buttons.append(cancel, importButton);
                 this.editorView;
                box.append(summary, buttons);
                 overlay.append(box);


            const selection =
                 $(document.body).append(overlay);
                 view.state.selection.main;


            const from =
                overlay.attr('tabindex', '-1');
                 selectionFrom === undefined
                 overlay.trigger('focus');
                    ? selection.from
                    : selectionFrom;


            const to =
                updateSummary();
                 selectionTo === undefined
                 search.trigger('focus');
                    ? selection.to
                    : selectionTo;


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


            view.dispatch({
                overlay.on(
                changes: {
                     'keydown.preloadEditor',
                     from,
                     close
                    to,
                 );
                     insert: text
                 },


                 selection: {
                 overlay.on(
                     anchor: cursor
                    'click.preloadEditor',
                 }
                    event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                     }
                 );
             });
             });
            view.focus();
         },
         },


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


        wrapSelectionWithVariable() {
             if (!source) {
            const selected =
                this.getEditorSelection();
 
             if (
                !selected ||
                selected.from ===
                    selected.to
            ) {
                this.focusEditor();
                 return;
                 return;
             }
             }


             const replacement =
             const configTitle = this.normalizeConfigTitle(source);
                '%%' +
                selected.text +
                '%%';


             this.insertEditorText(
             this.setStatus(
                 replacement,
                 'Loading source config...',
                selected.from,
                 'loading'
                selected.to,
                 selected.from +
                    replacement.length
             );
             );
        },


        insertVariable(name) {
            try {
            name =
                const page = await this.getPage(configTitle);
                String(name || '')
                    .trim()
                    .toUpperCase();


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


            const selected =
                 let sourceConfig;
                 this.getEditorSelection();


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


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


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


        insertCondition(
                const fields = this.getImportableFields(sourceConfig);
            type,
            variable
        ) {
            type =
                String(type || '')
                    .toLowerCase();


            variable =
                const selected =
                String(variable || '')
                     await this.createImportDefinitionsDialog(
                     .trim()
                        configTitle,
                     .toUpperCase();
                        fields
                     );


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


            if (!selected) {
                    return;
                return;
                }
            }


            let text;
                if (!selected.length) {
            let cursorOffset;
                    this.setStatus(
                        'No variable definitions were imported.',
                        'warning'
                    );
 
                    return;
                }


            switch (type) {
                if (!this.state.config) {
                 case 'if': {
                    this.state.config = this.emptyConfig();
                     if (!variable) {
                }
 
                 if (!this.state.config.fields) {
                    this.state.config.fields = {};
                }
 
                const imported = [];
                const replaced = [];
 
                selected.forEach(name => {
                     if (name === 'PAGE') {
                         return;
                         return;
                     }
                     }


                     const opening =
                     const field = fields[name];
                        '<!-- @if ' +
                        variable +
                        ' -->';


                     const closing =
                     if (!field) {
                         '<!-- @endif -->';
                         return;
                    }


                     if (
                     if (this.state.config.fields[name]) {
                        selected.from !==
                         replaced.push(name);
                         selected.to
                     } else {
                     ) {
                         imported.push(name);
                         text =
                    }
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                        cursorOffset =
                    const clone = this.cloneConfigField(field);
                            text.length;
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;


                         cursorOffset =
                    if (!clone) {
                            opening.length + 1;
                         return;
                     }
                     }


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


                 case 'elseif':
                 this.reanalyze();
                    text =
                        '<!-- @elseif -->';
                    cursorOffset =
                        text.length;
                    break;


                 case 'else':
                 this.renderVariablesBySelector();
                    text =
                this.renderVariableConfigurationBySelector();
                        '<!-- @else -->';
                this.renderAnalysisBySelector();
                    cursorOffset =
                this.updateEditorTools();
                        text.length;
                    break;


                 case 'endif':
                 this.saveDraft();
                    text =
                        '<!-- @endif -->';
                    cursorOffset =
                        text.length;
                    break;


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


            this.insertEditorText(
                if (replaced.length) {
                text,
                    status +=
                selected.from,
                        ' Replaced: ' +
                selected.to,
                        replaced.join(', ') +
                selected.from +
                        '.';
                    cursorOffset
                }
            );
        },


        getToolVariables() {
                 this.setStatus(status, 'success');
            const variables =
                 new Set(['PAGE']);


             if (
                mw.notify(status, {
                 this.analysis &&
                    type: 'success'
                 this.analysis.variables
                });
            ) {
             } catch (error) {
                 this.analysis.variables.forEach(
                 console.error(
                     name => {
                    'Preload Editor variable import:',
                         variables.add(
                    error
                            String(
                 );
                                name
 
                            ).toUpperCase()
                 this.setStatus(
                         );
                     error.message ||
                         'Could not import variable definitions.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not import variable definitions.',
                    {
                         type: 'error'
                     }
                     }
                 );
                 );
             }
             }
        },


             return Array.from(
        // =========================================================
                 variables
        // Preload parsing
        // =========================================================
 
        extractIncludeonly(source) {
             const match = String(source || '').match(
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
             );
             );
            return match
                ? match[1].trim()
                : String(source || '').trim();
         },
         },


         createToolSelect(
         findVariables(content) {
            options,
             const variables = [];
            className
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
        ) {
 
             const select =
            let match;
                $('<select>')
                    .addClass(
                        'preload-editor-tool-select'
                    );


             if (className) {
             while ((match = pattern.exec(content)) !== null) {
                 select.addClass(
                 const name = match[1].toUpperCase();
                    className
                );
            }


            options.forEach(
                 if (!variables.includes(name)) {
                 option => {
                    variables.push(name);
                    $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                        .text(
                            option.label
                        )
                        .appendTo(select);
                 }
                 }
             );
             }


             return select;
             return variables;
         },
         },


         updateEditorToolVariables() {
         findConditions(content) {
             if (!this.editorTools) {
             const conditions = [];
                 return;
            const pattern =
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
 
            let match;
 
            while ((match = pattern.exec(content)) !== null) {
                conditions.push({
                    type: match[1].toLowerCase(),
                    expression: match[2].trim(),
                    index: match.index
                 });
             }
             }


             const variables =
             return conditions;
                this.getToolVariables();
        },


             const current =
        findConditionVariables(content) {
                this.editorTools
             const variables = [];
                    .variableSelect
                    .val();


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


            const populate =
                const matches =
                (
                    condition.expression.match(
                    select,
                        /[A-Za-z0-9_-]+/g
                    value
                     ) || [];
                ) => {
                     select.empty();


                    variables.forEach(
                matches.forEach(name => {
                        name => {
                    name = name.toUpperCase();
                            $('<option>')
                                .attr(
                                    'value',
                                    name
                                )
                                .text(name)
                                .appendTo(
                                    select
                                );
                        }
                    );


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


             populate(
             return variables;
                this.editorTools
        },
                    .variableSelect,
                current
            );


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


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


            const type =
        getAutomaticPageField() {
                this.editorTools
             return {
                    .conditionTypeSelect
                 label: 'Page Name',
                    .val();
                 description: 'Name of the page.',
 
                type: 'page',
             this.editorTools
                required: true,
                 .conditionVariableWrap
                namespace: 'Main',
                 .toggle(
                 'allow-new': true
                    type === 'if'
            };
                 );
         },
         },


         renderEditorTools() {
         emptyConfig() {
             const tools =
             return {
                 $('<div>')
                 settings: {
                     .addClass(
                     incomplete: 'add-stub'
                        'preload-editor-tools'
                },
                    );


            const wrapGroup =
                 fields: {
                 $('<div>')
                     PAGE: this.getAutomaticPageField()
                     .addClass(
                }
                        'preload-editor-tool-group ' +
            };
                        'preload-editor-tool-group-wrap'
        },
                    );


             wrapGroup.append(
        normalizeConfig(config) {
                 this.createButton(
             if (
                    'Wrap selection with %%',
                 !config ||
                    'preload-editor-tool-button',
                typeof config !== 'object' ||
                    () =>
                Array.isArray(config)
                        this.wrapSelectionWithVariable()
            ) {
                 )
                config = this.emptyConfig();
             );
            }
 
            if (
                !config.settings ||
                 typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
             ) {
                config.settings = {};
            }


             const variableGroup =
             if (
                 $('<div>')
                !config.fields ||
                    .addClass(
                 typeof config.fields !== 'object' ||
                        'preload-editor-tool-group ' +
                Array.isArray(config.fields)
                        'preload-editor-tool-group-variable'
            ) {
                    );
                config.fields = {};
            }


             $('<span>')
             config.fields.PAGE =
                .addClass(
                 this.getAutomaticPageField();
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                 .appendTo(
                    variableGroup
                );


             const variableSelect =
             return config;
                 this.createToolSelect(
        },
                     [],
 
                    'preload-editor-variable-select'
        createDefaultField(name, analysis) {
                 );
            return {
                 label: this.humanizeName(name),
                description: '',
                type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                     : 'text'
            };
        },
 
        humanizeName(name) {
            return String(name || '')
                .replace(/[_-]+/g, ' ')
                .replace(/([a-z])([A-Z])/g, '$1 $2')
                .replace(/\s+/g, ' ')
                .trim()
                 .replace(/\b\w/g, char => char.toUpperCase());
        },
 
        prepareConfigForVariables(config, analysis) {
            config = this.normalizeConfig(config);


             variableGroup.append(
             const existing = config.fields || {};
                variableSelect,


                 this.createButton(
            const deleted = new Set(
                     'Insert',
                 Array.isArray(this.state.deletedVariables)
                    'preload-editor-tool-button',
                     ? this.state.deletedVariables.map(
                    () =>
                        name => String(name).toUpperCase()
                        this.insertVariable(
                    )
                            variableSelect.val()
                    : []
                        )
                )
             );
             );


             const conditionGroup =
             const fields = {};
                 $('<div>')
 
                     .addClass(
            fields.PAGE =
                         'preload-editor-tool-group ' +
                this.getAutomaticPageField();
                         'preload-editor-tool-group-condition'
 
            analysis.variables.forEach(name => {
                 if (
                    name === 'PAGE' ||
                    deleted.has(name)
                ) {
                     return;
                }
 
                fields[name] =
                    existing[name] ||
                    this.createDefaultField(
                         name,
                         analysis
                     );
                     );
            });


             $('<span>')
             Object.keys(existing).forEach(name => {
                 .addClass(
                 const upper = name.toUpperCase();
                    'preload-editor-tool-label'
 
                )
                 if (
                 .text(
                     upper !== 'PAGE' &&
                     'Insert condition'
                    !fields[upper] &&
                )
                    !deleted.has(upper)
                 .appendTo(
                 ) {
                     conditionGroup
                     fields[upper] =
                 );
                        existing[name];
                 }
            });


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


             const conditionVariableSelect =
             return config;
                this.createToolSelect(
        },
                    [],
                    'preload-editor-condition-variable-select'
                );


             const conditionVariableWrap =
        validateConfig(config, analysis) {
                $('<span>')
             const errors = [];
                    .addClass(
            const warnings = [];
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


             const insertCondition =
             if (
                 this.createButton(
                !config ||
                    'Insert',
                typeof config !== 'object' ||
                     'preload-editor-tool-button',
                 Array.isArray(config)
                     () =>
            ) {
                         this.insertCondition(
                return {
                            conditionTypeSelect.val(),
                     valid: false,
                            conditionVariableSelect.val()
                     errors: [
                        )
                         'Config must be an object.'
                 );
                    ],
                    warnings: []
                 };
            }


             conditionTypeSelect.on(
             if (
                 'change.preloadEditor',
                 !config.fields ||
                 () =>
                 typeof config.fields !== 'object' ||
                    this.updateConditionVariableVisibility()
                Array.isArray(config.fields)
             );
             ) {
 
                return {
            conditionGroup.append(
                    valid: false,
                conditionTypeSelect,
                    errors: [
                conditionVariableWrap,
                        '"fields" must be an object.'
                 insertCondition
                    ],
             );
                    warnings
                 };
             }


             tools.append(
             const configured =
                 wrapGroup,
                Object.keys(
                variableGroup,
                    config.fields
                 conditionGroup
                 ).map(
            );
                    name =>
                        name.toUpperCase()
                 );


             this.editorTools = {
             analysis.variables.forEach(name => {
                 root: tools,
                 if (!configured.includes(name)) {
                variableSelect,
                    errors.push(
                conditionTypeSelect,
                        'Variable "' +
                conditionVariableSelect,
                        name +
                conditionVariableWrap,
                        '" is not configured.'
                 insertCondition
                    );
             };
                 }
             });


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


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


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


        // =========================================================
                    return;
        // Preload syntax highlighting
                }
        // =========================================================


        getKnownVariables() {
                if (!field.type) {
            const known =
                    warnings.push(
                new Set(['PAGE']);
                        'Field "' +
 
                        name +
            const fields =
                        '" has no type.'
                 this.state.config &&
                    );
                 this.state.config.fields;
                }
 
                  
            if (
                 if (
                fields &&
                    field.type === 'file'
                typeof fields ===
                ) {
                    'object'
                    if (
            ) {
                        field.accept !== undefined &&
                Object.keys(fields).forEach(
                        !Array.isArray(field.accept)
                     name => {
                     ) {
                         known.add(
                         errors.push(
                             String(
                             'File field "' +
                                name
                            name +
                             ).toUpperCase()
                             '" must have "accept" as an array.'
                         );
                         );
                     }
                     }
                );
            }


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


        createSyntaxDecorations(
                    if (
            state,
                        field.filename !== undefined &&
            Decoration
                        typeof field.filename !== 'string'
        ) {
                    ) {
            const decorations = [];
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                        );
                    }


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


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


            const variablePattern =
                    if (
                /%%([A-Za-z0-9_-]+)%%/g;
                        !field.filename
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


            let match;
                 if (
 
                     (
            while (
                         field.type === 'select' ||
                 (match =
                        field.type === 'multiselect'
                     variablePattern.exec(
                    ) &&
                         source
                    !field.source &&
                    )) !== null
                     !Array.isArray(field.options)
            ) {
                 ) {
                const name =
                     warnings.push(
                     match[1].toUpperCase();
                        'Field "' +
 
                         name +
                 const known =
                        '" is a ' +
                     knownVariables.has(
                        field.type +
                         name
                        ' without a source or manual options.'
                     );
                     );
                }


                 decorations.push(
                 if (field.type === 'file') {
                     Decoration.mark({
                     if (
                         class: [
                         field.filename !== undefined &&
                            'preload-editor-syntax-variable',
                         typeof field.filename !== 'string'
                            known
                     ) {
                                ? 'preload-editor-syntax-variable-known'
                        errors.push(
                                : 'preload-editor-syntax-variable-unknown'
                            'File field "' +
                         ].join(' ')
                            name +
                     }).range(
                             '" has an invalid "filename" value.'
                        match.index,
                        );
                        match.index +
                    }
                             match[0].length
                    )
                );
            }


            const conditionPattern =
                    if (
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                        field.filetext !== undefined &&
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }


            while (
                     if (
                (match =
                         field.accept !== undefined &&
                     conditionPattern.exec(
                        (
                         source
                            !Array.isArray(field.accept) ||
                    )) !== null
                            field.accept.some(
            ) {
                                value =>
                decorations.push(
                                    typeof value !== 'string' ||
                    Decoration.mark({
                                    !value.trim()
                        class:
                            )
                            'preload-editor-syntax-condition'
                         )
                    }).range(
                    ) {
                         match.index,
                         errors.push(
                         match.index +
                            'File field "' +
                             match[0].length
                             name +
                     )
                            '" must have "accept" as an array of MIME types.'
                 );
                        );
                     }
                 }
            });


                 const directiveStart =
            return {
                    match.index +
                valid: !errors.length,
                    match[0].indexOf('@');
                 errors,
                warnings
            };
        },


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


                const type =
        transformationObject(
                    match[1].toLowerCase();
            transform,
            prefix,
            suffix,
            from,
            to
        ) {
            if (!transform) {
                return null;
            }


                if (
            switch (transform) {
                    type !== 'if' &&
                case 'remove-prefix':
                     type !== 'elseif'
                     return prefix
                ) {
                        ? {
                    continue;
                            transform,
                }
                            prefix
                        }
                        : null;


                 const expression =
                 case 'remove-suffix':
                     match[2];
                     return suffix
                        ? {
                            transform,
                            suffix
                        }
                        : null;


                 const expressionStart =
                 case 'replace':
                     match.index +
                     return from === ''
                    match[0].indexOf(
                        ? null
                         expression
                         : {
                    );
                            transform,
                            from,
                            to: to || ''
                        };


                 const expressionPattern =
                 default:
                     /[A-Za-z0-9_-]+/g;
                     return null;
            }
        },


                let expressionMatch;
        // =========================================================
        // UI helpers
        // =========================================================


                while (
        createSection(title, className) {
                    (
            const section = $('<section>')
                        expressionMatch =
                 .addClass('preload-editor-section');
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


                    if (
            if (className) {
                        !knownVariables.has(
                section.addClass(className);
                            name
            }
                        )
                    ) {
                        continue;
                    }


                    const start =
            $('<h2>')
                        expressionStart +
                .addClass('preload-editor-section-title')
                        expressionMatch.index;
                .text(title)
                .appendTo(section);


                    decorations.push(
            return section;
                        Decoration.mark({
        },
                            class:
 
                                'preload-editor-syntax-condition-variable'
        createButton(label, className, callback) {
                        }).range(
            const button = $('<button>')
                            start,
                .attr('type', 'button')
                            start +
                .addClass('preload-editor-button')
                                expressionMatch[0]
                .text(label);
                                    .length
 
                        )
            if (className) {
                     );
                button.addClass(className);
                }
            }
 
            if (callback) {
                button.on(
                    'click.preloadEditor',
                     callback
                );
             }
             }


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


         async installSyntaxHighlighting(
         fieldRow(label, input, description) {
             view
             const row = $('<div>')
        ) {
                .addClass('preload-editor-field');
             await mw.loader.using(
 
                 'ext.CodeMirror.v6.lib'
             $('<label>')
            );
                .addClass('preload-editor-label')
                .text(label)
                 .appendTo(row);


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


             const {
             row.append(input);
                StateField,
                StateEffect,
                EditorView,
                Decoration
            } = require(
                'ext.CodeMirror.v6.lib'
            );


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


                    update: (
        textInput(value, placeholder) {
                        decorations,
            return $('<input>')
                        transaction
                .attr({
                    ) =>
                    type: 'text',
                        transaction.docChanged
                    value: value == null ? '' : value,
                            ? this.createSyntaxDecorations(
                    placeholder: placeholder || ''
                                transaction.state,
                })
                                Decoration
                .addClass('preload-editor-input');
                            )
        },
                            : decorations,


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


             view.dispatch({
        checkbox(checked) {
                 effects:
            return $('<input>')
                     StateEffect.appendConfig.of(
                .attr('type', 'checkbox')
                         syntaxField
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },
 
        select(options, value) {
            const select = $('<select>')
                .addClass('preload-editor-select');
 
             options.forEach(option => {
                 $('<option>')
                     .attr('value', option.value)
                    .text(option.label)
                    .prop(
                        'selected',
                        String(option.value) ===
                         String(value === undefined ? '' : value)
                     )
                     )
                    .appendTo(select);
             });
             });


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


         // =========================================================
         // =========================================================
         // Editor state synchronization
         // In-wiki dialogs
         // =========================================================
         // =========================================================


         /*
         createConfirmDialog(
        * Re-analyze the current CodeMirror content,
            title,
        * create configuration fields for newly found
            message,
        * variables, keep selection valid, and update
            confirmLabel,
        * all live UI.
            cancelLabel
        */
         ) {
         syncEditorState() {
             return new Promise(resolve => {
             this.reanalyze();
                const overlay = $('<div>')
                    .addClass('preload-editor-prompt-overlay');


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


            this.renderVariableConfigurationBySelector();
                $('<h2>')
                    .text(title)
                    .appendTo(box);


            this.renderAnalysisBySelector();
                const messageLines =
                    String(message || '').split('\n');


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


            this.updateEditorTools();
                        return;
        },
                    }


        // =========================================================
                    $('<p>')
        // CodeMirror mounting
                        .text(line)
        // =========================================================
                        .appendTo(box);
                });


        async mountCodeMirror(
                const buttons = $('<div>')
            textarea
                    .addClass(
        ) {
                        'preload-editor-prompt-buttons'
            return new Promise(
                     );
                (resolve, reject) => {
                     let settled = false;


                    const cleanup =
                const cancel = this.createButton(
                        () => {
                    cancelLabel || 'Cancel',
                            mw.hook(
                    '',
                                'dev.CCM.ready'
                    () => {
                            ).remove(
                        overlay.remove();
                                onReady
                        resolve(false);
                            );
                    }
                );


                            mw.hook(
                const confirm = this.createButton(
                                'dev.CCM.load'
                    confirmLabel || 'Confirm',
                            ).remove(
                    'preload-editor-button-primary',
                                onLoad
                    () => {
                            );
                        overlay.remove();
                        };
                        resolve(true);
                    }
                );


                    const onReady =
                buttons.append(cancel, confirm);
                        async cm => {
                box.append(buttons);
                            if (
                overlay.append(box);
                                settled ||
 
                                !cm ||
                $(document.body).append(overlay);
                                cm.textarea !==
 
                                    textarea ||
                const close = value => {
                                !cm.view
                    if (value === 'Escape') {
                            ) {
                        cancel.trigger('click');
                                return;
                    }
                            }
                };


                            settled = true;
                overlay.on(
                            cleanup();
                    'keydown.preloadEditor',
                    event => {
                        close(event.key);
                    }
                );


                            const view =
                overlay.attr('tabindex', '-1');
                                cm.view;
                overlay.trigger('focus');


                            const inputHandler =
                overlay.on(
                                () => {
                    'click.preloadEditor',
                                    this.state
                    event => {
                                        .preloadContent =
                        if (event.target === overlay.get(0)) {
                                        view.state.doc.toString();
                            cancel.trigger('click');
                        }
                    }
                );
            });
        },


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


                                    /*
                const box = $('<div>')
                                    * This now performs the
                    .addClass(
                                    * entire live synchronization.
                        'preload-editor-prompt'
                                    *
                    );
                                    * So typing %%ZHS%% will:
                                    *
                                    * - detect ZHS
                                    * - create config.fields.ZHS
                                    * - add ZHS to the variable list
                                    * - make ZHS selectable
                                    * - update its configuration
                                    * - update config preview
                                    * - update editor tools
                                    */
                                    this.syncEditorState();
                                };


                            view.dom.addEventListener(
                $('<h2>')
                                'input',
                    .text(title)
                                inputHandler
                    .appendTo(box);
                            );


                            view.dom.classList.add(
                $('<p>')
                                'preload-editor-codemirror'
                    .text(message)
                            );
                    .appendTo(box);


                            const wrapper =
                const input = this.textInput();
                                view.dom.closest(
 
                                    '.ext-codemirror-wrapper'
                const buttons = $('<div>')
                                );
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


                            if (wrapper) {
                const cancel = this.createButton(
                                wrapper.classList.add(
                    'Cancel',
                                    'preload-editor-codemirror-wrapper'
                    '',
                                );
                    () => {
                            }
                        overlay.remove();
                        resolve(null);
                    }
                );


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


                             this.editorView =
                        if (!value) {
                                view;
                             return;
                        }


                            this.state
                        overlay.remove();
                                .preloadContent =
                        resolve(value);
                                view.state.doc.toString();
                    }
                );


                            try {
                buttons.append(cancel, confirm);
                                await this.installSyntaxHighlighting(
                                    view
                                );


                                /*
                box.append(
                                * Run one initial synchronization
                    input,
                                * after CodeMirror is mounted so the
                    buttons
                                * UI is based on the actual document.
                );
                                */
                                this.syncEditorState();


                                resolve(
                overlay.append(box);
                                    view
                                );
                            } catch (
                                error
                            ) {
                                reject(
                                    error
                                );
                            }
                        };


                     const onLoad =
                $(document.body).append(overlay);
                        loader => {
 
                            if (
                input.trigger('focus');
                                settled ||
 
                                typeof loader !==
                input.on(
                                    'function'
                     'keydown.preloadEditor',
                             ) {
                    event => {
                                return;
                        if (event.key === 'Enter') {
                            }
                             confirm.trigger('click');
                        }


                            try {
                        if (event.key === 'Escape') {
                                loader(
                            cancel.trigger('click');
                                    textarea
                        }
                                );
                    }
                            } catch (
                );
                                error
            });
                            ) {
        },
                                settled = true;
                                cleanup();
                                reject(
                                    error
                                );
                            }
                        };


                    mw.hook(
        createConfigReviewDialog() {
                        'dev.CCM.ready'
            return new Promise(resolve => {
                     ).add(
                const overlay = $('<div>')
                         onReady
                     .addClass(
                         'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                     );
                     );


                    mw.hook(
                const box = $('<div>')
                        'dev.CCM.load'
                     .addClass(
                     ).add(
                         'preload-editor-prompt preload-editor-code-review'
                         onLoad
                     );
                     );
                }
            );
        },


        // =========================================================
                $('<h2>')
        // Main UI
                    .text('Review config.json')
        // =========================================================
                    .appendTo(box);


        init() {
                $('<p>')
            const root =
                    .text(
                $('#mw-content-text');
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);


            if (!root.length) {
                const code = $('<pre>')
                return;
                    .addClass(
            }
                        'preload-editor-config-review'
                    )
                    .text(this.getConfigJSON());


            this.root =
                const codeWrap = $('<div>')
                $('<div>')
                     .addClass(
                     .attr(
                         'preload-editor-config-review-wrap'
                        'id',
                         'preload-editor'
                     )
                     )
                    .append(code);
                box.append(codeWrap);
                const buttons = $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor'
                         'preload-editor-prompt-buttons'
                     );
                     );


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


            this.renderShell();
                buttons.append(close);
        },
                box.append(buttons);
                overlay.append(box);


        renderShell() {
                $(document.body).append(overlay);
            this.destroyEditor();


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


            const loader =
                 overlay.on(
                 this.createSection(
                     'keydown.preloadEditor',
                     'Preload'
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                 );
                 );


            const titleInput =
                 overlay.on(
                 this.textInput(
                     'click.preloadEditor',
                     this.state.preloadTitle,
                     event => {
                     'Template:Example/Preload'
                        if (event.target === overlay.get(0)) {
                ).attr(
                            close.trigger('click');
                    'id',
                        }
                     'preload-editor-title-input'
                     }
                 );
                 );
            });
        },


             const loadButton =
        async confirmSave(mode, title) {
                 this.createButton(
             const configTitle =
                    'Load',
                 title.replace(/\/+$/, '') +
                     'preload-editor-button-primary',
                '/config.json';
                    () =>
 
                        this.loadExisting(
            let saveDescription;
                            titleInput.val()
 
                        )
            if (mode === 'preload') {
                saveDescription =
                     'Save the preload page only?';
            } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
            } else {
                saveDescription =
                    'Save both the preload and config.json?';
            }
 
            const pages = [];
 
            if (mode === 'preload' || mode === 'both') {
                pages.push(
                    'Preload: ' +
                    title
                 );
                 );
            }


             const newButton =
             if (mode === 'config' || mode === 'both') {
                 this.createButton(
                 pages.push(
                     'New',
                     'Config: ' +
                    '',
                     configTitle
                     () =>
                        this.startNew()
                 );
                 );


            const sampleButton =
                 pages.push(
                 this.createButton(
                     'Config content model: JSON'
                     'Load Sample Page',
                    '',
                    () =>
                        this.loadSamplePage()
                 );
                 );
            }


             loader.append(
             const message =
                 $('<div>')
                saveDescription +
                    .addClass(
                 '\n\n' +
                        'preload-editor-toolbar'
                pages.join('\n') +
                    )
                '\n\nThis will write the changes to the wiki.';
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );


             this.root.append(
             return this.createConfirmDialog(
                 loader
                 'Confirm save',
                message,
                'Save',
                'Cancel'
             );
             );
        },


            this.status =
        // =========================================================
                 $('<div>')
        // CodeMirror
                    .addClass(
        // =========================================================
                        'preload-editor-status'
                 destroyEditor() {
                    );
            if (!this.editor) {
                this.editorView = null;
                this.editorTools = null;
                return;
            }


             this.root.append(
             const {
                 this.status
                view,
            );
                 inputHandler
            } = this.editor;


             this.workspace =
             if (view && inputHandler) {
                $('<div>')
                view.dom.removeEventListener(
                    .addClass(
                    'input',
                        'preload-editor-workspace'
                     inputHandler
                     );
                );
            }


             this.root.append(
             if (view) {
                 this.workspace
                 view.destroy();
             );
             }


             this.renderWelcome();
             this.editor = null;
            this.editorView = null;
            this.editorTools = null;
         },
         },


         renderWelcome() {
         getEditorView() {
             this.workspace.empty();
             return this.editorView;
        },


             const section =
        getEditorContent() {
                 this.createSection(
             if (
                    'Get started'
                this.editorView &&
                 );
                 this.editorView.state
            ) {
                 return this.editorView.state.doc.toString();
            }


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


            const tips =
        setEditorContent(content) {
                $('<ul>')
            content = String(content || '');
                    .addClass(
                        'preload-editor-tips'
                    );


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


             section.append(
             const current =
                tips
                this.editorView.state.doc.toString();
            );


             this.workspace.append(
             if (current === content) {
                 section
                 return;
             );
             }
        },


        setStatus(
            this.editorView.dispatch({
             message,
                changes: {
            type
                    from: 0,
         ) {
                    to: this.editorView.state.doc.length,
             if (!this.status) {
                    insert: content
                 return;
                }
             });
        },
 
         getEditorSelection() {
             if (
                !this.editorView ||
                !this.editorView.state
            ) {
                 return null;
             }
             }


             this.status.removeClass(
             const selection =
                'is-error',
                this.editorView.state.selection.main;
                'is-success',
                'is-warning',
                'is-loading'
            );


             if (type) {
             return {
                 this.status.addClass(
                 from: selection.from,
                     'is-' + type
                to: selection.to,
                 );
                text: this.editorView.state.doc.sliceString(
             }
                     selection.from,
 
                    selection.to
            this.status.text(
                 )
                message || ''
             };
            );
         },
         },


         // =========================================================
         focusEditor() {
        // Load / create
            if (this.editorView) {
         // =========================================================
                this.editorView.focus();
            }
         },


         async loadExisting(
         insertEditorText(
             title
             text,
            selectionFrom,
            selectionTo,
            cursorPosition
         ) {
         ) {
            title =
             if (!this.editorView) {
                String(title || '')
                    .trim();
 
             if (!title) {
                mw.notify(
                    'Enter a preload page title first.',
                    {
                        type: 'warn'
                    }
                );
 
                 return;
                 return;
             }
             }


             this.setStatus(
             const view = this.editorView;
                'Loading preload...',
            const selection = view.state.selection.main;
                'loading'
            );


             try {
             const from =
                 const page =
                 selectionFrom === undefined
                     await this.getPage(
                     ? selection.from
                        title
                     : selectionFrom;
                     );


                 if (!page) {
            const to =
                     const suggestions =
                 selectionTo === undefined
                        await this.findSimilarPreloads(
                     ? selection.to
                            title
                    : selectionTo;
                        );


                     this.renderMissingPage(
            const cursor =
                        title,
                cursorPosition === undefined
                        suggestions
                     ? from + text.length
                     );
                     : cursorPosition;


                    this.setStatus(
            view.dispatch({
                        'Preload not found.',
                changes: {
                        'warning'
                    from,
                     );
                    to,
 
                     insert: text
                     return;
                },
                selection: {
                     anchor: cursor
                 }
                 }
            });


                await this.loadDefinition(
            view.focus();
                    page.title,
        },
                    page.content
                );


                this.setStatus(
        // =========================================================
                    'Preload loaded.',
        // Editor tools
                    'success'
        // =========================================================
                );
            } catch (
                error
            ) {
                console.error(
                    'Preload Editor:',
                    error
                );


                 this.setStatus(
        wrapSelectionWithVariable() {
                    error.message ||
            const selected =
                        'Could not load preload.',
                 this.getEditorSelection();
                    'error'
 
                 );
            if (
                !selected ||
                selected.from === selected.to
            ) {
                 this.focusEditor();
                return;
             }
             }
            const replacement =
                '%%' +
                selected.text +
                '%%';
            this.insertEditorText(
                replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
            );
         },
         },


         async findSimilarPreloads(
         insertVariable(name) {
            title
             name = String(name || '')
        ) {
                 .trim()
             let query =
                .toUpperCase();
                 title
                    .replace(
                        /\/Preload$/i,
                        ''
                    )
                    .trim();


             if (!query) {
             if (!name) {
                 query = title;
                 return;
             }
             }


             try {
             const selected =
                const results =
                this.getEditorSelection();
                    await this.searchPages(
                        query
                    );


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


                 return [];
            this.insertEditorText(
             }
                '%%' + name + '%%',
                selected.from,
                 selected.to
             );
         },
         },


         renderMissingPage(
         insertCondition(
             title,
             type,
             suggestions
             variable
         ) {
         ) {
             this.workspace.empty();
             type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();
 
            const selected =
                this.getEditorSelection();


             const section =
             if (!selected) {
                this.createSection(
                 return;
                    'Preload not found'
            }
                 );


             $('<p>')
             let text;
                .text(
            let cursorOffset;
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(
                    section
                );


             if (
             switch (type) {
                suggestions.length
                 case 'if': {
            ) {
                     if (!variable) {
                 $('<h3>')
                         return;
                     .text(
                     }
                        'Similar preloads'
                    )
                    .appendTo(
                         section
                     );


                const list =
                    const opening =
                    $('<div>')
                        '<!-- @if ' +
                         .addClass(
                         variable +
                            'preload-editor-suggestions'
                        ' -->';
                        );


                suggestions.forEach(
                     const closing =
                     result => {
                         '<!-- @endif -->';
                         list.append(
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                        );
                    }
                );


                section.append(
                    if (
                     list
                        selected.from !==
                );
                        selected.to
            }
                     ) {
 
                        text =
            section.append(
                            opening +
                this.createButton(
                            '\n' +
                    'Create this preload',
                            selected.text +
                    'preload-editor-button-primary',
                            '\n' +
                    () =>
                            closing;
                         this.startNew(
 
                            title
                         cursorOffset = text.length;
                         )
                    } else {
                )
                         text =
            );
                            opening +
                            '\n\n' +
                            closing;


            this.workspace.append(
                        cursorOffset =
                section
                            opening.length + 1;
            );
                    }
        },


        async startNew(
                    break;
            title
                 }
        ) {
            title =
                 String(title || '')
                    .trim();


            this.state = {
                 case 'elseif':
                 preloadTitle: title,
                     text =
                preloadSource: '',
                        '<!-- @elseif -->';
                preloadContent:
                     this.defaults.preload,
                config:
                    this.emptyConfig(),
                variables: ['PAGE'],
                conditions: [],
                selectedVariable:
                    'PAGE',
                mode: 'new',
                dirty: true
            };


            this.renderEditor();
                    cursorOffset =
                        text.length;


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


        async loadSamplePage() {
                 case 'else':
            const result =
                     text =
                 await this.createPromptDialog(
                        '<!-- @else -->';
                    'Load Sample Page',
                     'Enter the title of a normal wiki page to use as the starting point.'
                );


            if (!result) {
                    cursorOffset =
                return;
                        text.length;
            }


            this.setStatus(
                    break;
                'Loading sample page...',
                'loading'
            );


            try {
                 case 'endif':
                 const page =
                     text =
                     await this.getPage(
                         '<!-- @endif -->';
                         result
 
                     );
                     cursorOffset =
                        text.length;


                if (!page) {
                     break;
                     throw new Error(
                        'Sample page not found: ' +
                        result
                    );
                }


                 const sample =
                 default:
                     this.convertSampleToPreload(
                     return;
                        page.content
            }
                    );


                this.state = {
            this.insertEditorText(
                    preloadTitle: '',
                text,
                    preloadSource: '',
                selected.from,
                    preloadContent:
                selected.to,
                        sample,
                selected.from + cursorOffset
                    config:
            );
                        this.emptyConfig(),
        },
                    variables: ['PAGE'],
                    conditions: [],
                    selectedVariable:
                        'PAGE',
                    mode: 'new',
                    dirty: true
                };


                this.reanalyze();
        getToolVariables() {
                 this.renderEditor();
            const variables =
                 new Set(['PAGE']);


                 this.setStatus(
            if (
                    'Sample page loaded.',
                 this.analysis &&
                    'success'
                this.analysis.variables
                );
            } catch (
                error
             ) {
             ) {
                 console.error(
                 this.analysis.variables.forEach(
                     'Preload Editor sample:',
                     name => {
                     error
                        variables.add(
                            String(name).toUpperCase()
                        );
                     }
                 );
                 );
            }


                this.setStatus(
            return Array.from(variables);
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
         },
         },


         convertSampleToPreload(
         createToolSelect(
             source
             options,
            className
         ) {
         ) {
             let content =
             const select =
                 String(source || '')
                 $('<select>')
                     .trim();
                     .addClass(
                        'preload-editor-tool-select'
                    );


            const include =
             if (className) {
                content.match(
                 select.addClass(className);
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                );
 
             if (include) {
                 content =
                    include[1].trim();
             }
             }


             content =
             options.forEach(
                 content
                 option => {
                     .replace(
                     $('<option>')
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                         .attr(
                         ''
                            'value',
                    )
                            option.value
                    .trim();
                        )
                        .text(option.label)
                        .appendTo(select);
                }
            );


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


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


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


                     $('<h2>')
            const current =
                        .text(title)
                this.editorTools
                        .appendTo(
                     .variableSelect
                            box
                    .val();
                        );


                     $('<p>')
            const currentCondition =
                        .text(message)
                this.editorTools
                        .appendTo(
                     .conditionVariableSelect
                            box
                    .val();
                        );


                    const input =
            const populate = (
                        this.textInput();
                select,
                value
            ) => {
                select.empty();


                     const buttons =
                variables.forEach(
                         $('<div>')
                     name => {
                             .addClass(
                         $('<option>')
                                 'preload-editor-prompt-buttons'
                             .attr(
                             );
                                 'value',
                                name
                            )
                            .text(name)
                             .appendTo(select);
                    }
                );


                     const cancel =
                if (
                        this.createButton(
                     value &&
                            'Cancel',
                    variables.includes(value)
                            '',
                ) {
                            () => {
                    select.val(value);
                                overlay.remove();
                } else if (
                                resolve(
                    variables.length
                                    null
                ) {
                                );
                    select.val(
                            }
                        variables[0]
                        );
                    );
                }
            };


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


                                if (!value) {
            populate(
                                    return;
                this.editorTools.conditionVariableSelect,
                                }
                currentCondition
            );
        },


                                overlay.remove();
        updateConditionVariableVisibility() {
                                resolve(
            if (!this.editorTools) {
                                    value
                return;
                                );
            }
                            }
                        );


                     buttons.append(
            const type =
                        cancel,
                this.editorTools
                        confirm
                     .conditionTypeSelect
                     );
                     .val();


                    box.append(
            this.editorTools
                        input,
                .conditionVariableWrap
                        buttons
                .toggle(
                    );
                    type === 'if'
 
                );
                     overlay.append(
        },
                         box
 
        renderEditorTools() {
            const tools =
                $('<div>')
                     .addClass(
                         'preload-editor-tools'
                     );
                     );


                    $(document.body)
            const wrapGroup =
                        .append(
                $('<div>')
                            overlay
                     .addClass(
                        );
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
 
                     input.trigger(
                         'focus'
                     );
                     );


                    input.on(
            wrapGroup.append(
                        'keydown.preloadEditor',
                this.createButton(
                        event => {
                    'Wrap selection',
                            if (
                    'preload-editor-tool-button',
                                event.key ===
                    () =>
                                'Enter'
                        this.wrapSelectionWithVariable()
                            ) {
                )
                                confirm.trigger(
            );
                                    'click'
                                );
                            }


                            if (
            const variableGroup =
                                event.key ===
                $('<div>')
                                'Escape'
                    .addClass(
                            ) {
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                                cancel.trigger(
                                    'click'
                                );
                            }
                        }
                     );
                     );
                }
            );
        },


        async loadDefinition(
            $('<span>')
            title,
                .addClass(
            source
                    'preload-editor-tool-label'
        ) {
                )
             const content =
                .text(
                 this.extractIncludeonly(
                    'Insert existing variable'
                     source
                )
                .appendTo(variableGroup);
 
             const variableSelect =
                 this.createToolSelect(
                     [],
                    'preload-editor-variable-select'
                 );
                 );


             let config =
             variableGroup.append(
                 this.emptyConfig();
                 variableSelect,


            const configTitle =
                 this.createButton(
                 title.replace(
                     'Insert',
                     /\/+$/,
                     'preload-editor-tool-button',
                     ''
                    () =>
                 ) +
                        this.insertVariable(
                '/config.json';
                            variableSelect.val()
                        )
                 )
            );


             const configPage =
             const conditionGroup =
                 await this.getPage(
                 $('<div>')
                     configTitle
                    .addClass(
                );
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                     );


             if (configPage) {
             $('<span>')
                 try {
                 .addClass(
                    config =
                     'preload-editor-tool-label'
                        JSON.parse(
                 )
                            configPage.content
                .text('Insert condition')
                        );
                .appendTo(conditionGroup);
                } catch (
                     error
                 ) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }


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


             config =
             const conditionVariableSelect =
                 this.prepareConfigForVariables(
                 this.createToolSelect(
                     config,
                     [],
                     analysis
                     'preload-editor-condition-variable-select'
                 );
                 );


             this.state = {
             const conditionVariableWrap =
                 preloadTitle:
                 $('<span>')
                     title,
                    .addClass(
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                     );


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


                 preloadContent:
            conditionTypeSelect.on(
                     source,
                'change.preloadEditor',
                 () =>
                     this.updateConditionVariableVisibility()
            );


                 config,
            conditionGroup.append(
                 conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );


                 variables:
            tools.append(
                    analysis.variables,
                 wrapGroup,
                variableGroup,
                conditionGroup
            );


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


                selectedVariable:
            this.updateEditorToolVariables();
                    analysis.variables.includes(
            this.updateConditionVariableVisibility();
                        'PAGE'
                    )
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),


                mode: 'edit',
            return tools;
                dirty: false
        },
            };


             this.renderEditor();
        updateEditorTools() {
             this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
         },
         },


         // =========================================================
         // =========================================================
         // Editor
         // Syntax highlighting
         // =========================================================
         // =========================================================


         renderEditor() {
         getKnownVariables() {
             this.destroyEditor();
             const known =
                new Set(['PAGE']);


             this.workspace.empty();
             const fields =
                this.state.config &&
                this.state.config.fields;


             const layout =
             if (
                 $('<div>')
                fields &&
                     .addClass(
                typeof fields === 'object'
                         'preload-editor-layout'
            ) {
                     );
                 Object.keys(fields).forEach(
                     name => {
                        known.add(
                            String(name).toUpperCase()
                         );
                     }
                );
            }


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


             const right =
        createSyntaxDecorations(
                 $('<div>')
            state,
                    .addClass(
            Decoration
                        'preload-editor-right'
        ) {
                    );
            const decorations = [];
             const source =
                 state.doc.toString();


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


             const meta =
             const variablePattern =
                 $('<div>')
                 /%%([A-Za-z0-9_-]+)%%/g;
                    .addClass(
                        'preload-editor-meta'
                    );


             $('<strong>')
             let match;
                .text(
                    this.state.preloadTitle ||
                    'New preload'
                )
                .appendTo(
                    meta
                );


             if (
             while (
                 this.state.mode ===
                 (
                'new'
                    match =
                        variablePattern.exec(source)
                ) !== null
             ) {
             ) {
                 $('<span>')
                 const name =
                     .addClass(
                    match[1].toUpperCase();
                         'preload-editor-badge'
 
                const known =
                     knownVariables.has(name);
 
                decorations.push(
                    Decoration.mark({
                         class: [
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                     )
                     )
                    .text('NEW')
                );
                    .appendTo(
                        meta
                    );
             }
             }


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


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


            const textarea =
                const directiveStart =
                this.textarea(
                     match.index +
                     this.state.preloadContent
                     match[0].indexOf('@');
                )
                     .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


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


            editorSection.append(
                const type =
                editorMount
                    match[1].toLowerCase();
            );


            left.append(
                if (
                 editorSection
                    type !== 'if' &&
            );
                    type !== 'elseif'
                 ) {
                    continue;
                }


            /*
                const expression =
            * RIGHT PANEL
                    match[2];
            */


            const analysisSection =
                const expressionStart =
                this.createSection(
                    match.index +
                    'Analysis'
                     match[0].indexOf(
                );
                         expression
 
            const analysisContainer =
                $('<div>')
                     .addClass(
                         'preload-editor-analysis'
                     );
                     );


            analysisSection.append(
                 const expressionPattern =
                 analysisContainer
                    /[A-Za-z0-9_-]+/g;
            );


            const variablesSection =
                 let expressionMatch;
                 this.createSection(
                    'Variables'
                );


            const variableContainer =
                while (
                 $('<div>')
                    (
                     .addClass(
                        expressionMatch =
                         'preload-editor-variables'
                            expressionPattern.exec(
                    );
                                expression
                            )
                    ) !== null
                 ) {
                     const name =
                         expressionMatch[0]
                            .toUpperCase();


            variablesSection.append(
                    if (
                variableContainer
                        !knownVariables.has(name)
            );
                    ) {
                        continue;
                    }


            const configurationSection =
                    const start =
                this.createSection(
                        expressionStart +
                    'Variable configuration'
                        expressionMatch.index;
                );


            const configurationContainer =
                    decorations.push(
                $('<div>')
                        Decoration.mark({
                    .addClass(
                            class:
                        'preload-editor-variable-configuration'
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                     );
                     );
                }
            }


             configurationSection.append(
             return Decoration.set(
                 configurationContainer
                 decorations,
                true
             );
             );
        },


             const configSection =
        async installSyntaxHighlighting(view) {
                this.createSection(
             await mw.loader.using(
                    'Generated configuration'
                'ext.CodeMirror.v6.lib'
                );
            );


             const configPreview =
             const require =
                 $('<pre>')
                 mw.loader.require;
                    .addClass(
                        'preload-editor-config-preview'
                    );


             configSection.append(
             const {
                 configPreview
                StateField,
                StateEffect,
                EditorView,
                Decoration
            } = require(
                 'ext.CodeMirror.v6.lib'
             );
             );


             const actions =
             const syntaxField =
                 $('<div>')
                 StateField.define({
                    .addClass(
                    create: state =>
                         'preload-editor-actions'
                        this.createSyntaxDecorations(
                    );
                            state,
                            Decoration
                         ),


            actions.append(
                    update: (
                this.createButton(
                        decorations,
                    'Save Preload + Config',
                        transaction
                    'preload-editor-button-primary',
                     ) =>
                     () =>
                         transaction.docChanged
                         this.saveAll()
                            ? this.createSyntaxDecorations(
                ),
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                this.createButton(
                     provide: field =>
                    'Save Preload Only',
                         EditorView.decorations.from(
                    '',
                            field
                     () =>
                        )
                         this.savePreloadOnly()
                 });
                 )
            );


             right.append(
             view.dispatch({
                 analysisSection,
                 effects:
                variablesSection,
                    StateEffect.appendConfig.of(
                configurationSection,
                        syntaxField
                configSection,
                    )
                actions
             });
             );


             layout.append(
             this.editor.syntaxField =
                 left,
                 syntaxField;
                right
        },
            );


             this.workspace.append(
        async mountCodeMirror(textarea) {
                 layout
             return new Promise(
            );
                 (
                    resolve,
                    reject
                ) => {
                    let settled = false;


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


            this.renderVariables(
                        mw.hook(
                variableContainer
                            'dev.CCM.load'
            );
                        ).remove(onLoad);
                    };


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


            this.renderVariableConfiguration(
                            settled = true;
                configurationContainer
                            cleanup();
            );


            this.renderConfigPreview(
                            const view =
                configPreview
                                cm.view;
            );


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


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


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


        reanalyze() {
                                    this.renderVariablesBySelector();
            const source =
                                    this.renderVariableConfigurationBySelector();
                this.getEditorContent();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


            const content =
                                    this.saveDraft();
                this.extractIncludeonly(
                                };
                    source
                );


            const analysis =
                            view.dom.addEventListener(
                this.analyzePreload(
                                'input',
                    content
                                inputHandler
                );
                            );
 
                            view.dom.classList.add(
                                'preload-editor-codemirror'
                            );


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


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


            this.state.conditions =
                            this.editor = {
                analysis.conditions;
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


            /*
                            this.editorView =
            * This is where newly typed variables
                                view;
            * become configuration fields.
            *
            * For example:
            *
            * %%ZHS%%
            *
            * becomes:
            *
            * config.fields.ZHS = {
            *    label: 'Zhs',
            *    description: '',
            *    type: 'text'
            * };
            */
            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


            this.analysis =
                            this.state.preloadContent =
                analysis;
                                view.state.doc.toString();


            /*
                            try {
            * PAGE is always available.
                                await this.installSyntaxHighlighting(
            */
                                    view
            const available =
                                );
                ['PAGE'].concat(
                    analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );


            /*
                                if (
            * If the selected variable
                                    this.state.dirty
            * disappeared from the preload,
                                ) {
            * move selection to PAGE or
                                    this.saveDraft();
            * the first available variable.
                                }
            */
            if (
                !available.includes(
                    this.state
                        .selectedVariable
                )
            ) {
                this.state
                    .selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },


        renderAnalysis(
                                resolve(view);
            container
                            } catch (error) {
        ) {
                                reject(error);
            container.empty();
                            }
                        };


            const analysis =
                    const onLoad =
                this.analysis ||
                        loader => {
                this.analyzePreload(
                            if (
                    this.extractIncludeonly(
                                settled ||
                        this.getEditorContent()
                                typeof loader !==
                    )
                                    'function'
                );
                            ) {
                                return;
                            }


            const variableCount =
                            try {
                analysis.variables.length;
                                loader(textarea);
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };


            const conditionCount =
                    mw.hook(
                analysis.conditions.length;
                        'dev.CCM.ready'
                    ).add(onReady);


            const configuredCount =
                    mw.hook(
                Object.keys(
                        'dev.CCM.load'
                    this.state.config &&
                     ).add(onLoad);
                     this.state.config.fields
                }
                        ? this.state.config.fields
            );
                        : {}
        },
                ).length;


            const summary =
        // =========================================================
                $('<div>')
        // Main UI
                    .addClass(
        // =========================================================
                        'preload-editor-analysis-summary'
                    );


             const createMetric =
        init() {
                 (
             const root =
                    value,
                 $('#mw-content-text');
                    label
 
                ) =>
            if (!root.length) {
                    $('<div>')
                return;
                        .addClass(
            }
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                            $('<span>')
            this.root =
                                .addClass(
                $('<div>')
                                    'preload-editor-analysis-label'
                    .attr(
                                )
                        'id',
                                .text(label)
                        'preload-editor'
                         );
                    )
                    .addClass(
                         'preload-editor'
                    );


             summary.append(
             root.append(this.root);
                createMetric(
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),


                createMetric(
            this.renderShell();
                    conditionCount,
 
                    conditionCount === 1
            this.restoreDraft();
                        ? 'condition marker'
                        : 'condition markers'
                ),


                createMetric(
            window.addEventListener(
                    configuredCount,
                'beforeunload',
                     configuredCount === 1
                () => {
                         ? 'configured field'
                     if (this.state.dirty) {
                        : 'configured fields'
                         this.saveDraft();
                 )
                    }
                 }
             );
             );
        },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


             container.append(
             const loader =
                summary
                this.createSection('Preload');
            );


             if (
             const titleInput =
                 analysis.conditionVariables
                 this.textInput(
                     .length
                     this.state.preloadTitle,
            ) {
                    'Template:Example/Preload'
                 container.append(
                 ).attr(
                     $('<div>')
                     'id',
                        .addClass(
                    'preload-editor-title-input'
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(
                                ', '
                            )
                        )
                 );
                 );
            }


             const validation =
             titleInput.on(
                 this.validateConfig(
                 'input.preloadEditor',
                     this.state.config,
                () => {
                    analysis
                     this.state.preloadTitle =
                );
                        String(
                            titleInput.val() || ''
                        ).trim();


            if (
                    if (
                validation.errors.length
                        this.state.dirty &&
            ) {
                        this.state.mode === 'new'
                const errors =
                     ) {
                     $('<ul>')
                         this.saveDraft();
                         .addClass(
                    }
                            'preload-editor-validation-errors'
                }
                        );
            );


                 validation.errors.forEach(
            const loadButton =
                     error => {
                 this.createButton(
                        $('<li>')
                     'Load',
                            .text(error)
                    'preload-editor-button-primary',
                             .appendTo(
                    () =>
                                errors
                        this.loadExisting(
                            );
                             titleInput.val()
                    }
                        )
                 );
                 );


                 container.append(
            const newButton =
                     errors
                 this.createButton(
                     'New',
                    '',
                    () => this.startNew()
                 );
                 );
            }


             if (
             const sampleButton =
                validation.warnings.length
                this.createButton(
            ) {
                    'Load Sample Page',
                const warnings =
                     '',
                    $('<ul>')
                    () => this.loadSamplePage()
                        .addClass(
                            'preload-editor-validation-warnings'
                        );
 
                validation.warnings.forEach(
                     warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(
                                warnings
                            );
                    }
                 );
                 );


                 container.append(
            loader.append(
                     warnings
                 $('<div>')
                );
                    .addClass(
            }
                        'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                     )
            );


             if (
             this.root.append(loader);
                !validation.errors.length &&
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },


        renderAnalysisBySelector() {
             this.workspace =
             const container =
                 $('<div>')
                 this.root &&
                    .addClass(
                this.root.find(
                        'preload-editor-workspace'
                    '.preload-editor-analysis'
                    );
                );


             if (
             this.root.append(
                 container &&
                 this.workspace
                container.length
             );
             ) {
                this.renderAnalysis(
                    container
                );
            }
        },


        // =========================================================
            /*
        // Variables
            * Fixed footer
        // =========================================================
            *
            * Local draft status, normal status messages,
            * and save actions live here.
            */
            const footer =
                $('<div>')
                    .addClass(
                        'preload-editor-footer'
                    );


        renderVariables(
            this.localDraftStatus =
            container
                $('<div>')
        ) {
                    .addClass(
            container.empty();
                        'preload-editor-local-draft-status is-empty'
                    )
                    .text(
                        'No local draft'
                    );


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


             const variables =
             footer.append(
                 analysis.variables.slice();
                 this.localDraftStatus,
                this.status
            );


             /*
             this.root.append(
            * PAGE is always shown first.
                footer
            */
             );
             const ordered = ['PAGE'];


             variables.forEach(
             this.updateLocalDraftIndicator();
                name => {
                    if (
                        name !== 'PAGE' &&
                        !ordered.includes(
                            name
                        )
                    ) {
                        ordered.push(name);
                    }
                }
            );


             /*
             this.renderWelcome();
            * Existing configured fields which
        },
            * are no longer used are also shown.
            *
            * This preserves the previous behaviour
            * where unused configuration is visible.
            */
            const fields =
                this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};


            Object.keys(fields).forEach(
        renderWelcome() {
                name => {
            this.workspace.empty();
                    const upper =
                        name.toUpperCase();


                    if (
            const section =
                        upper !== 'PAGE' &&
                this.createSection('Get started');
                        !ordered.includes(
 
                            upper
            $('<p>')
                        )
                .text(
                    ) {
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                        ordered.push(
                )
                            upper
                 .appendTo(section);
                        );
                    }
                 }
            );


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


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


                    const isUsed =
            section.append(tips);
                        analysis.variables.includes(
            this.workspace.append(section);
                            name
        },
                        );


                    const item =
        setStatus(
                        $('<button>')
            message,
                            .attr({
            type
                                type: 'button',
        ) {
                                'data-variable':
            if (!this.status) {
                                    name
                return;
                            })
            }
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                    const nameLabel =
            this.status.removeClass(
                        $('<span>')
                'is-error',
                            .addClass(
                'is-success',
                                'preload-editor-variable-name'
                'is-warning',
                            )
                'is-loading'
                            .text(name);
            );


                    item.append(
            if (type) {
                        nameLabel
                this.status.addClass(
                    );
                    'is-' + type
                );
            }


                    if (
            this.status.text(
                        name === 'PAGE'
                message || ''
                    ) {
            );
                        item.append(
        },
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge'
                                )
                                .text(
                                    'AUTOMATIC'
                                )
                        );
                    } else if (
                        !isUsed
                    ) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    'UNUSED'
                                )
                        );
                    }


                    list.append(
        // =========================================================
                        item
        // Load / create
                    );
        // =========================================================
                }
            );


             container.append(
        async loadExisting(title) {
                list
             title =
            );
                String(title || '').trim();
        },


        renderVariablesBySelector() {
            if (!title) {
            const container =
                 mw.notify(
                 this.root &&
                    'Enter a preload page title first.',
                this.root.find(
                     {
                     '.preload-editor-variables'
                        type: 'warn'
                    }
                 );
                 );


             if (
                return;
                container &&
             }
                container.length
 
             ) {
             this.setStatus(
                this.renderVariables(
                'Loading preload...',
                    container
                 'loading'
                 );
            );
            }
        },


        // =========================================================
            try {
        // Variable selection / configuration
                const page =
        // =========================================================
                    await this.getPage(title);


        selectVariable(
                if (!page) {
            name
                    const suggestions =
        ) {
                        await this.findSimilarPreloads(
            name =
                            title
                String(name || '')
                        );
                    .trim()
                    .toUpperCase();


            if (!name) {
                    this.renderMissingPage(
                return;
                        title,
            }
                        suggestions
                    );


            const available =
                     this.setStatus(
                ['PAGE'].concat(
                         'Preload not found.',
                     (
                         'warning'
                        this.analysis &&
                     );
                         this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                         variable =>
                            variable !==
                            'PAGE'
                     )
                );


            /*
                    return;
            * Also allow selecting an existing
                 }
            * unused configuration field.
            */
            const fields =
                 this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};


            Object.keys(fields).forEach(
                await this.loadDefinition(
                fieldName => {
                    page.title,
                     const upper =
                     page.content
                        fieldName.toUpperCase();
                );


                    if (
                this.setStatus(
                        !available.includes(
                    'Preload loaded.',
                            upper
                    'success'
                        )
                );
                    ) {
            } catch (error) {
                        available.push(
                console.error(
                            upper
                    'Preload Editor:',
                        );
                     error
                     }
                 );
                 }
            );


            if (
                 this.setStatus(
                 !available.includes(
                     error.message ||
                     name
                        'Could not load preload.',
                )
                    'error'
            ) {
                 );
                 return;
             }
             }
        },


             this.state.selectedVariable =
        async findSimilarPreloads(title) {
                 name;
             let query =
                 title
                    .replace(
                        /\/Preload$/i,
                        ''
                    )
                    .trim();


             this.renderVariablesBySelector();
             if (!query) {
                query = title;
            }


             this.renderVariableConfigurationBySelector();
             try {
        },
                const results =
                    await this.searchPages(query);


        renderVariableConfigurationBySelector() {
                return results.filter(
            const container =
                    result =>
                 this.root &&
                        /\/Preload$/i.test(
                 this.root.find(
                            result.title
                     '.preload-editor-variable-configuration'
                        )
                 );
            } catch (error) {
                 console.error(
                     'Preload Editor search:',
                    error
                 );
                 );


            if (
                 return [];
                 container &&
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
             }
             }
         },
         },


         renderVariableConfiguration(
         renderMissingPage(
             container
             title,
            suggestions
         ) {
         ) {
             container.empty();
             this.workspace.empty();


             const analysis =
             const section =
                 this.analysis ||
                 this.createSection(
                this.analyzePreload(
                     'Preload not found'
                    this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );
                 );


             const name =
             $('<p>')
                 this.state.selectedVariable ||
                 .text(
                 'PAGE';
                    'No preload exists at "' +
                    title +
                    '".'
                )
                 .appendTo(section);


             const fields =
             if (suggestions.length) {
                this.state.config &&
                 $('<h3>')
                 this.state.config.fields
                     .text('Similar preloads')
                     ? this.state.config.fields
                     .appendTo(section);
                     : {};


            const field =
                const list =
                fields[name] ||
                    $('<div>')
                this.createDefaultField(
                        .addClass(
                    name,
                            'preload-editor-suggestions'
                    analysis
                        );
                );


            if (
                suggestions.forEach(
                name === 'PAGE'
                    result => {
            ) {
                        list.append(
                container.append(
                            this.createButton(
                    this.createAutomaticPageCard(
                                result.title,
                         field
                                'preload-editor-suggestion',
                     )
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                         );
                     }
                 );
                 );


                 return;
                 section.append(list);
             }
             }


             container.append(
             section.append(
                 this.createVariableCard(
                 this.createButton(
                     name,
                     'Create this preload',
                     field,
                     'preload-editor-button-primary',
                     analysis
                     () =>
                        this.startNew(title)
                 )
                 )
             );
             );
            this.workspace.append(section);
         },
         },


         // =========================================================
         async startNew(title) {
        // Automatic PAGE
            title =
        // =========================================================
                String(title || '').trim();
 
            this.state = {
                preloadTitle: title,
                preloadSource: '',
                preloadContent:
                    this.defaults.preload,


        createAutomaticPageCard(
                 config:
            field
                     this.emptyConfig(),
        ) {
            const card =
                 $('<div>')
                     .addClass(
                        'preload-editor-variable ' +
                        'preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );


            const header =
                variables: ['PAGE'],
                 $('<div>')
                conditions: [],
                    .addClass(
                 selectedVariable: 'PAGE',
                        'preload-editor-variable-header'
                deletedVariables: [],
                    );
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,


            header.append(
                localDraftSavedAt: null,
                 $('<h3>').text(
                 localDraftAvailable: false
                    'PAGE'
            };
                ),


                $('<span>')
            this.saveDraft();
                    .addClass(
            this.renderEditor();
                        'preload-editor-badge'
                    )
                    .text(
                        'AUTOMATIC'
                    )
            );


             card.append(
             this.setStatus(
                 header
                 'Creating a new preload.',
                'success'
             );
             );
        },


            $('<p>')
        async loadSamplePage() {
                 .addClass(
            const result =
                     'preload-editor-analysis-note'
                 await this.createPromptDialog(
                )
                     'Load Sample Page',
                .text(
                     'Enter the title of a normal wiki page to use as the starting point.'
                     'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(
                    card
                 );
                 );


             const label =
             if (!result) {
                 this.textInput(
                 return;
                    field.label ||
            }
                        'Page Name'
 
                ).prop(
            this.setStatus(
                    'disabled',
                'Loading sample page...',
                    true
                'loading'
                 );
            );
 
            try {
                 const page =
                    await this.getPage(result);


            const description =
                 if (!page) {
                 this.textarea(
                     throw new Error(
                    field.description ||
                         'Sample page not found: ' +
                        'Name of the page.'
                         result
                )
                     .addClass(
                         'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                         true
                     );
                     );
                }


            const type =
                const sample =
                this.textInput(
                    this.convertSampleToPreload(
                    field.type ||
                         page.content
                         'page'
                     );
                ).prop(
                    'disabled',
                     true
                );


            const required =
                 this.state = {
                 this.checkbox(
                     preloadTitle: '',
                     field.required !==
                     preloadSource: '',
                        false
                     preloadContent: sample,
                ).prop(
                     'disabled',
                     true
                );


            const namespace =
                    config:
                this.textInput(
                        this.emptyConfig(),
                    field.namespace ||
                        'Main'
                ).prop(
                    'disabled',
                    true
                );


            const allowNew =
                     variables: ['PAGE'],
                this.checkbox(
                    conditions: [],
                     field['allow-new'] ===
                    selectedVariable: 'PAGE',
                        true
                     deletedVariables: [],
                ).prop(
                    mode: 'new',
                     'disabled',
                     dirty: true,
                     true
                    dirtyPreload: true,
                );
                    dirtyConfig: true,


            card.append(
                     localDraftSavedAt: null,
                this.fieldRow(
                     localDraftAvailable: false
                     'Label',
                 };
                     label
                 ),


                 this.fieldRow(
                 this.reanalyze();
                    'Description',
                this.saveDraft();
                    description
                 this.renderEditor();
                 ),


                 this.fieldRow(
                 this.setStatus(
                     'Type',
                     'Sample page loaded.',
                     type
                     'success'
                 ),
                 );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );


                 this.fieldRow(
                 this.setStatus(
                     'Required',
                     error.message ||
                     required
                        'Could not load sample page.',
                 ),
                     'error'
                 );
            }
        },


                 this.fieldRow(
        convertSampleToPreload(source) {
                    'Namespace',
            let content =
                    namespace
                 String(source || '').trim();
                ),


                 this.fieldRow(
            const include =
                     'Allow new page',
                 content.match(
                    allowNew
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                 )
                 );
            );


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


        // =========================================================
             content =
        // Normal variable card
                 content
        // =========================================================
                     .replace(
 
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
        createVariableCard(
                         ''
             name,
            field,
            analysis
        ) {
            const card =
                 $('<div>')
                     .addClass(
                         'preload-editor-variable'
                     )
                     )
                     .attr(
                     .trim();
                        'data-variable',
                        name
                    );


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


            header.append(
        async loadDefinition(
                $('<h3>').text(
            title,
                    name
            source
                )
        ) {
             );
             const content =
                this.extractIncludeonly(source);


             if (
             let config =
                 !analysis.variables.includes(
                this.emptyConfig();
                     name
 
                 )
            const configTitle =
             ) {
                 title.replace(
                 header.append(
                     /\/+$/,
                    $('<span>')
                    ''
                         .addClass(
                 ) +
                             'preload-editor-badge is-warning'
                '/config.json';
                         )
 
                        .text(
             const configPage =
                            'UNUSED'
                 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
                    );
                 }
             }
             }


             card.append(
             const analysis =
                header
                this.analyzePreload(content);
            );


             // Label
             this.state.deletedVariables = [];


             const label =
             config =
                 this.textInput(
                 this.prepareConfigForVariables(
                     field.label || ''
                     config,
                    analysis
                 );
                 );


             label.on(
             this.state = {
                 'input.preloadEditor',
                 preloadTitle: title,
                 () => {
                 preloadSource: source,
                    field.label =
                preloadContent: source,
                        label.val();
                config,


                     this.markDirty();
                variables:
                     analysis.variables,


                     this.renderConfigPreviewBySelector();
                conditions:
                }
                     analysis.conditions,
            );


            card.append(
                selectedVariable:
                this.fieldRow(
                    analysis.variables.includes('PAGE')
                    'Label',
                        ? 'PAGE'
                    label
                        : (
                )
                            analysis.variables[0] ||
            );
                            'PAGE'
                        ),


            // Description
                deletedVariables: [],


            const description =
                 mode: 'edit',
                 this.textarea(
                 dirty: false,
                    field.description ||
                dirtyPreload: false,
                        ''
                 dirtyConfig: false,
                 ).addClass(
                    'preload-editor-small-textarea'
                 );


            description.on(
                 localDraftSavedAt: null,
                 'input.preloadEditor',
                 localDraftAvailable: false
                 () => {
            };
                    field.description =
                        description.val();


                    this.markDirty();
            this.clearDraft(title);
            this.renderEditor();
        },


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


            card.append(
        renderEditor() {
                this.fieldRow(
            this.destroyEditor();
                    'Description',
             this.workspace.empty();
                    description
                )
             );


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


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


             const typeSelect =
             const editorSection =
                 this.select(
                 this.createSection(
                     types.map(
                     'Preload',
                        (
                     'preload-editor-main-section'
                            [
                                value,
                                label
                            ]
                        ) => ({
                            value,
                            label
                        })
                     ),
                    field.type ||
                        'text'
                 );
                 );


             typeSelect.on(
             const meta =
                 'change.preloadEditor',
                 $('<div>')
                () => {
                     .addClass(
                     field.type =
                         'preload-editor-meta'
                         typeSelect.val();
                    );


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


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


                    this.renderConfigPreviewBySelector();
            editorSection.append(meta);
                 }
            editorSection.append(
                 this.renderEditorTools()
             );
             );


             card.append(
             const textarea =
                 this.fieldRow(
                 this.textarea(
                     'Type',
                     this.state.preloadContent
                    typeSelect
                 )
                 )
            );
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


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


             const required =
             editorSection.append(editorMount);
                this.checkbox(
            left.append(editorSection);
                    field.required ===
                        true
                );


             required.on(
             const analysisSection =
                'change.preloadEditor',
                 this.createSection('Analysis');
                 () => {
                    field.required =
                        required.prop(
                            'checked'
                        );


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


                    this.renderConfigPreviewBySelector();
            analysisSection.append(
                 }
                 analysisContainer
             );
             );


             card.append(
             const variablesSection =
                 this.fieldRow(
                 this.createSection('Variables');
                    'Required',
                    required
                )
            );


            // Placeholder
             const detectVariablesButton =
 
                 this.createButton(
             const placeholder =
                     'Detect variables',
                 this.textInput(
                    'preload-editor-button-primary preload-editor-detect-variables',
                     field.placeholder ||
                    () =>
                        ''
                        this.detectVariables()
                 );
                 );


             placeholder.on(
             const detectHelp =
                'input.preloadEditor',
                $('<div>')
                () => {
                    .addClass(
                     const value =
                        'preload-editor-help preload-editor-detect-variables-help'
                         placeholder.val();
                    )
                     .text(
                         'Refresh the variable list after editing the preload.'
                    );


                     if (value) {
            variablesSection.append(
                         field.placeholder =
                $('<div>')
                            value;
                     .addClass(
                     } else {
                         'preload-editor-variable-detect'
                         delete field.placeholder;
                    )
                     }
                     .append(
                        detectVariablesButton,
                         detectHelp
                     )
            );


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


                    this.renderConfigPreviewBySelector();
            variablesSection.append(
                 }
                 variableContainer
             );
             );


             card.append(
             const configurationSection =
                 this.fieldRow(
                 this.createSection(
                     'Placeholder',
                     'Variable configuration'
                    placeholder
                 );
                 )
            );


             // Default
             /*
            * 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 defaultInput =
             const importHelp =
                 this.textInput(
                 $('<div>')
                     field.default ===
                     .addClass(
                         undefined
                         'preload-editor-help preload-editor-import-definitions-help'
                        ? ''
                    )
                         : field.default
                    .text(
                );
                         'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );


             defaultInput.on(
             const importControls =
                'input.preloadEditor',
                $('<div>')
                () => {
                    .addClass(
                     const value =
                        'preload-editor-import-definition-controls'
                         defaultInput.val();
                    )
                     .append(
                        importDefinitionsButton,
                         importHelp
                    );


                    if (value) {
            configurationSection.append(
                        field.default =
                importControls
                            value;
            );
                    } else {
                        delete field.default;
                    }


                     this.markDirty();
            const configurationContainer =
                $('<div>')
                     .addClass(
                        'preload-editor-variable-configuration'
                    );


                    this.renderConfigPreviewBySelector();
            configurationSection.append(
                 }
                 configurationContainer
             );
             );


             card.append(
             const configSection =
                 this.fieldRow(
                this.createSection(
                     'Default',
                    'Configuration'
                     defaultInput,
                );
                     'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
 
                 )
            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
             );
             );


             // Textarea options
             right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );


             if (
             layout.append(
                 field.type ===
                 left,
                 'textarea'
                 right
             ) {
             );
                const maxRows =
 
                    this.textInput(
            const saveBar =
                        field.maxRows ||
                $('<div>')
                            ''
                     .addClass(
                     ).attr(
                         'preload-editor-save-bar'
                         'type',
                        'number'
                     );
                     );


                 maxRows.on(
            saveBar.append(
                     'input.preloadEditor',
                 this.createButton(
                     () => {
                     'Save Preload',
                         const value =
                    '',
                            parseInt(
                     () =>
                                maxRows.val(),
                         this.savePreloadOnly()
                                10
                ),
                            );
 
                this.createButton(
                    'Save Config',
                    '',
                    () =>
                        this.saveConfigOnly()
                ),


                        if (
                this.createButton(
                            Number.isFinite(
                    'Save',
                                value
                    'preload-editor-button-primary',
                            ) &&
                    () =>
                            value > 0
                         this.saveAll()
                         ) {
                )
                            field.maxRows =
            );
                                value;
                        } else {
                            delete field.maxRows;
                        }


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


                        this.renderConfigPreviewBySelector();
            this.workspace.append(
                    }
                layout
                );
            );


                card.append(
            this.reanalyze();
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                );
            }


             // Select / multiselect
             this.renderVariables(
                variableContainer
            );


             if (
             this.renderAnalysis(
                 field.type ===
                 analysisContainer
                    'select' ||
            );
                 field.type ===
 
                    'multiselect'
            this.renderVariableConfiguration(
             ) {
                configurationContainer
                this.renderSelectConfiguration(
            );
                    card,
 
                     field
            this.updateEditorTools();
                );
            this.updateLocalDraftIndicator();
            }
 
            this.mountCodeMirror(
                 textarea.get(0)
             ).catch(
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                     );


             return card;
                    this.setStatus(
                        error.message ||
                            'Could not initialize CodeMirror.',
                        'error'
                    );
                }
             );
         },
         },


         // =========================================================
         // =========================================================
         // Select configuration
         // Variable detection
         // =========================================================
         // =========================================================


         renderSelectConfiguration(
         detectVariables() {
            card,
            field
        ) {
             const source =
             const source =
                 this.textInput(
                 this.getEditorContent();
                    field.source ||
 
                        '',
            this.state.preloadContent =
                    'category:Example'
                 source;
                 );


             source.on(
             const content =
                 'input.preloadEditor',
                 this.extractIncludeonly(
                () => {
                     source
                     const value =
                );
                        source.val();


                    if (value) {
            const analysis =
                        field.source =
                this.analyzePreload(
                            value;
                     content
                     } else {
                );
                        delete field.source;
                    }


                     this.markDirty();
            /*
            * 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.renderConfigPreviewBySelector();
                this.state.deletedVariables =
                 }
                     this.state.deletedVariables
             );
                        .filter(
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                 this.state.deletedVariables = [];
             }


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


             const sourcePrefix =
             this.reanalyze();
                this.textInput(
                    field[
                        'source-prefix'
                    ] || ''
                );


             sourcePrefix.on(
             this.renderVariablesBySelector();
                'input.preloadEditor',
            this.renderVariableConfigurationBySelector();
                () => {
            this.renderAnalysisBySelector();
                    const value =
            this.updateEditorTools();
                        sourcePrefix.val();


                    if (value) {
            this.saveDraft();
                        field[
                            'source-prefix'
                        ] = value;
                    } else {
                        delete field[
                            'source-prefix'
                        ];
                    }


                    this.markDirty();
            this.setStatus(
                'Variables detected from the current preload.',
                'success'
            );
        },


                    this.renderConfigPreviewBySelector();
        reanalyze() {
                 }
            const source =
            );
                 this.getEditorContent();


             card.append(
             const content =
                 this.fieldRow(
                 this.extractIncludeonly(source);
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );


             const excludeCategory =
             const analysis =
                 this.textInput(
                 this.analyzePreload(
                     field.exclude &&
                     content
                    field.exclude.category ||
                        ''
                 );
                 );


             excludeCategory.on(
             this.state.preloadContent =
                'input.preloadEditor',
                 source;
                 () => {
                    const value =
                        excludeCategory.val();


                    if (value) {
            this.state.variables =
                        field.exclude =
                analysis.variables;
                            Object.assign(
                                {},
                                field.exclude ||
                                    {},
                                {
                                    category:
                                        value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field
                            .exclude
                            .category;


                        if (
            this.state.conditions =
                            !Object.keys(
                analysis.conditions;
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }


                     this.markDirty();
            this.state.config =
                this.prepareConfigForVariables(
                     this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


                    this.renderConfigPreviewBySelector();
            this.analysis =
                 }
                 analysis;
            );


             card.append(
             const available =
                this.fieldRow(
                ['PAGE'].concat(
                    'Exclude category',
                    analysis.variables.filter(
                     excludeCategory
                        name =>
                            name !== 'PAGE'
                     )
                );
 
            if (
                !available.includes(
                    this.state.selectedVariable
                 )
                 )
             );
             ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },


            card.append(
        // =========================================================
                this.createTransformControls(
        // Analysis
                    field,
        // =========================================================
                    'value',
                    'Value transformation'
                ),


                this.createTransformControls(
        renderAnalysis(container) {
                    field,
             container.empty();
                    'label',
                    'Label transformation'
                )
             );


             const optionsValue =
             const analysis =
                 Array.isArray(
                 this.analysis ||
                    field.options
                this.analyzePreload(
                )
                     this.extractIncludeonly(
                     ? field.options
                         this.getEditorContent()
                         .map(
                    )
                            option => {
                );
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


                                return (
            const variableCount =
                                    String(
                analysis.variables.length;
                                        option.value ||
                                        ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';


             const options =
             const conditionCount =
                 this.textarea(
                 analysis.conditions.length;
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );


             options.on(
             const configuredCount =
                 'input.preloadEditor',
                 Object.keys(
                () => {
                     this.state.config &&
                     const lines =
                    this.state.config.fields
                        options
                        ? this.state.config.fields
                            .val()
                        : {}
                            .split('\n')
                ).length;
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(
                                Boolean
                            );


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


                                    if (
            const createMetric =
                                        parts.length ===
                (
                                        1
                    value,
                                     ) {
                    label
                                        return parts[0];
                ) =>
                                    }
                    $('<div>')
 
                        .addClass(
                                     return {
                            'preload-editor-analysis-metric'
                                        value:
                        )
                                            parts[0],
                        .append(
                            $('<strong>')
                                .addClass(
                                     'preload-editor-analysis-value'
                                )
                                .text(value),
 
                            $('<span>')
                                .addClass(
                                     'preload-editor-analysis-label'
                                )
                                .text(label)
                        );


                                        label:
            summary.append(
                                            parts
                createMetric(
                                                .slice(
                    variableCount,
                                                    1
                    variableCount === 1
                                                )
                        ? 'variable'
                                                .join(
                        : 'variables'
                                                    ' | '
                ),
                                                )
                                    };
                                }
                            );
                    }


                     this.markDirty();
                createMetric(
                     conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),


                     this.renderConfigPreviewBySelector();
                createMetric(
                 }
                    configuredCount,
                     configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                 )
             );
             );


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


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


        createTransformControls(
             const validation =
            field,
                 this.validateConfig(
            property,
                     this.state.config,
            title
                     analysis
        ) {
             const wrapper =
                 $('<div>')
                    .addClass(
                        'preload-editor-transform'
                     );
 
            $('<h4>')
                .text(title)
                .appendTo(
                     wrapper
                 );
                 );


             const existing =
             if (validation.errors.length) {
                 field[property] &&
                 const errors =
                typeof field[property] ===
                     $('<ul>')
                     'object'
                        .addClass(
                    ? field[property]
                            'preload-editor-validation-errors'
                    : {};
                        );


            const transform =
                 validation.errors.forEach(
                 this.select(
                     error => {
                     [
                         $('<li>')
                        {
                             .text(error)
                            value: '',
                             .appendTo(errors);
                            label:
                    }
                                'No transformation'
                         },
                        {
                            value:
                                'remove-prefix',
                             label:
                                'Remove prefix'
                        },
                        {
                             value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value:
                                'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform ||
                        ''
                 );
                 );


            const prefix =
                 container.append(errors);
                 this.textInput(
            }
                    existing.prefix ||
                        ''
                );


             const suffix =
             if (validation.warnings.length) {
                 this.textInput(
                const warnings =
                     existing.suffix ||
                    $('<ul>')
                         ''
                        .addClass(
                            'preload-editor-validation-warnings'
                        );
 
                 validation.warnings.forEach(
                     warning => {
                         $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                 );
                 );


             const from =
                container.append(warnings);
                 this.textInput(
            }
                     existing.from ||
 
                         ''
            if (
                !validation.errors.length &&
                !validation.warnings.length
             ) {
                 container.append(
                     $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                         )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                 );
                 );
            }
        },


             const to =
        renderAnalysisBySelector() {
                 this.textInput(
             const container =
                     existing.to ||
                 this.root &&
                        ''
                this.root.find(
                     '.preload-editor-analysis'
                 );
                 );


             const controls =
             if (
                 $('<div>')
                container &&
                    .addClass(
                 container.length
                        'preload-editor-transform-controls'
            ) {
                    );
                this.renderAnalysis(container);
            }
        },


            const prefixRow =
        // =========================================================
                this.fieldRow(
        // Variables
                    'Prefix',
        // =========================================================
                    prefix
                );


             const suffixRow =
        renderVariables(container) {
                this.fieldRow(
             container.empty();
                    'Suffix',
                    suffix
                );


             const fromRow =
             const analysis =
                 this.fieldRow(
                 this.analysis ||
                     'From',
                this.analyzePreload(
                     from
                     this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );
                 );


             const toRow =
             const variables =
                 this.fieldRow(
                 analysis.variables.slice();
                    'To',
                    to
                );


             const renderInputs =
             const ordered =
                 () => {
                 ['PAGE'];
                    const type =
                        transform.val();


                     prefixRow.toggle(
            variables.forEach(
                         type ===
                name => {
                            'remove-prefix'
                     if (
                     );
                         name !== 'PAGE' &&
                        !ordered.includes(name)
                    ) {
                        ordered.push(name);
                     }
                }
            );


                     suffixRow.toggle(
            const configuredFields =
                         type ===
                this.state.config &&
                            'remove-suffix'
                this.state.config.fields
                     );
                     ? Object.keys(
                         this.state.config.fields
                    )
                     : [];


                    fromRow.toggle(
            configuredFields.forEach(
                        type ===
                name => {
                            'replace'
                    const upper =
                    );
                        name.toUpperCase();


                     toRow.toggle(
                     if (
                         type ===
                         upper !== 'PAGE' &&
                            'replace'
                        !ordered.includes(upper)
                     );
                     ) {
                 };
                        ordered.push(upper);
                    }
                 }
            );


             const update =
             const deleted =
                 () => {
                 Array.isArray(
                     const type =
                    this.state.deletedVariables
                        transform.val();
                )
                     ? this.state.deletedVariables
                    : [];


                     let object =
            deleted.forEach(
                         null;
                name => {
                     const upper =
                         String(name).toUpperCase();


                     if (
                     if (
                         type ===
                         upper !== 'PAGE' &&
                            'remove-prefix' &&
                         !ordered.includes(upper)
                         prefix.val()
                     ) {
                     ) {
                         object = {
                         ordered.push(upper);
                            transform:
                     }
                                type,
                }
                            prefix:
            );
                                prefix.val()
 
                        };
            const list =
                     } else if (
                $('<div>')
                        type ===
                     .addClass(
                            'remove-suffix' &&
                         'preload-editor-variable-list'
                        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) {
            ordered.forEach(
                        field[property] =
                name => {
                            object;
                     const isSelected =
                     } else {
                         name ===
                         delete field[
                         this.state.selectedVariable;
                            property
                         ];
                    }


                     this.markDirty();
                     const isUsed =
                        analysis.variables.includes(
                            name
                        );


                     this.renderConfigPreviewBySelector();
                     const isConfigured =
                };
                        !!(
                            this.state.config &&
                            this.state.config.fields &&
                            this.state.config.fields[name]
                        );


            transform.on(
                    const item =
                'change.preloadEditor',
                        $('<button>')
                () => {
                            .attr({
                    update();
                                type: 'button',
                    renderInputs();
                                'data-variable':
                }
                                    name
            );
                            })
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


            [
                    $('<span>')
                prefix,
                        .addClass(
                suffix,
                            'preload-editor-variable-name'
                from,
                         )
                to
                        .text(name)
            ].forEach(
                        .appendTo(item);
                input => {
                    input.on(
                        'input.preloadEditor',
                         update
                    );
                }
            );


            controls.append(
                    if (name === 'PAGE') {
                this.fieldRow(
                        item.append(
                     'Transformation',
                            $('<span>')
                     transform
                                .addClass(
                ),
                                    'preload-editor-badge'
                prefixRow,
                                )
                suffixRow,
                                .text('AUTOMATIC')
                fromRow,
                        );
                toRow
                     } else if (!isConfigured) {
            );
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    isUsed
                                        ? 'NOT CONFIGURED'
                                        : 'DELETED'
                                )
                        );
                     } else if (!isUsed) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                    }


            renderInputs();
                    list.append(item);
 
                 }
            wrapper.append(
                 controls
             );
             );


             return wrapper;
             container.append(list);
        },


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


         getCleanConfig() {
         renderVariablesBySelector() {
             const config =
             const container =
                 JSON.parse(
                 this.root &&
                    JSON.stringify(
                this.root.find(
                        this.state.config
                     '.preload-editor-variables'
                     )
                 );
                 );


             const fields =
             if (
                 config.fields || {};
                 container &&
                container.length
            ) {
                this.renderVariables(container);
            }
        },


             const orderedFields = {};
        selectVariable(name) {
             name =
                String(name || '')
                    .trim()
                    .toUpperCase();


             /*
             if (!name) {
            * PAGE is always first.
                return;
            */
             }
             orderedFields.PAGE =
                this.getAutomaticPageField();


             Object.keys(fields)
             const available =
                 .filter(
                 ['PAGE'].concat(
                     name =>
                     (
                         name.toUpperCase() !==
                         this.analysis &&
                         'PAGE'
                         this.analysis.variables
                )
                            ? this.analysis.variables
                .forEach(
                            : []
                    name => {
                    ).filter(
                        orderedFields[name] =
                        variable =>
                            fields[name];
                            variable !== 'PAGE'
                     }
                     )
                 );
                 );


             config.fields =
             const configuredUnused =
                orderedFields;
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];


             return config;
             configuredUnused.forEach(
        },
                variable => {
 
                    if (
        getConfigJSON() {
                        !available.includes(variable) &&
            return JSON.stringify(
                        variable !== 'PAGE'
                this.getCleanConfig(),
                    ) {
                null,
                        available.push(variable);
                 4
                    }
                 }
             );
             );
        },


        renderConfigPreview(
             if (!available.includes(name)) {
            container
                 return;
        ) {
             if (container) {
                container.text(
                    this.getConfigJSON()
                 );
             }
             }
        },


         renderConfigPreviewBySelector() {
            this.state.selectedVariable =
             const preview =
                name;
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },
 
         renderVariableConfigurationBySelector() {
             const container =
                 this.root &&
                 this.root &&
                 this.root.find(
                 this.root.find(
                     '.preload-editor-config-preview'
                     '.preload-editor-variable-configuration'
                 );
                 );


             if (
             if (
                 preview &&
                 container &&
                 preview.length
                 container.length
             ) {
             ) {
                 this.renderConfigPreview(
                 this.renderVariableConfiguration(
                     preview
                     container
                 );
                 );
             }
             }
            this.renderAnalysisBySelector();
         },
         },


         markDirty() {
         renderVariableConfiguration(container) {
             this.state.dirty =
             container.empty();
                true;
        },


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


        async savePreloadOnly() {
             const name =
             let title =
                 this.state.selectedVariable ||
                 String(
                'PAGE';
                    this.state.preloadTitle ||
                        ''
                ).trim();


             if (!title) {
             const fields =
                const result =
                this.state.config &&
                    await this.createPromptDialog(
                this.state.config.fields
                        'Preload title',
                    ? this.state.config.fields
                        'Enter the full title for the preload.'
                     : {};
                     );


                 if (!result) {
            const field =
                    return;
                 fields[name];
                }


                title = result;
            if (name === 'PAGE') {
 
                 container.append(
                this.state.preloadTitle =
                    this.createAutomaticPageCard(
                    title;
                        field ||
            }
                        this.getAutomaticPageField()
 
                     )
            this.state.preloadContent =
                 this.getEditorContent();
 
            const validation =
                this.validateBeforeSave();
 
            if (
                validation.errors.length
            ) {
                this.showValidationErrors(
                     validation
                 );
                 );


Line 4,495: Line 4,484:
             }
             }


             this.setStatus(
             if (!field) {
                 'Saving preload...',
                const missing =
                'loading'
                    $('<div>')
            );
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );
 
                 $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    )
                    .append(
                        $('<h3>')
                            .text(name),


            try {
                        $('<span>')
                const exists =
                            .addClass(
                    await this.pageExists(
                                'preload-editor-badge is-warning'
                        title
                            )
                     );
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                     .appendTo(missing);


                 await this.savePage(
                 $('<p>')
                     title,
                     .addClass(
                    this.state.preloadContent,
                         'preload-editor-analysis-note'
                    exists
                    )
                         ? 'Updated preload with Preload Editor'
                    .text(
                         : 'Created preload with Preload Editor',
                         'This variable is currently not present in config.json.'
                     !exists
                     )
                );
                    .appendTo(missing);


                 this.state.mode =
                 container.append(missing);
                    'edit';
                return;
            }


                 this.state.dirty =
            container.append(
                     false;
                 this.createVariableCard(
                    name,
                    field,
                     analysis
                )
            );
        },


                 this.setStatus(
        createAutomaticPageCard(field) {
                     'Preload saved successfully.',
            const card =
                    'success'
                 $('<div>')
                );
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                     )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );


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


                this.setStatus(
            header.append(
                    error.message ||
                $('<h3>').text('PAGE'),
                        'Could not save preload.',
                    'error'
                );


                 mw.notify(
                 $('<span>')
                     error.message ||
                     .addClass(
                         'Could not save preload.',
                         'preload-editor-badge'
                     {
                     )
                        type: 'error'
                    .text('AUTOMATIC')
                    }
            );
                );
            }
        },


        async saveAll() {
             card.append(header);
             let title =
                String(
                    this.state.preloadTitle ||
                        ''
                ).trim();


             if (!title) {
             $('<p>')
                 const result =
                 .addClass(
                    await this.createPromptDialog(
                    'preload-editor-analysis-note'
                        'Preload title',
                )
                        'Enter the full title for the preload.'
                .text(
                    );
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);


                 if (!result) {
            const label =
                     return;
                 this.textInput(
                 }
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                     true
                 );


                 title = result;
            const description =
                 this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                    .addClass(
                        'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                    );


                 this.state.preloadTitle =
            const type =
                     title;
                 this.textInput(
            }
                    field.type || 'page'
                ).prop(
                    'disabled',
                     true
                );


             this.state.preloadContent =
             const required =
                 this.getEditorContent();
                this.checkbox(
                    field.required !== false
                 ).prop(
                    'disabled',
                    true
                );


             /*
             const namespace =
            * Ensure the latest editor content is
                this.textInput(
            * represented in the config before saving.
                    field.namespace || 'Main'
            */
                ).prop(
            this.reanalyze();
                    'disabled',
                    true
                );


             const validation =
             const allowNew =
                 this.validateBeforeSave();
                 this.checkbox(
 
                    field['allow-new'] === true
            if (
                 ).prop(
                 validation.errors.length
                     'disabled',
            ) {
                    true
                this.showValidationErrors(
                     validation
                 );
                 );


                 return;
            card.append(
            }
                 this.fieldRow(
                    'Label',
                    label
                ),


            const configTitle =
                 this.fieldRow(
                 title.replace(
                     'Description',
                     /\/+$/,
                     description
                     ''
                 ),
                 ) +
                '/config.json';


            this.setStatus(
                this.fieldRow(
                'Saving preload and config...',
                    'Type',
                 'loading'
                    type
            );
                 ),
 
                this.fieldRow(
                    'Required',
                    required
                ),


            try {
                 this.fieldRow(
                 const preloadExists =
                    'Namespace',
                    await this.pageExists(
                     namespace
                        title
                ),
                     );


                 await this.savePage(
                 this.fieldRow(
                     title,
                     'Allow new page',
                    this.state.preloadContent,
                     allowNew
                    preloadExists
                 )
                        ? 'Updated preload with Preload Editor'
            );
                        : 'Created preload with Preload Editor',
                     !preloadExists
                 );


                const configExists =
            return card;
                    await this.pageExists(
        },
                        configTitle
                    );


                 await this.savePage(
        createVariableCard(
                     configTitle,
            name,
                     this.getConfigJSON(),
            field,
                     configExists
            analysis
                        ? 'Updated preload config with Preload Editor'
        ) {
                         : 'Created preload config with Preload Editor',
            const card =
                     !configExists
                 $('<div>')
                );
                    .addClass(
                        'preload-editor-variable'
                     )
                     .attr(
                        'data-variable',
                        name
                     );
 
            const header =
                $('<div>')
                    .addClass(
                         'preload-editor-variable-header'
                     );


                this.state.mode =
            header.append(
                    'edit';
                $('<h3>').text(name)
            );


                 this.state.dirty =
            if (
                     false;
                 !analysis.variables.includes(name)
            ) {
                header.append(
                     $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }


                this.state.preloadTitle =
            card.append(header);
                    title;


                 this.setStatus(
            const label =
                     'Preload and config saved successfully.',
                 this.textInput(
                    'success'
                     field.label || ''
                 );
                 );


                mw.notify(
            label.on(
                    'Preload and config saved.',
                'input.preloadEditor',
                    {
                () => {
                        type: 'success'
                     field.label =
                     }
                        label.val();
                );
 
            } catch (
                    this.markDirty();
                error
                    this.renderConfigReviewAvailability();
            ) {
                }
                console.error(
            );
                    'Preload Editor save:',
                    error
                );


                 this.setStatus(
            card.append(
                     error.message ||
                 this.fieldRow(
                        'Could not save preload/config.',
                     'Label',
                     'error'
                     label
                 );
                 )
            );


                 mw.notify(
            const description =
                     error.message ||
                 this.textarea(
                        'Could not save preload/config.',
                     field.description || ''
                     {
                ).addClass(
                        type: 'error'
                     'preload-editor-small-textarea'
                    }
                 );
                 );
            }
        },


        validateBeforeSave() {
            description.on(
            const errors = [];
                'input.preloadEditor',
            const warnings = [];
                () => {
                    field.description =
                        description.val();


            const title =
                    this.markDirty();
                String(
                     this.renderConfigReviewAvailability();
                     this.state.preloadTitle ||
                }
                        ''
            );
                ).trim();


             if (!title) {
             card.append(
                 errors.push(
                 this.fieldRow(
                     'A preload title is required.'
                     'Description',
                );
                     description
            }
 
            if (
                title &&
                !/\/Preload$/i.test(
                     title
                 )
                 )
             ) {
             );
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }


             const content =
             const types = [
                 this.getEditorContent();
                 ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];


             this.state.preloadContent =
             const typeSelect =
                 content;
                this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                 );
 
            typeSelect.on(
                'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();
 
                    this.markDirty();


            if (!content.trim()) {
                    this.renderVariableConfigurationBySelector();
                errors.push(
                    this.renderConfigReviewAvailability();
                    'The preload cannot be empty.'
                }
                );
            );
            }


             if (
             card.append(
                 !/<includeonly>/i.test(
                 this.fieldRow(
                     content
                     'Type',
                    typeSelect
                 )
                 )
             ) {
             );
                warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }


             if (
             const required =
                !/<noinclude>/i.test(
                 this.checkbox(
                    content
                     field.required === true
                )
            ) {
                 warnings.push(
                     'The preload does not contain a <noinclude> section.'
                 );
                 );
            }


             const analysis =
             required.on(
                 this.analyzePreload(
                 'change.preloadEditor',
                     this.extractIncludeonly(
                () => {
                         content
                     field.required =
                    )
                         required.prop('checked');
                );


            /*
                     this.markDirty();
            * Synchronize configuration one last
                     this.renderConfigReviewAvailability();
            * time before validation.
                 }
            */
            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(
             card.append(
                 ...configValidation.warnings
                 this.fieldRow(
                    'Required',
                    required
                )
             );
             );


             let depth = 0;
             const placeholder =
                this.textInput(
                    field.placeholder || ''
                );


             analysis.conditions.forEach(
             placeholder.on(
                 condition => {
                'input.preloadEditor',
                     if (
                () => {
                         condition.type ===
                    const value =
                        'if'
                        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++;
                         depth++;
                     } else if (
                     } else if (
                         condition.type ===
                         condition.type === 'endif'
                         'endif'
                    ) {
                     ) {
                        depth--;
                         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();


                        if (
             this.saveDraft();
                            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.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 4,863: Line 6,213:
     $(function () {
     $(function () {
         if (
         if (
             mw.config.get(
             mw.config.get('wgPageName') !==
                'wgPageName'
             'Petit_Planet_Wiki:Preload_Editor'
            ) !==
             'Petit_Planet:Preload_Editor'
         ) {
         ) {
             return;
             return;