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
 
(24 intermediate revisions by the same user not shown)
Line 3: Line 3:


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


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


Line 22: Line 30:
         workspace: null,
         workspace: null,
         status: null,
         status: null,
        localDraftStatus: null,
        editorTools: null,
        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 api = new mw.Api();
             try {
                const raw = window.localStorage.getItem(this.draftStorageKey);


            const response = await api.get({
                if (!raw) {
                action: 'query',
                    return {
                prop: 'revisions',
                        active: null,
                titles: title,
                        drafts: {}
                rvprop: 'content',
                    };
                rvslots: 'main',
                 }
                 formatversion: 2
            });


            const page =
                const parsed = JSON.parse(raw);
                response &&
                response.query &&
                response.query.pages &&
                response.query.pages[0];


            if (!page || page.missing) {
                if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
                return null;
                    return {
            }
                        active: null,
                        drafts: {}
                    };
                }


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


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


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


         async searchPages(query) {
         setDraftStorage(storage) {
             const api = new mw.Api();
             try {
                window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                return true;
            } catch (error) {
                console.warn('Preload Editor: Could not save local draft.', error);
                return false;
            }
        },


             const response = await api.get({
        getDraftId(title) {
                action: 'query',
             title = String(title || '').trim();
                list: 'search',
             return title ? title.toLowerCase() : '__untitled__';
                srsearch: query,
                srlimit: 10,
                srnamespace: 10,
                formatversion: 2
            });
 
             return (
                response &&
                response.query &&
                response.query.search
                    ? response.query.search
                    : []
            );
         },
         },


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


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


             return api.postWithToken('csrf', params);
             let config = null;
        },


        // Preload parsing
            try {
                config = this.state.config
                    ? JSON.parse(JSON.stringify(this.state.config))
                    : this.emptyConfig();
            } catch (error) {
                console.warn('Preload Editor: Could not clone config for local draft.', error);
                config = this.emptyConfig();
            }
 
            return {
                version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,


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


            return match
                mode: this.state.mode || 'edit',
                 ? match[1].trim()
                dirty: !!this.state.dirty,
                 : String(source || '').trim();
                dirtyPreload: !!this.state.dirtyPreload,
                 dirtyConfig: !!this.state.dirtyConfig,
                 savedAt: Date.now()
            };
         },
         },


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


             while ((match = pattern.exec(content)) !== null) {
             this.localDraftStatus.removeClass(
                 const name = match[1].toUpperCase();
                 'is-saved',
                'is-warning',
                'is-error',
                'is-empty'
            );


                if (!variables.includes(name)) {
            if (type) {
                    variables.push(name);
                this.localDraftStatus.addClass('is-' + type);
                }
             }
             }


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


         findConditions(content) {
         formatLocalDraftTime(timestamp) {
             const conditions = [];
             if (!timestamp) {
            const pattern =
                return '';
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
             }
             let match;


             while ((match = pattern.exec(content)) !== null) {
             try {
                 conditions.push({
                 return new Date(timestamp).toLocaleTimeString([], {
                     type: match[1].toLowerCase(),
                     hour: '2-digit',
                     expression: match[2].trim(),
                     minute: '2-digit',
                     index: match.index
                     second: '2-digit'
                 });
                 });
            } catch (error) {
                return '';
             }
             }
        },


             return conditions;
        updateLocalDraftIndicator() {
             if (!this.localDraftStatus) {
                return;
            }
 
            if (this.state.localDraftSavedAt) {
                const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);
 
                this.updateLocalDraftStatus(
                    time ? 'Saved locally at ' + time : 'Saved locally',
                    'saved'
                );
 
                return;
            }
 
            this.updateLocalDraftStatus('No local draft', 'empty');
         },
         },


         findConditionVariables(content) {
         saveDraft() {
             const variables = [];
             if (!this.state.dirty) {
            const conditions = this.findConditions(content);
                return false;
            }


             conditions.forEach(condition => {
             const snapshot = this.getDraftSnapshot();
                if (
            const id = this.getDraftId(snapshot.preloadTitle);
                    condition.type !== 'if' &&
            const storage = this.getDraftStorage();
                    condition.type !== 'elseif'
                ) {
                    return;
                }


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


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


                    if (!variables.includes(upper)) {
            if (saved) {
                        variables.push(upper);
                this.state.localDraftSavedAt = snapshot.savedAt;
                    }
                this.state.localDraftAvailable = true;
                 });
                this.updateLocalDraftIndicator();
             });
            } else {
                this.state.localDraftAvailable = false;
                 this.updateLocalDraftStatus('Could not save local draft', 'error');
             }


             return variables;
             return saved;
         },
         },


         analyzePreload(content) {
         clearDraft(title) {
             const variables = this.findVariables(content);
             const storage = this.getDraftStorage();
             const conditions = this.findConditions(content);
             const id = this.getDraftId(title);
             const conditionVariables =
 
                 this.findConditionVariables(content);
             if (storage.drafts && storage.drafts[id]) {
                 delete storage.drafts[id];
            }
 
            if (storage.active === id) {
                storage.active = null;
            }


             return {
             this.setDraftStorage(storage);
                variables,
                conditions,
                conditionVariables
            };
        },


        // Config
            this.state.localDraftSavedAt = null;
            this.state.localDraftAvailable = false;


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


         normalizeConfig(config) {
         getMostRecentDraft() {
             if (
            const storage = this.getDraftStorage();
                !config ||
 
                typeof config !== 'object' ||
             if (!storage.drafts || !Object.keys(storage.drafts).length) {
                Array.isArray(config)
                 return null;
            ) {
                 config = this.emptyConfig();
             }
             }


             if (
             if (storage.active && storage.drafts[storage.active]) {
                 !config.settings ||
                 return {
                typeof config.settings !== 'object' ||
                    id: storage.active,
                Array.isArray(config.settings)
                    draft: storage.drafts[storage.active]
            ) {
                 };
                 config.settings = {};
             }
             }


             if (
             let latestId = null;
                 !config.fields ||
            let latestDraft = null;
                typeof config.fields !== 'object' ||
 
                Array.isArray(config.fields)
            Object.entries(storage.drafts).forEach(([id, draft]) => {
            ) {
                 if (!draft || typeof draft !== 'object') {
                 config.fields = {};
                    return;
             }
                }
 
                if (
                    !latestDraft ||
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                ) {
                    latestId = id;
                    latestDraft = draft;
                 }
             });


             if (!config.fields.PAGE) {
             if (!latestDraft) {
                 config.fields.PAGE = {
                 return null;
                    label: 'Page Name',
                    description: 'Name of the page.',
                    type: 'page',
                    required: true,
                    namespace: 'Main',
                    'allow-new': true
                };
             }
             }
            return config;
        },
        createDefaultField(name, analysis) {
            const isConditionVariable =
                analysis.conditionVariables.includes(name);


             return {
             return {
                 label: this.humanizeName(name),
                 id: latestId,
                 description: '',
                 draft: latestDraft
                type: isConditionVariable ? 'boolean' : 'text'
             };
             };
         },
         },


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


        prepareConfigForVariables(config, analysis) {
            const draft = result.draft;
             config = this.normalizeConfig(config);
             const title = String(draft.preloadTitle || '').trim();
            const displayTitle = title || 'an untitled preload';


             const existing = config.fields || {};
             const savedAt = draft.savedAt
            const fields = {};
                ? new Date(draft.savedAt).toLocaleString()
                : '';


             fields.PAGE = existing.PAGE || {
             const message =
                 label: 'Page Name',
                 'Preload Editor found unsaved local work for ' +
                 description: 'Name of the page.',
                 displayTitle +
                 type: 'page',
                 (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                required: true,
                 '\n\nRestore it?';
                namespace: 'Main',
                 'allow-new': true
            };


             analysis.variables.forEach(name => {
             const restore = await this.createConfirmDialog(
                 if (name === 'PAGE') {
                 'Restore unsaved work',
                    return;
                message,
                 }
                'Restore',
                 'Discard'
            );


                 fields[name] =
            if (!restore) {
                    existing[name] ||
                 this.clearDraft(title);
                    this.createDefaultField(name, analysis);
                return false;
             });
             }


             Object.keys(existing).forEach(name => {
             let config = this.emptyConfig();
                const upper = name.toUpperCase();


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


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


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


            if (
                conditions: Array.isArray(draft.conditions)
                 !config ||
                    ? draft.conditions.slice()
                typeof config !== 'object' ||
                    : [],
                 Array.isArray(config)
 
            ) {
                 selectedVariable: String(draft.selectedVariable || 'PAGE'),
                return {
 
                     valid: false,
                 deletedVariables: Array.isArray(draft.deletedVariables)
                    errors: ['Config must be an object.'],
                    ? draft.deletedVariables
                    warnings: []
                        .map(name => String(name).toUpperCase())
                };
                        .filter(name => name !== 'PAGE')
            }
                     : [],
 
                mode: draft.mode || 'edit',


            if (
                dirty: hasDirtyFlags
                !config.fields ||
                    ? !!(draft.dirtyPreload || draft.dirtyConfig)
                typeof config.fields !== 'object' ||
                    : true,
                Array.isArray(config.fields)
            ) {
                errors.push('"fields" must be an object.');


                 return {
                 dirtyPreload: hasDirtyFlags
                     valid: false,
                     ? !!draft.dirtyPreload
                     errors,
                     : true,
                    warnings
                };
            }


            const configured =
                 dirtyConfig: hasDirtyFlags
                 Object.keys(config.fields).map(
                     ? !!draft.dirtyConfig
                     name => name.toUpperCase()
                    : true,
                );


            analysis.variables.forEach(name => {
                 localDraftSavedAt: Number(draft.savedAt) || null,
                 if (!configured.includes(name)) {
                 localDraftAvailable: true
                    errors.push(
             };
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                 }
             });


             configured.forEach(name => {
             this.reanalyze();
                if (!analysis.variables.includes(name)) {
            this.renderEditor();
                    warnings.push(
            this.updateLocalDraftIndicator();
                        'Field "' +
 
                        name +
            this.setStatus(
                        '" is not used by the preload.'
                'Restored unsaved local work from this browser.',
                    );
                'warning'
                 }
            );
 
            mw.notify('Unsaved Preload Editor work restored.', {
                 type: 'success'
             });
             });


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


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


                    if (!field.type) {
        async getPage(title) {
                        warnings.push(
            const response = await new mw.Api().get({
                            'Field "' +
                action: 'query',
                            name +
                prop: 'info|revisions',
                            '" has no type.'
                titles: title,
                        );
                rvprop: 'content',
                    }
                rvslots: 'main',
                formatversion: 2
            });


                    if (
            const page =
                        (
                response &&
                            field.type === 'select' ||
                response.query &&
                            field.type === 'multiselect'
                response.query.pages &&
                        ) &&
                response.query.pages[0];
                        !field.source &&
 
                        !Array.isArray(field.options)
            if (!page || page.missing) {
                    ) {
                return null;
                        warnings.push(
            }
                            'Field "' +
 
                            name +
            const content =
                            '" is a ' +
                page.revisions &&
                            field.type +
                page.revisions[0] &&
                            ' without a source or manual options.'
                page.revisions[0].slots &&
                        );
                page.revisions[0].slots.main &&
                    }
                 page.revisions[0].slots.main.content;
                 }
            );


             return {
             return {
                 valid: errors.length === 0,
                 title: page.title || title,
                 errors,
                content: typeof content === 'string' ? content : '',
                warnings
                 contentmodel: page.contentmodel || 'wikitext'
             };
             };
         },
         },


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


         transformationObject(
         async searchPages(query) {
             transform,
             const response = await new mw.Api().get({
             prefix,
                action: 'query',
             suffix,
                list: 'search',
            from,
                srsearch: query,
            to
                srlimit: 10,
         ) {
                srnamespace: 10,
             if (!transform) {
                formatversion: 2
                 return null;
            });
 
             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;
             }
             }


             switch (transform) {
             if (contentModel) {
                 case 'remove-prefix':
                 params.contentmodel = contentModel;
                    return prefix
            }
                        ? {
                            transform: 'remove-prefix',
                            prefix
                        }
                        : null;


                case 'remove-suffix':
            return new mw.Api().postWithToken('csrf', params);
                    return suffix
        },
                        ? {
                            transform: 'remove-suffix',
                            suffix
                        }
                        : null;


                case 'replace':
        /*
                    return from === ''
        * Change the content model of an existing page.
                        ? null
        *
                        : {
        * This is the API equivalent of using
                            transform: 'replace',
        * Special:ChangeContentModel manually.
                            from,
        *
                            to: to || ''
        * The page must already exist.
                        };
        */
 
        async changeContentModel(title, model, summary) {
                default:
            return new mw.Api().postWithToken('csrf', {
                    return null;
                action: 'changecontentmodel',
            }
                title,
                model,
                reason: summary || 'Changed content model with Preload Editor'
            });
         },
         },


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


        createSection(title, className) {
            if (!page) {
            const section =
                 return this.savePage(
                 $('<section>')
                     title,
                     .addClass('preload-editor-section');
                    content,
                    summary,
                    true,
                    'json'
                );
            }


             if (className) {
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                 section.addClass(className);
                 await this.changeContentModel(
                    title,
                    'json',
                    'Changed preload config content model to JSON'
                );
             }
             }


             $('<h2>')
             return this.savePage(
                 .addClass('preload-editor-section-title')
                 title,
                 .text(title)
                content,
                 .appendTo(section);
                 summary,
                 false
            );
        },


            return section;
        // =========================================================
         },
        // Config import helpers
         // =========================================================


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


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


             if (callback) {
             return title + '/config.json';
                 button.on(
        },
                     'click.preloadEditor',
 
                     callback
        /*
        * 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 button;
         },
         },


         fieldRow(label, input, description) {
         /*
             const row =
        * Normalize imported field names to the same uppercase
                $('<div>')
        * convention used throughout the editor.
                    .addClass('preload-editor-field');
        */
        getImportableFields(sourceConfig) {
             const fields = sourceConfig && sourceConfig.fields;


             $('<label>')
             if (
                 .addClass('preload-editor-label')
                 !fields ||
                 .text(label)
                typeof fields !== 'object' ||
                .appendTo(row);
                 Array.isArray(fields)
 
             ) {
             if (description) {
                 return {};
                 $('<div>')
                    .addClass('preload-editor-help')
                    .text(description)
                    .appendTo(row);
             }
             }


             row.append(input);
             const result = {};
            return row;
        },


        textInput(value, placeholder) {
             Object.entries(fields).forEach(([name, field]) => {
             return $('<input>')
                const upper = String(name || '').trim().toUpperCase();
                .attr({
                    type: 'text',
                    value:
                        value === undefined ||
                        value === null
                            ? ''
                            : value,
                    placeholder: placeholder || ''
                })
                .addClass('preload-editor-input');
        },


        textarea(value) {
                if (!upper || upper === 'PAGE') {
            return $('<textarea>')
                    return;
                 .val(
                }
                     value === undefined ||
 
                     value === null
                 if (
                        ? ''
                     !field ||
                        : value
                     typeof field !== 'object' ||
                 )
                    Array.isArray(field)
                .addClass('preload-editor-textarea');
                 ) {
        },
                    return;
                }


        checkbox(checked) {
                 const clone = this.cloneConfigField(field);
            return $('<input>')
                .attr('type', 'checkbox')
                .prop('checked', !!checked)
                 .addClass('preload-editor-checkbox');
        },


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


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


             return select;
             return result;
         },
         },


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


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


            const {
                 $('<h2>')
                 view,
                    .text('Import variable definitions')
                inputHandler
                    .appendTo(box);
            } = this.editor;


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


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


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


        getEditorView() {
                    const close = this.createButton(
            return this.editorView;
                        'Close',
        },
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );
 
                    emptyButtons.append(close);
                    box.append(emptyButtons);
                    overlay.append(box);
 
                    $(document.body).append(overlay);


        getEditorContent() {
                    overlay.attr('tabindex', '-1');
            if (
                    overlay.trigger('focus');
                this.editorView &&
                this.editorView.state
            ) {
                return this.editorView.state.doc.toString();
            }


            return this.state.preloadContent || '';
                    return;
        },
                }


        setEditorContent(content) {
                const search = this.textInput('', 'Search variables...')
            content = String(content || '');
                    .addClass('preload-editor-import-search');


            if (!this.editorView) {
                const searchWrap = $('<div>')
                this.state.preloadContent = content;
                    .addClass('preload-editor-import-search-wrap')
                return;
                    .append(search);
            }


            const current =
                 box.append(searchWrap);
                 this.editorView.state.doc.toString();


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


            this.editorView.dispatch({
                const selectAll = this.createButton(
                changes: {
                     'Select all',
                     from: 0,
                     '',
                     to: this.editorView.state.doc.length,
                     () => {
                     insert: content
                        list
                }
                            .find('input[type="checkbox"]:visible')
            });
                            .prop('checked', true);
        },


        async mountCodeMirror(textarea) {
                        updateSummary();
            return new Promise((resolve, reject) => {
                    }
                 let settled = false;
                 );


                 const cleanup = () => {
                 const deselectAll = this.createButton(
                     mw.hook('dev.CCM.ready').remove(
                     'Deselect all',
                        onReady
                    '',
                     );
                     () => {
                    mw.hook('dev.CCM.load').remove(
                        list
                        onLoad
                            .find('input[type="checkbox"]:visible')
                    );
                            .prop('checked', false);
                };


                const onReady = cm => {
                        updateSummary();
                    if (
                        settled ||
                        !cm ||
                        cm.textarea !== textarea ||
                        !cm.view
                    ) {
                        return;
                     }
                     }
                );


                    settled = true;
                controls.append(selectAll, deselectAll);
                    cleanup();
                box.append(controls);


                    const view = cm.view;
                const list = $('<div>')
                    .addClass('preload-editor-import-list');


                    const inputHandler = () => {
                const localFields =
                        this.state.preloadContent =
                    this.state.config && this.state.config.fields
                            view.state.doc.toString();
                        ? this.state.config.fields
                        : {};


                        this.state.dirty = true;
                names.forEach(name => {
                        this.reanalyze();
                    const existing = !!localFields[name];
                    const field = fields[name];


                        this.renderVariablesBySelector();
                    const type = field && field.type
                         this.renderAnalysisBySelector();
                         ? String(field.type)
                         this.renderConfigPreviewBySelector();
                         : 'text';
                    };


                     view.dom.addEventListener(
                     const label = field && field.label
                         'input',
                         ? String(field.label)
                         inputHandler
                         : this.humanizeName(name);
                    );


                     view.dom.classList.add(
                     const row = $('<label>')
                         'preload-editor-codemirror'
                         .addClass('preload-editor-import-row')
                    );
                        .attr('data-variable', name)
 
                         .attr(
                    const wrapper =
                             'data-search',
                         view.dom.closest(
                            (name + ' ' + label + ' ' + type).toLowerCase()
                             '.ext-codemirror-wrapper'
                         );
                         );


                     if (wrapper) {
                     const checkbox = this.checkbox(false)
                         wrapper.classList.add(
                         .attr('data-import-variable', name)
                            'preload-editor-codemirror-wrapper'
                        .addClass('preload-editor-import-checkbox');
                        );
                    }


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


                     this.editorView = view;
                     const header = $('<span>')
                        .addClass('preload-editor-import-header');


                     this.state.preloadContent =
                     $('<strong>')
                         view.state.doc.toString();
                        .text(name)
                         .appendTo(header);


                     resolve(view);
                     $('<span>')
                };
                        .addClass('preload-editor-import-type')
                        .text(type)
                        .appendTo(header);


                const onLoad = loader => {
                    const meta = $('<span>')
                    if (
                        .addClass('preload-editor-import-meta');
                        settled ||
                        typeof loader !== 'function'
                    ) {
                        return;
                    }


                     try {
                     $('<span>')
                        loader(textarea);
                         .text(label)
                    } catch (error) {
                         .appendTo(meta);
                         settled = true;
                        cleanup();
                         reject(error);
                    }
                };


                mw.hook('dev.CCM.ready').add(onReady);
                    const status = $('<span>')
                mw.hook('dev.CCM.load').add(onLoad);
                        .addClass('preload-editor-import-status')
            });
                        .toggleClass('is-existing', existing)
        },
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');


        // Main UI
                    content.append(header, meta, status);
                    row.append(checkbox, content);
                    list.append(row);
                });


        init() {
                box.append(list);
            const root = $('#mw-content-text');
 
                const summary = $('<div>')
                    .addClass('preload-editor-import-summary');
 
                const updateSummary = () => {
                    const selected = list.find(
                        'input[type="checkbox"]:checked'
                    ).length;
 
                    const existingSelected = list
                        .find('input[type="checkbox"]:checked')
                        .filter(function () {
                            const name = $(this).attr(
                                'data-import-variable'
                            );
 
                            return !!localFields[name];
                        }).length;
 
                    let text =
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';
 
                    if (existingSelected) {
                        text +=
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


            if (!root.length) {
                    summary.text(text);
                return;
            }


            this.root =
                     importButton.prop('disabled', selected === 0);
                $('<div>')
                };
                     .attr('id', 'preload-editor')
                    .addClass('preload-editor');


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


        renderShell() {
                    list.find('.preload-editor-import-row').each(function () {
            this.destroyEditor();
                        const row = $(this);
            this.root.empty();
                        const haystack = String(
                            row.attr('data-search') || ''
                        );


            const loader =
                        row.toggle(!query || haystack.includes(query));
                this.createSection('Preload');
                    });
                };


            const titleInput =
                 search.on(
                 this.textInput(
                     'input.preloadEditor',
                    this.state.preloadTitle,
                     filterRows
                     'Template:Example/Preload'
                ).attr(
                    'id',
                     'preload-editor-title-input'
                 );
                 );


            const loadButton =
                 list.on(
                 this.createButton(
                     'change.preloadEditor',
                     'Load',
                     'input[type="checkbox"]',
                     'preload-editor-button-primary',
                     updateSummary
                     () => this.loadExisting(titleInput.val())
                 );
                 );


            const newButton =
                const buttons = $('<div>')
                this.createButton(
                     .addClass('preload-editor-prompt-buttons');
                    'New',
                     '',
                    () => this.startNew()
                );


            const sampleButton =
                const cancel = this.createButton(
                this.createButton(
                     'Cancel',
                     'Load Sample Page',
                     '',
                     '',
                     () => this.loadSamplePage()
                     () => {
                        overlay.remove();
                        resolve(null);
                    }
                 );
                 );


            const loadRow =
                const importButton = this.createButton(
                $('<div>')
                    'Import selected',
                     .addClass('preload-editor-toolbar')
                     'preload-editor-button-primary',
                     .append(
                     () => {
                         titleInput,
                         const selected = [];
                        loadButton,
                        newButton,
                        sampleButton
                    );


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


            this.status =
                        overlay.remove();
                $('<div>')
                        resolve(selected);
                     .addClass('preload-editor-status');
                     }
                );


            this.root.append(this.status);
                buttons.append(cancel, importButton);
                box.append(summary, buttons);
                overlay.append(box);


            this.workspace =
                 $(document.body).append(overlay);
                 $('<div>')
                    .addClass('preload-editor-workspace');


            this.root.append(this.workspace);
                overlay.attr('tabindex', '-1');
            this.renderWelcome();
                overlay.trigger('focus');
        },


        renderWelcome() {
                updateSummary();
            this.workspace.empty();
                search.trigger('focus');


            const section =
                const close = event => {
                this.createSection('Get started');
                    if (event.key === 'Escape') {
                        cancel.trigger('click');
                    }
                };


            $('<p>')
                 overlay.on(
                 .text(
                     'keydown.preloadEditor',
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                    close
                )
                 );
                 .appendTo(section);


            const tips =
                 overlay.on(
                 $('<ul>')
                     'click.preloadEditor',
                     .addClass('preload-editor-tips');
                    event => {
 
                        if (event.target === overlay.get(0)) {
            [
                            cancel.trigger('click');
                'Existing preload: loads the preload and its config.json if available.',
                        }
                'New preload: starts with the standard Preload Template structure.',
                     }
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                );
            ].forEach(text => {
                $('<li>')
                     .text(text)
                    .appendTo(tips);
             });
             });
        },


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


        setStatus(message, type) {
             if (!source) {
             if (!this.status) {
                 return;
                 return;
             }
             }


             this.status
             const configTitle = this.normalizeConfigTitle(source);
                .removeClass(
                    'is-error',
                    'is-success',
                    'is-warning',
                    'is-loading'
                );


             if (type) {
             this.setStatus(
                 this.status.addClass('is-' + type);
                 'Loading source config...',
            }
                'loading'
            );


             this.status.text(message || '');
             try {
        },
                const page = await this.getPage(configTitle);


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


        async loadExisting(title) {
                let sourceConfig;
            title = String(title || '').trim();


            if (!title) {
                try {
                 mw.notify(
                    sourceConfig = JSON.parse(page.content);
                     'Enter a preload page title first.',
                 } catch (error) {
                     { type: 'warn' }
                     throw new Error(
                );
                        'The source config.json contains invalid JSON: ' +
                 return;
                        error.message
            }
                     );
                 }


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


            try {
                if (
                const page = await this.getPage(title);
                    !sourceConfig.fields ||
                    typeof sourceConfig.fields !== 'object' ||
                    Array.isArray(sourceConfig.fields)
                ) {
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }


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


                     this.renderMissingPage(
                const selected =
                         title,
                     await this.createImportDefinitionsDialog(
                         suggestions
                         configTitle,
                        fields
                    );
 
                if (selected === null) {
                    this.setStatus(
                        'Variable import cancelled.',
                         'warning'
                     );
                     );


                    return;
                }
                if (!selected.length) {
                     this.setStatus(
                     this.setStatus(
                         'Preload not found.',
                         'No variable definitions were imported.',
                         'warning'
                         'warning'
                     );
                     );
Line 920: Line 1,024:
                 }
                 }


                 await this.loadDefinition(
                 if (!this.state.config) {
                     page.title,
                     this.state.config = this.emptyConfig();
                    page.content
                 }
                 );


                 this.setStatus(
                 if (!this.state.config.fields) {
                    'Preload loaded.',
                    this.state.config.fields = {};
                    'success'
                 }
                );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                    error
                 );


                 this.setStatus(
                 const imported = [];
                    error.message ||
                 const replaced = [];
                        'Could not load preload.',
                    'error'
                 );
            }
        },


        async findSimilarPreloads(title) {
                selected.forEach(name => {
            let query =
                     if (name === 'PAGE') {
                title
                        return;
                     .replace(/\/Preload$/i, '')
                     }
                     .trim();


            if (!query) {
                    const field = fields[name];
                query = title;
 
            }
                    if (!field) {
                        return;
                    }
 
                    if (this.state.config.fields[name]) {
                        replaced.push(name);
                    } else {
                        imported.push(name);
                    }
 
                    const clone = this.cloneConfigField(field);
 
                    if (!clone) {
                        return;
                    }


            try {
                     this.state.config.fields[name] = clone;
                const results =
                     await this.searchPages(query);


                return results.filter(
                    /*
                     result =>
                    * If this variable was previously deleted,
                         /\/Preload$/i.test(
                    * importing its definition explicitly should
                             result.title
                    * restore it.
                        )
                    */
                );
                     if (Array.isArray(this.state.deletedVariables)) {
            } catch (error) {
                         this.state.deletedVariables =
                console.error(
                             this.state.deletedVariables.filter(
                    'Preload Editor search:',
                                deletedName =>
                     error
                                    String(deletedName).toUpperCase() !== name
                 );
                            );
                     }
                 });


                 return [];
                 /*
            }
                * Keep PAGE automatic regardless of what the
        },
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();


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


            const section =
                /*
                this.createSection(
                * Keep the current selection when possible.
                     'Preload not found'
                * Otherwise select the first imported definition.
                */
                const selectedStillExists = !!(
                    this.state.config.fields[
                        this.state.selectedVariable
                     ]
                 );
                 );


            $('<p>')
                 if (
                 .text(
                     !selectedStillExists ||
                     'No preload exists at "' +
                     this.state.selectedVariable === 'PAGE'
                    title +
                 ) {
                     '".'
                    this.state.selectedVariable =
                 )
                        selected[0] ||
                .appendTo(section);
                        'PAGE';
                }


            if (suggestions.length) {
                 this.reanalyze();
                 $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);


                 const list =
                 this.renderVariablesBySelector();
                    $('<div>')
                this.renderVariableConfigurationBySelector();
                        .addClass(
                this.renderAnalysisBySelector();
                            'preload-editor-suggestions'
                this.updateEditorTools();
                        );


                 suggestions.forEach(result => {
                 this.saveDraft();
                    list.append(
                        this.createButton(
                            result.title,
                            'preload-editor-suggestion',
                            () =>
                                this.loadExisting(
                                    result.title
                                )
                        )
                    );
                });


                 section.append(list);
                 let status =
            }
                    'Imported ' +
                    selected.length +
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                    '.';


            section.append(
                if (replaced.length) {
                this.createButton(
                     status +=
                     'Create this preload',
                        ' Replaced: ' +
                    'preload-editor-button-primary',
                        replaced.join(', ') +
                    () => this.startNew(title)
                        '.';
                 )
                 }
            );


            this.workspace.append(section);
                this.setStatus(status, 'success');
        },


        async startNew(title) {
                mw.notify(status, {
            title = String(title || '').trim();
                    type: 'success'
                });
            } catch (error) {
                console.error(
                    'Preload Editor variable import:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not import variable definitions.',
                    'error'
                );


            this.state = {
                 mw.notify(
                 preloadTitle: title,
                    error.message ||
                preloadSource: '',
                        'Could not import variable definitions.',
                preloadContent: this.defaults.preload,
                    {
                config: this.emptyConfig(),
                        type: 'error'
                variables: ['PAGE'],
                    }
                conditions: [],
                 );
                mode: 'new',
             }
                 dirty: true
        },
             };


            this.renderEditor();
        // =========================================================
        // Preload parsing
        // =========================================================


             this.setStatus(
        extractIncludeonly(source) {
                'Creating a new preload.',
             const match = String(source || '').match(
                 'success'
                 /<includeonly>([\s\S]*?)<\/includeonly>/i
             );
             );
            return match
                ? match[1].trim()
                : String(source || '').trim();
         },
         },


         async loadSamplePage() {
         findVariables(content) {
             const result =
             const variables = [];
                await this.createPromptDialog(
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                    'Load Sample Page',
                    'Enter the title of a normal wiki page to use as the starting point.'
                );


             if (!result) {
             let match;
                return;
            }


             this.setStatus(
             while ((match = pattern.exec(content)) !== null) {
                 'Loading sample page...',
                 const name = match[1].toUpperCase();
                'loading'
            );


            try {
                 if (!variables.includes(name)) {
                 const page =
                     variables.push(name);
                    await this.getPage(result);
 
                if (!page) {
                     throw new Error(
                        'Sample page not found: ' +
                        result
                    );
                 }
                 }
            }


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


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


                this.reanalyze();
            let match;
                this.renderEditor();


                this.setStatus(
            while ((match = pattern.exec(content)) !== null) {
                    'Sample page loaded.',
                conditions.push({
                    'success'
                    type: match[1].toLowerCase(),
                );
                     expression: match[2].trim(),
            } catch (error) {
                     index: match.index
                console.error(
                 });
                     'Preload Editor sample:',
            }
                     error
                 );


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


         convertSampleToPreload(source) {
         findConditionVariables(content) {
             let content =
             const variables = [];
                 String(source || '').trim();
 
            this.findConditions(content).forEach(condition => {
                 if (
                    condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }


            const include =
                const matches =
                content.match(
                    condition.expression.match(
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                        /[A-Za-z0-9_-]+/g
                );
                    ) || [];


            if (include) {
                matches.forEach(name => {
                content = include[1].trim();
                    name = name.toUpperCase();
            }


            content =
                     if (!variables.includes(name)) {
                content
                         variables.push(name);
                     .replace(
                    }
                         /<noinclude>[\s\S]*?<\/noinclude>/gi,
                });
                        ''
            });
                    )
                    .trim();


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


         createPromptDialog(title, message) {
         analyzePreload(content) {
             return new Promise(resolve => {
             return {
                 const overlay =
                 variables: this.findVariables(content),
                    $('<div>')
                conditions: this.findConditions(content),
                        .addClass(
                conditionVariables:
                            'preload-editor-prompt-overlay'
                    this.findConditionVariables(content)
                        );
            };
        },


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


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


                $('<p>')
        emptyConfig() {
                     .text(message)
            return {
                    .appendTo(box);
                settings: {
                     incomplete: 'add-stub'
                },


                 const input = this.textInput();
                 fields: {
                    PAGE: this.getAutomaticPageField()
                }
            };
        },


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


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


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


                            if (!value) {
            config.fields.PAGE =
                                return;
                this.getAutomaticPageField();
                            }


                            overlay.remove();
            return config;
                            resolve(value);
        },
                        }
 
                     );
        createDefaultField(name, analysis) {
            return {
                label: this.humanizeName(name),
                description: '',
                type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                     : 'text'
            };
        },


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


                input.trigger('focus');
        prepareConfigForVariables(config, analysis) {
            config = this.normalizeConfig(config);


                input.on(
            const existing = config.fields || {};
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


                        if (event.key === 'Escape') {
            const deleted = new Set(
                            cancel.trigger('click');
                Array.isArray(this.state.deletedVariables)
                        }
                    ? this.state.deletedVariables.map(
                     }
                        name => String(name).toUpperCase()
                );
                    )
             });
                     : []
        },
            );
 
             const fields = {};


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


             let config = this.emptyConfig();
             analysis.variables.forEach(name => {
                if (
                    name === 'PAGE' ||
                    deleted.has(name)
                ) {
                    return;
                }


            const configTitle =
                fields[name] =
                title.replace(/\/+$/, '') +
                    existing[name] ||
                '/config.json';
                    this.createDefaultField(
                        name,
                        analysis
                    );
            });


             const configPage =
             Object.keys(existing).forEach(name => {
                 await this.getPage(configTitle);
                 const upper = name.toUpperCase();


            if (configPage) {
                if (
                try {
                    upper !== 'PAGE' &&
                     config =
                     !fields[upper] &&
                        JSON.parse(
                    !deleted.has(upper)
                            configPage.content
                 ) {
                        );
                     fields[upper] =
                 } catch (error) {
                         existing[name];
                     throw new Error(
                         'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                 }
                 }
             }
             });


             const analysis =
             config.fields = fields;
                this.analyzePreload(content);


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


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


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


             const layout =
             if (
                 $('<div>')
                !config.fields ||
                     .addClass(
                typeof config.fields !== 'object' ||
                         'preload-editor-layout'
                 Array.isArray(config.fields)
                     );
            ) {
                return {
                     valid: false,
                    errors: [
                         '"fields" must be an object.'
                     ],
                    warnings
                };
            }


             const left =
             const configured =
                 $('<div>')
                 Object.keys(
                     .addClass(
                     config.fields
                         'preload-editor-left'
                ).map(
                    );
                    name =>
                         name.toUpperCase()
                );


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


             const editorSection =
             if (!configured.includes('PAGE')) {
                 this.createSection(
                 errors.push(
                     'Preload',
                     'PAGE must always be configured.'
                    'preload-editor-main-section'
                 );
                 );
            }


             const meta =
             Object.entries(config.fields).forEach(([name, field]) => {
                 $('<div>')
                 if (
                     .addClass(
                    !field ||
                         'preload-editor-meta'
                    typeof field !== 'object' ||
                    Array.isArray(field)
                ) {
                     errors.push(
                         'Field "' +
                        name +
                        '" must be an object.'
                     );
                     );


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


            if (this.state.mode === 'new') {
                if (!field.type) {
                 $('<span>')
                    warnings.push(
                     .addClass(
                        'Field "' +
                         'preload-editor-badge'
                        name +
                     )
                        '" has no type.'
                    .text('NEW')
                    );
                    .appendTo(meta);
                }
            }
               
                 if (
                    field.type === 'file'
                ) {
                     if (
                        field.accept !== undefined &&
                         !Array.isArray(field.accept)
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }


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


            const textarea =
                     if (
                this.textarea(
                         field.filename !== undefined &&
                    this.state.preloadContent
                         typeof field.filename !== 'string'
                )
                     ) {
                     .attr(
                        errors.push(
                         'id',
                            'File field "' +
                         'preload-editor-content'
                            name +
                     )
                            '" must have "filename" as a string.'
                    .addClass(
                        );
                        'preload-editor-content'
                    }
                    );


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


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


            left.append(editorSection);
                    if (
 
                        !field.filename
            const analysisSection =
                    ) {
                this.createSection('Analysis');
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


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


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


            const variablesSection =
                    if (
                this.createSection('Variables');
                        field.filetext !== undefined &&
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }


            const variableContainer =
                    if (
                $('<div>')
                        field.accept !== undefined &&
                     .addClass(
                        (
                        'preload-editor-variables'
                            !Array.isArray(field.accept) ||
                     );
                            field.accept.some(
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                            )
                        )
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                     }
                }
            });


             variablesSection.append(
             return {
                 variableContainer
                valid: !errors.length,
             );
                 errors,
                warnings
             };
        },


            const configSection =
        // =========================================================
                this.createSection(
        // Transformation helpers
                    'Generated configuration'
        // =========================================================
                );


             const configPreview =
        transformationObject(
                $('<pre>')
            transform,
                    .addClass(
            prefix,
                        'preload-editor-config-preview'
             suffix,
                    );
            from,
            to
        ) {
            if (!transform) {
                return null;
            }


             configSection.append(configPreview);
             switch (transform) {
                case 'remove-prefix':
                    return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;


            const actions =
                case 'remove-suffix':
                 $('<div>')
                    return suffix
                     .addClass(
                        ? {
                         'preload-editor-actions'
                            transform,
                    );
                            suffix
                        }
                        : null;
 
                 case 'replace':
                     return from === ''
                        ? null
                         : {
                            transform,
                            from,
                            to: to || ''
                        };


            const save =
                 default:
                 this.createButton(
                     return null;
                     'Save Preload + Config',
            }
                    'preload-editor-button-primary',
        },
                    () => this.saveAll()
                );


            const savePreload =
        // =========================================================
                this.createButton(
        // UI helpers
                    'Save Preload Only',
        // =========================================================
                    '',
                    () => this.savePreloadOnly()
                );


             actions.append(save, savePreload);
        createSection(title, className) {
             const section = $('<section>')
                .addClass('preload-editor-section');


             right.append(
             if (className) {
                 analysisSection,
                 section.addClass(className);
                variablesSection,
             }
                configSection,
                actions
             );


             layout.append(left, right);
             $('<h2>')
            this.workspace.append(layout);
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);


             this.reanalyze();
             return section;
            this.renderVariables(variableContainer);
        },
            this.renderAnalysis(analysisContainer);
            this.renderConfigPreview(configPreview);


             this.mountCodeMirror(textarea.get(0))
        createButton(label, className, callback) {
                 .catch(error => {
             const button = $('<button>')
                    console.error(
                 .attr('type', 'button')
                        'Preload Editor CodeMirror:',
                .addClass('preload-editor-button')
                        error
                .text(label);
                    );


                    this.setStatus(
            if (className) {
                        error.message ||
                 button.addClass(className);
                            'Could not initialize CodeMirror.',
            }
                        'error'
                    );
                 });
        },


        reanalyze() {
            if (callback) {
            const source = this.getEditorContent();
                button.on(
            const content = this.extractIncludeonly(source);
                    'click.preloadEditor',
             const analysis = this.analyzePreload(content);
                    callback
                );
             }


             this.state.preloadContent = source;
             return button;
            this.state.variables = analysis.variables;
        },
            this.state.conditions = analysis.conditions;


             this.state.config =
        fieldRow(label, input, description) {
                 this.prepareConfigForVariables(
             const row = $('<div>')
                    this.state.config ||
                 .addClass('preload-editor-field');
                        this.emptyConfig(),
                    analysis
                );


             this.analysis = analysis;
             $('<label>')
        },
                .addClass('preload-editor-label')
                .text(label)
                .appendTo(row);


        renderAnalysis(container) {
            if (description) {
            container.empty();
                $('<div>')
                    .addClass('preload-editor-help')
                    .text(description)
                    .appendTo(row);
            }


             const analysis =
             row.append(input);
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


             const variableCount =
             return row;
                analysis.variables.length;
        },


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


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


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


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


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


             if (validation.errors.length) {
             return select;
                const errors =
        },
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-errors'
                        );


                validation.errors.forEach(error => {
        // =========================================================
                    $('<li>')
        // In-wiki dialogs
                        .text(error)
        // =========================================================
                        .appendTo(errors);
                });


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


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


                 validation.warnings.forEach(warning => {
                 $('<h2>')
                    $('<li>')
                    .text(title)
                        .text(warning)
                    .appendTo(box);
                        .appendTo(warnings);
                });


                 container.append(warnings);
                 const messageLines =
            }
                    String(message || '').split('\n');


            if (
                 messageLines.forEach(line => {
                 !validation.errors.length &&
                    if (line === '') {
                !validation.warnings.length
                        $('<div>')
            ) {
                            .addClass(
                container.append(
                                'preload-editor-prompt-spacer'
                    $('<div>')
                            )
                        .addClass(
                            .appendTo(box);
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },


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


            if (container && container.length) {
                    $('<p>')
                this.renderAnalysis(container);
                        .text(line)
            }
                        .appendTo(box);
        },
                });


        renderVariables(container) {
                const buttons = $('<div>')
            container.empty();
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


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


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


            const ordered = ['PAGE'];
                buttons.append(cancel, confirm);
                box.append(buttons);
                overlay.append(box);


            variables.forEach(name => {
                 $(document.body).append(overlay);
                 if (
                    name !== 'PAGE' &&
                    !ordered.includes(name)
                ) {
                    ordered.push(name);
                }
            });


            Object.keys(
                 const close = value => {
                 this.state.config.fields || {}
                    if (value === 'Escape') {
            ).forEach(name => {
                        cancel.trigger('click');
                const upper = name.toUpperCase();
                    }
                };


                 if (!ordered.includes(upper)) {
                 overlay.on(
                     ordered.push(upper);
                     'keydown.preloadEditor',
                }
                    event => {
            });
                        close(event.key);
                    }
                );


            ordered.forEach(name => {
                overlay.attr('tabindex', '-1');
                 const field =
                 overlay.trigger('focus');
                    this.state.config.fields[name] ||
                    this.createDefaultField(
                        name,
                        analysis
                    );


                 this.state.config.fields[name] = field;
                 overlay.on(
 
                    'click.preloadEditor',
                container.append(
                    event => {
                    this.createVariableCard(
                        if (event.target === overlay.get(0)) {
                         name,
                            cancel.trigger('click');
                        field,
                         }
                        analysis
                     }
                     )
                 );
                 );
             });
             });
         },
         },


         renderVariablesBySelector() {
         createPromptDialog(title, message) {
             const container =
             return new Promise(resolve => {
                this.root &&
                 const overlay = $('<div>')
                this.root.find(
                    '.preload-editor-variables'
                );
 
            if (container && container.length) {
                 this.renderVariables(container);
            }
        },
 
        createVariableCard(name, field, analysis) {
            const card =
                $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable'
                         'preload-editor-prompt-overlay'
                    )
                    .attr(
                        'data-variable',
                        name
                     );
                     );


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


            header.append(
                 $('<h2>')
                 $('<h3>').text(name)
                    .text(title)
            );
                    .appendTo(box);


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


            card.append(header);
                const input = this.textInput();


            const label =
                const buttons = $('<div>')
                this.textInput(field.label || '');
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


            label.on(
                const cancel = this.createButton(
                'input.preloadEditor',
                    'Cancel',
                () => {
                    '',
                    field.label = label.val();
                    () => {
                    this.markDirty();
                        overlay.remove();
                     this.renderConfigPreviewBySelector();
                        resolve(null);
                 }
                     }
            );
                 );


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


            const description =
                 buttons.append(cancel, confirm);
                 this.textarea(
                    field.description || ''
                )
                    .addClass(
                        'preload-editor-small-textarea'
                    );


            description.on(
                box.append(
                'input.preloadEditor',
                    input,
                () => {
                     buttons
                     field.description = description.val();
                 );
                    this.markDirty();
                    this.renderConfigPreviewBySelector();
                 }
            );


            card.append(
                overlay.append(box);
                this.fieldRow(
                    'Description',
                    description
                )
            );


            const types = [
                 $(document.body).append(overlay);
                 ['text', 'Text'],
 
                ['textarea', 'Textarea'],
                 input.trigger('focus');
                 ['number', 'Number'],
 
                ['boolean', 'Boolean'],
                 input.on(
                 ['select', 'Select'],
                    'keydown.preloadEditor',
                ['multiselect', 'Multi-select'],
                    event => {
                ['page', 'Page'],
                        if (event.key === 'Enter') {
                ['user', 'User'],
                            confirm.trigger('click');
                ['date', 'Date']
                        }
            ];


            const typeSelect =
                        if (event.key === 'Escape') {
                this.select(
                             cancel.trigger('click');
                    types.map(
                         }
                        ([value, label]) => ({
                     }
                             value,
                            label
                         })
                     ),
                    field.type || 'text'
                 );
                 );
            });
        },


            typeSelect.on(
        createConfigReviewDialog() {
                'change.preloadEditor',
            return new Promise(resolve => {
                () => {
                const overlay = $('<div>')
                    field.type = typeSelect.val();
                     .addClass(
                     this.markDirty();
                         'preload-editor-prompt-overlay preload-editor-code-review-overlay'
 
                    card.replaceWith(
                         this.createVariableCard(
                            name,
                            field,
                            analysis
                        )
                     );
                     );


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


            card.append(
                $('<h2>')
                this.fieldRow(
                    .text('Review config.json')
                    'Type',
                     .appendTo(box);
                     typeSelect
                )
            );


            if (name === 'PAGE') {
                $('<p>')
                field.type = 'page';
                    .text(
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);


                 const required =
                 const code = $('<pre>')
                     this.checkbox(
                     .addClass(
                         field.required !== false
                         'preload-editor-config-review'
                     );
                    )
                     .text(this.getConfigJSON());


                 required.on(
                 const codeWrap = $('<div>')
                    'change.preloadEditor',
                    .addClass(
                     () => {
                        'preload-editor-config-review-wrap'
                        field.required =
                     )
                            required.prop('checked');
                    .append(code);


                        this.markDirty();
                box.append(codeWrap);
                        this.renderConfigPreviewBySelector();
                    }
                );


                 card.append(
                 const buttons = $('<div>')
                    this.fieldRow(
                     .addClass(
                        'Required',
                         'preload-editor-prompt-buttons'
                        required
                    )
                );
 
                const namespace =
                     this.select(
                         [
                            {
                                value: 'Main',
                                label: 'Main'
                            },
                            {
                                value: 'Template',
                                label: 'Template'
                            },
                            {
                                value: 'File',
                                label: 'File'
                            },
                            {
                                value: 'Category',
                                label: 'Category'
                            },
                            {
                                value: 'User',
                                label: 'User'
                            }
                        ],
                        field.namespace || 'Main'
                     );
                     );


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


                 card.append(
                 buttons.append(close);
                    this.fieldRow(
                box.append(buttons);
                        'Namespace',
                 overlay.append(box);
                        namespace
                    )
                 );


                 const allowNew =
                 $(document.body).append(overlay);
                    this.checkbox(
                        field['allow-new'] === true
                    );


                 allowNew.on(
                 overlay.attr('tabindex', '-1');
                    'change.preloadEditor',
                overlay.trigger('focus');
                    () => {
                        field['allow-new'] =
                            allowNew.prop('checked');


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


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


                 return card;
            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 required =
             const pages = [];
                 this.checkbox(
 
                     field.required === true
            if (mode === 'preload' || mode === 'both') {
                 pages.push(
                     'Preload: ' +
                    title
                );
            }
 
            if (mode === 'config' || mode === 'both') {
                pages.push(
                    'Config: ' +
                    configTitle
                 );
                 );


            required.on(
                pages.push(
                'change.preloadEditor',
                    'Config content model: JSON'
                 () => {
                 );
                    field.required =
            }
                        required.prop('checked');


                    this.markDirty();
            const message =
                    this.renderConfigPreviewBySelector();
                saveDescription +
                 }
                '\n\n' +
            );
                pages.join('\n') +
                 '\n\nThis will write the changes to the wiki.';


             card.append(
             return this.createConfirmDialog(
                 this.fieldRow(
                 'Confirm save',
                    'Required',
                message,
                    required
                'Save',
                 )
                 'Cancel'
             );
             );
        },


             const placeholder =
        // =========================================================
                 this.textInput(
        // CodeMirror
                    field.placeholder || ''
        // =========================================================
                 );
                destroyEditor() {
             if (!this.editor) {
                 this.editorView = null;
                this.editorTools = null;
                 return;
            }


             placeholder.on(
             const {
                 'input.preloadEditor',
                 view,
                 () => {
                 inputHandler
                    const value = placeholder.val();
            } = this.editor;


                    if (value) {
            if (view && inputHandler) {
                        field.placeholder = value;
                view.dom.removeEventListener(
                     } else {
                    'input',
                        delete field.placeholder;
                     inputHandler
                    }
                );
            }


                    this.markDirty();
            if (view) {
                    this.renderConfigPreviewBySelector();
                view.destroy();
                }
            }
            );


             card.append(
             this.editor = null;
                this.fieldRow(
            this.editorView = null;
                    'Placeholder',
             this.editorTools = null;
                    placeholder
        },
                )
             );


             const defaultInput =
        getEditorView() {
                this.textInput(
             return this.editorView;
                    field.default === undefined
        },
                        ? ''
                        : field.default
                );


             defaultInput.on(
        getEditorContent() {
                 'input.preloadEditor',
             if (
                 () => {
                 this.editorView &&
                    const value = defaultInput.val();
                 this.editorView.state
            ) {
                return this.editorView.state.doc.toString();
            }


                    if (value) {
            return this.state.preloadContent || '';
                        field.default = value;
        },
                    } else {
                        delete field.default;
                    }


                    this.markDirty();
        setEditorContent(content) {
                    this.renderConfigPreviewBySelector();
            content = String(content || '');
                }
            );


             card.append(
             if (!this.editorView) {
                this.fieldRow(
                this.state.preloadContent = content;
                    'Default',
                 return;
                    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 current =
                 const maxRows =
                 this.editorView.state.doc.toString();
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );


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


                        if (
            this.editorView.dispatch({
                            Number.isFinite(value) &&
                changes: {
                            value > 0
                    from: 0,
                        ) {
                    to: this.editorView.state.doc.length,
                            field.maxRows = value;
                    insert: content
                        } else {
                }
                            delete field.maxRows;
            });
                        }
        },


                        this.markDirty();
        getEditorSelection() {
                        this.renderConfigPreviewBySelector();
            if (
                    }
                !this.editorView ||
                );
                !this.editorView.state
            ) {
                return null;
            }


                 card.append(
            const selection =
                    this.fieldRow(
                 this.editorView.state.selection.main;
                        'Maximum rows',
                        maxRows
                    )
                );
            }


             if (
             return {
                 field.type === 'select' ||
                 from: selection.from,
                 field.type === 'multiselect'
                 to: selection.to,
            ) {
                 text: this.editorView.state.doc.sliceString(
                 this.renderSelectConfiguration(
                     selection.from,
                     card,
                     selection.to
                     field
                )
                 );
            };
        },
 
        focusEditor() {
            if (this.editorView) {
                 this.editorView.focus();
             }
             }
        },


             return card;
        insertEditorText(
        },
            text,
             selectionFrom,
            selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }


        renderSelectConfiguration(card, field) {
             const view = this.editorView;
             const source =
            const selection = view.state.selection.main;
                this.textInput(
                    field.source || '',
                    'category:Example'
                );


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


                    if (value) {
            const to =
                        field.source = value;
                selectionTo === undefined
                     } else {
                     ? selection.to
                        delete field.source;
                     : selectionTo;
                     }


                     this.markDirty();
            const cursor =
                     this.renderConfigPreviewBySelector();
                cursorPosition === undefined
                }
                     ? from + text.length
            );
                     : cursorPosition;


             card.append(
             view.dispatch({
                 this.fieldRow(
                 changes: {
                     'Source',
                     from,
                     source,
                     to,
                     'Currently supported source format: category:Category Name'
                     insert: text
                 )
                },
             );
                selection: {
                    anchor: cursor
                 }
            });
 
             view.focus();
        },
 
        // =========================================================
        // Editor tools
        // =========================================================


             const sourcePrefix =
        wrapSelectionWithVariable() {
                 this.textInput(
             const selected =
                    field['source-prefix'] || ''
                 this.getEditorSelection();
                );


             sourcePrefix.on(
             if (
                 'input.preloadEditor',
                 !selected ||
                () => {
                selected.from === selected.to
                    const value =
            ) {
                        sourcePrefix.val();
                this.focusEditor();
                return;
            }


                    if (value) {
            const replacement =
                        field['source-prefix'] = value;
                '%%' +
                    } else {
                selected.text +
                        delete field['source-prefix'];
                '%%';
                    }


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


             card.append(
        insertVariable(name) {
                 this.fieldRow(
             name = String(name || '')
                    'Source prefix',
                .trim()
                    sourcePrefix,
                .toUpperCase();
                    'Only source values beginning with this text are included.'
 
                )
            if (!name) {
                return;
            }
 
            const selected =
                 this.getEditorSelection();
 
            if (!selected) {
                return;
            }
 
            this.insertEditorText(
                '%%' + name + '%%',
                selected.from,
                selected.to
             );
             );
        },


             const excludeCategory =
        insertCondition(
                 this.textInput(
             type,
                    field.exclude &&
            variable
                    field.exclude.category
        ) {
                        ? field.exclude.category
            type = String(type || '').toLowerCase();
                        : ''
            variable = String(variable || '')
                 );
                 .trim()
                .toUpperCase();
 
            const selected =
                 this.getEditorSelection();


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


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


                         if (
            switch (type) {
                            !Object.keys(
                case 'if': {
                                field.exclude
                    if (!variable) {
                             ).length
                        return;
                         ) {
                    }
                             delete field.exclude;
 
                         }
                    const opening =
                         '<!-- @if ' +
                        variable +
                        ' -->';
 
                    const closing =
                        '<!-- @endif -->';
 
                    if (
                        selected.from !==
                        selected.to
                    ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                             '\n' +
                            closing;
 
                        cursorOffset = text.length;
                    } else {
                         text =
                            opening +
                            '\n\n' +
                             closing;
 
                         cursorOffset =
                            opening.length + 1;
                     }
                     }


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


            card.append(
                 case 'elseif':
                 this.fieldRow(
                     text =
                     'Exclude category',
                        '<!-- @elseif -->';
                     excludeCategory
 
                 )
                     cursorOffset =
            );
                        text.length;
 
                    break;
 
                 case 'else':
                    text =
                        '<!-- @else -->';


            card.append(
                     cursorOffset =
                this.createTransformControls(
                        text.length;
                     field,
                    'value',
                    'Value transformation'
                ),
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );


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


                            return (
                case 'endif':
                                String(
                    text =
                                    option.value || ''
                         '<!-- @endif -->';
                                ) +
                                ' | ' +
                                String(
                                    option.label ||
                                    option.value ||
                                    ''
                                )
                            );
                         })
                        .join('\n')
                    : '';


            const options =
                    cursorOffset =
                this.textarea(optionsValue)
                        text.length;
                    .addClass(
                        'preload-editor-small-textarea'
                    );


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


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


                                if (parts.length === 1) {
            this.insertEditorText(
                                    return parts[0];
                text,
                                }
                selected.from,
                selected.to,
                selected.from + cursorOffset
            );
        },


                                return {
        getToolVariables() {
                                    value: parts[0],
            const variables =
                                    label:
                new Set(['PAGE']);
                                        parts
                                            .slice(1)
                                            .join(' | ')
                                };
                            });
                    }


                    this.markDirty();
            if (
                     this.renderConfigPreviewBySelector();
                this.analysis &&
                }
                this.analysis.variables
            );
            ) {
                this.analysis.variables.forEach(
                     name => {
                        variables.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }


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


         createTransformControls(field, property, title) {
         createToolSelect(
             const wrapper =
            options,
                 $('<div>')
            className
        ) {
             const select =
                 $('<select>')
                     .addClass(
                     .addClass(
                         'preload-editor-transform'
                         'preload-editor-tool-select'
                     );
                     );


             $('<h4>')
             if (className) {
                .text(title)
                select.addClass(className);
                .appendTo(wrapper);
            }
 
            options.forEach(
                option => {
                    $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                }
            );


             const existing =
             return select;
                field[property] &&
        },
                typeof field[property] === 'object'
                    ? field[property]
                    : {};


             const transform =
        updateEditorToolVariables() {
                this.select(
             if (!this.editorTools) {
                    [
                return;
                        {
            }
                            value: '',
 
                            label: 'No transformation'
            const variables =
                        },
                this.getToolVariables();
                        {
                            value: 'remove-prefix',
                            label: 'Remove prefix'
                        },
                        {
                            value: 'remove-suffix',
                            label: 'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label: 'Replace'
                        }
                    ],
                    existing.transform || ''
                );


             const prefix =
             const current =
                 this.textInput(
                 this.editorTools
                     existing.prefix || ''
                     .variableSelect
                );
                    .val();


             const suffix =
             const currentCondition =
                 this.textInput(
                 this.editorTools
                     existing.suffix || ''
                     .conditionVariableSelect
                );
                    .val();


             const from =
             const populate = (
                 this.textInput(
                 select,
                    existing.from || ''
                value
                 );
            ) => {
                 select.empty();


            const to =
                 variables.forEach(
                 this.textInput(
                     name => {
                     existing.to || ''
                        $('<option>')
                            .attr(
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                 );
                 );


            const controls =
                if (
                 $('<div>')
                    value &&
                     .addClass(
                    variables.includes(value)
                         'preload-editor-transform-controls'
                ) {
                    select.val(value);
                 } else if (
                    variables.length
                ) {
                     select.val(
                         variables[0]
                     );
                     );
                }
            };


             const prefixRow =
             populate(
                 this.fieldRow(
                 this.editorTools.variableSelect,
                    'Prefix',
                current
                    prefix
            );
                );


             const suffixRow =
             populate(
                 this.fieldRow(
                 this.editorTools.conditionVariableSelect,
                    'Suffix',
                currentCondition
                    suffix
            );
                );
        },


             const fromRow =
        updateConditionVariableVisibility() {
                this.fieldRow(
             if (!this.editorTools) {
                    'From',
                 return;
                    from
            }
                 );


             const toRow =
             const type =
                 this.fieldRow(
                 this.editorTools
                     'To',
                     .conditionTypeSelect
                     to
                     .val();
                );


             const renderInputs = () => {
             this.editorTools
                 const type = transform.val();
                 .conditionVariableWrap
 
                 .toggle(
                 prefixRow.toggle(
                     type === 'if'
                     type === 'remove-prefix'
                 );
                 );
        },


                 suffixRow.toggle(
        renderEditorTools() {
                    type === 'remove-suffix'
            const tools =
                );
                 $('<div>')
                    .addClass(
                        'preload-editor-tools'
                    );


                 fromRow.toggle(
            const wrapGroup =
                    type === 'replace'
                 $('<div>')
                );
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );


                 toRow.toggle(
            wrapGroup.append(
                     type === 'replace'
                 this.createButton(
                 );
                     'Wrap selection',
             };
                    'preload-editor-tool-button',
                    () =>
                        this.wrapSelectionWithVariable()
                 )
             );


             const update = () => {
             const variableGroup =
                const type = transform.val();
                $('<div>')
                let object = null;
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-variable'
                    );


                if (type === 'remove-prefix') {
            $('<span>')
                    if (prefix.val()) {
                .addClass(
                        object = {
                     'preload-editor-tool-label'
                            transform: type,
                )
                            prefix: prefix.val()
                .text(
                        };
                     'Insert existing variable'
                     }
                )
                } else if (type === 'remove-suffix') {
                .appendTo(variableGroup);
                    if (suffix.val()) {
                        object = {
                            transform: type,
                            suffix: suffix.val()
                        };
                     }
                } else if (type === 'replace') {
                    if (from.val()) {
                        object = {
                            transform: type,
                            from: from.val(),
                            to: to.val()
                        };
                    }
                }


                 if (object) {
            const variableSelect =
                     field[property] = object;
                 this.createToolSelect(
                } else {
                     [],
                     delete field[property];
                     'preload-editor-variable-select'
                 }
                 );


                this.markDirty();
            variableGroup.append(
                 this.renderConfigPreviewBySelector();
                 variableSelect,
            };


            transform.on(
                this.createButton(
                'change.preloadEditor',
                    'Insert',
                () => {
                    'preload-editor-tool-button',
                    update();
                    () =>
                    renderInputs();
                        this.insertVariable(
                 }
                            variableSelect.val()
                        )
                 )
             );
             );


             [
             const conditionGroup =
                prefix,
                 $('<div>')
                suffix,
                    .addClass(
                 from,
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                to
                     );
            ].forEach(input => {
                input.on(
                    'input.preloadEditor',
                     update
                );
            });


             controls.append(
             $('<span>')
                 this.fieldRow(
                 .addClass(
                     'Transformation',
                     'preload-editor-tool-label'
                    transform
                 )
                 ),
                 .text('Insert condition')
                 prefixRow,
                 .appendTo(conditionGroup);
                 suffixRow,
                fromRow,
                toRow
            );


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


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


        // Config output
            const conditionVariableWrap =
                $('<span>')
                    .addClass(
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


        getCleanConfig() {
             const insertCondition =
             const config =
                 this.createButton(
                 JSON.parse(
                     'Insert',
                     JSON.stringify(
                    'preload-editor-tool-button',
                         this.state.config
                    () =>
                    )
                         this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                 );
                 );


             const fields = config.fields || {};
             conditionTypeSelect.on(
             const orderedFields = {};
                'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
             );


             if (fields.PAGE) {
             conditionGroup.append(
                 orderedFields.PAGE = fields.PAGE;
                 conditionTypeSelect,
             }
                conditionVariableWrap,
                insertCondition
             );


             Object.keys(fields)
             tools.append(
                 .filter(
                 wrapGroup,
                    name =>
                 variableGroup,
                        name.toUpperCase() !== 'PAGE'
                 conditionGroup
                 )
            );
                 .forEach(name => {
                    orderedFields[name] = fields[name];
                });


             config.fields = orderedFields;
             this.editorTools = {
             return config;
                root: tools,
        },
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
             };


        getConfigJSON() {
            this.updateEditorToolVariables();
             return JSON.stringify(
            this.updateConditionVariableVisibility();
                this.getCleanConfig(),
 
                null,
             return tools;
                4
        },
             );
 
        updateEditorTools() {
            this.updateEditorToolVariables();
             this.updateConditionVariableVisibility();
         },
         },


         renderConfigPreview(container) {
         // =========================================================
             if (!container) {
        // Syntax highlighting
                return;
        // =========================================================
            }
 
        getKnownVariables() {
             const known =
                new Set(['PAGE']);


             container.text(
             const fields =
                 this.getConfigJSON()
                this.state.config &&
            );
                 this.state.config.fields;
        },


        renderConfigPreviewBySelector() {
            if (
            const preview =
                 fields &&
                 this.root &&
                 typeof fields === 'object'
                 this.root.find(
            ) {
                     '.preload-editor-config-preview'
                Object.keys(fields).forEach(
                     name => {
                        known.add(
                            String(name).toUpperCase()
                        );
                    }
                 );
                 );
            if (preview && preview.length) {
                this.renderConfigPreview(preview);
             }
             }


             this.renderAnalysisBySelector();
             return known;
         },
         },


         markDirty() {
         createSyntaxDecorations(
             this.state.dirty = true;
            state,
        },
            Decoration
        ) {
             const decorations = [];
            const source =
                state.doc.toString();
 
            const knownVariables =
                this.getKnownVariables();


        // Save
            const variablePattern =
                /%%([A-Za-z0-9_-]+)%%/g;


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


             if (!title) {
             while (
                 const result =
                (
                     await this.createPromptDialog(
                    match =
                        'Preload title',
                        variablePattern.exec(source)
                        'Enter the full title for the preload.'
                ) !== null
                    );
            ) {
                 const name =
                     match[1].toUpperCase();


                 if (!result) {
                 const known =
                    return;
                    knownVariables.has(name);
                }


                 title = result;
                 decorations.push(
                this.state.preloadTitle = title;
                    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
                    )
                );
             }
             }


             this.state.preloadContent =
             const conditionPattern =
                 this.getEditorContent();
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


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


            if (validation.errors.length) {
                const directiveStart =
                this.showValidationErrors(validation);
                    match.index +
                return;
                    match[0].indexOf('@');
            }


            this.setStatus(
                decorations.push(
                'Saving preload...',
                    Decoration.mark({
                 'loading'
                        class:
            );
                            'preload-editor-syntax-directive'
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                 );


            try {
                 const type =
                 const exists =
                     match[1].toLowerCase();
                     await this.pageExists(title);


                 await this.savePage(
                 if (
                     title,
                     type !== 'if' &&
                     this.state.preloadContent,
                     type !== 'elseif'
                    exists
                ) {
                        ? 'Updated preload with Preload Editor'
                     continue;
                        : 'Created preload with Preload Editor',
                 }
                     !exists
                 );


                 this.state.mode = 'edit';
                 const expression =
                this.state.dirty = false;
                    match[2];


                 this.setStatus(
                 const expressionStart =
                     'Preload saved successfully.',
                    match.index +
                     'success'
                     match[0].indexOf(
                );
                        expression
                     );


                 mw.notify(
                 const expressionPattern =
                     'Preload saved.',
                     /[A-Za-z0-9_-]+/g;
                    { type: 'success' }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );


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


                 mw.notify(
                 while (
                     error.message ||
                     (
                         'Could not save preload.',
                         expressionMatch =
                     { type: 'error' }
                            expressionPattern.exec(
                 );
                                expression
            }
                            )
        },
                     ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


        async saveAll() {
                    if (
            let title =
                        !knownVariables.has(name)
                String(
                    ) {
                     this.state.preloadTitle || ''
                        continue;
                ).trim();
                    }
 
                     const start =
                        expressionStart +
                        expressionMatch.index;


            if (!title) {
                    decorations.push(
                const result =
                        Decoration.mark({
                    await this.createPromptDialog(
                            class:
                        'Preload title',
                                'preload-editor-syntax-condition-variable'
                         'Enter the full title for the preload.'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                         )
                     );
                     );
                if (!result) {
                    return;
                 }
                 }
                title = result;
                this.state.preloadTitle = title;
             }
             }


             this.state.preloadContent =
             return Decoration.set(
                 this.getEditorContent();
                decorations,
                 true
            );
        },


             const validation =
        async installSyntaxHighlighting(view) {
                 this.validateBeforeSave();
             await mw.loader.using(
                 'ext.CodeMirror.v6.lib'
            );


             if (validation.errors.length) {
             const require =
                 this.showValidationErrors(validation);
                 mw.loader.require;
                return;
            }


             const configTitle =
             const {
                 title.replace(/\/+$/, '') +
                StateField,
                 '/config.json';
                StateEffect,
                EditorView,
                 Decoration
            } = require(
                 'ext.CodeMirror.v6.lib'
            );


             this.setStatus(
             const syntaxField =
                'Saving preload and config...',
                StateField.define({
                'loading'
                    create: state =>
            );
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


            try {
                    update: (
                const preloadExists =
                        decorations,
                     await this.pageExists(title);
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,
 
                     provide: field =>
                        EditorView.decorations.from(
                            field
                        )
                });


                await this.savePage(
            view.dispatch({
                    title,
                effects:
                     this.state.preloadContent,
                     StateEffect.appendConfig.of(
                    preloadExists
                         syntaxField
                         ? 'Updated preload with Preload Editor'
                     )
                        : 'Created preload with Preload Editor',
            });
                     !preloadExists
                );


                const configExists =
            this.editor.syntaxField =
                    await this.pageExists(configTitle);
                syntaxField;
        },


                await this.savePage(
        async mountCodeMirror(textarea) {
                    configTitle,
            return new Promise(
                    this.getConfigJSON(),
                (
                     configExists
                     resolve,
                        ? 'Updated preload config with Preload Editor'
                     reject
                        : 'Created preload config with Preload Editor',
                 ) => {
                     !configExists
                    let settled = false;
                 );


                this.state.mode = 'edit';
                    const cleanup = () => {
                this.state.dirty = false;
                        mw.hook(
                this.state.preloadTitle = title;
                            'dev.CCM.ready'
                        ).remove(onReady);


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


                mw.notify(
                     const onReady =
                     'Preload and config saved.',
                        async cm => {
                    { type: 'success' }
                            if (
                );
                                settled ||
            } catch (error) {
                                !cm ||
                console.error(
                                cm.textarea !== textarea ||
                    'Preload Editor save:',
                                !cm.view
                    error
                            ) {
                );
                                return;
                            }


                this.setStatus(
                            settled = true;
                    error.message ||
                            cleanup();
                        'Could not save preload/config.',
                    'error'
                );


                mw.notify(
                            const view =
                    error.message ||
                                cm.view;
                        'Could not save preload/config.',
                    { type: 'error' }
                );
            }
        },


        validateBeforeSave() {
                            const inputHandler =
            const errors = [];
                                () => {
            const warnings = [];
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();


            const title =
                                    this.markPreloadDirty();
                String(
                    this.state.preloadTitle || ''
                ).trim();


            if (!title) {
                                    this.reanalyze();
                errors.push(
                    'A preload title is required.'
                );
            }


            if (
                                    this.renderVariablesBySelector();
                title &&
                                    this.renderVariableConfigurationBySelector();
                !/\/Preload$/i.test(title)
                                    this.renderAnalysisBySelector();
            ) {
                                    this.updateEditorTools();
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }


            const content =
                                    this.saveDraft();
                this.getEditorContent();
                                };


            this.state.preloadContent = content;
                            view.dom.addEventListener(
                                'input',
                                inputHandler
                            );


            if (!content.trim()) {
                            view.dom.classList.add(
                errors.push(
                                'preload-editor-codemirror'
                    'The preload cannot be empty.'
                            );
                );
            }


            if (!/<includeonly>/i.test(content)) {
                            const wrapper =
                warnings.push(
                                view.dom.closest(
                    'The preload does not contain an <includeonly> section.'
                                    '.ext-codemirror-wrapper'
                );
                                );
            }


            if (!/<noinclude>/i.test(content)) {
                            if (wrapper) {
                warnings.push(
                                wrapper.classList.add(
                    'The preload does not contain a <noinclude> section.'
                                    'preload-editor-codemirror-wrapper'
                );
                                );
            }
                            }


            const analysis =
                            this.editor = {
                this.analyzePreload(
                                cm,
                    this.extractIncludeonly(content)
                                view,
                );
                                textarea,
                                inputHandler
                            };


            const configValidation =
                            this.editorView =
                this.validateConfig(
                                view;
                    this.state.config,
                    analysis
                );


            errors.push(
                            this.state.preloadContent =
                ...configValidation.errors
                                view.state.doc.toString();
            );


            warnings.push(
                            try {
                ...configValidation.warnings
                                await this.installSyntaxHighlighting(
            );
                                    view
                                );


            let depth = 0;
                                if (
                                    this.state.dirty
                                ) {
                                    this.saveDraft();
                                }


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


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


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