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


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


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


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


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


         // API
         // =========================================================
        // Browser-local draft storage
        // =========================================================
 
        getDraftStorage() {
            try {
                const raw = window.localStorage.getItem(this.draftStorageKey);
 
                if (!raw) {
                    return {
                        active: null,
                        drafts: {}
                    };
                }
 
                const parsed = JSON.parse(raw);


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


             return conditions;
             return saved;
         },
         },


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


             /*
             const hasDirtyFlags =
            * PAGE is always a special,
                typeof draft.dirtyPreload === 'boolean' ||
            * automatic field.
                typeof draft.dirtyConfig === 'boolean';
            *
 
            * Its configuration is precompiled
            this.state = {
            * and cannot be edited.
                preloadTitle: title,
            */
                preloadSource: String(draft.preloadSource || ''),
            config.fields.PAGE =
                preloadContent: String(draft.preloadContent || ''),
                this.getAutomaticPageField();
                config,
 
                variables: Array.isArray(draft.variables)
                    ? draft.variables.slice()
                    : [],
 
                conditions: Array.isArray(draft.conditions)
                    ? draft.conditions.slice()
                    : [],
 
                selectedVariable: String(draft.selectedVariable || 'PAGE'),
 
                deletedVariables: Array.isArray(draft.deletedVariables)
                    ? draft.deletedVariables
                        .map(name => String(name).toUpperCase())
                        .filter(name => name !== 'PAGE')
                    : [],
 
                mode: draft.mode || 'edit',


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


        createDefaultField(
                 dirtyPreload: hasDirtyFlags
            name,
                     ? !!draft.dirtyPreload
            analysis
                     : true,
        ) {
            return {
                 label:
                     this.humanizeName(
                        name
                     ),


                 description: '',
                 dirtyConfig: hasDirtyFlags
                    ? !!draft.dirtyConfig
                    : true,


                 type:
                 localDraftSavedAt: Number(draft.savedAt) || null,
                    analysis.conditionVariables.includes(
                localDraftAvailable: true
                        name
                    )
                        ? 'boolean'
                        : 'text'
             };
             };
        },


        humanizeName(name) {
            this.reanalyze();
             return String(name || '')
             this.renderEditor();
                .replace(
            this.updateLocalDraftIndicator();
                    /[_-]+/g,
 
                    ' '
            this.setStatus(
                )
                 'Restored unsaved local work from this browser.',
                 .replace(
                'warning'
                    /([a-z])([A-Z])/g,
            );
                    '$1 $2'
 
                )
            mw.notify('Unsaved Preload Editor work restored.', {
                .replace(
                type: 'success'
                    /\s+/g,
            });
                    ' '
 
                )
            return true;
                .trim()
                .replace(
                    /\b\w/g,
                    char =>
                        char.toUpperCase()
                );
         },
         },


         prepareConfigForVariables(
         // =========================================================
            config,
        // API
            analysis
         // =========================================================
         ) {
            config =
                this.normalizeConfig(
                    config
                );


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


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


             /*
             if (!page || page.missing) {
            * PAGE is always automatic.
                return null;
            */
             }
             fields.PAGE =
                this.getAutomaticPageField();


             /*
             const content =
            * Add every variable currently
                page.revisions &&
            * detected in the preload.
                page.revisions[0] &&
            *
                page.revisions[0].slots &&
            * Existing configuration is
                page.revisions[0].slots.main &&
            * preserved.
                 page.revisions[0].slots.main.content;
            *
            * New variables receive a
            * default configuration.
            */
            analysis.variables.forEach(
                 name => {
                    if (name === 'PAGE') {
                        return;
                    }


                    fields[name] =
            return {
                        existing[name] ||
                title: page.title || title,
                        this.createDefaultField(
                content: typeof content === 'string' ? content : '',
                            name,
                contentmodel: page.contentmodel || 'wikitext'
                            analysis
            };
                        );
        },
                }
            );


            /*
        async pageExists(title) {
            * Preserve existing fields even
            return !!await this.getPage(title);
            * if they are currently unused.
            *
            * This allows users to keep
            * configuration around while
            * editing the preload.
            */
            Object.keys(existing).forEach(
                name => {
                    const upper =
                        name.toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !fields[upper]
                    ) {
                        fields[upper] =
                            existing[name];
                    }
                }
            );
 
            config.fields = fields;
 
            return config;
         },
         },


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


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


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


             const configured =
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                 Object.keys(
                 await this.changeContentModel(
                     config.fields
                     title,
                ).map(
                    'json',
                     name =>
                     'Changed preload config content model to JSON'
                        name.toUpperCase()
                 );
                 );
            }


             analysis.variables.forEach(
             return this.savePage(
                 name => {
                 title,
                    if (
                content,
                        !configured.includes(
                summary,
                            name
                 false
                        )
                    ) {
                        errors.push(
                            'Variable "' +
                            name +
                            '" is not configured.'
                        );
                    }
                 }
             );
             );
        },


            configured.forEach(
        // =========================================================
                name => {
        // Config import helpers
                    if (
        // =========================================================
                        !analysis.variables.includes(
 
                            name
        /*
                        )
        * Accept either:
                    ) {
        *
                        warnings.push(
        *  Template:Example/Preload
                            'Field "' +
        *
                            name +
        * or:
                            '" is not used by the preload.'
        *
                        );
        *  Template:Example/Preload/config.json
                    }
        *
                }
        * and always return the config.json title.
             );
        */
        normalizeConfigTitle(title) {
            title = String(title || '').trim();
             title = title.replace(/\/+$/, '');


             if (
             if (/\/config\.json$/i.test(title)) {
                !configured.includes(
                 return title;
                    'PAGE'
                )
            ) {
                 errors.push(
                    'PAGE must always be configured.'
                );
             }
             }


             Object.entries(
             return title + '/config.json';
                config.fields
        },
            ).forEach(
 
                ([name, field]) => {
        /*
                    if (
        * Return a safe clone of a config field.
                        !field ||
        *
                        typeof field !==
        * This is deliberately JSON-based because config
                            'object' ||
        * definitions are JSON-compatible objects.
                        Array.isArray(field)
        */
                    ) {
        cloneConfigField(field) {
                        errors.push(
            try {
                            'Field "' +
                return JSON.parse(JSON.stringify(field));
                            name +
            } catch (error) {
                            '" must be an object.'
                console.warn(
                        );
                    'Preload Editor: Could not clone imported field.',
                    error
                );


                        return;
                return null;
                    }
            }
        },


                    if (!field.type) {
        /*
                        warnings.push(
        * Normalize imported field names to the same uppercase
                            'Field "' +
        * convention used throughout the editor.
                            name +
        */
                            '" has no type.'
        getImportableFields(sourceConfig) {
                        );
            const fields = sourceConfig && sourceConfig.fields;
                    }
 
            if (
                !fields ||
                typeof fields !== 'object' ||
                Array.isArray(fields)
            ) {
                return {};
            }
 
            const result = {};
 
            Object.entries(fields).forEach(([name, field]) => {
                const upper = String(name || '').trim().toUpperCase();
 
                if (!upper || upper === 'PAGE') {
                    return;
                }
 
                if (
                    !field ||
                    typeof field !== 'object' ||
                    Array.isArray(field)
                ) {
                    return;
                }
 
                const clone = this.cloneConfigField(field);


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


            return {
                 result[upper] = clone;
                 valid:
            });
                    !errors.length,
 
                errors,
             return result;
                warnings
             };
         },
         },


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


        transformationObject(
                const overlay = $('<div>')
            transform,
                    .addClass(
            prefix,
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
            suffix,
                    );
            from,
            to
        ) {
            if (!transform) {
                return null;
            }


            switch (transform) {
                const box = $('<div>')
                case 'remove-prefix':
                    .addClass(
                     return prefix
                        'preload-editor-prompt preload-editor-import-dialog'
                        ? {
                     );
                            transform,
                            prefix
                        }
                        : null;


                 case 'remove-suffix':
                 $('<h2>')
                     return suffix
                     .text('Import variable definitions')
                        ? {
                    .appendTo(box);
                            transform,
                            suffix
                        }
                        : null;


                 case 'replace':
                 $('<p>')
                     return from === ''
                     .text(
                         ? null
                        'Choose which variable definitions to import from "' +
                         : {
                         sourceTitle +
                            transform,
                         '". Existing local definitions can be replaced.'
                            from,
                    )
                            to: to || ''
                    .appendTo(box);
                        };


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


        // UI helpers
                    const emptyButtons = $('<div>')
                        .addClass('preload-editor-prompt-buttons');


        createSection(
                    const close = this.createButton(
            title,
                        'Close',
            className
                        'preload-editor-button-primary',
        ) {
                        () => {
            const section =
                            overlay.remove();
                $('<section>')
                            resolve(null);
                    .addClass(
                         }
                         'preload-editor-section'
                     );
                     );


            if (className) {
                    emptyButtons.append(close);
                section.addClass(
                    box.append(emptyButtons);
                     className
                     overlay.append(box);
                );
 
            }
                    $(document.body).append(overlay);


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


            return section;
                    return;
        },
                }


        createButton(
                const search = this.textInput('', 'Search variables...')
            label,
                     .addClass('preload-editor-import-search');
            className,
            callback
        ) {
            const button =
                $('<button>')
                    .attr(
                        'type',
                        'button'
                    )
                     .addClass(
                        'preload-editor-button'
                    )
                    .text(label);


            if (className) {
                const searchWrap = $('<div>')
                button.addClass(
                    .addClass('preload-editor-import-search-wrap')
                     className
                     .append(search);
                );
            }


            if (callback) {
                 box.append(searchWrap);
                 button.on(
                    'click.preloadEditor',
                    callback
                );
            }


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


        fieldRow(
                const selectAll = this.createButton(
            label,
                    'Select all',
            input,
                    '',
            description
                    () => {
        ) {
                        list
            const row =
                            .find('input[type="checkbox"]:visible')
                $('<div>')
                            .prop('checked', true);
                    .addClass(
                        'preload-editor-field'
                    );


            $('<label>')
                        updateSummary();
                .addClass(
                     }
                     'preload-editor-label'
                 );
                 )
                .text(label)
                .appendTo(row);


            if (description) {
                const deselectAll = this.createButton(
                $('<div>')
                    'Deselect all',
                     .addClass(
                     '',
                        'preload-editor-help'
                     () => {
                     )
                        list
                    .text(description)
                            .find('input[type="checkbox"]:visible')
                    .appendTo(row);
                            .prop('checked', false);
            }


            row.append(input);
                        updateSummary();
                    }
                );


            return row;
                controls.append(selectAll, deselectAll);
        },
                box.append(controls);


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


                     placeholder:
                const localFields =
                         placeholder || ''
                     this.state.config && this.state.config.fields
                })
                         ? this.state.config.fields
                .addClass(
                        : {};
                    'preload-editor-input'
                );
        },


        textarea(value) {
                 names.forEach(name => {
            return $('<textarea>')
                     const existing = !!localFields[name];
                 .val(
                     const field = fields[name];
                     value == null
                        ? ''
                        : value
                )
                .addClass(
                     'preload-editor-textarea'
                );
        },


        checkbox(checked) {
                    const type = field && field.type
            return $('<input>')
                        ? String(field.type)
                .attr(
                        : 'text';
                    'type',
                    'checkbox'
                )
                .prop(
                    'checked',
                    !!checked
                )
                .addClass(
                    'preload-editor-checkbox'
                );
        },


        select(
                    const label = field && field.label
            options,
                        ? String(field.label)
            value
                        : this.humanizeName(name);
        ) {
            const select =
                $('<select>')
                    .addClass(
                        'preload-editor-select'
                    );


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


            return select;
                    const checkbox = this.checkbox(false)
        },
                        .attr('data-import-variable', name)
                        .addClass('preload-editor-import-checkbox');
 
                    const content = $('<span>')
                        .addClass('preload-editor-import-content');


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


        destroyEditor() {
                    $('<strong>')
            if (!this.editor) {
                        .text(name)
                this.editorView = null;
                        .appendTo(header);
                this.editorTools = null;
                return;
            }


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


            if (
                    const meta = $('<span>')
                view &&
                        .addClass('preload-editor-import-meta');
                inputHandler
            ) {
                view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }


            if (view) {
                    $('<span>')
                view.destroy();
                        .text(label)
            }
                        .appendTo(meta);


            this.editor = null;
                    const status = $('<span>')
            this.editorView = null;
                        .addClass('preload-editor-import-status')
            this.editorTools = null;
                        .toggleClass('is-existing', existing)
        },
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');


        getEditorView() {
                    content.append(header, meta, status);
            return this.editorView;
                    row.append(checkbox, content);
        },
                    list.append(row);
                });


        getEditorContent() {
                 box.append(list);
            /*
            * Always read directly from the
            * CodeMirror state when available.
            *
            * This is important because the
            * native textarea may not contain
            * the actual current document.
            */
            if (
                this.editorView &&
                this.editorView.state
            ) {
                 return this.editorView.state.doc.toString();
            }


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


        setEditorContent(content) {
                const updateSummary = () => {
            content =
                    const selected = list.find(
                String(content || '');
                        'input[type="checkbox"]:checked'
                    ).length;


            if (!this.editorView) {
                    const existingSelected = list
                this.state.preloadContent =
                        .find('input[type="checkbox"]:checked')
                    content;
                        .filter(function () {
                            const name = $(this).attr(
                                'data-import-variable'
                            );


                return;
                            return !!localFields[name];
            }
                        }).length;


            const current =
                    let text =
                this.editorView.state.doc.toString();
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';


            if (current === content) {
                    if (existingSelected) {
                return;
                        text +=
            }
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


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


        getEditorSelection() {
                    importButton.prop('disabled', selected === 0);
            if (
                 };
                 !this.editorView ||
                !this.editorView.state
            ) {
                return null;
            }


            const selection =
                const filterRows = () => {
                this.editorView.state
                    const query = String(search.val() || '')
                    .selection.main;
                        .trim()
                        .toLowerCase();


            return {
                    list.find('.preload-editor-import-row').each(function () {
                from:
                        const row = $(this);
                    selection.from,
                        const haystack = String(
                            row.attr('data-search') || ''
                        );


                to:
                        row.toggle(!query || haystack.includes(query));
                     selection.to,
                     });
                };


                 text:
                 search.on(
                    this.editorView.state.doc.sliceString(
                    'input.preloadEditor',
                        selection.from,
                    filterRows
                        selection.to
                );
                    )
            };
        },


        focusEditor() {
                list.on(
            if (this.editorView) {
                    'change.preloadEditor',
                 this.editorView.focus();
                    'input[type="checkbox"]',
            }
                    updateSummary
        },
                 );


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


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


            const selection =
                const importButton = this.createButton(
                view.state.selection.main;
                    'Import selected',
                    'preload-editor-button-primary',
                    () => {
                        const selected = [];


            const from =
                        list
                selectionFrom ===
                            .find('input[type="checkbox"]:checked')
                    undefined
                            .each(function () {
                    ? selection.from
                                selected.push(
                    : selectionFrom;
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });


            const to =
                        overlay.remove();
                selectionTo ===
                        resolve(selected);
                     undefined
                     }
                    ? selection.to
                );
                    : selectionTo;


            const cursor =
                buttons.append(cancel, importButton);
                 cursorPosition ===
                 box.append(summary, buttons);
                    undefined
                overlay.append(box);
                    ? from + text.length
                    : cursorPosition;


            view.dispatch({
                $(document.body).append(overlay);
                changes: {
                    from,
                    to,
                    insert: text
                },


                 selection: {
                 overlay.attr('tabindex', '-1');
                    anchor: cursor
                 overlay.trigger('focus');
                 }
            });


            view.focus();
                updateSummary();
        },
                search.trigger('focus');


        // V2.3 editor tools
                const close = event => {
                    if (event.key === 'Escape') {
                        cancel.trigger('click');
                    }
                };


        wrapSelectionWithVariable() {
                overlay.on(
            const selected =
                    'keydown.preloadEditor',
                 this.getEditorSelection();
                    close
                 );


            if (
                overlay.on(
                !selected ||
                    'click.preloadEditor',
                selected.from ===
                    event => {
                     selected.to
                        if (event.target === overlay.get(0)) {
            ) {
                            cancel.trigger('click');
                this.focusEditor();
                        }
                     }
                );
            });
        },
 
        /*
        * Main import workflow.
        */
        async importVariableDefinitions() {
            const source = await this.createPromptDialog(
                'Import variable definitions',
                'Enter a preload title or its config.json title.'
            );
 
            if (!source) {
                 return;
                 return;
             }
             }


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


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


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


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


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


            const text =
                try {
                 '%%' +
                    sourceConfig = JSON.parse(page.content);
                name +
                 } catch (error) {
                 '%%';
                    throw new Error(
                        'The source config.json contains invalid JSON: ' +
                        error.message
                    );
                 }


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


        insertCondition(
                if (
            type,
                    !sourceConfig.fields ||
            variable
                    typeof sourceConfig.fields !== 'object' ||
        ) {
                    Array.isArray(sourceConfig.fields)
            type =
                ) {
                String(type || '')
                    throw new Error(
                     .toLowerCase();
                        'The source config.json does not contain a valid "fields" object.'
                     );
                }


            variable =
                const fields = this.getImportableFields(sourceConfig);
                String(variable || '')
                    .trim()
                    .toUpperCase();


            const selected =
                const selected =
                this.getEditorSelection();
                    await this.createImportDefinitionsDialog(
                        configTitle,
                        fields
                    );


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


            let text;
                    return;
            let cursorOffset;
                }


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


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


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


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


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


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


                     break;
                     this.state.config.fields[name] = clone;
                }


                case 'elseif':
                    /*
                     text =
                    * If this variable was previously deleted,
                        '<!-- @elseif -->';
                    * importing its definition explicitly should
                    * restore it.
                    */
                     if (Array.isArray(this.state.deletedVariables)) {
                        this.state.deletedVariables =
                            this.state.deletedVariables.filter(
                                deletedName =>
                                    String(deletedName).toUpperCase() !== name
                            );
                    }
                });


                    cursorOffset =
                /*
                        text.length;
                * Keep PAGE automatic regardless of what the
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();


                    break;
                this.markConfigDirty();


                 case 'else':
                 /*
                     text =
                * Keep the current selection when possible.
                         '<!-- @else -->';
                * Otherwise select the first imported definition.
                */
                const selectedStillExists = !!(
                     this.state.config.fields[
                         this.state.selectedVariable
                    ]
                );


                     cursorOffset =
                if (
                         text.length;
                     !selectedStillExists ||
                    this.state.selectedVariable === 'PAGE'
                ) {
                    this.state.selectedVariable =
                        selected[0] ||
                         'PAGE';
                }


                    break;
                this.reanalyze();


                 case 'endif':
                 this.renderVariablesBySelector();
                    text =
                this.renderVariableConfigurationBySelector();
                        '<!-- @endif -->';
                this.renderAnalysisBySelector();
                this.updateEditorTools();


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


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


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


            this.insertEditorText(
                this.setStatus(status, 'success');
                text,
                selected.from,
                selected.to,
                selected.from +
                    cursorOffset
            );
        },


        getToolVariables() {
                mw.notify(status, {
            const variables =
                    type: 'success'
                 new Set(['PAGE']);
                });
            } catch (error) {
                console.error(
                    'Preload Editor variable import:',
                    error
                );
 
                 this.setStatus(
                    error.message ||
                        'Could not import variable definitions.',
                    'error'
                );


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


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


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


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


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


             return select;
             return variables;
         },
         },


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


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


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


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


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


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


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


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


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


         updateConditionVariableVisibility() {
         // =========================================================
             if (!this.editorTools) {
        // Config
                 return;
        // =========================================================
            }
 
        getAutomaticPageField() {
             return {
                label: 'Page Name',
                description: 'Name of the page.',
                type: 'page',
                required: true,
                namespace: 'Main',
                 'allow-new': true
            };
        },


             const type =
        emptyConfig() {
                 this.editorTools
             return {
                     .conditionTypeSelect
                 settings: {
                    .val();
                     incomplete: 'add-stub'
                },


            this.editorTools
                 fields: {
                 .conditionVariableWrap
                    PAGE: this.getAutomaticPageField()
                .toggle(
                }
                    type === 'if'
            };
                );
         },
         },


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


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


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


             const variableGroup =
             config.fields.PAGE =
                 $('<div>')
                 this.getAutomaticPageField();
                    .addClass(
                        'preload-editor-tool-group ' +
                        'preload-editor-tool-group-variable'
                    );


             $('<span>')
             return config;
                .addClass(
        },
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(
                    variableGroup
                );


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


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


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


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


             $('<span>')
             Object.keys(existing).forEach(name => {
                .addClass(
                 const upper = name.toUpperCase();
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert condition'
                )
                 .appendTo(
                    conditionGroup
                );


            const conditionTypeSelect =
                 if (
                 this.createToolSelect(
                     upper !== 'PAGE' &&
                     [
                    !fields[upper] &&
                        {
                    !deleted.has(upper)
                            value: 'if',
                ) {
                            label: '@if'
                    fields[upper] =
                        },
                         existing[name];
                        {
                }
                            value: 'elseif',
            });
                            label: '@elseif'
                         },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                );


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


             const conditionVariableWrap =
             return config;
                $('<span>')
        },
                    .addClass(
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


             const insertCondition =
        validateConfig(config, analysis) {
                this.createButton(
             const errors = [];
                    'Insert',
            const warnings = [];
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


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


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


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


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


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


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


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


        // Preload syntax highlighting
                    return;
                }


        getKnownVariables() {
                if (!field.type) {
            const known =
                    warnings.push(
                 new Set(['PAGE']);
                        'Field "' +
                        name +
                        '" has no type.'
                    );
                }
               
                if (
                    field.type === 'file'
                 ) {
                    if (
                        field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }


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


            if (
                    if (
                fields &&
                        field.filename !== undefined &&
                typeof fields ===
                        typeof field.filename !== 'string'
                    'object'
                     ) {
            ) {
                         errors.push(
                Object.keys(
                             'File field "' +
                     fields
                            name +
                ).forEach(
                             '" must have "filename" as a string.'
                    name => {
                         known.add(
                             String(
                                name
                             ).toUpperCase()
                         );
                         );
                     }
                     }
                );
            }


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


            const source =
                    if (
                state.doc.toString();
                        !field.accept ||
                        !field.accept.length
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


            const knownVariables =
                    if (
                this.getKnownVariables();
                        !field.filename
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


            const variablePattern =
                if (
                 /%%([A-Za-z0-9_-]+)%%/g;
                    (
                        field.type === 'select' ||
                        field.type === 'multiselect'
                    ) &&
                    !field.source &&
                    !Array.isArray(field.options)
                 ) {
                    warnings.push(
                        'Field "' +
                        name +
                        '" is a ' +
                        field.type +
                        ' without a source or manual options.'
                    );
                }


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


            while (
                    if (
                (
                        field.filetext !== undefined &&
                     match =
                        typeof field.filetext !== 'string'
                         variablePattern.exec(
                    ) {
                             source
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                     }
 
                    if (
                        field.accept !== undefined &&
                         (
                            !Array.isArray(field.accept) ||
                            field.accept.some(
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                             )
                         )
                         )
                 ) !== null
                    ) {
             ) {
                        errors.push(
                 const name =
                            'File field "' +
                    match[1].toUpperCase();
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                    }
                 }
            });
 
             return {
                 valid: !errors.length,
                errors,
                warnings
            };
        },


                const known =
        // =========================================================
                    knownVariables.has(
        // Transformation helpers
                        name
        // =========================================================
                    );


                decorations.push(
        transformationObject(
                    Decoration.mark({
            transform,
                        class: [
            prefix,
                            'preload-editor-syntax-variable',
            suffix,
                            known
            from,
                                ? 'preload-editor-syntax-variable-known'
            to
                                : 'preload-editor-syntax-variable-unknown'
        ) {
                        ].join(' ')
            if (!transform) {
                    }).range(
                 return null;
                        match.index,
                        match.index +
                            match[0].length
                    )
                 );
             }
             }


             const conditionPattern =
             switch (transform) {
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                 case 'remove-prefix':
                    return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;


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


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


                 decorations.push(
                 default:
                     Decoration.mark({
                     return null;
                        class:
            }
                            'preload-editor-syntax-directive'
        },
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


                const type =
        // =========================================================
                    match[1].toLowerCase();
        // UI helpers
        // =========================================================


                if (
        createSection(title, className) {
                    type !== 'if' &&
            const section = $('<section>')
                    type !== 'elseif'
                .addClass('preload-editor-section');
                ) {
                    continue;
                }


                 const expression =
            if (className) {
                    match[2];
                 section.addClass(className);
            }


                 const expressionStart =
            $('<h2>')
                    match.index +
                 .addClass('preload-editor-section-title')
                    match[0].indexOf(
                .text(title)
                        expression
                .appendTo(section);
                    );
 
            return section;
        },


                const expressionPattern =
        createButton(label, className, callback) {
                    /[A-Za-z0-9_-]+/g;
            const button = $('<button>')
                .attr('type', 'button')
                .addClass('preload-editor-button')
                .text(label);


                 let expressionMatch;
            if (className) {
                 button.addClass(className);
            }


                 while (
            if (callback) {
                     (
                 button.on(
                        expressionMatch =
                     'click.preloadEditor',
                            expressionPattern.exec(
                     callback
                                expression
                 );
                            )
            }
                     ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


                    if (
            return button;
                        !knownVariables.has(
        },
                            name
                        )
                    ) {
                        continue;
                    }


                    const start =
        fieldRow(label, input, description) {
                        expressionStart +
            const row = $('<div>')
                        expressionMatch.index;
                .addClass('preload-editor-field');


                    decorations.push(
            $('<label>')
                        Decoration.mark({
                .addClass('preload-editor-label')
                            class:
                .text(label)
                                'preload-editor-syntax-condition-variable'
                .appendTo(row);
                        }).range(
 
                            start,
            if (description) {
                            start +
                $('<div>')
                                expressionMatch[0]
                    .addClass('preload-editor-help')
                                    .length
                    .text(description)
                        )
                     .appendTo(row);
                     );
                }
             }
             }


             return Decoration.set(
            row.append(input);
                decorations,
 
                 true
             return row;
            );
        },
 
        textInput(value, placeholder) {
            return $('<input>')
                .attr({
                    type: 'text',
                    value: value == null ? '' : value,
                    placeholder: placeholder || ''
                 })
                .addClass('preload-editor-input');
         },
         },


         async installSyntaxHighlighting(
         textarea(value) {
             view
             return $('<textarea>')
        ) {
                .val(value == null ? '' : value)
            await mw.loader.using(
                 .addClass('preload-editor-textarea');
                 'ext.CodeMirror.v6.lib'
        },
            );


             const require =
        checkbox(checked) {
                 mw.loader.require;
             return $('<input>')
                 .attr('type', 'checkbox')
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },


            const {
        select(options, value) {
                StateField,
             const select = $('<select>')
                StateEffect,
                 .addClass('preload-editor-select');
                EditorView,
                Decoration
             } = require(
                 'ext.CodeMirror.v6.lib'
            );


             const syntaxField =
             options.forEach(option => {
                StateField.define({
                $('<option>')
                    create: state =>
                     .attr('value', option.value)
                        this.createSyntaxDecorations(
                     .text(option.label)
                            state,
                     .prop(
                            Decoration
                        'selected',
                        ),
                         String(option.value) ===
 
                        String(value === undefined ? '' : value)
                     update: (
                        decorations,
                        transaction
                     ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,
 
                     provide: field =>
                        EditorView.decorations.from(
                            field
                         )
                });
 
            view.dispatch({
                effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                     )
                     )
                    .appendTo(select);
             });
             });


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


         async mountCodeMirror(
         // =========================================================
             textarea
        // In-wiki dialogs
        // =========================================================
 
        createConfirmDialog(
             title,
            message,
            confirmLabel,
            cancelLabel
         ) {
         ) {
             return new Promise(
             return new Promise(resolve => {
                 (
                 const overlay = $('<div>')
                     resolve,
                     .addClass('preload-editor-prompt-overlay');
                    reject
 
                 ) => {
                 const box = $('<div>')
                     let settled = false;
                     .addClass('preload-editor-prompt');


                    const cleanup =
                $('<h2>')
                        () => {
                    .text(title)
                            mw.hook(
                    .appendTo(box);
                                'dev.CCM.ready'
                            ).remove(
                                onReady
                            );


                            mw.hook(
                const messageLines =
                                'dev.CCM.load'
                    String(message || '').split('\n');
                            ).remove(
                                onLoad
                            );
                        };


                    const onReady =
                messageLines.forEach(line => {
                        async cm => {
                    if (line === '') {
                            if (
                        $('<div>')
                                settled ||
                            .addClass(
                                !cm ||
                                 'preload-editor-prompt-spacer'
                                cm.textarea !==
                             )
                                    textarea ||
                            .appendTo(box);
                                 !cm.view
                             ) {
                                return;
                            }


                            settled = true;
                        return;
                            cleanup();
                    }


                            const view =
                    $('<p>')
                                cm.view;
                        .text(line)
                        .appendTo(box);
                });


                            const inputHandler =
                const buttons = $('<div>')
                                () => {
                    .addClass(
                                    this.state
                        'preload-editor-prompt-buttons'
                                        .preloadContent =
                    );
                                        view.state.doc.toString();


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


                                    /*
                const confirm = this.createButton(
                                    * Keep the editor state
                    confirmLabel || 'Confirm',
                                    * synchronized, but do not
                    'preload-editor-button-primary',
                                    * rebuild the right panel
                    () => {
                                    * on every CodeMirror event.
                        overlay.remove();
                                    *
                        resolve(true);
                                    * The Detect variables
                    }
                                    * button is the explicit
                );
                                    * refresh action.
                                    */
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();
                                };


                            view.dom.addEventListener(
                buttons.append(cancel, confirm);
                                'input',
                box.append(buttons);
                                inputHandler
                overlay.append(box);
                            );


                            view.dom.classList.add(
                $(document.body).append(overlay);
                                'preload-editor-codemirror'
                            );


                            const wrapper =
                const close = value => {
                                view.dom.closest(
                    if (value === 'Escape') {
                                    '.ext-codemirror-wrapper'
                        cancel.trigger('click');
                                );
                    }
                };


                            if (wrapper) {
                overlay.on(
                                wrapper.classList.add(
                    'keydown.preloadEditor',
                                    'preload-editor-codemirror-wrapper'
                    event => {
                                );
                        close(event.key);
                            }
                    }
                );


                            this.editor = {
                overlay.attr('tabindex', '-1');
                                cm,
                overlay.trigger('focus');
                                view,
                                textarea,
                                inputHandler
                            };


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


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


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


                                resolve(view);
                $('<h2>')
                            } catch (
                    .text(title)
                                error
                    .appendTo(box);
                            ) {
                                reject(error);
                            }
                        };


                    const onLoad =
                $('<p>')
                        loader => {
                    .text(message)
                            if (
                    .appendTo(box);
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                            try {
                const input = this.textInput();
                                loader(
                                    textarea
                                );
                            } catch (
                                error
                            ) {
                                settled = true;
                                cleanup();
                                reject(
                                    error
                                );
                            }
                        };


                    mw.hook(
                const buttons = $('<div>')
                        'dev.CCM.ready'
                     .addClass(
                     ).add(
                         'preload-editor-prompt-buttons'
                         onReady
                     );
                     );


                    mw.hook(
                const cancel = this.createButton(
                        'dev.CCM.load'
                    'Cancel',
                     ).add(
                    '',
                         onLoad
                     () => {
                    );
                        overlay.remove();
                }
                         resolve(null);
            );
                    }
        },
                );


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


        init() {
                        overlay.remove();
            const root =
                        resolve(value);
                 $('#mw-content-text');
                    }
                 );


            if (!root.length) {
                buttons.append(cancel, confirm);
                return;
            }


            this.root =
                box.append(
                $('<div>')
                     input,
                     .attr(
                     buttons
                        'id',
                );
                        'preload-editor'
                     )
                    .addClass(
                        'preload-editor'
                    );


            root.append(
                overlay.append(box);
                this.root
            );


            this.renderShell();
                $(document.body).append(overlay);
        },


        renderShell() {
                input.trigger('focus');
            this.destroyEditor();
            this.root.empty();


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


            const titleInput =
                        if (event.key === 'Escape') {
                this.textInput(
                            cancel.trigger('click');
                    this.state.preloadTitle,
                        }
                    'Template:Example/Preload'
                     }
                ).attr(
                    'id',
                     'preload-editor-title-input'
                 );
                 );
            });
        },


             const loadButton =
        createConfigReviewDialog() {
                 this.createButton(
             return new Promise(resolve => {
                    'Load',
                 const overlay = $('<div>')
                     'preload-editor-button-primary',
                     .addClass(
                     () =>
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                        this.loadExisting(
                     );
                            titleInput.val()
 
                         )
                const box = $('<div>')
                );
                    .addClass(
                         'preload-editor-prompt preload-editor-code-review'
                    );


            const newButton =
                 $('<h2>')
                 this.createButton(
                     .text('Review config.json')
                    'New',
                     .appendTo(box);
                     '',
                     () =>
                        this.startNew()
                );


            const sampleButton =
                 $('<p>')
                 this.createButton(
                     .text(
                    'Load Sample Page',
                        'This is the config.json that will be saved for the current preload.'
                     '',
                     )
                     () =>
                    .appendTo(box);
                        this.loadSamplePage()
                );


            loader.append(
                 const code = $('<pre>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-toolbar'
                         'preload-editor-config-review'
                     )
                     )
                     .append(
                     .text(this.getConfigJSON());
                        titleInput,
 
                        loadButton,
                const codeWrap = $('<div>')
                        newButton,
                    .addClass(
                         sampleButton
                         'preload-editor-config-review-wrap'
                     )
                     )
            );
                    .append(code);


            this.root.append(
                box.append(codeWrap);
                loader
            );


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


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


            this.workspace =
                buttons.append(close);
                 $('<div>')
                 box.append(buttons);
                    .addClass(
                overlay.append(box);
                        'preload-editor-workspace'
                    );


            this.root.append(
                $(document.body).append(overlay);
                this.workspace
            );


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


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


            const section =
                overlay.on(
                this.createSection(
                    'click.preloadEditor',
                    'Get started'
                    event => {
                        if (event.target === overlay.get(0)) {
                            close.trigger('click');
                        }
                    }
                 );
                 );
            });
        },


            $('<p>')
        async confirmSave(mode, title) {
                 .text(
            const configTitle =
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                 title.replace(/\/+$/, '') +
                )
                 '/config.json';
                 .appendTo(
                    section
                );


             const tips =
             let saveDescription;
                $('<ul>')
                    .addClass(
                        'preload-editor-tips'
                    );


             [
             if (mode === 'preload') {
                 'Existing preload: loads the preload and its config.json if available.',
                 saveDescription =
                 'New preload: starts with the standard Preload Template structure.',
                    'Save the preload page only?';
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
            } else if (mode === 'config') {
             ].forEach(
                 saveDescription =
                 text => {
                    'Save the config.json page only?';
                     $('<li>')
             } else {
                        .text(text)
                 saveDescription =
                        .appendTo(
                     'Save both the preload and config.json?';
                            tips
            }
                        );
                }
            );


             section.append(
             const pages = [];
                tips
            );


             this.workspace.append(
             if (mode === 'preload' || mode === 'both') {
                 section
                 pages.push(
            );
                    'Preload: ' +
        },
                    title
 
                );
        setStatus(
            message,
            type
        ) {
            if (!this.status) {
                return;
             }
             }


             this.status.removeClass(
             if (mode === 'config' || mode === 'both') {
                'is-error',
                 pages.push(
                'is-success',
                    'Config: ' +
                 'is-warning',
                    configTitle
                 'is-loading'
                 );
            );


            if (type) {
                 pages.push(
                 this.status.addClass(
                     'Config content model: JSON'
                     'is-' + type
                 );
                 );
             }
             }


             this.status.text(
             const message =
                 message || ''
                saveDescription +
                '\n\n' +
                pages.join('\n') +
                '\n\nThis will write the changes to the wiki.';
 
            return this.createConfirmDialog(
                'Confirm save',
                 message,
                'Save',
                'Cancel'
             );
             );
         },
         },


         // Load / create
         // =========================================================
 
        // CodeMirror
        async loadExisting(
        // =========================================================
             title
                destroyEditor() {
        ) {
             if (!this.editor) {
             title =
                this.editorView = null;
                 String(title || '')
                this.editorTools = null;
                    .trim();
                return;
             }
 
            const {
                view,
                 inputHandler
            } = this.editor;


             if (!title) {
             if (view && inputHandler) {
                 mw.notify(
                 view.dom.removeEventListener(
                     'Enter a preload page title first.',
                     'input',
                     {
                     inputHandler
                        type: 'warn'
                    }
                 );
                 );
            }


                 return;
            if (view) {
                 view.destroy();
             }
             }


             this.setStatus(
             this.editor = null;
                'Loading preload...',
            this.editorView = null;
                'loading'
             this.editorTools = null;
             );
        },


            try {
        getEditorView() {
                const page =
            return this.editorView;
                    await this.getPage(
        },
                        title
                    );


                if (!page) {
        getEditorContent() {
                    const suggestions =
            if (
                        await this.findSimilarPreloads(
                this.editorView &&
                            title
                this.editorView.state
                        );
            ) {
                return this.editorView.state.doc.toString();
            }


                    this.renderMissingPage(
            return this.state.preloadContent || '';
                        title,
        },
                        suggestions
                    );


                    this.setStatus(
        setEditorContent(content) {
                        'Preload not found.',
            content = String(content || '');
                        'warning'
                    );


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


                 await this.loadDefinition(
            const current =
                    page.title,
                 this.editorView.state.doc.toString();
                    page.content
                );


                this.setStatus(
            if (current === content) {
                    'Preload loaded.',
                 return;
                    'success'
             }
                 );
             } catch (
                error
            ) {
                console.error(
                    'Preload Editor:',
                    error
                );


                this.setStatus(
            this.editorView.dispatch({
                     error.message ||
                changes: {
                        'Could not load preload.',
                     from: 0,
                     'error'
                    to: this.editorView.state.doc.length,
                 );
                     insert: content
             }
                 }
             });
         },
         },


         async findSimilarPreloads(
         getEditorSelection() {
            title
             if (
        ) {
                 !this.editorView ||
             let query =
                !this.editorView.state
                 title
            ) {
                    .replace(
                return null;
                        /\/Preload$/i,
            }
                        ''
                    )
                    .trim();


             if (!query) {
             const selection =
                 query = title;
                 this.editorView.state.selection.main;
            }


             try {
             return {
                 const results =
                 from: selection.from,
                    await this.searchPages(
                to: selection.to,
                        query
                text: this.editorView.state.doc.sliceString(
                     );
                    selection.from,
                     selection.to
                )
            };
        },


                return results.filter(
        focusEditor() {
                    result =>
             if (this.editorView) {
                        /\/Preload$/i.test(
                 this.editorView.focus();
                            result.title
                        )
                );
             } catch (
                error
            ) {
                 console.error(
                    'Preload Editor search:',
                    error
                );
 
                return [];
             }
             }
         },
         },


         renderMissingPage(
         insertEditorText(
             title,
             text,
             suggestions
             selectionFrom,
            selectionTo,
            cursorPosition
         ) {
         ) {
             this.workspace.empty();
             if (!this.editorView) {
                return;
            }


             const section =
             const view = this.editorView;
                this.createSection(
            const selection = view.state.selection.main;
                    'Preload not found'
                );


             $('<p>')
             const from =
                 .text(
                 selectionFrom === undefined
                    'No preload exists at "' +
                     ? selection.from
                    title +
                     : selectionFrom;
                     '".'
                )
                .appendTo(
                     section
                );


             if (
             const to =
                 suggestions.length
                 selectionTo === undefined
             ) {
                    ? selection.to
                 $('<h3>')
                    : selectionTo;
                     .text(
 
                        'Similar preloads'
             const cursor =
                    )
                 cursorPosition === undefined
                    .appendTo(
                     ? from + text.length
                        section
                     : cursorPosition;
                     );


                 const list =
            view.dispatch({
                     $('<div>')
                 changes: {
                        .addClass(
                    from,
                            'preload-editor-suggestions'
                    to,
                        );
                     insert: text
                },
                selection: {
                    anchor: cursor
                }
            });


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


                section.append(
        // =========================================================
                    list
        // Editor tools
                );
        // =========================================================
            }


             section.append(
        wrapSelectionWithVariable() {
                 this.createButton(
             const selected =
                    'Create this preload',
                 this.getEditorSelection();
                    'preload-editor-button-primary',
 
                    () =>
            if (
                        this.startNew(
                !selected ||
                            title
                selected.from === selected.to
                        )
            ) {
                 )
                this.focusEditor();
            );
                return;
            }
 
            const replacement =
                '%%' +
                 selected.text +
                '%%';


             this.workspace.append(
             this.insertEditorText(
                 section
                replacement,
                selected.from,
                selected.to,
                 selected.from + replacement.length
             );
             );
         },
         },


         async startNew(
         insertVariable(name) {
            title
             name = String(name || '')
        ) {
                .trim()
             title =
                .toUpperCase();
                String(title || '')
                    .trim();


             this.state = {
             if (!name) {
                 preloadTitle: title,
                 return;
                preloadSource: '',
            }
                preloadContent:
                    this.defaults.preload,


                 config:
            const selected =
                    this.emptyConfig(),
                 this.getEditorSelection();


                variables: ['PAGE'],
            if (!selected) {
                 conditions: [],
                 return;
                selectedVariable: 'PAGE',
             }
                mode: 'new',
                dirty: true
             };


             this.renderEditor();
             this.insertEditorText(
 
                '%%' + name + '%%',
            this.setStatus(
                 selected.from,
                 'Creating a new preload.',
                 selected.to
                 'success'
             );
             );
         },
         },


         async loadSamplePage() {
         insertCondition(
             const result =
            type,
                await this.createPromptDialog(
            variable
                    'Load Sample Page',
        ) {
                    'Enter the title of a normal wiki page to use as the starting point.'
             type = String(type || '').toLowerCase();
                 );
            variable = String(variable || '')
                .trim()
                .toUpperCase();
 
            const selected =
                 this.getEditorSelection();


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


             this.setStatus(
             let text;
                'Loading sample page...',
             let cursorOffset;
                'loading'
             );


             try {
             switch (type) {
                 const page =
                 case 'if': {
                     await this.getPage(
                     if (!variable) {
                         result
                         return;
                     );
                     }


                if (!page) {
                     const opening =
                     throw new Error(
                         '<!-- @if ' +
                         'Sample page not found: ' +
                         variable +
                         result
                        ' -->';
                    );
                }


                const sample =
                    const closing =
                    this.convertSampleToPreload(
                         '<!-- @endif -->';
                         page.content
                    );


                this.state = {
                    if (
                    preloadTitle: '',
                        selected.from !==
                    preloadSource: '',
                        selected.to
                    preloadContent:
                    ) {
                        sample,
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                     config:
                        cursorOffset = text.length;
                         this.emptyConfig(),
                     } else {
                         text =
                            opening +
                            '\n\n' +
                            closing;


                    variables: ['PAGE'],
                        cursorOffset =
                    conditions: [],
                            opening.length + 1;
                     selectedVariable: 'PAGE',
                     }
                    mode: 'new',
                    dirty: true
                };


                this.reanalyze();
                    break;
                 this.renderEditor();
                 }


                 this.setStatus(
                 case 'elseif':
                    'Sample page loaded.',
                     text =
                     'success'
                        '<!-- @elseif -->';
                );
            } catch (
                error
            ) {
                console.error(
                    'Preload Editor sample:',
                    error
                );


                this.setStatus(
                     cursorOffset =
                     error.message ||
                         text.length;
                         'Could not load sample page.',
                    'error'
                );
            }
        },


        convertSampleToPreload(
                     break;
            source
        ) {
            let content =
                String(source || '')
                     .trim();


            const include =
                 case 'else':
                 content.match(
                     text =
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                        '<!-- @else -->';
                );


            if (include) {
                    cursorOffset =
                content =
                        text.length;
                    include[1].trim();
            }


            content =
                     break;
                content
                     .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();


            return (
                 case 'endif':
                 '<includeonly>\n' +
                    text =
                content +
                        '<!-- @endif -->';
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },


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


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


                     $('<h2>')
                default:
                        .text(title)
                     return;
                        .appendTo(
            }
                            box
                        );


                    $('<p>')
            this.insertEditorText(
                        .text(message)
                text,
                        .appendTo(
                selected.from,
                            box
                selected.to,
                        );
                selected.from + cursorOffset
            );
        },


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


                    const buttons =
            if (
                        $('<div>')
                this.analysis &&
                            .addClass(
                this.analysis.variables
                                'preload-editor-prompt-buttons'
            ) {
                            );
                this.analysis.variables.forEach(
 
                     name => {
                     const cancel =
                         variables.add(
                         this.createButton(
                             String(name).toUpperCase()
                             'Cancel',
                            '',
                            () => {
                                overlay.remove();
                                resolve(null);
                            }
                         );
                         );
                    }
                );
            }


                    const confirm =
            return Array.from(variables);
                        this.createButton(
        },
                            'Load',
                            'preload-editor-button-primary',
                            () => {
                                const value =
                                    String(
                                        input.val() ||
                                        ''
                                    ).trim();


                                if (!value) {
        createToolSelect(
                                    return;
            options,
                                }
            className
 
        ) {
                                overlay.remove();
            const select =
                                resolve(value);
                $('<select>')
                            }
                     .addClass(
                        );
                         'preload-editor-tool-select'
 
                     buttons.append(
                         cancel,
                        confirm
                     );
                     );


                    box.append(
            if (className) {
                        input,
                select.addClass(className);
                        buttons
            }
                    );


                    overlay.append(
            options.forEach(
                        box
                option => {
                    );
                     $('<option>')
 
                         .attr(
                     $(document.body)
                             'value',
                         .append(
                             option.value
                             overlay
                        )
                        );
                        .text(option.label)
 
                        .appendTo(select);
                    input.trigger(
                        'focus'
                    );
 
                    input.on(
                        'keydown.preloadEditor',
                        event => {
                             if (
                                event.key ===
                                'Enter'
                            ) {
                                confirm.trigger(
                                    'click'
                                );
                            }
 
                            if (
                                event.key ===
                                'Escape'
                            ) {
                                cancel.trigger(
                                    'click'
                                );
                            }
                        }
                    );
                 }
                 }
             );
             );
            return select;
         },
         },


         async loadDefinition(
         updateEditorToolVariables() {
            title,
             if (!this.editorTools) {
            source
                 return;
        ) {
            }
             const content =
                this.extractIncludeonly(
                    source
                 );


             let config =
             const variables =
                 this.emptyConfig();
                 this.getToolVariables();


             const configTitle =
             const current =
                 title.replace(
                 this.editorTools
                     /\/+$/,
                    .variableSelect
                     ''
                    .val();
                 ) +
 
                 '/config.json';
            const currentCondition =
                this.editorTools
                     .conditionVariableSelect
                     .val();
 
            const populate = (
                select,
                 value
            ) => {
                 select.empty();


            const configPage =
                variables.forEach(
                await this.getPage(
                    name => {
                     configTitle
                        $('<option>')
                            .attr(
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                     }
                 );
                 );


            if (configPage) {
                if (
                 try {
                    value &&
                     config =
                    variables.includes(value)
                        JSON.parse(
                 ) {
                            configPage.content
                     select.val(value);
                        );
                 } else if (
                 } catch (
                     variables.length
                     error
                 ) {
                 ) {
                     throw new Error(
                     select.val(
                         'The existing config.json contains invalid JSON: ' +
                         variables[0]
                        error.message
                     );
                     );
                 }
                 }
             }
             };


             const analysis =
             populate(
                 this.analyzePreload(
                 this.editorTools.variableSelect,
                    content
                current
                );
            );


             config =
             populate(
                 this.prepareConfigForVariables(
                 this.editorTools.conditionVariableSelect,
                    config,
                currentCondition
                    analysis
            );
                 );
        },
 
        updateConditionVariableVisibility() {
            if (!this.editorTools) {
                 return;
            }


             this.state = {
             const type =
                 preloadTitle: title,
                 this.editorTools
                preloadSource: source,
                    .conditionTypeSelect
                preloadContent: source,
                    .val();
                config,


                 variables:
            this.editorTools
                     analysis.variables,
                .conditionVariableWrap
                 .toggle(
                     type === 'if'
                );
        },


                 conditions:
        renderEditorTools() {
                     analysis.conditions,
            const tools =
                 $('<div>')
                     .addClass(
                        'preload-editor-tools'
                    );


                selectedVariable:
             const wrapGroup =
                    analysis.variables.includes(
                        'PAGE'
                    )
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),
 
                mode: 'edit',
                dirty: false
            };
 
            this.renderEditor();
        },
 
        // Editor
 
        renderEditor() {
            this.destroyEditor();
            this.workspace.empty();
 
             const layout =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-layout'
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                     );
                     );


             const left =
             wrapGroup.append(
                 $('<div>')
                 this.createButton(
                     .addClass(
                    'Wrap selection',
                        'preload-editor-left'
                     'preload-editor-tool-button',
                     );
                     () =>
                        this.wrapSelectionWithVariable()
                )
            );


             const right =
             const variableGroup =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-right'
                         'preload-editor-tool-group preload-editor-tool-group-variable'
                     );
                     );


             const editorSection =
            $('<span>')
                 this.createSection(
                .addClass(
                     'Preload',
                    'preload-editor-tool-label'
                     'preload-editor-main-section'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);
 
             const variableSelect =
                 this.createToolSelect(
                     [],
                     'preload-editor-variable-select'
                 );
                 );


             const meta =
             variableGroup.append(
                $('<div>')
                variableSelect,
                    .addClass(
                        'preload-editor-meta'
                    );


            $('<strong>')
                this.createButton(
                .text(
                    'Insert',
                    this.state.preloadTitle ||
                    'preload-editor-tool-button',
                    'New preload'
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                 )
                 )
                .appendTo(
            );
                    meta
                );


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


             editorSection.append(
             $('<span>')
                 meta
                .addClass(
            );
                    'preload-editor-tool-label'
                 )
                .text('Insert condition')
                .appendTo(conditionGroup);


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


             const textarea =
             const conditionVariableWrap =
                 this.textarea(
                 $('<span>')
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                     .addClass(
                     .addClass(
                         'preload-editor-content'
                         'preload-editor-condition-variable'
                    );
 
            const editorMount =
                $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                     )
                     )
                     .append(
                     .append(
                         textarea
                         conditionVariableSelect
                     );
                     );


             editorSection.append(
             const insertCondition =
                 editorMount
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );
 
            conditionTypeSelect.on(
                'change.preloadEditor',
                 () =>
                    this.updateConditionVariableVisibility()
             );
             );


             left.append(
             conditionGroup.append(
                 editorSection
                 conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
             );
             );


             /*
             tools.append(
            * RIGHT PANEL
                wrapGroup,
            *
                variableGroup,
            * Analysis
                conditionGroup
            * Variables
            );
            * Variable configuration
            * Generated configuration
            * Actions
            */


             const analysisSection =
             this.editorTools = {
                 this.createSection(
                 root: tools,
                    'Analysis'
                variableSelect,
                 );
                 conditionTypeSelect,
 
                conditionVariableSelect,
            const analysisContainer =
                conditionVariableWrap,
                 $('<div>')
                 insertCondition
                    .addClass(
            };
                        'preload-editor-analysis'
                    );


             analysisSection.append(
             this.updateEditorToolVariables();
                analysisContainer
             this.updateConditionVariableVisibility();
             );


             const variablesSection =
             return tools;
                this.createSection(
        },
                    'Variables'
                );


            /*
        updateEditorTools() {
            * Explicit variable detection button.
             this.updateEditorToolVariables();
            *
            this.updateConditionVariableVisibility();
            * This is intentionally separate from
        },
            * CodeMirror's input event because
            * CodeMirror 6 owns its own document
            * state and does not always synchronize
            * through the native textarea/input event.
            */
             const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );


            const detectHelp =
        // =========================================================
                $('<div>')
        // Syntax highlighting
                    .addClass(
        // =========================================================
                        'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );


             const detectControls =
        getKnownVariables() {
                 $('<div>')
             const known =
                    .addClass(
                 new Set(['PAGE']);
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    );


             variablesSection.append(
             const fields =
                 detectControls
                this.state.config &&
            );
                 this.state.config.fields;


             const variableContainer =
             if (
                 $('<div>')
                fields &&
                    .addClass(
                 typeof fields === 'object'
                         'preload-editor-variables'
            ) {
                    );
                Object.keys(fields).forEach(
 
                    name => {
            variablesSection.append(
                         known.add(
                variableContainer
                            String(name).toUpperCase()
            );
                        );
 
                     }
            const configurationSection =
                this.createSection(
                     'Variable configuration'
                 );
                 );
            }


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


             configurationSection.append(
        createSyntaxDecorations(
                configurationContainer
            state,
             );
             Decoration
        ) {
            const decorations = [];
             const source =
                state.doc.toString();


             const configSection =
             const knownVariables =
                 this.createSection(
                 this.getKnownVariables();
                    'Generated configuration'
                );


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


             configSection.append(
             let match;
                configPreview
            );


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


            actions.append(
                 const known =
                 this.createButton(
                     knownVariables.has(name);
                    'Save Preload + Config',
                     'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                ),


                 this.createButton(
                 decorations.push(
                     'Save Preload Only',
                     Decoration.mark({
                    '',
                        class: [
                     () =>
                            'preload-editor-syntax-variable',
                         this.savePreloadOnly()
                            known
                 )
                                ? 'preload-editor-syntax-variable-known'
             );
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                     }).range(
                         match.index,
                        match.index +
                            match[0].length
                    )
                 );
             }


             right.append(
             const conditionPattern =
                 analysisSection,
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                variablesSection,
                configurationSection,
                configSection,
                actions
            );


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


            this.workspace.append(
                const directiveStart =
                layout
                    match.index +
            );
                    match[0].indexOf('@');


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


            this.renderVariables(
                const type =
                variableContainer
                    match[1].toLowerCase();
            );


            this.renderAnalysis(
                if (
                 analysisContainer
                    type !== 'if' &&
            );
                    type !== 'elseif'
                 ) {
                    continue;
                }


            this.renderVariableConfiguration(
                 const expression =
                 configurationContainer
                    match[2];
            );


            this.renderConfigPreview(
                const expressionStart =
                configPreview
                    match.index +
            );
                    match[0].indexOf(
                        expression
                    );


            this.updateEditorTools();
                const expressionPattern =
                    /[A-Za-z0-9_-]+/g;


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


                     this.setStatus(
                while (
                         error.message ||
                     (
                             'Could not initialize CodeMirror.',
                         expressionMatch =
                        'error'
                             expressionPattern.exec(
                     );
                                expression
                 }
                            )
            );
                     ) !== null
        },
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


        /*
                    if (
        * Explicitly re-read the CodeMirror document
                        !knownVariables.has(name)
        * and refresh every part of the right panel.
                    ) {
        *
                        continue;
        * This is the important new part.
                    }
        */
        detectVariables() {
            const source =
                this.getEditorContent();


            /*
                    const start =
            * Make sure the editor's actual document
                        expressionStart +
            * becomes the canonical preload content.
                        expressionMatch.index;
            */
            this.state.preloadContent =
                source;


            /*
                    decorations.push(
            * Mark the preload as modified because
                        Decoration.mark({
            * the user has edited the CodeMirror
                            class:
            * document.
                                'preload-editor-syntax-condition-variable'
            */
                        }).range(
             this.state.dirty = true;
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                }
             }


             /*
             return Decoration.set(
            * Re-run the complete preload analysis.
                decorations,
            *
                true
            * This discovers new variables such as:
             );
            *
        },
            * %%ZHS%%
            *
            * and creates their default config
            * entries.
            */
             this.reanalyze();


             /*
        async installSyntaxHighlighting(view) {
            * Refresh the right panel.
             await mw.loader.using(
            */
                'ext.CodeMirror.v6.lib'
             this.renderVariablesBySelector();
             );


             this.renderVariableConfigurationBySelector();
             const require =
                mw.loader.require;


             this.renderAnalysisBySelector();
             const {
 
                 StateField,
            this.renderConfigPreviewBySelector();
                 StateEffect,
 
                 EditorView,
            /*
                 Decoration
            * Refresh the variable selectors in
             } = require(
            * the editor toolbar too.
                 'ext.CodeMirror.v6.lib'
            */
            this.updateEditorTools();
 
            /*
            * Refresh syntax highlighting so a newly
            * detected variable becomes "known".
            */
            if (
                this.editorView &&
                this.editor &&
                this.editor.syntaxField
            ) {
                 /*
                * The syntax decoration field normally
                * updates when CodeMirror's document
                * changes. Here we force a tiny
                * configuration refresh by replacing
                * the current syntax field with the
                * same configuration.
                *
                * If the field is already up to date,
                * CodeMirror simply keeps the current
                * document unchanged.
                */
                 try {
                    this.editorView.dispatch({
                        effects:
                            this.editorView.state
                                .field(
                                    this.editor.syntaxField
                                )
                                ? []
                                : []
                    });
                } catch (
                    error
                 ) {
                    /*
                    * Syntax highlighting is cosmetic;
                    * never let it break variable
                    * detection.
                    */
                    console.warn(
                        'Preload Editor syntax refresh:',
                        error
                    );
                 }
             }
 
            this.setStatus(
                 'Variables detected from the current preload.',
                'success'
             );
             );
        },


        reanalyze() {
            const syntaxField =
            const source =
                StateField.define({
                this.getEditorContent();
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


            const content =
                    update: (
                this.extractIncludeonly(
                        decorations,
                    source
                        transaction
                );
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


            const analysis =
                    provide: field =>
                this.analyzePreload(
                        EditorView.decorations.from(
                    content
                            field
                 );
                        )
                 });


             this.state.preloadContent =
             view.dispatch({
                source;
                effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });


             this.state.variables =
             this.editor.syntaxField =
                 analysis.variables;
                 syntaxField;
        },


             this.state.conditions =
        async mountCodeMirror(textarea) {
                analysis.conditions;
             return new Promise(
                (
                    resolve,
                    reject
                ) => {
                    let settled = false;


            this.state.config =
                    const cleanup = () => {
                this.prepareConfigForVariables(
                        mw.hook(
                    this.state.config ||
                            'dev.CCM.ready'
                         this.emptyConfig(),
                         ).remove(onReady);
                    analysis
                );


            this.analysis =
                        mw.hook(
                analysis;
                            'dev.CCM.load'
                        ).remove(onLoad);
                    };


            /*
                    const onReady =
            * PAGE is always available.
                         async cm => {
            *
                             if (
            * If the selected variable
                                settled ||
            * disappeared, select PAGE or
                                !cm ||
            * the first currently used variable.
                                cm.textarea !== textarea ||
            */
                                !cm.view
            const available =
                             ) {
                ['PAGE'].concat(
                                return;
                    analysis.variables.filter(
                            }
                         name =>
                             name !==
                             'PAGE'
                    )
                );


            if (
                            settled = true;
                !available.includes(
                            cleanup();
                    this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },


        renderAnalysis(
                            const view =
            container
                                cm.view;
        ) {
            container.empty();


            const analysis =
                            const inputHandler =
                this.analysis ||
                                () => {
                this.analyzePreload(
                                    this.state
                    this.extractIncludeonly(
                                        .preloadContent =
                        this.getEditorContent()
                                        view.state.doc.toString();
                    )
 
                );
                                    this.markPreloadDirty();


            const variableCount =
                                    this.reanalyze();
                analysis.variables.length;


            const conditionCount =
                                    this.renderVariablesBySelector();
                analysis.conditions.length;
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


            const configuredCount =
                                    this.saveDraft();
                Object.keys(
                                };
                    this.state.config &&
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;


            const summary =
                            view.dom.addEventListener(
                $('<div>')
                                'input',
                    .addClass(
                                inputHandler
                        'preload-editor-analysis-summary'
                            );
                    );


            const createMetric =
                            view.dom.classList.add(
                (
                                 'preload-editor-codemirror'
                    value,
                            );
                    label
                ) =>
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                 .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                             $('<span>')
                             const wrapper =
                                 .addClass(
                                 view.dom.closest(
                                     'preload-editor-analysis-label'
                                     '.ext-codemirror-wrapper'
                                 )
                                 );
                                .text(label)
                        );


            summary.append(
                            if (wrapper) {
                createMetric(
                                wrapper.classList.add(
                    variableCount,
                                    'preload-editor-codemirror-wrapper'
                    variableCount === 1
                                );
                        ? 'variable'
                            }
                        : 'variables'
                ),


                createMetric(
                            this.editor = {
                    conditionCount,
                                cm,
                    conditionCount === 1
                                view,
                        ? 'condition marker'
                                textarea,
                        : 'condition markers'
                                inputHandler
                ),
                            };


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


            container.append(
                            this.state.preloadContent =
                summary
                                view.state.doc.toString();
            );


            if (
                            try {
                analysis.conditionVariables
                                await this.installSyntaxHighlighting(
                    .length
                                    view
            ) {
                                 );
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis
                                 .conditionVariables
                                .join(', ')
                        )
                );
            }


            const validation =
                                if (
                this.validateConfig(
                                    this.state.dirty
                    this.state.config,
                                ) {
                    analysis
                                    this.saveDraft();
                );
                                }


            if (
                                resolve(view);
                validation.errors.length
                            } catch (error) {
            ) {
                                reject(error);
                const errors =
                             }
                    $('<ul>')
                         };
                        .addClass(
                             'preload-editor-validation-errors'
                         );


                validation.errors.forEach(
                     const onLoad =
                     error => {
                         loader => {
                         $('<li>')
                             if (
                             .text(error)
                                settled ||
                            .appendTo(
                                 typeof loader !==
                                 errors
                                    'function'
                             );
                             ) {
                    }
                                return;
                );
                            }


                container.append(
                            try {
                    errors
                                loader(textarea);
                );
                            } catch (error) {
            }
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };


            if (
                    mw.hook(
                validation.warnings.length
                        'dev.CCM.ready'
            ) {
                     ).add(onReady);
                const warnings =
                     $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );


                validation.warnings.forEach(
                    mw.hook(
                    warning => {
                         'dev.CCM.load'
                         $('<li>')
                    ).add(onLoad);
                            .text(warning)
                }
                            .appendTo(
            );
                                warnings
        },
                            );
 
                    }
        // =========================================================
                );
        // Main UI
        // =========================================================


                container.append(
        init() {
                    warnings
            const root =
                 );
                 $('#mw-content-text');
            }


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


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


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


        /*
            this.renderShell();
        * Variable list
        */


        renderVariables(
             this.restoreDraft();
             container
        ) {
            container.empty();


             const analysis =
             window.addEventListener(
                this.analysis ||
                 'beforeunload',
                this.analyzePreload(
                 () => {
                    this.extractIncludeonly(
                     if (this.state.dirty) {
                        this.getEditorContent()
                         this.saveDraft();
                    )
                 );
 
            const variables =
                 analysis.variables.slice();
 
            const ordered =
                ['PAGE'];
 
            variables.forEach(
                name => {
                     if (
                        name !== 'PAGE' &&
                        !ordered.includes(
                            name
                        )
                    ) {
                         ordered.push(
                            name
                        );
                     }
                     }
                 }
                 }
             );
             );
        },
                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'
                );


             const list =
             titleInput.on(
                 $('<div>')
                 'input.preloadEditor',
                    .addClass(
                () => {
                        'preload-editor-variable-list'
                     this.state.preloadTitle =
                    );
                         String(
 
                            titleInput.val() || ''
            ordered.forEach(
                        ).trim();
                name => {
                     const isSelected =
                         name ===
                        this.state
                            .selectedVariable;


                     const isUsed =
                     if (
                         analysis.variables.includes(
                        this.state.dirty &&
                            name
                        this.state.mode === 'new'
                        );
                    ) {
                         this.saveDraft();
                    }
                }
            );


                    const item =
            const loadButton =
                        $('<button>')
                this.createButton(
                            .attr({
                    'Load',
                                type: 'button',
                    'preload-editor-button-primary',
                                'data-variable':
                    () =>
                                    name
                        this.loadExisting(
                            })
                            titleInput.val()
                            .addClass(
                        )
                                'preload-editor-variable-item'
                );
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                    const nameLabel =
            const newButton =
                        $('<span>')
                this.createButton(
                            .addClass(
                    'New',
                                'preload-editor-variable-name'
                    '',
                            )
                    () => this.startNew()
                            .text(name);
                );


                    item.append(
            const sampleButton =
                        nameLabel
                this.createButton(
                     );
                    'Load Sample Page',
                     '',
                    () => this.loadSamplePage()
                );


                    if (
            loader.append(
                        name ===
                $('<div>')
                        'PAGE'
                    .addClass(
                    ) {
                        'preload-editor-toolbar'
                        item.append(
                    )
                            $('<span>')
                    .append(
                                .addClass(
                        titleInput,
                                    'preload-editor-badge'
                        loadButton,
                                )
                         newButton,
                                .text(
                         sampleButton
                                    'AUTOMATIC'
                     )
                                )
            );
                         );
 
                    } else if (
            this.root.append(loader);
                         !isUsed
                     ) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    'UNUSED'
                                )
                        );
                    }


                     list.append(
            this.workspace =
                         item
                $('<div>')
                     .addClass(
                         'preload-editor-workspace'
                     );
                     );
                }
            );


             container.append(
             this.root.append(
                 list
                 this.workspace
             );
             );


             if (
             /*
                !ordered.length
            * Fixed footer
             ) {
            *
                container.append(
            * Local draft status, normal status messages,
                     $('<div>')
            * and save actions live here.
                        .addClass(
            */
                            'preload-editor-empty'
             const footer =
                        )
                $('<div>')
                        .text(
                    .addClass(
                            'No variables found in the preload.'
                        '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'
                    );


        renderVariablesBySelector() {
            footer.append(
            const container =
                 this.localDraftStatus,
                 this.root &&
                 this.status
                 this.root.find(
            );
                    '.preload-editor-variables'
                );


             if (
             this.root.append(
                 container &&
                 footer
                container.length
             );
             ) {
                this.renderVariables(
                    container
                );
            }
        },


        /*
            this.updateLocalDraftIndicator();
        * Select a variable and display only
 
        * its configuration.
             this.renderWelcome();
        *
        },
        * No scrolling.
        */
        selectVariable(
            name
        ) {
             name =
                String(name || '')
                    .trim()
                    .toUpperCase();


            if (!name) {
        renderWelcome() {
                return;
            this.workspace.empty();
            }


             const available =
             const section =
                 ['PAGE'].concat(
                 this.createSection('Get started');
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis
                                .variables
                            : []
                    ).filter(
                        variable =>
                            variable !==
                            'PAGE'
                    )
                );


             if (
             $('<p>')
                 !available.includes(
                 .text(
                     name
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                 )
                 )
            ) {
                .appendTo(section);
                return;
            }


             this.state.selectedVariable =
             const tips =
                 name;
                 $('<ul>')
 
                    .addClass(
            this.renderVariablesBySelector();
                        'preload-editor-tips'
                    );


             this.renderVariableConfigurationBySelector();
             [
        },
                '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);
                }
            );


        renderVariableConfigurationBySelector() {
             section.append(tips);
             const container =
             this.workspace.append(section);
                this.root &&
                this.root.find(
                    '.preload-editor-variable-configuration'
                );
 
             if (
                container &&
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
            }
         },
         },


         renderVariableConfiguration(
         setStatus(
             container
             message,
            type
         ) {
         ) {
             container.empty();
             if (!this.status) {
                return;
            }


             const analysis =
             this.status.removeClass(
                 this.analysis ||
                'is-error',
                 this.analyzePreload(
                'is-success',
                    this.extractIncludeonly(
                 'is-warning',
                        this.getEditorContent()
                 'is-loading'
                     )
            );
 
            if (type) {
                this.status.addClass(
                     'is-' + type
                 );
                 );
            }


             const name =
             this.status.text(
                this.state.selectedVariable ||
                message || ''
                'PAGE';
            );
        },


            const fields =
        // =========================================================
                this.state.config &&
        // Load / create
                this.state.config.fields
        // =========================================================
                    ? this.state.config.fields
                    : {};


             const field =
        async loadExisting(title) {
                 fields[name] ||
             title =
                this.createDefaultField(
                 String(title || '').trim();
                    name,
                    analysis
                );


             if (
             if (!title) {
                name ===
                 mw.notify(
                'PAGE'
                     'Enter a preload page title first.',
            ) {
                    {
                 container.append(
                         type: 'warn'
                     this.createAutomaticPageCard(
                     }
                         field
                     )
                 );
                 );


Line 3,432: Line 3,226:
             }
             }


             container.append(
             this.setStatus(
                 this.createVariableCard(
                 'Loading preload...',
                    name,
                 'loading'
                    field,
                    analysis
                 )
             );
             );
        },


        /*
            try {
        * PAGE is automatic/precompiled.
                const page =
        */
                    await this.getPage(title);
 
                if (!page) {
                    const suggestions =
                        await this.findSimilarPreloads(
                            title
                        );


        createAutomaticPageCard(
                     this.renderMissingPage(
            field
                         title,
        ) {
                         suggestions
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                     .attr(
                         'data-variable',
                         'PAGE'
                     );
                     );


            const header =
                    this.setStatus(
                $('<div>')
                        'Preload not found.',
                    .addClass(
                         'warning'
                         'preload-editor-variable-header'
                     );
                     );


            header.append(
                    return;
                 $('<h3>')
                 }
                    .text('PAGE'),


                 $('<span>')
                 await this.loadDefinition(
                     .addClass(
                     page.title,
                        'preload-editor-badge'
                     page.content
                    )
                );
                     .text(
                        'AUTOMATIC'
                    )
            );


            card.append(
                this.setStatus(
                header
                    'Preload loaded.',
            );
                     'success'
 
                 );
            $('<p>')
            } catch (error) {
                .addClass(
                 console.error(
                     'preload-editor-analysis-note'
                     'Preload Editor:',
                 )
                     error
                 .text(
                     'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(
                     card
                 );
                 );


            const label =
                 this.setStatus(
                 this.textInput(
                     error.message ||
                     field.label ||
                        'Could not load preload.',
                    'Page Name'
                     'error'
                ).prop(
                     'disabled',
                    true
                 );
                 );
            }
        },


             const description =
        async findSimilarPreloads(title) {
                 this.textarea(
             let query =
                     field.description ||
                 title
                    'Name of the page.'
                     .replace(
                )
                        /\/Preload$/i,
                    .addClass(
                         ''
                         'preload-editor-small-textarea'
                     )
                     )
                     .prop(
                     .trim();
                        'disabled',
 
                        true
            if (!query) {
                     );
                query = title;
            }
 
            try {
                const results =
                     await this.searchPages(query);


            const type =
                 return results.filter(
                 this.textInput(
                     result =>
                     field.type ||
                        /\/Preload$/i.test(
                    'page'
                            result.title
                ).prop(
                        )
                    'disabled',
                    true
                 );
                 );
 
             } catch (error) {
             const required =
                 console.error(
                this.checkbox(
                     'Preload Editor search:',
                    field.required !==
                     error
                        false
                 ).prop(
                     'disabled',
                     true
                 );
                 );


             const namespace =
                return [];
                this.textInput(
             }
                    field.namespace ||
        },
                    'Main'
 
                ).prop(
        renderMissingPage(
                    'disabled',
            title,
                    true
            suggestions
                );
        ) {
            this.workspace.empty();


             const allowNew =
             const section =
                 this.checkbox(
                 this.createSection(
                     field['allow-new'] ===
                     'Preload not found'
                        true
                ).prop(
                    'disabled',
                    true
                 );
                 );


             card.append(
             $('<p>')
                 this.fieldRow(
                 .text(
                     'Label',
                     'No preload exists at "' +
                     label
                     title +
                 ),
                    '".'
                 )
                .appendTo(section);


                 this.fieldRow(
            if (suggestions.length) {
                     'Description',
                 $('<h3>')
                     description
                     .text('Similar preloads')
                ),
                     .appendTo(section);


                 this.fieldRow(
                 const list =
                    'Type',
                    $('<div>')
                    type
                        .addClass(
                ),
                            'preload-editor-suggestions'
                        );


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


                 this.fieldRow(
                 section.append(list);
                    'Namespace',
            }
                    namespace
                ),


                 this.fieldRow(
            section.append(
                     'Allow new page',
                 this.createButton(
                     allowNew
                     'Create this preload',
                    'preload-editor-button-primary',
                     () =>
                        this.startNew(title)
                 )
                 )
             );
             );


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


         createVariableCard(
         async startNew(title) {
            name,
             title =
            field,
                 String(title || '').trim();
            analysis
 
        ) {
            this.state = {
             const card =
                preloadTitle: title,
                 $('<div>')
                preloadSource: '',
                    .addClass(
                preloadContent:
                        'preload-editor-variable'
                     this.defaults.preload,
                     )
 
                     .attr(
                config:
                        'data-variable',
                     this.emptyConfig(),
                        name
 
                    );
                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
            };


             const header =
             this.saveDraft();
                $('<div>')
            this.renderEditor();
                    .addClass(
                        'preload-editor-variable-header'
                    );


             header.append(
             this.setStatus(
                 $('<h3>')
                 'Creating a new preload.',
                    .text(name)
                'success'
             );
             );
        },


            if (
        async loadSamplePage() {
                !analysis.variables.includes(
             const result =
                    name
                 await this.createPromptDialog(
                )
                     'Load Sample Page',
             ) {
                    'Enter the title of a normal wiki page to use as the starting point.'
                 header.append(
                     $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text(
                            'UNUSED'
                        )
                 );
                 );
            if (!result) {
                return;
             }
             }


             card.append(
             this.setStatus(
                 header
                 'Loading sample page...',
                'loading'
             );
             );


             const label =
             try {
                this.textInput(
                const page =
                    field.label || ''
                    await this.getPage(result);
                );


            label.on(
                 if (!page) {
                'input.preloadEditor',
                     throw new Error(
                 () => {
                        'Sample page not found: ' +
                     field.label =
                         result
                         label.val();
                    );
                }


                     this.markDirty();
                const sample =
                     this.convertSampleToPreload(
                        page.content
                    );


                    this.renderConfigPreviewBySelector();
                this.state = {
                }
                    preloadTitle: '',
            );
                    preloadSource: '',
                    preloadContent: sample,


            card.append(
                    config:
                this.fieldRow(
                        this.emptyConfig(),
                    'Label',
                    label
                )
            );


            const description =
                    variables: ['PAGE'],
                this.textarea(
                     conditions: [],
                     field.description ||
                     selectedVariable: 'PAGE',
                     ''
                    deletedVariables: [],
                ).addClass(
                     mode: 'new',
                     'preload-editor-small-textarea'
                    dirty: true,
                );
                    dirtyPreload: true,
                    dirtyConfig: true,


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


                    this.markDirty();
                this.reanalyze();
                this.saveDraft();
                this.renderEditor();


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


            card.append(
                 this.setStatus(
                 this.fieldRow(
                     error.message ||
                     'Description',
                        'Could not load sample page.',
                     description
                     'error'
                 )
                 );
             );
             }
        },


             const types = [
        convertSampleToPreload(source) {
                [
             let content =
                    'text',
                 String(source || '').trim();
                    'Text'
                ],
                 [
                    'textarea',
                    'Textarea'
                ],
                [
                    'number',
                    'Number'
                ],
                [
                    'boolean',
                    'Boolean'
                ],
                [
                    'select',
                    'Select'
                ],
                [
                    'multiselect',
                    'Multi-select'
                ],
                [
                    'page',
                    'Page'
                ],
                [
                    'user',
                    'User'
                ],
                [
                    'date',
                    'Date'
                ]
            ];


             const typeSelect =
             const include =
                 this.select(
                 content.match(
                     types.map(
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                        (
                            [
                                value,
                                label
                            ]
                        ) => ({
                            value,
                            label
                        })
                    ),
                    field.type ||
                        'text'
                 );
                 );


             typeSelect.on(
             if (include) {
                 'change.preloadEditor',
                 content =
                () => {
                     include[1].trim();
                     field.type =
            }
                        typeSelect.val();


                     this.markDirty();
            content =
                content
                     .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();


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


            card.append(
        async loadDefinition(
                this.fieldRow(
            title,
                    'Type',
            source
                    typeSelect
        ) {
                )
             const content =
             );
                this.extractIncludeonly(source);


             const required =
             let config =
                 this.checkbox(
                 this.emptyConfig();
                    field.required ===
                        true
                );


             required.on(
             const configTitle =
                'change.preloadEditor',
                title.replace(
                 () => {
                    /\/+$/,
                    field.required =
                    ''
                        required.prop(
                 ) +
                            'checked'
                '/config.json';
                        );


                    this.markDirty();
            const configPage =
                await this.getPage(configTitle);


                     this.renderConfigPreviewBySelector();
            if (configPage) {
                 }
                try {
            );
                     config =
 
                        JSON.parse(
             card.append(
                            configPage.content
                 this.fieldRow(
                        );
                    'Required',
                 } catch (error) {
                    required
                    throw new Error(
                )
                        'The existing config.json contains invalid JSON: ' +
             );
                        error.message
                    );
                }
            }
 
             const analysis =
                 this.analyzePreload(content);
 
             this.state.deletedVariables = [];


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


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


                    if (value) {
                variables:
                        field.placeholder =
                     analysis.variables,
                            value;
                     } else {
                        delete field.placeholder;
                    }


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


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


            card.append(
                 deletedVariables: [],
                 this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );


            const defaultInput =
                 mode: 'edit',
                 this.textInput(
                dirty: false,
                    field.default ===
                 dirtyPreload: false,
                        undefined
                dirtyConfig: false,
                        ? ''
                        : field.default
                 );


            defaultInput.on(
                 localDraftSavedAt: null,
                 'input.preloadEditor',
                 localDraftAvailable: false
                 () => {
            };
                    const value =
                        defaultInput.val();


                    if (value) {
            this.clearDraft(title);
                        field.default =
            this.renderEditor();
                            value;
        },
                    } else {
                        delete field.default;
                    }


                    this.markDirty();
        // =========================================================
        // Editor
        // =========================================================


                    this.renderConfigPreviewBySelector();
        renderEditor() {
                }
            this.destroyEditor();
             );
             this.workspace.empty();


             card.append(
             const layout =
                this.fieldRow(
                $('<div>')
                     'Default',
                    .addClass(
                     defaultInput,
                        'preload-editor-layout'
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                     );
                )
 
            );
            const left =
                $('<div>')
                     .addClass(
                        'preload-editor-left'
                    );


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


                 maxRows.on(
            const editorSection =
                     'input.preloadEditor',
                 this.createSection(
                     () => {
                     'Preload',
                        const value =
                     'preload-editor-main-section'
                            parseInt(
                );
                                maxRows.val(),
                                10
                            );


                        if (
            const meta =
                            Number.isFinite(
                $('<div>')
                                value
                    .addClass(
                            ) &&
                         'preload-editor-meta'
                            value > 0
                    );
                        ) {
                            field.maxRows =
                                value;
                         } else {
                            delete field.maxRows;
                        }


                        this.markDirty();
            $('<strong>')
 
                 .text(
                        this.renderConfigPreviewBySelector();
                     this.state.preloadTitle ||
                    }
                    'New preload'
                );
                )
 
                 .appendTo(meta);
                 card.append(
                     this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                 );
            }


             if (
             if (
                 field.type ===
                 this.state.mode === 'new'
                    'select' ||
                field.type ===
                    'multiselect'
             ) {
             ) {
                 this.renderSelectConfiguration(
                 $('<span>')
                     card,
                    .addClass(
                     field
                        'preload-editor-badge'
                );
                     )
                     .text('NEW')
                    .appendTo(meta);
             }
             }


             return card;
             editorSection.append(meta);
        },
            editorSection.append(
                this.renderEditorTools()
            );


        renderSelectConfiguration(
             const textarea =
            card,
                 this.textarea(
            field
                     this.state.preloadContent
        ) {
                )
             const source =
                    .attr(
                 this.textInput(
                        'id',
                     field.source || '',
                        'preload-editor-content'
                     'category:Example'
                     )
                );
                    .addClass(
                        'preload-editor-content'
                    );


             source.on(
             const editorMount =
                'input.preloadEditor',
                $('<div>')
                () => {
                    .addClass(
                     const value =
                        'preload-editor-codemirror-mount'
                        source.val();
                    )
                     .append(textarea);


                    if (value) {
            editorSection.append(editorMount);
                        field.source =
            left.append(editorSection);
                            value;
                    } else {
                        delete field.source;
                    }


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


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


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


             const sourcePrefix =
             const variablesSection =
                 this.textInput(
                 this.createSection('Variables');
                     field['source-prefix'] ||
 
                     ''
            const detectVariablesButton =
                this.createButton(
                     'Detect variables',
                     'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                 );
                 );


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


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


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


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


             const excludeCategory =
             const configurationSection =
                 this.textInput(
                 this.createSection(
                    field.exclude &&
                     'Variable configuration'
                    field.exclude.category ||
                     ''
                 );
                 );


             excludeCategory.on(
             /*
                'input.preloadEditor',
            * Import button lives at the top of the
                () => {
            * variable configuration section so the
                    const value =
            * workflow is always easy to find.
                         excludeCategory.val();
            */
            const importDefinitionsButton =
                this.createButton(
                    'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                         this.importVariableDefinitions()
                );


                    if (value) {
            const importHelp =
                        field.exclude =
                $('<div>')
                            Object.assign(
                    .addClass(
                                {},
                        'preload-editor-help preload-editor-import-definitions-help'
                                field.exclude ||
                    )
                                    {},
                     .text(
                                {
                         'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                                    category:
                     );
                                        value
                                }
                            );
                     } else if (
                         field.exclude
                     ) {
                        delete field.exclude
                            .category;


                        if (
            const importControls =
                            !Object.keys(
                $('<div>')
                                field.exclude
                    .addClass(
                            ).length
                        'preload-editor-import-definition-controls'
                         ) {
                    )
                            delete field.exclude;
                    .append(
                         }
                         importDefinitionsButton,
                     }
                         importHelp
                     );


                    this.markDirty();
            configurationSection.append(
                importControls
            );


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


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


             card.append(
             const configSection =
                 this.createTransformControls(
                this.createSection(
                     field,
                    'Configuration'
                     'value',
                );
                     'Value transformation'
 
                 ),
            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()
                 );


                this.createTransformControls(
            configSection.append(
                    field,
                configHelp,
                    'label',
                 reviewConfigButton
                    'Label transformation'
                 )
             );
             );


             const optionsValue =
             right.append(
                Array.isArray(
                analysisSection,
                    field.options
                 variablesSection,
                 )
                configurationSection,
                    ? field.options
                configSection
                        .map(
            );
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


                                return (
            layout.append(
                                    String(
                left,
                                        option.value ||
                right
                                        ''
            );
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';


             const options =
             const saveBar =
                 this.textarea(
                 $('<div>')
                     optionsValue
                     .addClass(
                ).addClass(
                        'preload-editor-save-bar'
                    'preload-editor-small-textarea'
                    );
                );


             options.on(
             saveBar.append(
                 'input.preloadEditor',
                 this.createButton(
                () => {
                    'Save Preload',
                     const lines =
                     '',
                        options
                    () =>
                            .val()
                        this.savePreloadOnly()
                            .split('\n')
                ),
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(
                                Boolean
                            );


                    if (!lines.length) {
                this.createButton(
                        delete field.options;
                    'Save Config',
                     } else {
                     '',
                        field.options =
                    () =>
                            lines.map(
                        this.saveConfigOnly()
                                line => {
                ),
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );


                                    if (
                this.createButton(
                                        parts.length ===
                    'Save',
                                        1
                    'preload-editor-button-primary',
                                    ) {
                    () =>
                                        return parts[0];
                        this.saveAll()
                                    }
                )
            );


                                    return {
            this.root
                                        value:
                .find('.preload-editor-footer')
                                            parts[0],
                .append(saveBar);


                                        label:
            this.workspace.append(
                                            parts
                layout
                                                .slice(
            );
                                                    1
                                                )
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }


                    this.markDirty();
            this.reanalyze();


                    this.renderConfigPreviewBySelector();
            this.renderVariables(
                 }
                 variableContainer
             );
             );


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


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


             $('<h4>')
             this.updateEditorTools();
                .text(title)
            this.updateLocalDraftIndicator();
                .appendTo(
                    wrapper
                );


             const existing =
             this.mountCodeMirror(
                 field[property] &&
                 textarea.get(0)
                 typeof field[property] ===
            ).catch(
                     'object'
                 error => {
                    ? field[property]
                     console.error(
                     : {};
                        'Preload Editor CodeMirror:',
                        error
                     );


            const transform =
                    this.setStatus(
                this.select(
                         error.message ||
                    [
                             'Could not initialize CodeMirror.',
                         {
                         'error'
                             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(
        // Variable detection
                    existing.prefix ||
        // =========================================================
                    ''
                );


             const suffix =
        detectVariables() {
                 this.textInput(
             const source =
                    existing.suffix ||
                 this.getEditorContent();
                    ''
 
                 );
            this.state.preloadContent =
                 source;


             const from =
             const content =
                 this.textInput(
                 this.extractIncludeonly(
                     existing.from ||
                     source
                    ''
                 );
                 );


             const to =
             const analysis =
                 this.textInput(
                 this.analyzePreload(
                     existing.to ||
                     content
                    ''
                 );
                 );


             const controls =
             /*
                $('<div>')
            * If a variable was previously deleted from
                    .addClass(
            * the configuration, detecting the current
                        'preload-editor-transform-controls'
            * 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()
                            )
                     );
                     );


            const prefixRow =
                this.state.deletedVariables =
                this.fieldRow(
                    this.state.deletedVariables
                    'Prefix',
                        .filter(
                    prefix
                            name =>
                 );
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                 this.state.deletedVariables = [];
            }
 
            this.markDirty();


             const suffixRow =
             this.reanalyze();
                this.fieldRow(
                    'Suffix',
                    suffix
                );


             const fromRow =
             this.renderVariablesBySelector();
                this.fieldRow(
            this.renderVariableConfigurationBySelector();
                    'From',
            this.renderAnalysisBySelector();
                    from
            this.updateEditorTools();
                );


             const toRow =
             this.saveDraft();
                this.fieldRow(
                    'To',
                    to
                );


             const renderInputs =
             this.setStatus(
                 () => {
                 'Variables detected from the current preload.',
                    const type =
                'success'
                        transform.val();
            );
        },


                    prefixRow.toggle(
        reanalyze() {
                        type ===
            const source =
                            'remove-prefix'
                this.getEditorContent();
                    );


                    suffixRow.toggle(
            const content =
                        type ===
                this.extractIncludeonly(source);
                            'remove-suffix'
                    );


                    fromRow.toggle(
            const analysis =
                        type ===
                this.analyzePreload(
                            'replace'
                    content
                    );
                );


                    toRow.toggle(
            this.state.preloadContent =
                        type ===
                 source;
                            'replace'
                    );
                 };


             const update =
             this.state.variables =
                 () => {
                 analysis.variables;
                    const type =
                        transform.val();


                    let object =
            this.state.conditions =
                        null;
                analysis.conditions;


                    if (
            this.state.config =
                        type ===
                this.prepareConfigForVariables(
                            'remove-prefix' &&
                     this.state.config ||
                        prefix.val()
                         this.emptyConfig(),
                    ) {
                    analysis
                        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) {
            this.analysis =
                         field[property] =
                analysis;
                             object;
 
                     } else {
            const available =
                        delete field[property];
                ['PAGE'].concat(
                    }
                     analysis.variables.filter(
                         name =>
                             name !== 'PAGE'
                     )
                );


                     this.markDirty();
            if (
                !available.includes(
                     this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },


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


            transform.on(
        renderAnalysis(container) {
                'change.preloadEditor',
            container.empty();
                () => {
                    update();
                    renderInputs();
                }
            );


             [
             const analysis =
                 prefix,
                 this.analysis ||
                suffix,
                 this.analyzePreload(
                from,
                     this.extractIncludeonly(
                 to
                         this.getEditorContent()
            ].forEach(
                     )
                input => {
                 );
                     input.on(
                         'input.preloadEditor',
                        update
                     );
                 }
            );


             controls.append(
             const variableCount =
                 this.fieldRow(
                 analysis.variables.length;
                    'Transformation',
                    transform
                ),


                prefixRow,
            const conditionCount =
                suffixRow,
                 analysis.conditions.length;
                fromRow,
                 toRow
            );


             renderInputs();
             const configuredCount =
                Object.keys(
                    this.state.config &&
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;


             wrapper.append(
             const summary =
                controls
                $('<div>')
            );
                    .addClass(
                        'preload-editor-analysis-summary'
                    );


             return wrapper;
             const createMetric =
        },
                (
 
                    value,
        // Config output
                    label
                ) =>
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


        getCleanConfig() {
                            $('<span>')
            const config =
                                .addClass(
                JSON.parse(
                                    'preload-editor-analysis-label'
                    JSON.stringify(
                                )
                         this.state.config
                                .text(label)
                    )
                         );
                );


             const fields =
             summary.append(
                 config.fields || {};
                createMetric(
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                 ),


            const orderedFields =
                createMetric(
                 {};
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                 ),


            /*
                 createMetric(
            * PAGE is always first and automatic.
                    configuredCount,
            */
                     configuredCount === 1
            orderedFields.PAGE =
                         ? 'configured field'
                 this.getAutomaticPageField();
                         : 'configured fields'
 
            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.append(summary);
            container
        ) {
             if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },
 
        renderConfigPreviewBySelector() {
            const preview =
                this.root &&
                this.root.find(
                    '.preload-editor-config-preview'
                );


             if (
             if (
                 preview &&
                 analysis.conditionVariables.length
                preview.length
             ) {
             ) {
                 this.renderConfigPreview(
                 container.append(
                     preview
                     $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                 );
                 );
             }
             }


             this.renderAnalysisBySelector();
             const validation =
        },
                this.validateConfig(
                    this.state.config,
                    analysis
                );


        markDirty() {
            if (validation.errors.length) {
            this.state.dirty = true;
                const errors =
        },
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-errors'
                        );


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


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


             if (!title) {
             if (validation.warnings.length) {
                 const result =
                 const warnings =
                     await this.createPromptDialog(
                     $('<ul>')
                        'Preload title',
                         .addClass(
                         'Enter the full title for the preload.'
                            'preload-editor-validation-warnings'
                    );
                        );


                 if (!result) {
                 validation.warnings.forEach(
                    return;
                    warning => {
                }
                        $('<li>')
 
                            .text(warning)
                 title = result;
                            .appendTo(warnings);
                    }
                 );


                 this.state.preloadTitle =
                 container.append(warnings);
                    title;
             }
             }
            /*
            * Always pull the actual CodeMirror
            * document before saving.
            */
            this.state.preloadContent =
                this.getEditorContent();
            const validation =
                this.validateBeforeSave();


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


            this.setStatus(
        renderAnalysisBySelector() {
                'Saving preload...',
             const container =
                'loading'
                this.root &&
            );
                 this.root.find(
 
                     '.preload-editor-analysis'
             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 =
            if (
                    'edit';
                container &&
                container.length
            ) {
                 this.renderAnalysis(container);
            }
        },


                this.state.dirty =
        // =========================================================
                    false;
        // Variables
        // =========================================================


                this.setStatus(
        renderVariables(container) {
                    'Preload saved successfully.',
            container.empty();
                    'success'
                );


                 mw.notify(
            const analysis =
                     'Preload saved.',
                 this.analysis ||
                    {
                this.analyzePreload(
                         type:
                     this.extractIncludeonly(
                            'success'
                         this.getEditorContent()
                    }
                     )
                );
            } catch (
                error
            ) {
                console.error(
                     'Preload Editor save:',
                    error
                 );
                 );


                 this.setStatus(
            const variables =
                    error.message ||
                 analysis.variables.slice();
                        'Could not save preload.',
 
                    'error'
            const ordered =
                );
                ['PAGE'];


                mw.notify(
            variables.forEach(
                     error.message ||
                name => {
                         'Could not save preload.',
                     if (
                     {
                         name !== 'PAGE' &&
                         type:
                        !ordered.includes(name)
                            'error'
                     ) {
                         ordered.push(name);
                     }
                     }
                 );
                 }
            }
            );
        },


        async saveAll() {
             const configuredFields =
             let title =
                 this.state.config &&
                 String(
                this.state.config.fields
                    this.state.preloadTitle ||
                     ? Object.keys(
                     ''
                        this.state.config.fields
                ).trim();
                    )
                    : [];


             if (!title) {
             configuredFields.forEach(
                 const result =
                 name => {
                     await this.createPromptDialog(
                     const upper =
                        'Preload title',
                         name.toUpperCase();
                         'Enter the full title for the preload.'
                    );


                if (!result) {
                    if (
                     return;
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                     }
                 }
                 }
            );


                 title = result;
            const deleted =
                 Array.isArray(
                    this.state.deletedVariables
                )
                    ? this.state.deletedVariables
                    : [];


                 this.state.preloadTitle =
            deleted.forEach(
                     title;
                 name => {
            }
                     const upper =
                        String(name).toUpperCase();


            /*
                    if (
            * Always use the actual CodeMirror
                        upper !== 'PAGE' &&
            * document when saving.
                        !ordered.includes(upper)
            */
                    ) {
            this.state.preloadContent =
                        ordered.push(upper);
                 this.getEditorContent();
                    }
                 }
            );


             /*
             const list =
            * Make sure the configuration is
                $('<div>')
            * synchronized with anything newly
                    .addClass(
            * typed into the preload.
                        'preload-editor-variable-list'
            *
                    );
            * This means even if the user forgot
            * to click Detect variables, saving
            * will still catch new variables.
            */
            this.reanalyze();


             const validation =
             ordered.forEach(
                this.validateBeforeSave();
                name => {
                    const isSelected =
                        name ===
                        this.state.selectedVariable;


            if (
                    const isUsed =
                validation.errors.length
                        analysis.variables.includes(
            ) {
                            name
                this.showValidationErrors(
                        );
                    validation
                );


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


            const configTitle =
                    const item =
                title.replace(
                        $('<button>')
                    /\/+$/,
                            .attr({
                    ''
                                type: 'button',
                ) +
                                'data-variable':
                '/config.json';
                                    name
                            })
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


            this.setStatus(
                    $('<span>')
                'Saving preload and config...',
                        .addClass(
                'loading'
                            'preload-editor-variable-name'
            );
                        )
                        .text(name)
                        .appendTo(item);


            try {
                    if (name === 'PAGE') {
                const preloadExists =
                        item.append(
                     await this.pageExists(
                            $('<span>')
                         title
                                .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')
                        );
                    }


                await this.savePage(
                    list.append(item);
                    title,
                }
                    this.state.preloadContent,
            );
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );


                const configExists =
            container.append(list);
                    await this.pageExists(
                        configTitle
                    );


                 await this.savePage(
            if (!ordered.length) {
                     configTitle,
                 container.append(
                    this.getConfigJSON(),
                     $('<div>')
                    configExists
                        .addClass(
                        ? 'Updated preload config with Preload Editor'
                            'preload-editor-empty'
                         : 'Created preload config with Preload Editor',
                         )
                    !configExists
                        .text(
                            'No variables found in the preload.'
                        )
                 );
                 );
            }
        },


                 this.state.mode =
        renderVariablesBySelector() {
                     'edit';
            const container =
                 this.root &&
                this.root.find(
                     '.preload-editor-variables'
                );


                 this.state.dirty =
            if (
                    false;
                container &&
                container.length
            ) {
                 this.renderVariables(container);
            }
        },


                 this.state.preloadTitle =
        selectVariable(name) {
                     title;
            name =
                 String(name || '')
                    .trim()
                     .toUpperCase();


                this.setStatus(
            if (!name) {
                    'Preload and config saved successfully.',
                 return;
                    'success'
            }
                 );


                 mw.notify(
            const available =
                     'Preload and config saved.',
                 ['PAGE'].concat(
                    {
                     (
                        type:
                        this.analysis &&
                             'success'
                        this.analysis.variables
                     }
                            ? this.analysis.variables
                );
                             : []
            } catch (
                     ).filter(
                error
                        variable =>
            ) {
                            variable !== 'PAGE'
                console.error(
                     )
                    'Preload Editor save:',
                     error
                 );
                 );


                 this.setStatus(
            const configuredUnused =
                     error.message ||
                this.state.config &&
                         'Could not save preload/config.',
                 this.state.config.fields
                     'error'
                     ? Object.keys(
                );
                         this.state.config.fields
                     )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];


                mw.notify(
            configuredUnused.forEach(
                     error.message ||
                variable => {
                         'Could not save preload/config.',
                     if (
                     {
                        !available.includes(variable) &&
                         type:
                         variable !== 'PAGE'
                            'error'
                     ) {
                         available.push(variable);
                     }
                     }
                 );
                 }
            );
 
            if (!available.includes(name)) {
                return;
             }
             }
            this.state.selectedVariable =
                name;
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
         },
         },


         validateBeforeSave() {
         renderVariableConfigurationBySelector() {
             const errors = [];
             const container =
            const warnings = [];
                 this.root &&
 
                 this.root.find(
            const title =
                     '.preload-editor-variable-configuration'
                 String(
                    this.state.preloadTitle ||
                    ''
                 ).trim();
 
            if (!title) {
                errors.push(
                     'A preload title is required.'
                 );
                 );
            }


             if (
             if (
                 title &&
                 container &&
                 !/\/Preload$/i.test(
                 container.length
                    title
                )
             ) {
             ) {
                 warnings.push(
                 this.renderVariableConfiguration(
                     'The title does not end with "/Preload".'
                     container
                 );
                 );
             }
             }
        },


             const content =
        renderVariableConfiguration(container) {
                this.getEditorContent();
             container.empty();


             this.state.preloadContent =
             const analysis =
                 content;
                this.analysis ||
 
                 this.analyzePreload(
            if (!content.trim()) {
                    this.extractIncludeonly(
                errors.push(
                        this.getEditorContent()
                     'The preload cannot be empty.'
                     )
                 );
                 );
            }


             if (
             const name =
                 !/<includeonly>/i.test(
                this.state.selectedVariable ||
                     content
                'PAGE';
                 )
 
             ) {
            const fields =
                 warnings.push(
                this.state.config &&
                     'The preload does not contain an <includeonly> section.'
                 this.state.config.fields
                    ? this.state.config.fields
                     : {};
 
            const field =
                 fields[name];
 
             if (name === 'PAGE') {
                 container.append(
                     this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                 );
                 );
                return;
             }
             }


             if (
             if (!field) {
                 !/<noinclude>/i.test(
                 const missing =
                    content
                    $('<div>')
                )
                        .addClass(
            ) {
                            'preload-editor-variable preload-editor-variable-missing'
                warnings.push(
                        );
                    'The preload does not contain a <noinclude> section.'
                );
            }


            const analysis =
                 $('<div>')
                 this.analyzePreload(
                     .addClass(
                     this.extractIncludeonly(
                         'preload-editor-variable-header'
                         content
                     )
                     )
                );
                    .append(
                        $('<h3>')
                            .text(name),


            /*
                        $('<span>')
            * Synchronize configuration one final
                            .addClass(
            * time before saving.
                                'preload-editor-badge is-warning'
            *
                            )
            * This catches variables even if the
                            .text(
            * user never clicked Detect variables.
                                'NOT CONFIGURED'
            */
                            )
            this.state.config =
                    )
                this.prepareConfigForVariables(
                     .appendTo(missing);
                     this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


            const configValidation =
                $('<p>')
                this.validateConfig(
                    .addClass(
                     this.state.config,
                        'preload-editor-analysis-note'
                     analysis
                    )
                );
                     .text(
                        'This variable is currently not present in config.json.'
                     )
                    .appendTo(missing);


            errors.push(
                container.append(missing);
                 ...configValidation.errors
                 return;
             );
             }


             warnings.push(
             container.append(
                 ...configValidation.warnings
                 this.createVariableCard(
                    name,
                    field,
                    analysis
                )
             );
             );
        },


             let depth = 0;
        createAutomaticPageCard(field) {
             const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );


             analysis.conditions.forEach(
             const header =
                 condition => {
                $('<div>')
                     if (
                    .addClass(
                         condition.type ===
                        'preload-editor-variable-header'
                         'if'
                    );
                     ) {
 
                         depth++;
            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 (
                     } else if (
                         condition.type ===
                        field.exclude
                         'endif'
                    ) {
                     ) {
                        delete field.exclude.category;
                         depth--;
 
                        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();


                        if (
             this.saveDraft();
                            depth < 0
                        ) {
                            errors.push(
                                'Found @endif without a matching @if.'
                            );
 
                            depth = 0;
                        }
                    } else if (
                        condition.type ===
                            'elseif' ||
                        condition.type ===
                            'else'
                    ) {
                        if (
                            depth === 0
                        ) {
                            errors.push(
                                '@' +
                                condition.type +
                                ' exists outside an @if block.'
                            );
                        }
                    }
                }
            );
 
            if (depth > 0) {
                errors.push(
                    'One or more @if blocks are missing @endif.'
                );
            }
 
            return {
                errors,
                warnings,
                valid:
                    errors.length === 0
            };
        },
 
        showValidationErrors(
            validation
        ) {
             this.renderAnalysisBySelector();


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


             mw.notify(
             mw.notify(
                 validation.errors.join(
                 validation.errors.join('\n'),
                    '\n'
                ),
                 {
                 {
                     type:
                     type: 'error'
                        'error'
                 }
                 }
             );
             );
Line 4,907: Line 6,213:
     $(function () {
     $(function () {
         if (
         if (
             mw.config.get(
             mw.config.get('wgPageName') !==
                'wgPageName'
             'Petit_Planet_Wiki:Preload_Editor'
            ) !==
             'Petit_Planet:Preload_Editor'
         ) {
         ) {
             return;
             return;