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


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


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


Line 24: Line 30:
         workspace: null,
         workspace: null,
         status: null,
         status: null,
        localDraftStatus: null,
         editorTools: null,
         editorTools: null,


         draftStorageKey:
         draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',
            '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'
         },
         },


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


         getDraftStorage() {
         getDraftStorage() {
             try {
             try {
                 const raw =
                 const raw = window.localStorage.getItem(this.draftStorageKey);
                    window.localStorage.getItem(
                        this.draftStorageKey
                    );


                 if (!raw) {
                 if (!raw) {
Line 50: Line 54:
                 }
                 }


                 const parsed =
                 const parsed = JSON.parse(raw);
                    JSON.parse(raw);


                 if (
                 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
                    !parsed ||
                    typeof parsed !== 'object' ||
                    Array.isArray(parsed)
                ) {
                     return {
                     return {
                         active: null,
                         active: null,
Line 64: Line 63:
                 }
                 }


                 if (
                 if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
                    !parsed.drafts ||
                    typeof parsed.drafts !== 'object' ||
                    Array.isArray(parsed.drafts)
                ) {
                     parsed.drafts = {};
                     parsed.drafts = {};
                 }
                 }
Line 74: Line 69:
                 return parsed;
                 return parsed;
             } catch (error) {
             } catch (error) {
                 console.warn(
                 console.warn('Preload Editor: Could not read local drafts.', error);
                    'Preload Editor: Could not read local drafts.',
                    error
                );


                 return {
                 return {
Line 88: Line 80:
         setDraftStorage(storage) {
         setDraftStorage(storage) {
             try {
             try {
                 window.localStorage.setItem(
                 window.localStorage.setItem(this.draftStorageKey, JSON.stringify(storage));
                    this.draftStorageKey,
                    JSON.stringify(storage)
                );
 
                 return true;
                 return true;
             } catch (error) {
             } catch (error) {
                 console.warn(
                 console.warn('Preload Editor: Could not save local draft.', error);
                    'Preload Editor: Could not save local draft.',
                    error
                );
 
                 return false;
                 return false;
             }
             }
Line 105: Line 89:


         getDraftId(title) {
         getDraftId(title) {
             title =
             title = String(title || '').trim();
                String(title || '').trim();
             return title ? title.toLowerCase() : '__untitled__';
 
             return title
                ? title.toLowerCase()
                : '__untitled__';
         },
         },


         getDraftSnapshot() {
         getDraftSnapshot() {
             let content =
             let content = this.getEditorContent();
                this.getEditorContent();


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


Line 129: Line 103:


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


             return {
             return {
                 version: 1,
                 version: 3,
                preloadTitle: String(this.state.preloadTitle || ''),
                preloadSource: String(this.state.preloadSource || ''),
                preloadContent: String(content || ''),
                config,


                 preloadTitle:
                 variables: Array.isArray(this.state.variables)
                     String(
                     ? this.state.variables.slice()
                        this.state.preloadTitle || ''
                     : [],
                     ),


                 preloadSource:
                 conditions: Array.isArray(this.state.conditions)
                     String(
                     ? this.state.conditions.slice()
                        this.state.preloadSource || ''
                     : [],
                     ),


                 preloadContent:
                 selectedVariable: String(this.state.selectedVariable || 'PAGE'),
                    String(
                        content || ''
                    ),


                 config,
                 deletedVariables: Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.slice()
                    : [],


                 variables:
                 mode: this.state.mode || 'edit',
                    Array.isArray(
                dirty: !!this.state.dirty,
                        this.state.variables
                dirtyPreload: !!this.state.dirtyPreload,
                    )
                dirtyConfig: !!this.state.dirtyConfig,
                        ? this.state.variables.slice()
                savedAt: Date.now()
                        : [],
            };
        },


                conditions:
        updateLocalDraftStatus(message, type) {
                    Array.isArray(
            if (!this.localDraftStatus) {
                        this.state.conditions
                return;
                    )
            }
                        ? this.state.conditions.slice()
                        : [],


                 selectedVariable:
            this.localDraftStatus.removeClass(
                    String(
                 'is-saved',
                        this.state.selectedVariable ||
                'is-warning',
                        'PAGE'
                'is-error',
                    ),
                'is-empty'
            );


                deletedVariables:
            if (type) {
                    Array.isArray(
                this.localDraftStatus.addClass('is-' + type);
                        this.state.deletedVariables
            }
                    )
                        ? this.state.deletedVariables.slice()
                        : [],


                mode:
            this.localDraftStatus.text(message || '');
                    this.state.mode ||
        },
                    'edit',


                 dirty: true,
        formatLocalDraftTime(timestamp) {
            if (!timestamp) {
                 return '';
            }


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


         saveDraft() {
         updateLocalDraftIndicator() {
             if (!this.state.dirty) {
             if (!this.localDraftStatus) {
                 return;
                 return;
             }
             }


             const snapshot =
             if (this.state.localDraftSavedAt) {
                this.getDraftSnapshot();
                const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);


            const id =
                 this.updateLocalDraftStatus(
                 this.getDraftId(
                     time ? 'Saved locally at ' + time : 'Saved locally',
                     snapshot.preloadTitle
                    'saved'
                 );
                 );


            const storage =
                 return;
                 this.getDraftStorage();
            }


             storage.drafts[id] =
             this.updateLocalDraftStatus('No local draft', 'empty');
                snapshot;
        },


        saveDraft() {
            if (!this.state.dirty) {
                return false;
            }
            const snapshot = this.getDraftSnapshot();
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();
            storage.drafts[id] = snapshot;
             storage.active = id;
             storage.active = id;


             this.setDraftStorage(
             const saved = this.setDraftStorage(storage);
                 storage
 
             );
            if (saved) {
                 this.state.localDraftSavedAt = snapshot.savedAt;
                this.state.localDraftAvailable = true;
                this.updateLocalDraftIndicator();
             } else {
                this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
            }
 
            return saved;
         },
         },


         clearDraft(title) {
         clearDraft(title) {
             const storage =
             const storage = this.getDraftStorage();
                this.getDraftStorage();
            const id = this.getDraftId(title);


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


             if (
             if (storage.active === id) {
                storage.active === id
            ) {
                 storage.active = null;
                 storage.active = null;
             }
             }


             this.setDraftStorage(
             this.setDraftStorage(storage);
                storage
 
             );
            this.state.localDraftSavedAt = null;
            this.state.localDraftAvailable = false;
 
             this.updateLocalDraftIndicator();
         },
         },


         getMostRecentDraft() {
         getMostRecentDraft() {
             const storage =
             const storage = this.getDraftStorage();
                this.getDraftStorage();


             if (
             if (!storage.drafts || !Object.keys(storage.drafts).length) {
                !storage.drafts ||
                !Object.keys(
                    storage.drafts
                ).length
            ) {
                 return null;
                 return null;
             }
             }


             if (
             if (storage.active && storage.drafts[storage.active]) {
                storage.active &&
                storage.drafts[
                    storage.active
                ]
            ) {
                 return {
                 return {
                     id: storage.active,
                     id: storage.active,
                     draft:
                     draft: storage.drafts[storage.active]
                        storage.drafts[
                            storage.active
                        ]
                 };
                 };
             }
             }
Line 287: Line 257:
             let latestDraft = null;
             let latestDraft = null;


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


                    if (
                if (
                        !latestDraft ||
                    !latestDraft ||
                        (
                    (Number(draft.savedAt) || 0) > (Number(latestDraft.savedAt) || 0)
                            Number(
                ) {
                                draft.savedAt
                    latestId = id;
                            ) || 0
                    latestDraft = draft;
                        ) >
                        (
                            Number(
                                latestDraft.savedAt
                            ) || 0
                        )
                    ) {
                        latestId = id;
                        latestDraft = draft;
                    }
                 }
                 }
             );
             });


             if (!latestDraft) {
             if (!latestDraft) {
Line 328: Line 282:


         async restoreDraft() {
         async restoreDraft() {
             const result =
             const result = this.getMostRecentDraft();
                this.getMostRecentDraft();


             if (
             if (!result || !result.draft) {
                !result ||
                !result.draft
            ) {
                 return false;
                 return false;
             }
             }


             const draft =
             const draft = result.draft;
                result.draft;
            const title = String(draft.preloadTitle || '').trim();
            const displayTitle = title || 'an untitled preload';


             const title =
             const savedAt = draft.savedAt
                String(
                 ? new Date(draft.savedAt).toLocaleString()
                    draft.preloadTitle || ''
                : '';
                ).trim();
 
            const displayTitle =
                title ||
                'an untitled preload';
 
            const savedAt =
                 draft.savedAt
                    ? new Date(
                        draft.savedAt
                    ).toLocaleString()
                    : '';


             const message =
             const message =
                 'Preload Editor found unsaved local work for ' +
                 'Preload Editor found unsaved local work for ' +
                 displayTitle +
                 displayTitle +
                 (
                 (savedAt ? '\n\nLast saved locally: ' + savedAt : '') +
                    savedAt
                        ? '\n\nLast saved locally: ' +
                          savedAt
                        : ''
                ) +
                 '\n\nRestore it?';
                 '\n\nRestore it?';


             const restore =
             const restore = await this.createConfirmDialog(
                await this.createConfirmDialog(
                'Restore unsaved work',
                    'Restore unsaved work',
                message,
                    message,
                'Restore',
                    'Restore',
                'Discard'
                    'Discard'
            );
                );


             if (!restore) {
             if (!restore) {
Line 381: Line 314:
             }
             }


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


             if (
             if (
Line 390: Line 322:
             ) {
             ) {
                 try {
                 try {
                     config =
                     config = this.normalizeConfig(
                        this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                            JSON.parse(
                    );
                                JSON.stringify(
                                    draft.config
                                )
                            )
                        );
                 } catch (error) {
                 } catch (error) {
                     console.warn(
                     console.warn(
Line 405: Line 332:
                 }
                 }
             }
             }
            const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';


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


                 preloadSource:
                 variables: Array.isArray(draft.variables)
                     String(
                     ? draft.variables.slice()
                        draft.preloadSource || ''
                     : [],
                     ),


                 preloadContent:
                 conditions: Array.isArray(draft.conditions)
                     String(
                     ? draft.conditions.slice()
                        draft.preloadContent || ''
                     : [],
                     ),


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


                 variables:
                 deletedVariables: Array.isArray(draft.deletedVariables)
                    Array.isArray(
                     ? draft.deletedVariables
                        draft.variables
                         .map(name => String(name).toUpperCase())
                     )
                         .filter(name => name !== 'PAGE')
                         ? draft.variables.slice()
                    : [],
                         : [],


                 conditions:
                 mode: draft.mode || 'edit',
                    Array.isArray(
                        draft.conditions
                    )
                        ? draft.conditions.slice()
                        : [],


                 selectedVariable:
                 dirty: hasDirtyFlags
                     String(
                     ? !!(draft.dirtyPreload || draft.dirtyConfig)
                        draft.selectedVariable ||
                     : true,
                        'PAGE'
                     ),


                 deletedVariables:
                 dirtyPreload: hasDirtyFlags
                     Array.isArray(
                     ? !!draft.dirtyPreload
                        draft.deletedVariables
                     : true,
                     )
                        ? draft.deletedVariables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                            .filter(
                                name =>
                                    name !==
                                    'PAGE'
                            )
                        : [],


                 mode:
                 dirtyConfig: hasDirtyFlags
                     draft.mode ||
                     ? !!draft.dirtyConfig
                     'edit',
                     : true,


                 dirty: true
                 localDraftSavedAt: Number(draft.savedAt) || null,
                localDraftAvailable: true
             };
             };


             this.reanalyze();
             this.reanalyze();
             this.renderEditor();
             this.renderEditor();
            this.updateLocalDraftIndicator();


             this.setStatus(
             this.setStatus(
Line 475: Line 386:
             );
             );


             mw.notify(
             mw.notify('Unsaved Preload Editor work restored.', {
                'Unsaved Preload Editor work restored.',
                 type: 'success'
                 {
            });
                    type: 'success'
                }
            );


             return true;
             return true;
         },
         },


        // =========================================================
         // API
         // API
        // =========================================================


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


             const page =
             const page =
Line 516: Line 425:


             return {
             return {
                 title:
                 title: page.title || title,
                    page.title ||
                 content: typeof content === 'string' ? content : '',
                    title,
                contentmodel: page.contentmodel || 'wikitext'
 
                 content:
                    typeof content === 'string'
                        ? content
                        : ''
             };
             };
         },
         },
Line 532: Line 436:


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


             return (
             return (
Line 549: Line 452:
         },
         },


         async savePage(
        /*
            title,
        * Save a page.
            content,
        *
            summary,
        * contentModel is mainly used when creating a page.
            createOnly
        *
        ) {
        * For an existing page whose content model needs
        * changing, use changeContentModel() first.
        */
         async savePage(title, content, summary, createOnly, contentModel) {
             const params = {
             const params = {
                 action: 'edit',
                 action: 'edit',
                 title,
                 title,
                 text: content,
                 text: content,
                 summary:
                 summary: summary || 'Updated with Preload Editor',
                    summary ||
                    'Updated with Preload Editor',
                 formatversion: 2
                 formatversion: 2
             };
             };
Line 569: Line 473:
             }
             }


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


         // Preload parsing
         /*
        * 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);


        extractIncludeonly(source) {
            if (!page) {
            const match =
                 return this.savePage(
                 String(source || '').match(
                     title,
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                    content,
                    summary,
                    true,
                    'json'
                 );
                 );
            }


             return match
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                ? match[1].trim()
                 await this.changeContentModel(
                 : String(source || '').trim();
                    title,
                    'json',
                    'Changed preload config content model to JSON'
                );
            }
 
            return this.savePage(
                title,
                content,
                summary,
                false
            );
         },
         },


         findVariables(content) {
         // =========================================================
            const variables = [];
        // Config import helpers
            const pattern =
        // =========================================================
                /%%([A-Za-z0-9_-]+)%%/g;


             let match;
        /*
        * Accept either:
        *
        *  Template:Example/Preload
        *
        * or:
        *
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
             title = String(title || '').trim();
            title = title.replace(/\/+$/, '');


             while (
             if (/\/config\.json$/i.test(title)) {
                (match = pattern.exec(content)) !== null
                 return title;
            ) {
                 const name =
                    match[1].toUpperCase();
 
                if (!variables.includes(name)) {
                    variables.push(name);
                }
             }
             }


             return variables;
             return title + '/config.json';
         },
         },


         findConditions(content) {
         /*
             const conditions = [];
        * Return a safe clone of a config field.
             const pattern =
        *
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
        * This is deliberately JSON-based because config
        * definitions are JSON-compatible objects.
        */
        cloneConfigField(field) {
             try {
                return JSON.parse(JSON.stringify(field));
             } catch (error) {
                 console.warn(
                    'Preload Editor: Could not clone imported field.',
                    error
                );
 
                return null;
            }
        },


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


             while (
             if (
                 (match = pattern.exec(content)) !== null
                 !fields ||
                typeof fields !== 'object' ||
                Array.isArray(fields)
             ) {
             ) {
                 conditions.push({
                 return {};
                    type:
            }
                        match[1].toLowerCase(),


                    expression:
            const result = {};
                        match[2].trim(),


                    index:
            Object.entries(fields).forEach(([name, field]) => {
                        match.index
                 const upper = String(name || '').trim().toUpperCase();
                 });
            }


            return conditions;
                if (!upper || upper === 'PAGE') {
        },
                    return;
                }


        findConditionVariables(content) {
                 if (
            const variables = [];
                    !field ||
 
                    typeof field !== 'object' ||
            this.findConditions(content).forEach(
                     Array.isArray(field)
                 condition => {
                ) {
                    if (
                    return;
                        condition.type !== 'if' &&
                }
                        condition.type !== 'elseif'
                     ) {
                        return;
                    }


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


                    matches.forEach(
                if (!clone) {
                        name => {
                    return;
                            name =
                }
                                name.toUpperCase();


                            if (
                result[upper] = clone;
                                !variables.includes(
            });
                                    name
                                )
                            ) {
                                variables.push(
                                    name
                                );
                            }
                        }
                    );
                }
            );


             return variables;
             return result;
         },
         },


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


                 conditions:
                 $('<h2>')
                     this.findConditions(content),
                    .text('Import variable definitions')
                     .appendTo(box);


                 conditionVariables:
                 $('<p>')
                     this.findConditionVariables(
                     .text(
                         content
                         'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                     )
                     )
            };
                    .appendTo(box);
        },


        // Config
                if (!names.length) {
 
                    $('<div>')
        getAutomaticPageField() {
                        .addClass(
            return {
                            'preload-editor-empty preload-editor-import-empty'
                label: 'Page Name',
                        )
                description: 'Name of the page.',
                        .text(
                type: 'page',
                            'This config.json does not contain any importable variable definitions.'
                required: true,
                        )
                namespace: 'Main',
                        .appendTo(box);
                'allow-new': true
 
            };
                    const emptyButtons = $('<div>')
        },
                        .addClass('preload-editor-prompt-buttons');
 
                    const close = this.createButton(
                        'Close',
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );
 
                    emptyButtons.append(close);
                    box.append(emptyButtons);
                    overlay.append(box);
 
                    $(document.body).append(overlay);


        emptyConfig() {
                    overlay.attr('tabindex', '-1');
            return {
                     overlay.trigger('focus');
                settings: {
                     incomplete: 'add-stub'
                },


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


        normalizeConfig(config) {
                const search = this.textInput('', 'Search variables...')
            if (
                    .addClass('preload-editor-import-search');
                !config ||
 
                 typeof config !== 'object' ||
                 const searchWrap = $('<div>')
                Array.isArray(config)
                    .addClass('preload-editor-import-search-wrap')
            ) {
                     .append(search);
                config =
                     this.emptyConfig();
            }


            if (
                box.append(searchWrap);
                !config.settings ||
 
                 typeof config.settings !== 'object' ||
                 const controls = $('<div>')
                Array.isArray(config.settings)
                    .addClass('preload-editor-import-controls');
            ) {
                config.settings = {};
            }


            if (
                const selectAll = this.createButton(
                !config.fields ||
                    'Select all',
                typeof config.fields !== 'object' ||
                    '',
                Array.isArray(config.fields)
                    () => {
            ) {
                        list
                config.fields = {};
                            .find('input[type="checkbox"]:visible')
            }
                            .prop('checked', true);


            config.fields.PAGE =
                        updateSummary();
                 this.getAutomaticPageField();
                    }
                 );


            return config;
                const deselectAll = this.createButton(
        },
                    'Deselect all',
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', false);


        createDefaultField(
                        updateSummary();
            name,
                    }
            analysis
                 );
        ) {
            return {
                 label:
                    this.humanizeName(name),


                 description: '',
                 controls.append(selectAll, deselectAll);
                box.append(controls);


                 type:
                 const list = $('<div>')
                     analysis.conditionVariables.includes(
                     .addClass('preload-editor-import-list');
                        name
                    )
                        ? 'boolean'
                        : 'text'
            };
        },


        humanizeName(name) {
                 const localFields =
            return String(name || '')
                     this.state.config && this.state.config.fields
                 .replace(
                         ? this.state.config.fields
                     /[_-]+/g,
                        : {};
                    ' '
                )
                .replace(
                    /([a-z])([A-Z])/g,
                    '$1 $2'
                )
                .replace(
                    /\s+/g,
                    ' '
                )
                .trim()
                .replace(
                    /\b\w/g,
                    char =>
                         char.toUpperCase()
                );
        },


        prepareConfigForVariables(
                names.forEach(name => {
            config,
                    const existing = !!localFields[name];
            analysis
                    const field = fields[name];
        ) {
            config =
                this.normalizeConfig(config);


            const existing =
                    const type = field && field.type
                config.fields || {};
                        ? String(field.type)
                        : 'text';


            const deleted =
                    const label = field && field.label
                new Set(
                        ? String(field.label)
                    Array.isArray(
                         : this.humanizeName(name);
                         this.state.deletedVariables
 
                     )
                     const row = $('<label>')
                         ? this.state.deletedVariables
                         .addClass('preload-editor-import-row')
                            .map(
                        .attr('data-variable', name)
                                name =>
                        .attr(
                                    String(
                            'data-search',
                                        name
                            (name + ' ' + label + ' ' + type).toLowerCase()
                                    ).toUpperCase()
                         );
                            )
                         : []
                );


            const fields = {};
                    const checkbox = this.checkbox(false)
                        .attr('data-import-variable', name)
                        .addClass('preload-editor-import-checkbox');


            fields.PAGE =
                    const content = $('<span>')
                this.getAutomaticPageField();
                        .addClass('preload-editor-import-content');


            analysis.variables.forEach(
                    const header = $('<span>')
                name => {
                         .addClass('preload-editor-import-header');
                    if (
                        name === 'PAGE' ||
                         deleted.has(name)
                    ) {
                        return;
                    }


                     fields[name] =
                     $('<strong>')
                         existing[name] ||
                         .text(name)
                         this.createDefaultField(
                         .appendTo(header);
                            name,
                            analysis
                        );
                }
            );


            Object.keys(existing).forEach(
                    $('<span>')
                name => {
                        .addClass('preload-editor-import-type')
                    const upper =
                        .text(type)
                         name.toUpperCase();
                         .appendTo(header);


                     if (
                     const meta = $('<span>')
                        upper !== 'PAGE' &&
                         .addClass('preload-editor-import-meta');
                         !fields[upper] &&
                        !deleted.has(upper)
                    ) {
                        fields[upper] =
                            existing[name];
                    }
                }
            );


            config.fields = fields;
                    $('<span>')
                        .text(label)
                        .appendTo(meta);


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


        validateConfig(
                    content.append(header, meta, status);
            config,
                    row.append(checkbox, content);
            analysis
                    list.append(row);
        ) {
                });
            const errors = [];
            const warnings = [];


            if (
                box.append(list);
                 !config ||
 
                 typeof config !== 'object' ||
                 const summary = $('<div>')
                Array.isArray(config)
                    .addClass('preload-editor-import-summary');
            ) {
 
                return {
                 const updateSummary = () => {
                     valid: false,
                    const selected = list.find(
                     errors: [
                        'input[type="checkbox"]:checked'
                        'Config must be an object.'
                    ).length;
                     ],
 
                     warnings: []
                    const existingSelected = list
                        .find('input[type="checkbox"]:checked')
                        .filter(function () {
                            const name = $(this).attr(
                                'data-import-variable'
                            );
 
                            return !!localFields[name];
                        }).length;
 
                     let text =
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';
 
                     if (existingSelected) {
                        text +=
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }
 
                     summary.text(text);
 
                     importButton.prop('disabled', selected === 0);
                 };
                 };
            }


            if (
                const filterRows = () => {
                !config.fields ||
                    const query = String(search.val() || '')
                typeof config.fields !== 'object' ||
                        .trim()
                Array.isArray(config.fields)
                        .toLowerCase();
            ) {
 
                return {
                     list.find('.preload-editor-import-row').each(function () {
                     valid: false,
                        const row = $(this);
                    errors: [
                         const haystack = String(
                         '"fields" must be an object.'
                            row.attr('data-search') || ''
                    ],
                        );
                     warnings
 
                        row.toggle(!query || haystack.includes(query));
                     });
                 };
                 };
            }


            const configured =
                 search.on(
                 Object.keys(
                     'input.preloadEditor',
                     config.fields
                    filterRows
                 ).map(
                 );
                     name =>
 
                        name.toUpperCase()
                list.on(
                     'change.preloadEditor',
                    'input[type="checkbox"]',
                    updateSummary
                 );
                 );


            analysis.variables.forEach(
                 const buttons = $('<div>')
                 name => {
                     .addClass('preload-editor-prompt-buttons');
                     if (
 
                        !configured.includes(name)
                const cancel = this.createButton(
                    ) {
                    'Cancel',
                        errors.push(
                    '',
                            'Variable "' +
                    () => {
                            name +
                        overlay.remove();
                            '" is not configured.'
                         resolve(null);
                         );
                     }
                     }
                 }
                 );
            );
 
                const importButton = this.createButton(
                    'Import selected',
                    'preload-editor-button-primary',
                    () => {
                        const selected = [];
 
                        list
                            .find('input[type="checkbox"]:checked')
                            .each(function () {
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });


            configured.forEach(
                         overlay.remove();
                name => {
                         resolve(selected);
                    if (
                         !analysis.variables.includes(
                            name
                        )
                    ) {
                         warnings.push(
                            'Field "' +
                            name +
                            '" is not used by the preload.'
                        );
                     }
                     }
                }
            );
            if (
                !configured.includes('PAGE')
            ) {
                errors.push(
                    'PAGE must always be configured.'
                 );
                 );
            }


            Object.entries(
                 buttons.append(cancel, importButton);
                 config.fields
                box.append(summary, buttons);
            ).forEach(
                overlay.append(box);
                ([name, field]) => {
                    if (
                        !field ||
                        typeof field !== 'object' ||
                        Array.isArray(field)
                    ) {
                        errors.push(
                            'Field "' +
                            name +
                            '" must be an object.'
                        );


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


                    if (!field.type) {
                overlay.attr('tabindex', '-1');
                        warnings.push(
                overlay.trigger('focus');
                            'Field "' +
                            name +
                            '" has no type.'
                        );
                    }


                    if (
                updateSummary();
                        (
                search.trigger('focus');
                            field.type === 'select' ||
 
                            field.type === 'multiselect'
                const close = event => {
                        ) &&
                    if (event.key === 'Escape') {
                        !field.source &&
                         cancel.trigger('click');
                        !Array.isArray(field.options)
                    ) {
                         warnings.push(
                            'Field "' +
                            name +
                            '" is a ' +
                            field.type +
                            ' without a source or manual options.'
                        );
                     }
                     }
                 }
                 };
            );
 
                overlay.on(
                    'keydown.preloadEditor',
                    close
                );


            return {
                 overlay.on(
                 valid:
                     'click.preloadEditor',
                     !errors.length,
                    event => {
                errors,
                        if (event.target === overlay.get(0)) {
                 warnings
                            cancel.trigger('click');
             };
                        }
                    }
                 );
             });
         },
         },


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


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


             switch (transform) {
             const configTitle = this.normalizeConfigTitle(source);
                case 'remove-prefix':
                    return prefix
                        ? {
                            transform,
                            prefix
                        }
                        : null;


                 case 'remove-suffix':
            this.setStatus(
                    return suffix
                 'Loading source config...',
                        ? {
                'loading'
                            transform,
            );
                            suffix
                        }
                        : null;


                 case 'replace':
            try {
                    return from === ''
                 const page = await this.getPage(configTitle);
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


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


        // UI helpers
                let sourceConfig;


        createSection(
                try {
            title,
                    sourceConfig = JSON.parse(page.content);
            className
                 } catch (error) {
        ) {
                     throw new Error(
            const section =
                         'The source config.json contains invalid JSON: ' +
                 $('<section>')
                        error.message
                     .addClass(
                         'preload-editor-section'
                     );
                     );
                }


            if (className) {
                if (
                section.addClass(className);
                    !sourceConfig ||
            }
                    typeof sourceConfig !== 'object' ||
                    Array.isArray(sourceConfig)
                ) {
                    throw new Error(
                        'The source config.json must contain a JSON object.'
                    );
                }


            $('<h2>')
                if (
                .addClass(
                    !sourceConfig.fields ||
                     'preload-editor-section-title'
                     typeof sourceConfig.fields !== 'object' ||
                 )
                    Array.isArray(sourceConfig.fields)
                .text(title)
                 ) {
                .appendTo(section);
                    throw new Error(
                        'The source config.json does not contain a valid "fields" object.'
                    );
                }


            return section;
                const fields = this.getImportableFields(sourceConfig);
        },


        createButton(
                const selected =
            label,
                     await this.createImportDefinitionsDialog(
            className,
                         configTitle,
            callback
                         fields
        ) {
                     );
            const button =
                $('<button>')
                     .attr(
                         'type',
                         'button'
                    )
                    .addClass(
                        'preload-editor-button'
                    )
                     .text(label);


            if (className) {
                if (selected === null) {
                button.addClass(className);
                    this.setStatus(
            }
                        'Variable import cancelled.',
                        'warning'
                    );


            if (callback) {
                     return;
                button.on(
                 }
                     'click.preloadEditor',
                    callback
                 );
            }


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


        fieldRow(
                    return;
            label,
                 }
            input,
            description
        ) {
            const row =
                 $('<div>')
                    .addClass(
                        'preload-editor-field'
                    );


            $('<label>')
                if (!this.state.config) {
                .addClass(
                    this.state.config = this.emptyConfig();
                    'preload-editor-label'
                 }
                )
                .text(label)
                 .appendTo(row);


            if (description) {
                if (!this.state.config.fields) {
                $('<div>')
                     this.state.config.fields = {};
                     .addClass(
                }
                        'preload-editor-help'
                    )
                    .text(description)
                    .appendTo(row);
            }


            row.append(input);
                const imported = [];
                const replaced = [];


            return row;
                selected.forEach(name => {
        },
                    if (name === 'PAGE') {
                        return;
                    }


        textInput(
                     const field = fields[name];
            value,
            placeholder
        ) {
            return $('<input>')
                .attr({
                     type: 'text',
                    value:
                        value == null
                            ? ''
                            : value,


                     placeholder:
                     if (!field) {
                         placeholder || ''
                         return;
                })
                     }
                .addClass(
                     'preload-editor-input'
                );
        },


        textarea(value) {
                    if (this.state.config.fields[name]) {
            return $('<textarea>')
                        replaced.push(name);
                .val(
                     } else {
                     value == null
                         imported.push(name);
                         ? ''
                    }
                        : value
                )
                .addClass(
                    'preload-editor-textarea'
                );
        },


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


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


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


            return select;
                    /*
        },
                    * If this variable was previously deleted,
                    * importing its definition explicitly should
                    * restore it.
                    */
                    if (Array.isArray(this.state.deletedVariables)) {
                        this.state.deletedVariables =
                            this.state.deletedVariables.filter(
                                deletedName =>
                                    String(deletedName).toUpperCase() !== name
                            );
                    }
                });


        // In-wiki dialogs
                /*
                * Keep PAGE automatic regardless of what the
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();


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


                    const box =
                /*
                         $('<div>')
                * Keep the current selection when possible.
                            .addClass(
                * Otherwise select the first imported definition.
                                'preload-editor-prompt'
                */
                            );
                const selectedStillExists = !!(
                    this.state.config.fields[
                         this.state.selectedVariable
                    ]
                );


                     $('<h2>')
                if (
                         .text(title)
                    !selectedStillExists ||
                         .appendTo(box);
                     this.state.selectedVariable === 'PAGE'
                ) {
                    this.state.selectedVariable =
                         selected[0] ||
                         'PAGE';
                }


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


                    messageLines.forEach(
                this.renderVariablesBySelector();
                        line => {
                this.renderVariableConfigurationBySelector();
                            $('<p>')
                this.renderAnalysisBySelector();
                                .text(line)
                this.updateEditorTools();
                                .appendTo(box);
                        }
                    );


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


                    const cancel =
                let status =
                        this.createButton(
                    'Imported ' +
                            cancelLabel || 'Cancel',
                    selected.length +
                            '',
                    ' variable ' +
                            () => {
                    (selected.length === 1
                                overlay.remove();
                        ? 'definition'
                                resolve(false);
                        : 'definitions') +
                            }
                    '.';
                        );


                     const confirm =
                if (replaced.length) {
                         this.createButton(
                     status +=
                            confirmLabel || 'Confirm',
                         ' Replaced: ' +
                            'preload-editor-button-primary',
                        replaced.join(', ') +
                            () => {
                        '.';
                                overlay.remove();
                }
                                resolve(true);
                            }
                        );


                    buttons.append(
                this.setStatus(status, 'success');
                        cancel,
                        confirm
                    );


                    box.append(buttons);
                mw.notify(status, {
                    overlay.append(box);
                    type: 'success'
                });
            } catch (error) {
                console.error(
                    'Preload Editor variable import:',
                    error
                );


                     $(document.body)
                this.setStatus(
                         .append(overlay);
                     error.message ||
                         'Could not import variable definitions.',
                    'error'
                );


                     const close =
                mw.notify(
                         value => {
                     error.message ||
                            if (value === 'Escape') {
                         'Could not import variable definitions.',
                                cancel.trigger('click');
                    {
                            }
                        type: 'error'
                        };
                    }
                );
            }
        },


                    overlay.on(
        // =========================================================
                        'keydown.preloadEditor',
        // Preload parsing
                        event => {
        // =========================================================
                            close(event.key);
                        }
                    );


                    overlay.attr(
        extractIncludeonly(source) {
                        'tabindex',
            const match = String(source || '').match(
                        '-1'
                /<includeonly>([\s\S]*?)<\/includeonly>/i
                    );
            );


                    overlay.trigger('focus');
            return match
 
                ? match[1].trim()
                    /*
                : String(source || '').trim();
                    * Keep the browser from submitting or
                    * otherwise handling Enter/Escape itself.
                    */
                    overlay.on(
                        'click.preloadEditor',
                        event => {
                            if (
                                event.target ===
                                overlay.get(0)
                            ) {
                                cancel.trigger('click');
                            }
                        }
                    );
                }
            );
         },
         },


         createPromptDialog(
         findVariables(content) {
            title,
             const variables = [];
            message
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
        ) {
             return new Promise(
                resolve => {
                    const overlay =
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


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


                    $('<h2>')
            while ((match = pattern.exec(content)) !== null) {
                        .text(title)
                const name = match[1].toUpperCase();
                        .appendTo(box);


                    $('<p>')
                if (!variables.includes(name)) {
                        .text(message)
                    variables.push(name);
                        .appendTo(box);
                }
            }


                    const input =
            return variables;
                        this.textInput();
        },


                    const buttons =
        findConditions(content) {
                        $('<div>')
            const conditions = [];
                            .addClass(
            const pattern =
                                'preload-editor-prompt-buttons'
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                            );


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


                    const confirm =
            while ((match = pattern.exec(content)) !== null) {
                        this.createButton(
                conditions.push({
                            'Load',
                    type: match[1].toLowerCase(),
                            'preload-editor-button-primary',
                    expression: match[2].trim(),
                            () => {
                    index: match.index
                                const value =
                });
                                    String(
            }
                                        input.val() || ''
                                    ).trim();


                                if (!value) {
            return conditions;
                                    return;
        },
                                }


                                overlay.remove();
        findConditionVariables(content) {
                                resolve(value);
            const variables = [];
                            }
                        );


                    buttons.append(
            this.findConditions(content).forEach(condition => {
                        cancel,
                if (
                        confirm
                    condition.type !== 'if' &&
                     );
                     condition.type !== 'elseif'
                ) {
                    return;
                }


                     box.append(
                const matches =
                         input,
                     condition.expression.match(
                        buttons
                         /[A-Za-z0-9_-]+/g
                     );
                     ) || [];


                     overlay.append(box);
                matches.forEach(name => {
                     name = name.toUpperCase();


                     $(document.body)
                     if (!variables.includes(name)) {
                         .append(overlay);
                         variables.push(name);
                    }
                });
            });


                    input.trigger('focus');
            return variables;
        },


                    input.on(
        analyzePreload(content) {
                        'keydown.preloadEditor',
            return {
                        event => {
                variables: this.findVariables(content),
                            if (
                conditions: this.findConditions(content),
                                event.key === 'Enter'
                conditionVariables:
                            ) {
                     this.findConditionVariables(content)
                                confirm.trigger('click');
            };
                            }
 
                            if (
                                event.key === 'Escape'
                            ) {
                                cancel.trigger('click');
                            }
                        }
                     );
                }
            );
         },
         },


         // CodeMirror
         // =========================================================
        // Config
        // =========================================================


         destroyEditor() {
         getAutomaticPageField() {
             if (!this.editor) {
             return {
                 this.editorView = null;
                 label: 'Page Name',
                 this.editorTools = null;
                description: 'Name of the page.',
                 return;
                type: 'page',
             }
                required: true,
                 namespace: 'Main',
                 'allow-new': true
            };
        },
 
        emptyConfig() {
             return {
                settings: {
                    incomplete: 'add-stub'
                },


            const {
                fields: {
                view,
                    PAGE: this.getAutomaticPageField()
                 inputHandler
                 }
             } = this.editor;
             };
        },


        normalizeConfig(config) {
             if (
             if (
                 view &&
                 !config ||
                 inputHandler
                 typeof config !== 'object' ||
                Array.isArray(config)
             ) {
             ) {
                 view.dom.removeEventListener(
                 config = this.emptyConfig();
                    'input',
                    inputHandler
                );
             }
             }


             if (view) {
             if (
                 view.destroy();
                !config.settings ||
                typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
            ) {
                 config.settings = {};
             }
             }


             this.editor = null;
             if (
             this.editorView = null;
                !config.fields ||
             this.editorTools = null;
                typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
             ) {
                config.fields = {};
             }
 
            config.fields.PAGE =
                this.getAutomaticPageField();
 
            return config;
         },
         },


         getEditorView() {
         createDefaultField(name, analysis) {
             return this.editorView;
             return {
                label: this.humanizeName(name),
                description: '',
                type: analysis.conditionVariables.includes(name)
                    ? 'boolean'
                    : 'text'
            };
         },
         },


         getEditorContent() {
         humanizeName(name) {
             if (
             return String(name || '')
                 this.editorView &&
                 .replace(/[_-]+/g, ' ')
                 this.editorView.state
                 .replace(/([a-z])([A-Z])/g, '$1 $2')
            ) {
                 .replace(/\s+/g, ' ')
                 return this.editorView.state.doc.toString();
                .trim()
            }
                 .replace(/\b\w/g, char => char.toUpperCase());
 
            return (
                 this.state.preloadContent || ''
            );
         },
         },


         setEditorContent(content) {
         prepareConfigForVariables(config, analysis) {
             content =
             config = this.normalizeConfig(config);
                String(content || '');


             if (!this.editorView) {
             const existing = config.fields || {};
                this.state.preloadContent =
                    content;
                return;
            }


             const current =
             const deleted = new Set(
                 this.editorView.state.doc.toString();
                 Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.map(
                        name => String(name).toUpperCase()
                    )
                    : []
            );


             if (current === content) {
             const fields = {};
                return;
            }


             this.editorView.dispatch({
             fields.PAGE =
                 changes: {
                this.getAutomaticPageField();
                     from: 0,
 
                     to:
            analysis.variables.forEach(name => {
                        this.editorView.state.doc.length,
                 if (
                     insert: content
                     name === 'PAGE' ||
                     deleted.has(name)
                ) {
                     return;
                 }
                 }
                fields[name] =
                    existing[name] ||
                    this.createDefaultField(
                        name,
                        analysis
                    );
             });
             });
        },


        getEditorSelection() {
            Object.keys(existing).forEach(name => {
            if (
                 const upper = name.toUpperCase();
                 !this.editorView ||
                !this.editorView.state
            ) {
                return null;
            }


            const selection =
                if (
                 this.editorView.state
                    upper !== 'PAGE' &&
                     .selection.main;
                    !fields[upper] &&
                    !deleted.has(upper)
                 ) {
                     fields[upper] =
                        existing[name];
                }
            });


             return {
             config.fields = fields;
                from:
                    selection.from,


                to:
             return config;
                    selection.to,
 
                text:
                    this.editorView.state.doc.sliceString(
                        selection.from,
                        selection.to
                    )
             };
         },
         },


         focusEditor() {
         validateConfig(config, analysis) {
             if (this.editorView) {
             const errors = [];
                this.editorView.focus();
             const warnings = [];
             }
        },


        insertEditorText(
            if (
            text,
                !config ||
            selectionFrom,
                typeof config !== 'object' ||
            selectionTo,
                Array.isArray(config)
             cursorPosition
             ) {
        ) {
                return {
            if (!this.editorView) {
                    valid: false,
                 return;
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                 };
             }
             }


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


             const selection =
             const configured =
                 view.state.selection.main;
                 Object.keys(
                    config.fields
                ).map(
                    name =>
                        name.toUpperCase()
                );


             const from =
             analysis.variables.forEach(name => {
                 selectionFrom === undefined
                 if (!configured.includes(name)) {
                     ? selection.from
                     errors.push(
                     : selectionFrom;
                        'Variable "' +
                        name +
                        '" is not configured.'
                     );
                }
            });


             const to =
             configured.forEach(name => {
                 selectionTo === undefined
                 if (!analysis.variables.includes(name)) {
                     ? selection.to
                     warnings.push(
                     : selectionTo;
                        'Field "' +
                        name +
                        '" is not used by the preload.'
                     );
                }
            });


             const cursor =
             if (!configured.includes('PAGE')) {
                 cursorPosition === undefined
                 errors.push(
                     ? from + text.length
                     'PAGE must always be configured.'
                    : cursorPosition;
                );
            }


             view.dispatch({
             Object.entries(config.fields).forEach(([name, field]) => {
                 changes: {
                 if (
                     from,
                     !field ||
                     to,
                     typeof field !== 'object' ||
                     insert: text
                     Array.isArray(field)
                 },
                 ) {
                    errors.push(
                        'Field "' +
                        name +
                        '" must be an object.'
                    );


                selection: {
                     return;
                     anchor: cursor
                 }
                 }
            });


            view.focus();
                if (!field.type) {
        },
                    warnings.push(
                        '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.'
                        );
                    }


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


        wrapSelectionWithVariable() {
                    if (
            const selected =
                        field.filename !== undefined &&
                this.getEditorSelection();
                        typeof field.filename !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                        );
                    }


            if (
                    if (
                !selected ||
                        field.filetext !== undefined &&
                selected.from === selected.to
                        typeof field.filetext !== 'string'
            ) {
                    ) {
                this.focusEditor();
                        errors.push(
                return;
                            'File field "' +
            }
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


            const replacement =
                    if (
                '%%' +
                        !field.accept ||
                selected.text +
                        !field.accept.length
                '%%';
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


            this.insertEditorText(
                    if (
                replacement,
                        !field.filename
                selected.from,
                    ) {
                selected.to,
                        warnings.push(
                selected.from +
                            'File field "' +
                    replacement.length
                            name +
            );
                            '" has no filename template.'
        },
                        );
                    }
                }


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


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


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


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


             this.insertEditorText(
             return {
                 '%%' + name + '%%',
                 valid: !errors.length,
                 selected.from,
                 errors,
                 selected.to
                 warnings
             );
             };
         },
         },


         insertCondition(
         // =========================================================
             type,
        // Transformation helpers
             variable
        // =========================================================
 
        transformationObject(
             transform,
            prefix,
            suffix,
            from,
             to
         ) {
         ) {
             type =
             if (!transform) {
                String(type || '')
                return null;
                    .toLowerCase();
            }


             variable =
             switch (transform) {
                 String(variable || '')
                 case 'remove-prefix':
                     .trim()
                     return prefix
                    .toUpperCase();
                        ? {
                            transform,
                            prefix
                        }
                        : null;


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


            if (!selected) {
                case 'replace':
                return;
                    return from === ''
            }
                        ? null
 
                        : {
            let text;
                            transform,
            let cursorOffset;
                            from,
 
                            to: to || ''
            switch (type) {
                         };
                case 'if': {
                    if (!variable) {
                         return;
                    }


                     const opening =
                default:
                        '<!-- @if ' +
                     return null;
                        variable +
            }
                        ' -->';
        },


                    const closing =
        // =========================================================
                        '<!-- @endif -->';
        // UI helpers
        // =========================================================


                    if (
        createSection(title, className) {
                        selected.from !==
            const section = $('<section>')
                        selected.to
                .addClass('preload-editor-section');
                    ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                        cursorOffset =
            if (className) {
                            text.length;
                section.addClass(className);
                    } else {
            }
                        text =
                            opening +
                            '\n\n' +
                            closing;


                        cursorOffset =
            $('<h2>')
                            opening.length + 1;
                .addClass('preload-editor-section-title')
                    }
                .text(title)
                .appendTo(section);


                    break;
            return section;
                }
        },


                 case 'elseif':
        createButton(label, className, callback) {
                    text =
            const button = $('<button>')
                        '<!-- @elseif -->';
                 .attr('type', 'button')
                    cursorOffset =
                .addClass('preload-editor-button')
                        text.length;
                .text(label);
                    break;


                 case 'else':
            if (className) {
                    text =
                 button.addClass(className);
                        '<!-- @else -->';
            }
                    cursorOffset =
                        text.length;
                    break;


                 case 'endif':
            if (callback) {
                     text =
                 button.on(
                        '<!-- @endif -->';
                     'click.preloadEditor',
                     cursorOffset =
                     callback
                        text.length;
                 );
                    break;
 
                 default:
                    return;
             }
             }


             this.insertEditorText(
             return button;
                text,
                selected.from,
                selected.to,
                selected.from +
                    cursorOffset
            );
         },
         },


         getToolVariables() {
         fieldRow(label, input, description) {
             const variables =
             const row = $('<div>')
                 new Set(['PAGE']);
                 .addClass('preload-editor-field');


             if (
             $('<label>')
                 this.analysis &&
                 .addClass('preload-editor-label')
                 this.analysis.variables
                 .text(label)
             ) {
                .appendTo(row);
                 this.analysis.variables.forEach(
 
                     name => {
             if (description) {
                        variables.add(
                 $('<div>')
                            String(
                     .addClass('preload-editor-help')
                                name
                    .text(description)
                            ).toUpperCase()
                     .appendTo(row);
                        );
                     }
                );
             }
             }


             return Array.from(variables);
             row.append(input);
 
            return row;
         },
         },


         createToolSelect(
         textInput(value, placeholder) {
            options,
             return $('<input>')
            className
                .attr({
        ) {
                    type: 'text',
             const select =
                    value: value == null ? '' : value,
                $('<select>')
                     placeholder: placeholder || ''
                     .addClass(
                })
                        'preload-editor-tool-select'
                .addClass('preload-editor-input');
                    );
        },


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


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


             return select;
             return select;
         },
         },


         updateEditorToolVariables() {
         // =========================================================
            if (!this.editorTools) {
        // In-wiki dialogs
                return;
        // =========================================================
            }


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


            const current =
                const box = $('<div>')
                this.editorTools
                     .addClass('preload-editor-prompt');
                    .variableSelect
                     .val();


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


            const populate =
                const messageLines =
                (
                    String(message || '').split('\n');
                    select,
                    value
                ) => {
                    select.empty();


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


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


            populate(
                 const confirm = this.createButton(
                 this.editorTools.variableSelect,
                    confirmLabel || 'Confirm',
                 current
                    'preload-editor-button-primary',
            );
                    () => {
                        overlay.remove();
                        resolve(true);
                    }
                 );


            populate(
                buttons.append(cancel, confirm);
                 this.editorTools.conditionVariableSelect,
                 box.append(buttons);
                 currentCondition
                 overlay.append(box);
            );
        },


        updateConditionVariableVisibility() {
                $(document.body).append(overlay);
            if (!this.editorTools) {
                return;
            }


            const type =
                const close = value => {
                this.editorTools
                     if (value === 'Escape') {
                     .conditionTypeSelect
                        cancel.trigger('click');
                    .val();
                    }
                };


            this.editorTools
                overlay.on(
                 .conditionVariableWrap
                    'keydown.preloadEditor',
                 .toggle(
                    event => {
                     type === 'if'
                        close(event.key);
                    }
                );
 
                 overlay.attr('tabindex', '-1');
                 overlay.trigger('focus');
 
                overlay.on(
                    'click.preloadEditor',
                     event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                    }
                 );
                 );
            });
         },
         },


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


            const wrapGroup =
                const box = $('<div>')
                $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                         'preload-editor-prompt'
                     );
                     );


            wrapGroup.append(
                $('<h2>')
                this.createButton(
                    .text(title)
                    'Wrap selection with %%',
                    .appendTo(box);
                    'preload-editor-tool-button',
 
                     () =>
                $('<p>')
                        this.wrapSelectionWithVariable()
                     .text(message)
                 )
                    .appendTo(box);
            );
 
                 const input = this.textInput();


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


            $('<span>')
                 const cancel = this.createButton(
                 .addClass(
                     'Cancel',
                     'preload-editor-tool-label'
                     '',
                )
                    () => {
                .text(
                        overlay.remove();
                     'Insert existing variable'
                        resolve(null);
                )
                     }
                .appendTo(variableGroup);
 
            const variableSelect =
                this.createToolSelect(
                     [],
                    'preload-editor-variable-select'
                 );
                 );


            variableGroup.append(
                const confirm = this.createButton(
                 variableSelect,
                    'Load',
                    'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();
 
                        if (!value) {
                            return;
                        }
 
                        overlay.remove();
                        resolve(value);
                    }
                );
 
                buttons.append(cancel, confirm);
 
                box.append(
                    input,
                    buttons
                );
 
                overlay.append(box);
 
                $(document.body).append(overlay);
 
                 input.trigger('focus');
 
                input.on(
                    'keydown.preloadEditor',
                    event => {
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }
 
                        if (event.key === 'Escape') {
                            cancel.trigger('click');
                        }
                    }
                );
            });
        },


                 this.createButton(
        createConfigReviewDialog() {
                    'Insert',
            return new Promise(resolve => {
                     'preload-editor-tool-button',
                 const overlay = $('<div>')
                     () =>
                     .addClass(
                        this.insertVariable(
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                            variableSelect.val()
                     );
                        )
                )
            );


            const conditionGroup =
                const box = $('<div>')
                $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tool-group preload-editor-tool-group-condition'
                         'preload-editor-prompt preload-editor-code-review'
                     );
                     );


            $('<span>')
                $('<h2>')
                 .addClass(
                    .text('Review config.json')
                    'preload-editor-tool-label'
                    .appendTo(box);
                )
 
                .text('Insert condition')
                $('<p>')
                .appendTo(conditionGroup);
                    .text(
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);
 
                 const code = $('<pre>')
                    .addClass(
                        'preload-editor-config-review'
                    )
                    .text(this.getConfigJSON());


            const conditionTypeSelect =
                const codeWrap = $('<div>')
                this.createToolSelect(
                    .addClass(
                    [
                         'preload-editor-config-review-wrap'
                        {
                    )
                            value: 'if',
                    .append(code);
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                         {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                );


            const conditionVariableSelect =
                 box.append(codeWrap);
                 this.createToolSelect(
                    [],
                    'preload-editor-condition-variable-select'
                );


            const conditionVariableWrap =
                const buttons = $('<div>')
                $('<span>')
                     .addClass(
                     .addClass(
                         'preload-editor-condition-variable'
                         'preload-editor-prompt-buttons'
                    )
                    .append(
                        conditionVariableSelect
                     );
                     );


            const insertCondition =
                const close = this.createButton(
                this.createButton(
                     'Close',
                     'Insert',
                     'preload-editor-button-primary',
                     'preload-editor-tool-button',
                     () => {
                     () =>
                         overlay.remove();
                         this.insertCondition(
                        resolve();
                            conditionTypeSelect.val(),
                    }
                            conditionVariableSelect.val()
                        )
                 );
                 );


            conditionTypeSelect.on(
                buttons.append(close);
                 'change.preloadEditor',
                 box.append(buttons);
                () =>
                overlay.append(box);
                    this.updateConditionVariableVisibility()
            );


            conditionGroup.append(
                $(document.body).append(overlay);
                conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );


            tools.append(
                overlay.attr('tabindex', '-1');
                wrapGroup,
                 overlay.trigger('focus');
                 variableGroup,
                conditionGroup
            );


            this.editorTools = {
                overlay.on(
                root: tools,
                    'keydown.preloadEditor',
                variableSelect,
                    event => {
                conditionTypeSelect,
                        if (event.key === 'Escape') {
                conditionVariableSelect,
                            close.trigger('click');
                conditionVariableWrap,
                        }
                 insertCondition
                    }
            };
                 );


            this.updateEditorToolVariables();
                overlay.on(
             this.updateConditionVariableVisibility();
                    'click.preloadEditor',
                    event => {
                        if (event.target === overlay.get(0)) {
                            close.trigger('click');
                        }
                    }
                );
             });
        },


             return tools;
        async confirmSave(mode, title) {
        },
             const configTitle =
                title.replace(/\/+$/, '') +
                '/config.json';
 
            let saveDescription;


        updateEditorTools() {
            if (mode === 'preload') {
             this.updateEditorToolVariables();
                saveDescription =
             this.updateConditionVariableVisibility();
                    'Save the preload page only?';
        },
             } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
             } else {
                saveDescription =
                    'Save both the preload and config.json?';
            }


        // Syntax highlighting
            const pages = [];


        getKnownVariables() {
            if (mode === 'preload' || mode === 'both') {
            const known =
                 pages.push(
                 new Set(['PAGE']);
                    'Preload: ' +
                    title
                );
            }


             const fields =
             if (mode === 'config' || mode === 'both') {
                 this.state.config &&
                 pages.push(
                 this.state.config.fields;
                    'Config: ' +
                    configTitle
                 );


            if (
                 pages.push(
                fields &&
                     'Config content model: JSON'
                 typeof fields === 'object'
            ) {
                Object.keys(fields).forEach(
                     name => {
                        known.add(
                            String(
                                name
                            ).toUpperCase()
                        );
                    }
                 );
                 );
             }
             }


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


         createSyntaxDecorations(
         // =========================================================
             state,
        // CodeMirror
             Decoration
        // =========================================================
        ) {
                destroyEditor() {
             const decorations = [];
             if (!this.editor) {
             const source =
                this.editorView = null;
                 state.doc.toString();
                this.editorTools = null;
                return;
             }
 
            const {
                view,
                inputHandler
             } = this.editor;
 
             if (view && inputHandler) {
                 view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }


             const knownVariables =
             if (view) {
                 this.getKnownVariables();
                 view.destroy();
            }


             const variablePattern =
             this.editor = null;
                /%%([A-Za-z0-9_-]+)%%/g;
            this.editorView = null;
            this.editorTools = null;
        },


             let match;
        getEditorView() {
             return this.editorView;
        },


             while (
        getEditorContent() {
                 (
             if (
                    match =
                 this.editorView &&
                        variablePattern.exec(
                 this.editorView.state
                            source
                        )
                 ) !== null
             ) {
             ) {
                 const name =
                 return this.editorView.state.doc.toString();
                    match[1].toUpperCase();
            }


                const known =
            return this.state.preloadContent || '';
                    knownVariables.has(name);
        },


                decorations.push(
        setEditorContent(content) {
                    Decoration.mark({
            content = String(content || '');
                        class: [
 
                            'preload-editor-syntax-variable',
            if (!this.editorView) {
                            known
                this.state.preloadContent = content;
                                ? 'preload-editor-syntax-variable-known'
                 return;
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                 );
             }
             }


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


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


                 const directiveStart =
            this.editorView.dispatch({
                     match.index +
                 changes: {
                     match[0].indexOf('@');
                     from: 0,
                    to: this.editorView.state.doc.length,
                     insert: content
                }
            });
        },


                decorations.push(
        getEditorSelection() {
                    Decoration.mark({
            if (
                        class:
                !this.editorView ||
                            'preload-editor-syntax-directive'
                !this.editorView.state
                    }).range(
            ) {
                        directiveStart,
                 return null;
                        directiveStart +
            }
                            match[1].length +
                            1
                    )
                 );


                const type =
            const selection =
                    match[1].toLowerCase();
                this.editorView.state.selection.main;


                 if (
            return {
                     type !== 'if' &&
                from: selection.from,
                     type !== 'elseif'
                to: selection.to,
                 ) {
                 text: this.editorView.state.doc.sliceString(
                    continue;
                     selection.from,
                }
                     selection.to
                 )
            };
        },


                 const expression =
        focusEditor() {
                    match[2];
            if (this.editorView) {
                 this.editorView.focus();
            }
        },


                const expressionStart =
        insertEditorText(
                    match.index +
            text,
                    match[0].indexOf(
            selectionFrom,
                        expression
            selectionTo,
                    );
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }


                const expressionPattern =
            const view = this.editorView;
                    /[A-Za-z0-9_-]+/g;
            const selection = view.state.selection.main;


                 let expressionMatch;
            const from =
                 selectionFrom === undefined
                    ? selection.from
                    : selectionFrom;


                 while (
            const to =
                    (
                 selectionTo === undefined
                        expressionMatch =
                    ? selection.to
                            expressionPattern.exec(
                     : selectionTo;
                                expression
                            )
                    ) !== null
                ) {
                     const name =
                        expressionMatch[0]
                            .toUpperCase();


                     if (
            const cursor =
                        !knownVariables.has(name)
                cursorPosition === undefined
                     ) {
                     ? from + text.length
                        continue;
                     : cursorPosition;
                    }


                    const start =
            view.dispatch({
                        expressionStart +
                changes: {
                        expressionMatch.index;
                     from,
 
                    to,
                     decorations.push(
                    insert: text
                        Decoration.mark({
                },
                            class:
                selection: {
                                'preload-editor-syntax-condition-variable'
                     anchor: cursor
                        }).range(
                            start,
                            start +
                                expressionMatch[0]
                                    .length
                        )
                     );
                 }
                 }
             }
             });


             return Decoration.set(
             view.focus();
                decorations,
                true
            );
         },
         },


         async installSyntaxHighlighting(view) {
         // =========================================================
            await mw.loader.using(
        // Editor tools
                'ext.CodeMirror.v6.lib'
        // =========================================================
            );


             const require =
        wrapSelectionWithVariable() {
                 mw.loader.require;
             const selected =
                 this.getEditorSelection();


             const {
             if (
                 StateField,
                 !selected ||
                 StateEffect,
                 selected.from === selected.to
                 EditorView,
            ) {
                 Decoration
                 this.focusEditor();
             } = require(
                 return;
                 'ext.CodeMirror.v6.lib'
             }
 
            const replacement =
                '%%' +
                selected.text +
                '%%';
 
            this.insertEditorText(
                 replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
             );
             );
        },


             const syntaxField =
        insertVariable(name) {
                 StateField.define({
             name = String(name || '')
                    create: state =>
                 .trim()
                        this.createSyntaxDecorations(
                .toUpperCase();
                            state,
                            Decoration
                        ),


                    update: (
            if (!name) {
                        decorations,
                return;
                        transaction
            }
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                    provide: field =>
            const selected =
                        EditorView.decorations.from(
                this.getEditorSelection();
                            field
                        )
                });


             view.dispatch({
             if (!selected) {
                 effects:
                 return;
                    StateEffect.appendConfig.of(
             }
                        syntaxField
                    )
             });


             this.editor.syntaxField =
             this.insertEditorText(
                 syntaxField;
                '%%' + name + '%%',
                selected.from,
                 selected.to
            );
         },
         },


         async mountCodeMirror(textarea) {
         insertCondition(
             return new Promise(
            type,
                 (
            variable
                    resolve,
        ) {
                    reject
             type = String(type || '').toLowerCase();
                 ) => {
            variable = String(variable || '')
                    let settled = false;
                 .trim()
                .toUpperCase();
 
            const selected =
                 this.getEditorSelection();


                    const cleanup =
            if (!selected) {
                        () => {
                return;
                            mw.hook(
            }
                                'dev.CCM.ready'
                            ).remove(onReady);


                            mw.hook(
            let text;
                                'dev.CCM.load'
            let cursorOffset;
                            ).remove(onLoad);
                        };


                    const onReady =
            switch (type) {
                        async cm => {
                case 'if': {
                            if (
                    if (!variable) {
                                settled ||
                        return;
                                !cm ||
                    }
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                            settled = true;
                    const opening =
                            cleanup();
                        '<!-- @if ' +
                        variable +
                        ' -->';


                            const view =
                    const closing =
                                cm.view;
                        '<!-- @endif -->';


                            const inputHandler =
                    if (
                                () => {
                        selected.from !==
                                    this.state
                        selected.to
                                        .preloadContent =
                    ) {
                                        view.state.doc.toString();
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                                    this.state.dirty =
                        cursorOffset = text.length;
                                        true;
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;


                                    this.reanalyze();
                        cursorOffset =
                            opening.length + 1;
                    }


                                    this.renderVariablesBySelector();
                    break;
                                    this.renderVariableConfigurationBySelector();
                }
                                    this.renderAnalysisBySelector();
                                    this.renderConfigPreviewBySelector();
                                    this.updateEditorTools();


                                    this.saveDraft();
                case 'elseif':
                                };
                    text =
                        '<!-- @elseif -->';


                            view.dom.addEventListener(
                    cursorOffset =
                                'input',
                        text.length;
                                inputHandler
                            );


                            view.dom.classList.add(
                    break;
                                'preload-editor-codemirror'
                            );


                            const wrapper =
                case 'else':
                                view.dom.closest(
                    text =
                                    '.ext-codemirror-wrapper'
                        '<!-- @else -->';
                                );


                            if (wrapper) {
                    cursorOffset =
                                wrapper.classList.add(
                        text.length;
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


                            this.editor = {
                    break;
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


                            this.editorView =
                case 'endif':
                                view;
                    text =
                        '<!-- @endif -->';


                            this.state.preloadContent =
                    cursorOffset =
                                view.state.doc.toString();
                        text.length;


                            try {
                    break;
                                await this.installSyntaxHighlighting(
                                    view
                                );


                                if (
                default:
                                    this.state.dirty
                    return;
                                ) {
            }
                                    this.saveDraft();
                                }


                                resolve(view);
            this.insertEditorText(
                            } catch (error) {
                text,
                                reject(error);
                selected.from,
                            }
                selected.to,
                        };
                selected.from + cursorOffset
            );
        },


                    const onLoad =
        getToolVariables() {
                        loader => {
            const variables =
                            if (
                new Set(['PAGE']);
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                            try {
            if (
                                loader(textarea);
                this.analysis &&
                             } catch (error) {
                this.analysis.variables
                                settled = true;
            ) {
                                cleanup();
                this.analysis.variables.forEach(
                                reject(error);
                    name => {
                            }
                        variables.add(
                        };
                             String(name).toUpperCase()
                        );
                    }
                );
            }


                    mw.hook(
            return Array.from(variables);
                        'dev.CCM.ready'
                    ).add(onReady);
 
                    mw.hook(
                        'dev.CCM.load'
                    ).add(onLoad);
                }
            );
         },
         },


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


        init() {
            if (className) {
            const root =
                 select.addClass(className);
                 $('#mw-content-text');
 
            if (!root.length) {
                return;
             }
             }


             this.root =
             options.forEach(
                $('<div>')
                option => {
                    .attr(
                    $('<option>')
                        'id',
                        .attr(
                        'preload-editor'
                            'value',
                    )
                            option.value
                    .addClass(
                         )
                         'preload-editor'
                        .text(option.label)
                    );
                         .appendTo(select);
 
            root.append(this.root);
 
            this.renderShell();
 
            this.restoreDraft();
 
            window.addEventListener(
                'beforeunload',
                () => {
                    if (this.state.dirty) {
                         this.saveDraft();
                    }
                 }
                 }
             );
             );
            return select;
         },
         },


         renderShell() {
         updateEditorToolVariables() {
             this.destroyEditor();
             if (!this.editorTools) {
             this.root.empty();
                return;
             }


             const loader =
             const variables =
                 this.createSection('Preload');
                 this.getToolVariables();


             const titleInput =
             const current =
                 this.textInput(
                 this.editorTools
                     this.state.preloadTitle,
                     .variableSelect
                    'Template:Example/Preload'
                    .val();
                 ).attr(
 
                     'id',
            const currentCondition =
                     'preload-editor-title-input'
                 this.editorTools
                );
                     .conditionVariableSelect
                     .val();


             titleInput.on(
             const populate = (
                 'input.preloadEditor',
                 select,
                 () => {
                 value
                    this.state.preloadTitle =
            ) => {
                        String(
                select.empty();
                            titleInput.val() || ''
                        ).trim();


                     if (
                variables.forEach(
                        this.state.dirty &&
                     name => {
                        this.state.mode === 'new'
                        $('<option>')
                    ) {
                            .attr(
                        this.saveDraft();
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                     }
                     }
                );
                if (
                    value &&
                    variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                        variables[0]
                    );
                 }
                 }
            };
            populate(
                this.editorTools.variableSelect,
                current
             );
             );


             const loadButton =
             populate(
                 this.createButton(
                 this.editorTools.conditionVariableSelect,
                    'Load',
                currentCondition
                    'preload-editor-button-primary',
            );
                    () =>
        },
                        this.loadExisting(
 
                            titleInput.val()
        updateConditionVariableVisibility() {
                        )
            if (!this.editorTools) {
                 );
                 return;
            }


             const newButton =
             const type =
                 this.createButton(
                 this.editorTools
                     'New',
                     .conditionTypeSelect
                     '',
                     .val();
                    () => this.startNew()
                );


             const sampleButton =
             this.editorTools
                 this.createButton(
                .conditionVariableWrap
                     'Load Sample Page',
                 .toggle(
                    '',
                     type === 'if'
                    () => this.loadSamplePage()
                 );
                 );
        },


             loader.append(
        renderEditorTools() {
             const tools =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-toolbar'
                         'preload-editor-tools'
                     )
                     );
                    .append(
 
                        titleInput,
             const wrapGroup =
                        loadButton,
                 $('<div>')
                        newButton,
                        sampleButton
                    )
            );
 
            this.root.append(loader);
 
             this.status =
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-status'
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                     );
                     );


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


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


             this.root.append(this.workspace);
             $('<span>')
                .addClass(
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);


             this.renderWelcome();
             const variableSelect =
        },
                this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );


        renderWelcome() {
             variableGroup.append(
             this.workspace.empty();
                variableSelect,


            const section =
                 this.createButton(
                 this.createSection('Get started');
                    'Insert',
 
                    'preload-editor-tool-button',
            $('<p>')
                    () =>
                .text(
                        this.insertVariable(
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                            variableSelect.val()
                        )
                 )
                 )
                .appendTo(section);
            );


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


             [
             $('<span>')
                'Existing preload: loads the preload and its config.json if available.',
                 .addClass(
                 'New preload: starts with the standard Preload Template structure.',
                    'preload-editor-tool-label'
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                )
            ].forEach(
                 .text('Insert condition')
                 text => {
                .appendTo(conditionGroup);
                    $('<li>')
                        .text(text)
                        .appendTo(tips);
                }
            );


             section.append(tips);
             const conditionTypeSelect =
            this.workspace.append(section);
                this.createToolSelect(
        },
                    [
 
                        {
        setStatus(
                            value: 'if',
            message,
                            label: '@if'
            type
                        },
        ) {
                        {
            if (!this.status) {
                            value: 'elseif',
                 return;
                            label: '@elseif'
            }
                        },
                        {
                            value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                 );


             this.status.removeClass(
             const conditionVariableSelect =
                'is-error',
                this.createToolSelect(
                'is-success',
                    [],
                'is-warning',
                    'preload-editor-condition-variable-select'
                'is-loading'
            );
 
            if (type) {
                this.status.addClass(
                    'is-' + type
                 );
                 );
            }


             this.status.text(
             const conditionVariableWrap =
                message || ''
                $('<span>')
            );
                    .addClass(
        },
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


        // Load / create
             const insertCondition =
 
                 this.createButton(
        async loadExisting(title) {
                    'Insert',
             title =
                    'preload-editor-tool-button',
                 String(title || '').trim();
                    () =>
 
                        this.insertCondition(
            if (!title) {
                            conditionTypeSelect.val(),
                mw.notify(
                            conditionVariableSelect.val()
                    'Enter a preload page title first.',
                         )
                    {
                         type: 'warn'
                    }
                 );
                 );


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


             this.setStatus(
             conditionGroup.append(
                 'Loading preload...',
                 conditionTypeSelect,
                 'loading'
                conditionVariableWrap,
                 insertCondition
             );
             );


             try {
             tools.append(
                 const page =
                wrapGroup,
                    await this.getPage(title);
                variableGroup,
                 conditionGroup
            );


                 if (!page) {
            this.editorTools = {
                    const suggestions =
                root: tools,
                        await this.findSimilarPreloads(
                variableSelect,
                            title
                 conditionTypeSelect,
                        );
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };


                    this.renderMissingPage(
            this.updateEditorToolVariables();
                        title,
            this.updateConditionVariableVisibility();
                        suggestions
                    );


                    this.setStatus(
            return tools;
                        'Preload not found.',
        },
                        'warning'
                    );


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


                await this.loadDefinition(
        // =========================================================
                    page.title,
        // Syntax highlighting
                    page.content
        // =========================================================
                );


                this.setStatus(
        getKnownVariables() {
                    'Preload loaded.',
            const known =
                    'success'
                new Set(['PAGE']);
                );
 
             } catch (error) {
             const fields =
                 console.error(
                 this.state.config &&
                    'Preload Editor:',
                 this.state.config.fields;
                    error
                 );


                 this.setStatus(
            if (
                     error.message ||
                fields &&
                         'Could not load preload.',
                typeof fields === 'object'
                     'error'
            ) {
                 Object.keys(fields).forEach(
                     name => {
                        known.add(
                            String(name).toUpperCase()
                         );
                     }
                 );
                 );
             }
             }
            return known;
         },
         },


         async findSimilarPreloads(title) {
         createSyntaxDecorations(
             let query =
            state,
                 title
            Decoration
                    .replace(
        ) {
                        /\/Preload$/i,
             const decorations = [];
                        ''
            const source =
                    )
                 state.doc.toString();
                    .trim();


             if (!query) {
             const knownVariables =
                query = title;
                this.getKnownVariables();
            }


             try {
             const variablePattern =
                const results =
                /%%([A-Za-z0-9_-]+)%%/g;
                    await this.searchPages(query);


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


                 return [];
            while (
            }
                (
        },
                    match =
                        variablePattern.exec(source)
                ) !== null
            ) {
                 const name =
                    match[1].toUpperCase();


        renderMissingPage(
                const known =
            title,
                    knownVariables.has(name);
            suggestions
        ) {
            this.workspace.empty();


            const section =
                 decorations.push(
                 this.createSection(
                     Decoration.mark({
                     'Preload not found'
                        class: [
                 );
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                 );
            }


             $('<p>')
             const conditionPattern =
                 .text(
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


             if (suggestions.length) {
             while (
                 $('<h3>')
                (
                     .text('Similar preloads')
                    match =
                     .appendTo(section);
                        conditionPattern.exec(source)
                ) !== null
            ) {
                 decorations.push(
                     Decoration.mark({
                        class:
                            'preload-editor-syntax-condition'
                     }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


                 const list =
                 const directiveStart =
                     $('<div>')
                     match.index +
                        .addClass(
                    match[0].indexOf('@');
                            'preload-editor-suggestions'
                        );


                 suggestions.forEach(
                 decorations.push(
                     result => {
                     Decoration.mark({
                         list.append(
                         class:
                             this.createButton(
                             'preload-editor-syntax-directive'
                                result.title,
                    }).range(
                                'preload-editor-suggestion',
                        directiveStart,
                                () =>
                        directiveStart +
                                    this.loadExisting(
                             match[1].length +
                                        result.title
                            1
                                    )
                     )
                             )
                        );
                     }
                 );
                 );


                 section.append(list);
                 const type =
            }
                    match[1].toLowerCase();


            section.append(
                 if (
                 this.createButton(
                     type !== 'if' &&
                     'Create this preload',
                     type !== 'elseif'
                     'preload-editor-button-primary',
                ) {
                    () =>
                    continue;
                        this.startNew(title)
                 }
                 )
            );


            this.workspace.append(section);
                const expression =
        },
                    match[2];


        async startNew(title) {
                const expressionStart =
            title =
                    match.index +
                String(title || '').trim();
                    match[0].indexOf(
                        expression
                    );


            this.state = {
                const expressionPattern =
                preloadTitle: title,
                     /[A-Za-z0-9_-]+/g;
                preloadSource: '',
                preloadContent:
                     this.defaults.preload,


                 config:
                 let expressionMatch;
                    this.emptyConfig(),


                 variables: ['PAGE'],
                 while (
                 conditions: [],
                    (
                selectedVariable: 'PAGE',
                        expressionMatch =
                deletedVariables: [],
                            expressionPattern.exec(
                mode: 'new',
                                expression
                dirty: true
                            )
            };
                    ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


            this.saveDraft();
                    if (
            this.renderEditor();
                        !knownVariables.has(name)
                    ) {
                        continue;
                    }


            this.setStatus(
                    const start =
                'Creating a new preload.',
                        expressionStart +
                 'success'
                        expressionMatch.index;
 
                    decorations.push(
                        Decoration.mark({
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                }
            }
 
            return Decoration.set(
                decorations,
                 true
             );
             );
         },
         },


         async loadSamplePage() {
         async installSyntaxHighlighting(view) {
             const result =
             await mw.loader.using(
                await this.createPromptDialog(
                'ext.CodeMirror.v6.lib'
                    'Load Sample Page',
            );
                    'Enter the title of a normal wiki page to use as the starting point.'
                );


             if (!result) {
             const require =
                 return;
                 mw.loader.require;
            }


             this.setStatus(
             const {
                 'Loading sample page...',
                StateField,
                'loading'
                StateEffect,
                EditorView,
                Decoration
            } = require(
                 'ext.CodeMirror.v6.lib'
             );
             );


             try {
             const syntaxField =
                const page =
                StateField.define({
                    await this.getPage(result);
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


                if (!page) {
                     update: (
                     throw new Error(
                         decorations,
                         'Sample page not found: ' +
                         transaction
                         result
                     ) =>
                     );
                        transaction.docChanged
                }
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                const sample =
                    provide: field =>
                    this.convertSampleToPreload(
                        EditorView.decorations.from(
                         page.content
                            field
                    );
                         )
                });


                this.state = {
            view.dispatch({
                    preloadTitle: '',
                effects:
                     preloadSource: '',
                     StateEffect.appendConfig.of(
                     preloadContent: sample,
                        syntaxField
                     )
            });


                    config:
            this.editor.syntaxField =
                        this.emptyConfig(),
                syntaxField;
        },


                    variables: ['PAGE'],
        async mountCodeMirror(textarea) {
                    conditions: [],
            return new Promise(
                     selectedVariable: 'PAGE',
                (
                     deletedVariables: [],
                     resolve,
                    mode: 'new',
                     reject
                     dirty: true
                ) => {
                };
                     let settled = false;


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


                this.setStatus(
                        mw.hook(
                    'Sample page loaded.',
                            'dev.CCM.load'
                    'success'
                        ).remove(onLoad);
                );
                     };
            } catch (error) {
                console.error(
                     'Preload Editor sample:',
                    error
                );


                this.setStatus(
                     const onReady =
                     error.message ||
                         async cm => {
                         'Could not load sample page.',
                            if (
                    'error'
                                settled ||
                );
                                !cm ||
            }
                                cm.textarea !== textarea ||
        },
                                !cm.view
 
                            ) {
        convertSampleToPreload(source) {
                                return;
            let content =
                            }
                String(source || '').trim();


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


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


            content =
                            const inputHandler =
                content
                                () => {
                    .replace(
                                    this.state
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                                        .preloadContent =
                        ''
                                        view.state.doc.toString();
                    )
                    .trim();


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


        async loadDefinition(
                                    this.reanalyze();
            title,
            source
        ) {
            const content =
                this.extractIncludeonly(source);


            let config =
                                    this.renderVariablesBySelector();
                this.emptyConfig();
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


            const configTitle =
                                    this.saveDraft();
                title.replace(
                                };
                    /\/+$/,
                    ''
                ) +
                '/config.json';


            const configPage =
                            view.dom.addEventListener(
                await this.getPage(configTitle);
                                'input',
                                inputHandler
                            );


            if (configPage) {
                            view.dom.classList.add(
                try {
                                'preload-editor-codemirror'
                    config =
                            );
                        JSON.parse(
                            configPage.content
                        );
                } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }


            const analysis =
                            const wrapper =
                this.analyzePreload(content);
                                view.dom.closest(
                                    '.ext-codemirror-wrapper'
                                );


            this.state.deletedVariables = [];
                            if (wrapper) {
 
                                wrapper.classList.add(
            config =
                                    'preload-editor-codemirror-wrapper'
                this.prepareConfigForVariables(
                                );
                    config,
                            }
                    analysis
                );


            this.state = {
                            this.editor = {
                preloadTitle: title,
                                cm,
                preloadSource: source,
                                view,
                preloadContent: source,
                                textarea,
                config,
                                inputHandler
                            };


                variables:
                            this.editorView =
                    analysis.variables,
                                view;


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


                selectedVariable:
                            try {
                    analysis.variables.includes('PAGE')
                                await this.installSyntaxHighlighting(
                        ? 'PAGE'
                                    view
                        : (
                                );
                            analysis.variables[0] ||
                            'PAGE'
                        ),


                deletedVariables: [],
                                if (
                                    this.state.dirty
                                ) {
                                    this.saveDraft();
                                }


                mode: 'edit',
                                resolve(view);
                dirty: false
                            } catch (error) {
            };
                                reject(error);
                            }
                        };
 
                    const onLoad =
                        loader => {
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }
 
                            try {
                                loader(textarea);
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };
 
                    mw.hook(
                        'dev.CCM.ready'
                    ).add(onReady);


            this.clearDraft(title);
                    mw.hook(
             this.renderEditor();
                        'dev.CCM.load'
                    ).add(onLoad);
                }
             );
         },
         },


         // Editor
         // =========================================================
        // Main UI
        // =========================================================


         renderEditor() {
         init() {
             this.destroyEditor();
             const root =
            this.workspace.empty();
                $('#mw-content-text');


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


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


             const right =
             root.append(this.root);
                $('<div>')
                    .addClass(
                        'preload-editor-right'
                    );


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


             const meta =
             this.restoreDraft();
                $('<div>')
                    .addClass(
                        'preload-editor-meta'
                    );


             $('<strong>')
             window.addEventListener(
                 .text(
                'beforeunload',
                     this.state.preloadTitle ||
                 () => {
                     'New preload'
                     if (this.state.dirty) {
                 )
                        this.saveDraft();
                 .appendTo(meta);
                     }
                }
            );
        },
                 renderShell() {
            this.destroyEditor();
            this.root.empty();
 
            const loader =
                 this.createSection('Preload');


             if (
             const titleInput =
                this.state.mode === 'new'
                this.textInput(
            ) {
                    this.state.preloadTitle,
                $('<span>')
                    'Template:Example/Preload'
                     .addClass(
                ).attr(
                        'preload-editor-badge'
                    'id',
                    )
                     'preload-editor-title-input'
                    .text('NEW')
                );
                     .appendTo(meta);
 
            }
            titleInput.on(
                'input.preloadEditor',
                () => {
                     this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();


            editorSection.append(meta);
                    if (
            editorSection.append(
                        this.state.dirty &&
                this.renderEditorTools()
                        this.state.mode === 'new'
                    ) {
                        this.saveDraft();
                    }
                }
             );
             );


             const textarea =
             const loadButton =
                 this.textarea(
                 this.createButton(
                     this.state.preloadContent
                     'Load',
                )
                    'preload-editor-button-primary',
                    .attr(
                     () =>
                        'id',
                        this.loadExisting(
                        'preload-editor-content'
                            titleInput.val()
                     )
                         )
                    .addClass(
                );
                         'preload-editor-content'
                    );


             const editorMount =
             const newButton =
                 $('<div>')
                 this.createButton(
                     .addClass(
                    'New',
                        'preload-editor-codemirror-mount'
                     '',
                     )
                     () => this.startNew()
                    .append(textarea);
                );


             editorSection.append(editorMount);
             const sampleButton =
            left.append(editorSection);
                this.createButton(
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );


             const analysisSection =
             loader.append(
                this.createSection('Analysis');
 
            const analysisContainer =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-analysis'
                         'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );
 
            this.root.append(loader);
 
            this.workspace =
                $('<div>')
                    .addClass(
                        'preload-editor-workspace'
                     );
                     );


             analysisSection.append(
             this.root.append(
                 analysisContainer
                 this.workspace
             );
             );


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


             const detectVariablesButton =
             this.localDraftStatus =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );
 
            const detectHelp =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-help preload-editor-detect-variables-help'
                         'preload-editor-local-draft-status is-empty'
                     )
                     )
                     .text(
                     .text(
                         'Refresh the variable list after editing the preload.'
                         'No local draft'
                     );
                     );


             variablesSection.append(
             this.status =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-detect'
                         'preload-editor-status'
                     )
                     );
                    .append(
 
                        detectVariablesButton,
            footer.append(
                        detectHelp
                this.localDraftStatus,
                    )
                this.status
             );
             );


             const variableContainer =
             this.root.append(
                $('<div>')
                 footer
                    .addClass(
                        'preload-editor-variables'
                    );
 
            variablesSection.append(
                 variableContainer
             );
             );


             const configurationSection =
             this.updateLocalDraftIndicator();
                this.createSection(
                    'Variable configuration'
                );


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


             configurationSection.append(
        renderWelcome() {
                configurationContainer
             this.workspace.empty();
            );


             const configSection =
             const section =
                 this.createSection(
                 this.createSection('Get started');
                    'Generated configuration'
                );


             const configPreview =
             $('<p>')
                $('<pre>')
                .text(
                    .addClass(
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                        'preload-editor-config-preview'
                )
                    );
                .appendTo(section);


            configSection.append(
             const tips =
                configPreview
                 $('<ul>')
            );
 
             const actions =
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-actions'
                         'preload-editor-tips'
                     );
                     );


             actions.append(
             [
                 this.createButton(
                 'Existing preload: loads the preload and its config.json if available.',
                    'Save Preload + Config',
                'New preload: starts with the standard Preload Template structure.',
                    'preload-editor-button-primary',
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                     () =>
            ].forEach(
                         this.saveAll()
                text => {
                 ),
                     $('<li>')
                        .text(text)
                         .appendTo(tips);
                 }
            );


                this.createButton(
            section.append(tips);
                    'Save Preload Only',
            this.workspace.append(section);
                    '',
        },
                    () =>
                        this.savePreloadOnly()
                )
            );


            right.append(
        setStatus(
                analysisSection,
            message,
                variablesSection,
            type
                configurationSection,
        ) {
                configSection,
            if (!this.status) {
                 actions
                 return;
             );
             }


             layout.append(
             this.status.removeClass(
                 left,
                 'is-error',
                 right
                'is-success',
                'is-warning',
                 'is-loading'
             );
             );


             this.workspace.append(layout);
            if (type) {
                this.status.addClass(
                    'is-' + type
                );
            }
 
             this.status.text(
                message || ''
            );
        },


            this.reanalyze();
        // =========================================================
        // Load / create
        // =========================================================


             this.renderVariables(
        async loadExisting(title) {
                variableContainer
             title =
            );
                String(title || '').trim();


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


            this.renderVariableConfiguration(
                 return;
                 configurationContainer
             }
             );


             this.renderConfigPreview(
             this.setStatus(
                 configPreview
                 'Loading preload...',
                'loading'
             );
             );


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


            this.mountCodeMirror(
                if (!page) {
                textarea.get(0)
                    const suggestions =
            ).catch(
                        await this.findSimilarPreloads(
                error => {
                            title
                     console.error(
                        );
                         'Preload Editor CodeMirror:',
 
                         error
                     this.renderMissingPage(
                         title,
                         suggestions
                     );
                     );


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


        detectVariables() {
                await this.loadDefinition(
            const source =
                    page.title,
                 this.getEditorContent();
                    page.content
                 );


            this.state.preloadContent =
                this.setStatus(
                 source;
                    'Preload loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                    error
                 );


            this.state.dirty = true;
                this.setStatus(
                    error.message ||
                        'Could not load preload.',
                    'error'
                );
            }
        },


             this.reanalyze();
        async findSimilarPreloads(title) {
             let query =
                title
                    .replace(
                        /\/Preload$/i,
                        ''
                    )
                    .trim();
 
            if (!query) {
                query = title;
            }


             this.renderVariablesBySelector();
             try {
            this.renderVariableConfigurationBySelector();
                const results =
            this.renderAnalysisBySelector();
                    await this.searchPages(query);
            this.renderConfigPreviewBySelector();
            this.updateEditorTools();


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


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


         reanalyze() {
         renderMissingPage(
             const source =
            title,
                this.getEditorContent();
            suggestions
        ) {
             this.workspace.empty();


             const content =
             const section =
                 this.extractIncludeonly(source);
                 this.createSection(
                    'Preload not found'
                );


             const analysis =
             $('<p>')
                 this.analyzePreload(content);
                .text(
                    'No preload exists at "' +
                    title +
                    '".'
                )
                 .appendTo(section);


             this.state.preloadContent =
             if (suggestions.length) {
                source;
                $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);


            this.state.variables =
                const list =
                analysis.variables;
                    $('<div>')
                        .addClass(
                            'preload-editor-suggestions'
                        );


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


            this.state.config =
                 section.append(list);
                 this.prepareConfigForVariables(
            }
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


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


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


         renderAnalysis(container) {
         async startNew(title) {
             container.empty();
             title =
                String(title || '').trim();


             const analysis =
             this.state = {
                 this.analysis ||
                preloadTitle: title,
                 this.analyzePreload(
                 preloadSource: '',
                     this.extractIncludeonly(
                 preloadContent:
                        this.getEditorContent()
                     this.defaults.preload,
                    )
                );


            const variableCount =
                config:
                analysis.variables.length;
                    this.emptyConfig(),


            const conditionCount =
                variables: ['PAGE'],
                 analysis.conditions.length;
                 conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,


            const configuredCount =
                localDraftSavedAt: null,
                 Object.keys(
                 localDraftAvailable: false
                    this.state.config &&
            };
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;


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


             const createMetric =
             this.setStatus(
                (
                 'Creating a new preload.',
                    value,
                'success'
                    label
            );
                 ) =>
        },
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                            $('<span>')
        async loadSamplePage() {
                                .addClass(
            const result =
                                    'preload-editor-analysis-label'
                await this.createPromptDialog(
                                )
                    'Load Sample Page',
                                .text(label)
                    'Enter the title of a normal wiki page to use as the starting point.'
                        );
                );


             summary.append(
             if (!result) {
                 createMetric(
                 return;
                    variableCount,
            }
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),


                createMetric(
            this.setStatus(
                    conditionCount,
                'Loading sample page...',
                    conditionCount === 1
                'loading'
                        ? 'condition marker'
            );
                        : 'condition markers'
                ),


                 createMetric(
            try {
                     configuredCount,
                 const page =
                    configuredCount === 1
                     await this.getPage(result);
                        ? 'configured field'
                        : 'configured fields'
                )
            );


            container.append(summary);
                if (!page) {
                    throw new Error(
                        'Sample page not found: ' +
                        result
                    );
                }


            if (
                 const sample =
                analysis.conditionVariables.length
                     this.convertSampleToPreload(
            ) {
                         page.content
                 container.append(
                    );
                     $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                         .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }


            const validation =
                 this.state = {
                 this.validateConfig(
                     preloadTitle: '',
                     this.state.config,
                     preloadSource: '',
                     analysis
                    preloadContent: sample,
                );


            if (validation.errors.length) {
                     config:
                const errors =
                         this.emptyConfig(),
                     $('<ul>')
                         .addClass(
                            'preload-editor-validation-errors'
                        );


                validation.errors.forEach(
                    variables: ['PAGE'],
                     error => {
                     conditions: [],
                        $('<li>')
                    selectedVariable: 'PAGE',
                            .text(error)
                    deletedVariables: [],
                            .appendTo(errors);
                    mode: 'new',
                     }
                     dirty: true,
                );
                    dirtyPreload: true,
                    dirtyConfig: true,


                 container.append(errors);
                    localDraftSavedAt: null,
            }
                    localDraftAvailable: false
                 };


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


                 validation.warnings.forEach(
                 this.setStatus(
                     warning => {
                     'Sample page loaded.',
                        $('<li>')
                    'success'
                            .text(warning)
                );
                            .appendTo(warnings);
            } catch (error) {
                     }
                console.error(
                     'Preload Editor sample:',
                    error
                 );
                 );


                 container.append(warnings);
                 this.setStatus(
            }
                    error.message ||
 
                        'Could not load sample page.',
            if (
                    'error'
                !validation.errors.length &&
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                 );
                 );
             }
             }
         },
         },


         renderAnalysisBySelector() {
         convertSampleToPreload(source) {
             const container =
             let content =
                 this.root &&
                 String(source || '').trim();
                 this.root.find(
 
                     '.preload-editor-analysis'
            const include =
                 content.match(
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                 );
                 );


             if (
             if (include) {
                container &&
                 content =
                container.length
                    include[1].trim();
            ) {
                 this.renderAnalysis(container);
             }
             }
        },


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


         renderVariables(container) {
            return (
             container.empty();
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
        },
 
         async loadDefinition(
            title,
            source
        ) {
             const content =
                this.extractIncludeonly(source);


             const analysis =
             let config =
                 this.analysis ||
                 this.emptyConfig();
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


             const variables =
             const configTitle =
                 analysis.variables.slice();
                 title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';


             const ordered =
             const configPage =
                 ['PAGE'];
                 await this.getPage(configTitle);


             variables.forEach(
             if (configPage) {
                 name => {
                 try {
                     if (
                     config =
                        name !== 'PAGE' &&
                         JSON.parse(
                         !ordered.includes(name)
                            configPage.content
                    ) {
                        );
                         ordered.push(name);
                } catch (error) {
                    }
                    throw new Error(
                         'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                 }
                 }
             );
             }


             const configuredFields =
             const analysis =
                 this.state.config &&
                 this.analyzePreload(content);
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];


             configuredFields.forEach(
             this.state.deletedVariables = [];
                name => {
                    const upper =
                        name.toUpperCase();


                    if (
            config =
                        upper !== 'PAGE' &&
                this.prepareConfigForVariables(
                        !ordered.includes(upper)
                     config,
                     ) {
                     analysis
                        ordered.push(upper);
                 );
                     }
                 }
            );


             const deleted =
             this.state = {
                Array.isArray(
                 preloadTitle: title,
                    this.state.deletedVariables
                preloadSource: source,
                 )
                preloadContent: source,
                    ? this.state.deletedVariables
                config,
                    : [];


            deleted.forEach(
                 variables:
                 name => {
                     analysis.variables,
                     const upper =
                        String(name).toUpperCase();


                    if (
                conditions:
                        upper !== 'PAGE' &&
                     analysis.conditions,
                        !ordered.includes(upper)
                     ) {
                        ordered.push(upper);
                    }
                }
            );


            const list =
                selectedVariable:
                $('<div>')
                    analysis.variables.includes('PAGE')
                    .addClass(
                        ? 'PAGE'
                        'preload-editor-variable-list'
                        : (
                    );
                            analysis.variables[0] ||
                            'PAGE'
                        ),


            ordered.forEach(
                 deletedVariables: [],
                 name => {
                    const isSelected =
                        name ===
                        this.state.selectedVariable;


                    const isUsed =
                mode: 'edit',
                        analysis.variables.includes(
                dirty: false,
                            name
                dirtyPreload: false,
                        );
                dirtyConfig: false,


                    const isConfigured =
                localDraftSavedAt: null,
                        !!(
                localDraftAvailable: false
                            this.state.config &&
            };
                            this.state.config.fields &&
 
                            this.state.config.fields[name]
            this.clearDraft(title);
                        );
            this.renderEditor();
        },


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


                    $('<span>')
        renderEditor() {
                        .addClass(
            this.destroyEditor();
                            'preload-editor-variable-name'
            this.workspace.empty();
                        )
                        .text(name)
                        .appendTo(item);


                    if (name === 'PAGE') {
            const layout =
                        item.append(
                $('<div>')
                            $('<span>')
                    .addClass(
                                .addClass(
                         'preload-editor-layout'
                                    'preload-editor-badge'
                     );
                                )
                                .text('AUTOMATIC')
                        );
                    } else if (!isConfigured) {
                         item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    isUsed
                                        ? 'NOT CONFIGURED'
                                        : 'DELETED'
                                )
                        );
                     } else if (!isUsed) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                    }


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


             container.append(list);
             const right =
                $('<div>')
                    .addClass(
                        'preload-editor-right'
                    );


             if (!ordered.length) {
             const editorSection =
                 container.append(
                 this.createSection(
                     $('<div>')
                     'Preload',
                        .addClass(
                    'preload-editor-main-section'
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                 );
                 );
            }
        },


        renderVariablesBySelector() {
            const meta =
             const container =
                $('<div>')
                 this.root &&
                    .addClass(
                this.root.find(
                        'preload-editor-meta'
                     '.preload-editor-variables'
                    );
                 );
 
             $('<strong>')
                 .text(
                    this.state.preloadTitle ||
                     'New preload'
                 )
                .appendTo(meta);


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


        selectVariable(name) {
            editorSection.append(meta);
             name =
             editorSection.append(
                 String(name || '')
                 this.renderEditorTools()
                    .trim()
            );
                    .toUpperCase();


             if (!name) {
             const textarea =
                return;
                this.textarea(
            }
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


             const available =
             const editorMount =
                 ['PAGE'].concat(
                 $('<div>')
                     (
                     .addClass(
                        this.analysis &&
                         'preload-editor-codemirror-mount'
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                         variable =>
                            variable !== 'PAGE'
                     )
                     )
                );
                    .append(textarea);
 
            editorSection.append(editorMount);
            left.append(editorSection);


             const configuredUnused =
             const analysisSection =
                 this.state.config &&
                 this.createSection('Analysis');
                this.state.config.fields
 
                    ? Object.keys(
            const analysisContainer =
                        this.state.config.fields
                $('<div>')
                    )
                    .addClass(
                        .map(
                         'preload-editor-analysis'
                            variable =>
                     );
                                variable.toUpperCase()
                         )
                     : [];


             configuredUnused.forEach(
             analysisSection.append(
                 variable => {
                 analysisContainer
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                }
             );
             );


             if (!available.includes(name)) {
             const variablesSection =
                return;
                this.createSection('Variables');
            }


             this.state.selectedVariable =
             const detectVariablesButton =
                 name;
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                 );


             this.renderVariablesBySelector();
             const detectHelp =
            this.renderVariableConfigurationBySelector();
                $('<div>')
        },
                    .addClass(
                        'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );


        renderVariableConfigurationBySelector() {
            variablesSection.append(
            const container =
                 $('<div>')
                 this.root &&
                    .addClass(
                this.root.find(
                        'preload-editor-variable-detect'
                    '.preload-editor-variable-configuration'
                    )
                );
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );


             if (
             const variableContainer =
                 container &&
                 $('<div>')
                container.length
                    .addClass(
            ) {
                        'preload-editor-variables'
                this.renderVariableConfiguration(
                     );
                     container
                );
            }
        },


        renderVariableConfiguration(container) {
            variablesSection.append(
             container.empty();
                variableContainer
             );


             const analysis =
             const configurationSection =
                 this.analysis ||
                 this.createSection(
                 this.analyzePreload(
                    'Variable configuration'
                     this.extractIncludeonly(
                );
                         this.getEditorContent()
 
                    )
            /*
            * Import button lives at the top of the
            * variable configuration section so the
            * workflow is always easy to find.
            */
            const importDefinitionsButton =
                 this.createButton(
                     'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                         this.importVariableDefinitions()
                 );
                 );


             const name =
             const importHelp =
                 this.state.selectedVariable ||
                 $('<div>')
                'PAGE';
                     .addClass(
 
                         'preload-editor-help preload-editor-import-definitions-help'
            const fields =
                this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};
 
            const field =
                fields[name];
 
            if (name === 'PAGE') {
                container.append(
                     this.createAutomaticPageCard(
                         field ||
                        this.getAutomaticPageField()
                     )
                     )
                );
                     .text(
 
                         'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                return;
                    );
            }
 
            if (!field) {
                const missing =
                     $('<div>')
                         .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );


            const importControls =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor-import-definition-controls'
                     )
                     )
                     .append(
                     .append(
                         $('<h3>')
                         importDefinitionsButton,
                            .text(name),
                        importHelp
                    );


                        $('<span>')
            configurationSection.append(
                            .addClass(
                importControls
                                'preload-editor-badge is-warning'
            );
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


                 $('<p>')
            const configurationContainer =
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-analysis-note'
                         'preload-editor-variable-configuration'
                     )
                     );
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);


                container.append(missing);
            configurationSection.append(
                 return;
                 configurationContainer
             }
             );


             container.append(
             const configSection =
                 this.createVariableCard(
                 this.createSection(
                     name,
                     'Configuration'
                    field,
                 );
                    analysis
                 )
            );
        },


        createAutomaticPageCard(field) {
             const configHelp =
             const card =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable preload-editor-variable-automatic'
                         'preload-editor-help'
                     )
                     )
                     .attr(
                     .text(
                         'data-variable',
                         'Review the exact config.json that will be uploaded to the wiki.'
                        'PAGE'
                     );
                     );


             const header =
             const reviewConfigButton =
                this.createButton(
                    'Review config.json',
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );
 
            configSection.append(
                configHelp,
                reviewConfigButton
            );
 
            right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );
 
            layout.append(
                left,
                right
            );
 
            const saveBar =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor-save-bar'
                     );
                     );


             header.append(
             saveBar.append(
                 $('<h3>').text('PAGE'),
                 this.createButton(
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),


                 $('<span>')
                 this.createButton(
                     .addClass(
                    'Save Config',
                        'preload-editor-badge'
                     '',
                     )
                     () =>
                    .text('AUTOMATIC')
                        this.saveConfigOnly()
            );
                ),


            card.append(header);
                this.createButton(
 
                    'Save',
            $('<p>')
                     'preload-editor-button-primary',
                .addClass(
                    () =>
                     'preload-editor-analysis-note'
                        this.saveAll()
                 )
                 )
                .text(
            );
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);


             const label =
             this.root
                 this.textInput(
                 .find('.preload-editor-footer')
                    field.label ||
                 .append(saveBar);
                    'Page Name'
                 ).prop(
                    'disabled',
                    true
                );


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


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


             const required =
             this.renderVariables(
                this.checkbox(
                 variableContainer
                    field.required !== false
            );
                 ).prop(
                    'disabled',
                    true
                );


             const namespace =
             this.renderAnalysis(
                this.textInput(
                 analysisContainer
                    field.namespace || 'Main'
            );
                 ).prop(
                    'disabled',
                    true
                );


             const allowNew =
             this.renderVariableConfiguration(
                this.checkbox(
                 configurationContainer
                    field['allow-new'] === true
            );
                 ).prop(
                    'disabled',
                    true
                );


             card.append(
             this.updateEditorTools();
                this.fieldRow(
            this.updateLocalDraftIndicator();
                    'Label',
                    label
                ),


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


                this.fieldRow(
                    this.setStatus(
                    'Type',
                        error.message ||
                     type
                            'Could not initialize CodeMirror.',
                 ),
                        'error'
                     );
                 }
            );
        },
 
        // =========================================================
        // Variable detection
        // =========================================================


                 this.fieldRow(
        detectVariables() {
                    'Required',
            const source =
                    required
                 this.getEditorContent();
                ),


                this.fieldRow(
            this.state.preloadContent =
                    'Namespace',
                 source;
                    namespace
                 ),


                 this.fieldRow(
            const content =
                     'Allow new page',
                 this.extractIncludeonly(
                    allowNew
                     source
                 )
                 );
            );


             return card;
             const analysis =
        },
                this.analyzePreload(
                    content
                );


        createVariableCard(
            /*
            name,
            * If a variable was previously deleted from
            field,
            * the configuration, detecting the current
            analysis
            * preload again should allow it to come back.
        ) {
            */
             const card =
             if (
                 $('<div>')
                 Array.isArray(
                     .addClass(
                     this.state.deletedVariables
                        'preload-editor-variable'
                )
                    )
            ) {
                     .attr(
                const detected =
                        'data-variable',
                     new Set(
                        name
                        analysis.variables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                     );
                     );


            const header =
                this.state.deletedVariables =
                $('<div>')
                    this.state.deletedVariables
                    .addClass(
                        .filter(
                         'preload-editor-variable-header'
                            name =>
                    );
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                         );
            } else {
                this.state.deletedVariables = [];
            }
 
            this.markDirty();


             header.append(
             this.reanalyze();
                $('<h3>').text(name)
            );


             if (
             this.renderVariablesBySelector();
                !analysis.variables.includes(name)
             this.renderVariableConfigurationBySelector();
             ) {
            this.renderAnalysisBySelector();
                header.append(
            this.updateEditorTools();
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }


             card.append(header);
             this.saveDraft();


             const label =
             this.setStatus(
                this.textInput(
                'Variables detected from the current preload.',
                    field.label || ''
                'success'
                );
            );
        },


            label.on(
        reanalyze() {
                'input.preloadEditor',
            const source =
                () => {
                this.getEditorContent();
                    field.label =
                        label.val();


                    this.markDirty();
            const content =
                    this.renderConfigPreviewBySelector();
                this.extractIncludeonly(source);
                }
            );


            card.append(
             const analysis =
                this.fieldRow(
                 this.analyzePreload(
                    'Label',
                     content
                    label
                )
            );
 
             const description =
                 this.textarea(
                    field.description || ''
                ).addClass(
                     'preload-editor-small-textarea'
                 );
                 );


             description.on(
             this.state.preloadContent =
                'input.preloadEditor',
                 source;
                 () => {
                    field.description =
                        description.val();


                    this.markDirty();
            this.state.variables =
                    this.renderConfigPreviewBySelector();
                 analysis.variables;
                 }
            );


             card.append(
             this.state.conditions =
                 this.fieldRow(
                 analysis.conditions;
                    'Description',
                    description
                )
            );


             const types = [
             this.state.config =
                ['text', 'Text'],
                 this.prepareConfigForVariables(
                ['textarea', 'Textarea'],
                     this.state.config ||
                ['number', 'Number'],
                         this.emptyConfig(),
                ['boolean', 'Boolean'],
                     analysis
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date']
            ];
 
            const typeSelect =
                 this.select(
                     types.map(
                         ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                     field.type || 'text'
                 );
                 );


             typeSelect.on(
             this.analysis =
                 'change.preloadEditor',
                 analysis;
                () => {
                    field.type =
                        typeSelect.val();


                     this.markDirty();
            const available =
                ['PAGE'].concat(
                     analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );


                    this.renderVariableConfigurationBySelector();
            if (
                    this.renderConfigPreviewBySelector();
                 !available.includes(
                 }
                    this.state.selectedVariable
            );
 
            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                 )
                 )
             );
             ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },


            const required =
        // =========================================================
                this.checkbox(
        // Analysis
                    field.required === true
        // =========================================================
                );


            required.on(
        renderAnalysis(container) {
                'change.preloadEditor',
            container.empty();
                () => {
                    field.required =
                        required.prop('checked');


                    this.markDirty();
            const analysis =
                    this.renderConfigPreviewBySelector();
                this.analysis ||
                 }
                 this.analyzePreload(
            );
                    this.extractIncludeonly(
 
                        this.getEditorContent()
            card.append(
                     )
                this.fieldRow(
                    'Required',
                    required
                )
            );
 
            const placeholder =
                this.textInput(
                     field.placeholder || ''
                 );
                 );


             placeholder.on(
             const variableCount =
                 'input.preloadEditor',
                 analysis.variables.length;
                () => {
                    const value =
                        placeholder.val();


                    if (value) {
            const conditionCount =
                        field.placeholder =
                analysis.conditions.length;
                            value;
                    } else {
                        delete field.placeholder;
                    }


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


             card.append(
             const summary =
                this.fieldRow(
                $('<div>')
                    'Placeholder',
                    .addClass(
                     placeholder
                        'preload-editor-analysis-summary'
                )
                     );
            );


             const defaultInput =
             const createMetric =
                 this.textInput(
                 (
                     field.default === undefined
                     value,
                         ? ''
                    label
                         : field.default
                ) =>
                );
                    $('<div>')
                         .addClass(
                            'preload-editor-analysis-metric'
                         )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


            defaultInput.on(
                            $('<span>')
                'input.preloadEditor',
                                .addClass(
                () => {
                                    'preload-editor-analysis-label'
                    const value =
                                )
                         defaultInput.val();
                                .text(label)
                         );


                    if (value) {
            summary.append(
                        field.default =
                createMetric(
                            value;
                    variableCount,
                     } else {
                     variableCount === 1
                         delete field.default;
                        ? 'variable'
                    }
                         : 'variables'
                ),


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


            card.append(
                 createMetric(
                 this.fieldRow(
                     configuredCount,
                     'Default',
                     configuredCount === 1
                     defaultInput,
                        ? 'configured field'
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                        : 'configured fields'
                 )
                 )
             );
             );
            container.append(summary);


             if (
             if (
                 field.type === 'textarea'
                 analysis.conditionVariables.length
             ) {
             ) {
                 const maxRows =
                 container.append(
                     this.textInput(
                     $('<div>')
                         field.maxRows || ''
                         .addClass(
                    ).attr(
                            'preload-editor-analysis-note'
                        'type',
                        )
                         'number'
                        .text(
                    );
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                         )
                );
            }


                 maxRows.on(
            const validation =
                     'input.preloadEditor',
                 this.validateConfig(
                     () => {
                     this.state.config,
                        const value =
                     analysis
                            parseInt(
                );
                                maxRows.val(),
                                10
                            );


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


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


                 card.append(
                 container.append(errors);
                     this.fieldRow(
            }
                        'Maximum rows',
 
                         maxRows
            if (validation.warnings.length) {
                     )
                const warnings =
                     $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                         );
 
                validation.warnings.forEach(
                     warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                 );
                 );
                container.append(warnings);
             }
             }


             if (
             if (
                 field.type === 'select' ||
                 !validation.errors.length &&
                 field.type === 'multiselect'
                 !validation.warnings.length
             ) {
             ) {
                 this.renderSelectConfiguration(
                 container.append(
                     card,
                     $('<div>')
                    field
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                 );
                 );
             }
             }
        },


            /*
        renderAnalysisBySelector() {
            * DELETE VARIABLE
             const container =
            *
                 this.root &&
            * This removes the field from the generated
                this.root.find(
            * config.json, but does not remove %%VARIABLE%%
                     '.preload-editor-analysis'
            * from the preload itself.
                );
            */
 
             const deleteButton =
            if (
                 this.createButton(
                container &&
                     'Delete variable',
                container.length
                    'preload-editor-button-danger preload-editor-delete-variable',
            ) {
                    async () => {
                this.renderAnalysis(container);
                        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;
        // Variables
                        }
        // =========================================================


                        this.deleteVariable(name);
        renderVariables(container) {
                    }
            container.empty();
                );


             card.append(
             const analysis =
                 $('<div>')
                this.analysis ||
                     .addClass(
                 this.analyzePreload(
                         'preload-editor-variable-delete'
                     this.extractIncludeonly(
                         this.getEditorContent()
                     )
                     )
                    .append(deleteButton)
                );
            );


             return card;
             const variables =
        },
                analysis.variables.slice();


        async deleteVariable(name) {
             const ordered =
             name =
                 ['PAGE'];
                 String(name || '')
                    .trim()
                    .toUpperCase();


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


             if (
             const configuredFields =
                 !this.state.config ||
                 this.state.config &&
                 !this.state.config.fields
                 this.state.config.fields
            ) {
                    ? Object.keys(
                return;
                        this.state.config.fields
            }
                    )
                    : [];


             delete this.state.config.fields[name];
             configuredFields.forEach(
                name => {
                    const upper =
                        name.toUpperCase();


            if (
                    if (
                 !Array.isArray(
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );
 
            const deleted =
                 Array.isArray(
                     this.state.deletedVariables
                     this.state.deletedVariables
                 )
                 )
            ) {
                    ? this.state.deletedVariables
                this.state.deletedVariables = [];
                    : [];
            }


             if (
             deleted.forEach(
                 !this.state.deletedVariables.includes(
                 name => {
                     name
                     const upper =
                )
                        String(name).toUpperCase();
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }


            this.state.selectedVariable =
                    if (
                 name;
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                 }
            );


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


             this.renderVariablesBySelector();
             ordered.forEach(
            this.renderVariableConfigurationBySelector();
                name => {
            this.renderAnalysisBySelector();
                    const isSelected =
            this.renderConfigPreviewBySelector();
                        name ===
                        this.state.selectedVariable;


            this.setStatus(
                    const isUsed =
                'Variable "' +
                        analysis.variables.includes(
                name +
                            name
                '" removed from the configuration.',
                        );
                'warning'
            );
        },


        renderSelectConfiguration(
                    const isConfigured =
            card,
                        !!(
            field
                            this.state.config &&
        ) {
                            this.state.config.fields &&
            const source =
                            this.state.config.fields[name]
                this.textInput(
                        );
                    field.source || '',
                    'category:Example'
                );


            source.on(
                    const item =
                'input.preloadEditor',
                        $('<button>')
                () => {
                            .attr({
                    const value =
                                type: 'button',
                        source.val();
                                'data-variable':
 
                                    name
                    if (value) {
                            })
                        field.source = value;
                            .addClass(
                    } else {
                                'preload-editor-variable-item'
                        delete field.source;
                            )
                    }
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                     this.markDirty();
                     $('<span>')
                    this.renderConfigPreviewBySelector();
                        .addClass(
                }
                            'preload-editor-variable-name'
            );
                        )
                        .text(name)
                        .appendTo(item);


            card.append(
                    if (name === 'PAGE') {
                this.fieldRow(
                        item.append(
                    'Source',
                            $('<span>')
                    source,
                                .addClass(
                    'Currently supported source format: category:Category Name'
                                    'preload-editor-badge'
                )
                                )
            );
                                .text('AUTOMATIC')
 
                        );
            const sourcePrefix =
                    } else if (!isConfigured) {
                this.textInput(
                        item.append(
                    field['source-prefix'] || ''
                            $('<span>')
                );
                                .addClass(
 
                                    'preload-editor-badge is-warning'
            sourcePrefix.on(
                                )
                'input.preloadEditor',
                                .text(
                () => {
                                    isUsed
                    const value =
                                        ? 'NOT CONFIGURED'
                         sourcePrefix.val();
                                        : 'DELETED'
 
                                )
                     if (value) {
                         );
                         field['source-prefix'] =
                     } else if (!isUsed) {
                            value;
                         item.append(
                    } else {
                            $('<span>')
                         delete field['source-prefix'];
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                         );
                     }
                     }


                     this.markDirty();
                     list.append(item);
                    this.renderConfigPreviewBySelector();
                 }
                 }
             );
             );


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


             const excludeCategory =
             if (!ordered.length) {
                 this.textInput(
                 container.append(
                     field.exclude &&
                     $('<div>')
                    field.exclude.category ||
                        .addClass(
                     ''
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                );
            }
        },
 
        renderVariablesBySelector() {
            const container =
                this.root &&
                this.root.find(
                     '.preload-editor-variables'
                 );
                 );


             excludeCategory.on(
             if (
                 'input.preloadEditor',
                 container &&
                () => {
                container.length
                    const value =
            ) {
                        excludeCategory.val();
                this.renderVariables(container);
            }
        },


                    if (value) {
        selectVariable(name) {
                        field.exclude =
            name =
                            Object.assign(
                String(name || '')
                                {},
                     .trim()
                                field.exclude || {},
                    .toUpperCase();
                                {
                                    category: value
                                }
                            );
                     } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
            if (!name) {
                            !Object.keys(
                return;
                                field.exclude
            }
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }


                     this.markDirty();
            const available =
                     this.renderConfigPreviewBySelector();
                ['PAGE'].concat(
                 }
                     (
            );
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                     ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                 );


             card.append(
             const configuredUnused =
                this.fieldRow(
                this.state.config &&
                     'Exclude category',
                this.state.config.fields
                     excludeCategory
                    ? Object.keys(
                 )
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                     : [];
 
            configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                     ) {
                        available.push(variable);
                    }
                 }
             );
             );


             card.append(
             if (!available.includes(name)) {
                 this.createTransformControls(
                 return;
                    field,
            }
                    'value',
 
                    'Value transformation'
            this.state.selectedVariable =
                 ),
                 name;


                this.createTransformControls(
            this.renderVariablesBySelector();
                    field,
             this.renderVariableConfigurationBySelector();
                    'label',
        },
                    'Label transformation'
                )
             );


             const optionsValue =
        renderVariableConfigurationBySelector() {
                 Array.isArray(field.options)
             const container =
                    ? field.options
                 this.root &&
                        .map(
                this.root.find(
                            option => {
                    '.preload-editor-variable-configuration'
                                if (
                );
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


                                return (
            if (
                                    String(
                container &&
                                        option.value || ''
                container.length
                                    ) +
            ) {
                                    ' | ' +
                this.renderVariableConfiguration(
                                    String(
                    container
                                        option.label ||
                );
                                        option.value ||
            }
                                        ''
        },
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';


            const options =
        renderVariableConfiguration(container) {
                this.textarea(
            container.empty();
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );


             options.on(
             const analysis =
                 'input.preloadEditor',
                 this.analysis ||
                 () => {
                 this.analyzePreload(
                     const lines =
                     this.extractIncludeonly(
                        options
                        this.getEditorContent()
                            .val()
                    )
                            .split('\n')
                );
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                    if (!lines.length) {
            const name =
                        delete field.options;
                this.state.selectedVariable ||
                    } else {
                'PAGE';
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );


                                    if (
            const fields =
                                        parts.length ===
                this.state.config &&
                                        1
                this.state.config.fields
                                    ) {
                    ? this.state.config.fields
                                        return parts[0];
                    : {};
                                    }


                                    return {
            const field =
                                        value:
                fields[name];
                                            parts[0],


                                        label:
            if (name === 'PAGE') {
                                            parts
                container.append(
                                                .slice(1)
                    this.createAutomaticPageCard(
                                                .join(
                        field ||
                                                    ' | '
                        this.getAutomaticPageField()
                                                )
                    )
                                    };
                );
                                }
                            );
                    }


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


             card.append(
             if (!field) {
                 this.fieldRow(
                 const missing =
                     'Manual options',
                     $('<div>')
                    options,
                        .addClass(
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                            'preload-editor-variable preload-editor-variable-missing'
                )
                        );
            );
        },


        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-transform'
                         'preload-editor-variable-header'
                     );
                     )
                    .append(
                        $('<h3>')
                            .text(name),
 
                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


            $('<h4>')
                $('<p>')
                .text(title)
                    .addClass(
                .appendTo(wrapper);
                        'preload-editor-analysis-note'
                    )
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);


            const existing =
                 container.append(missing);
                 field[property] &&
                 return;
                 typeof field[property] === 'object'
            }
                    ? field[property]
                    : {};


             const transform =
             container.append(
                 this.select(
                 this.createVariableCard(
                     [
                     name,
                        {
                     field,
                            value: '',
                     analysis
                            label:
                 )
                                'No transformation'
            );
                        },
        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                     ],
                     existing.transform || ''
                 );


             const prefix =
        createAutomaticPageCard(field) {
                 this.textInput(
             const card =
                     existing.prefix || ''
                 $('<div>')
                );
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                     .attr(
                        'data-variable',
                        'PAGE'
                    );


             const suffix =
             const header =
                 this.textInput(
                 $('<div>')
                     existing.suffix || ''
                     .addClass(
                );
                        'preload-editor-variable-header'
                    );


             const from =
             header.append(
                 this.textInput(
                 $('<h3>').text('PAGE'),
                     existing.from || ''
 
                 );
                $('<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 to =
             const label =
                 this.textInput(
                 this.textInput(
                     existing.to || ''
                     field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                 );
                 );


             const controls =
             const description =
                 $('<div>')
                 this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                     .addClass(
                     .addClass(
                         'preload-editor-transform-controls'
                         'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                     );
                     );


             const prefixRow =
             const type =
                 this.fieldRow(
                 this.textInput(
                     'Prefix',
                    field.type || 'page'
                     prefix
                ).prop(
                     'disabled',
                     true
                 );
                 );


             const suffixRow =
             const required =
                 this.fieldRow(
                 this.checkbox(
                     'Suffix',
                    field.required !== false
                     suffix
                ).prop(
                     'disabled',
                     true
                 );
                 );


             const fromRow =
             const namespace =
                 this.fieldRow(
                 this.textInput(
                     'From',
                    field.namespace || 'Main'
                     from
                ).prop(
                     'disabled',
                     true
                 );
                 );


             const toRow =
             const allowNew =
                 this.fieldRow(
                 this.checkbox(
                     'To',
                     field['allow-new'] === true
                     to
                ).prop(
                    'disabled',
                     true
                 );
                 );


             const renderInputs =
             card.append(
                 () => {
                 this.fieldRow(
                     const type =
                     'Label',
                        transform.val();
                    label
                ),


                    prefixRow.toggle(
                this.fieldRow(
                        type === 'remove-prefix'
                    'Description',
                     );
                     description
                ),


                    suffixRow.toggle(
                this.fieldRow(
                        type === 'remove-suffix'
                    'Type',
                     );
                     type
                ),


                    fromRow.toggle(
                this.fieldRow(
                        type === 'replace'
                    'Required',
                     );
                     required
                ),


                    toRow.toggle(
                this.fieldRow(
                        type === 'replace'
                    'Namespace',
                     );
                     namespace
                 };
                 ),


            const update =
                 this.fieldRow(
                 () => {
                     'Allow new page',
                     const type =
                    allowNew
                        transform.val();
                )
            );


                    let object = null;
            return card;
        },


                    if (
        createVariableCard(
                        type === 'remove-prefix' &&
            name,
                        prefix.val()
            field,
                    ) {
            analysis
                        object = {
        ) {
                            transform: type,
            const card =
                            prefix:
                $('<div>')
                                prefix.val()
                     .addClass(
                        };
                         'preload-editor-variable'
                     } else if (
                    )
                         type === 'remove-suffix' &&
                     .attr(
                        suffix.val()
                         'data-variable',
                     ) {
                         name
                        object = {
                     );
                            transform: type,
                            suffix:
                                suffix.val()
                         };
                    } else if (
                        type === 'replace' &&
                         from.val()
                     ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }


                     if (object) {
            const header =
                         field[property] = object;
                $('<div>')
                    } else {
                    .addClass(
                         delete field[property];
                        '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);


                    this.markDirty();
            const label =
                     this.renderConfigPreviewBySelector();
                this.textInput(
                 };
                     field.label || ''
                 );


             transform.on(
             label.on(
                 'change.preloadEditor',
                 'input.preloadEditor',
                 () => {
                 () => {
                     update();
                     field.label =
                     renderInputs();
                        label.val();
 
                    this.markDirty();
                     this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             [
             card.append(
                 prefix,
                 this.fieldRow(
                 suffix,
                    'Label',
                from,
                    label
                to
                 )
             ].forEach(
            );
                 input => {
 
                     input.on(
             const description =
                        'input.preloadEditor',
                this.textarea(
                         update
                    field.description || ''
                     );
                 ).addClass(
                     'preload-editor-small-textarea'
                );
 
            description.on(
                'input.preloadEditor',
                () => {
                    field.description =
                         description.val();
 
                     this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             controls.append(
             card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Transformation',
                     'Description',
                     transform
                     description
                 ),
                 )
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
             );
             );


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


            return wrapper;
             const typeSelect =
        },
                 this.select(
 
                     types.map(
        // Config output
                        ([value, label]) => ({
 
                            value,
        getCleanConfig() {
                            label
             const config =
                         })
                 JSON.parse(
                     ),
                     JSON.stringify(
                    field.type || 'text'
                         this.state.config
                     )
                 );
                 );


             const fields =
             typeSelect.on(
                 config.fields || {};
                 'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();


            const orderedFields = {};
                    this.markDirty();


            orderedFields.PAGE =
                    this.renderVariableConfigurationBySelector();
                this.getAutomaticPageField();
                    this.renderConfigReviewAvailability();
                }
            );


             Object.keys(fields)
             card.append(
                 .filter(
                 this.fieldRow(
                     name =>
                     'Type',
                        name.toUpperCase() !== 'PAGE'
                    typeSelect
                 )
                 )
                 .forEach(
            );
                     name => {
 
                        orderedFields[name] =
            const required =
                            fields[name];
                 this.checkbox(
                    }
                     field.required === true
                 );
                 );


             config.fields =
             required.on(
                orderedFields;
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');


            return config;
                    this.markDirty();
        },
                    this.renderConfigReviewAvailability();
                }
            );


        getConfigJSON() {
             card.append(
             return JSON.stringify(
                 this.fieldRow(
                 this.getCleanConfig(),
                    'Required',
                null,
                    required
                 4
                 )
             );
             );
        },


        renderConfigPreview(container) {
             const placeholder =
             if (container) {
                 this.textInput(
                 container.text(
                     field.placeholder || ''
                     this.getConfigJSON()
                 );
                 );
            }
        },


        renderConfigPreviewBySelector() {
            placeholder.on(
            const preview =
                 'input.preloadEditor',
                 this.root &&
                 () => {
                 this.root.find(
                     const value =
                     '.preload-editor-config-preview'
                        placeholder.val();
                );


            if (
                    if (value) {
                preview &&
                        field.placeholder =
                preview.length
                            value;
            ) {
                     } else {
                this.renderConfigPreview(
                        delete field.placeholder;
                     preview
                    }
                );
            }


            this.renderAnalysisBySelector();
                    this.markDirty();
        },
                    this.renderConfigReviewAvailability();
                }
            );


        markDirty() {
            card.append(
            this.state.dirty = true;
                this.fieldRow(
             this.saveDraft();
                    'Placeholder',
        },
                    placeholder
                )
             );


        // Save
            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                );


        async savePreloadOnly() {
            defaultInput.on(
            let title =
                'input.preloadEditor',
                 String(
                 () => {
                     this.state.preloadTitle || ''
                     const value =
                ).trim();
                        defaultInput.val();


            if (!title) {
                    if (value) {
                const result =
                        field.default =
                     await this.createPromptDialog(
                            value;
                        'Preload title',
                     } else {
                         'Enter the full title for the preload.'
                         delete field.default;
                     );
                     }


                if (!result) {
                    this.markDirty();
                     return;
                     this.renderConfigReviewAvailability();
                 }
                 }
            );


                 title = result;
            card.append(
                this.state.preloadTitle =
                 this.fieldRow(
                    title;
                    'Default',
             }
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
             );


             this.state.preloadContent =
             if (
                 this.getEditorContent();
                field.type === 'textarea'
 
            ) {
            const validation =
                 const maxRows =
                this.validateBeforeSave();
                    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;
                        }


            if (validation.errors.length) {
                        this.markDirty();
                this.showValidationErrors(
                        this.renderConfigReviewAvailability();
                     validation
                     }
                 );
                 );


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


             this.setStatus(
             if (
                 'Saving preload...',
                 field.type === 'select' ||
                 'loading'
                 field.type === 'multiselect'
             );
             ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }


             try {
             if (
                 const exists =
                 field.type === 'file'
                    await this.pageExists(title);
            ) {
 
                 this.renderFileConfiguration(
                 await this.savePage(
                     card,
                     title,
                     field
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                     !exists
                 );
                 );
            }


                 this.state.mode = 'edit';
            const deleteButton =
                this.state.dirty = false;
                 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'
                            );


                this.clearDraft(title);
                        if (!confirmed) {
                            return;
                        }


                this.setStatus(
                        this.deleteVariable(name);
                    'Preload saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload saved.',
                    {
                        type: 'success'
                     }
                     }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                 );
                 );


                 this.saveDraft();
            card.append(
                 $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );


                this.setStatus(
            return card;
                    error.message ||
                        'Could not save preload.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
         },
         },


         async saveAll() {
         async deleteVariable(name) {
             let title =
             name =
                 String(
                 String(name || '')
                    this.state.preloadTitle || ''
                    .trim()
                ).trim();
                    .toUpperCase();


             if (!title) {
             if (
                 const result =
                !name ||
                    await this.createPromptDialog(
                 name === 'PAGE'
                        'Preload title',
            ) {
                        'Enter the full title for the preload.'
                return;
                    );
            }


                if (!result) {
            if (
                    return;
                 !this.state.config ||
                 }
                 !this.state.config.fields
 
            ) {
                title = result;
                return;
                 this.state.preloadTitle =
                    title;
             }
             }


             this.state.preloadContent =
             delete this.state.config.fields[name];
                this.getEditorContent();


             this.reanalyze();
             if (
 
                 !Array.isArray(
            const validation =
                    this.state.deletedVariables
                 this.validateBeforeSave();
                 )
 
            ) {
            if (validation.errors.length) {
                 this.state.deletedVariables = [];
                this.showValidationErrors(
                    validation
                 );
 
                 this.saveDraft();
                return;
             }
             }


             const configTitle =
             if (
                 title.replace(
                 !this.state.deletedVariables.includes(
                     /\/+$/,
                     name
                     ''
                )
                 ) +
            ) {
                 '/config.json';
                this.state.deletedVariables.push(
                     name
                 );
            }
 
            this.state.selectedVariable =
                 name;
 
            this.markDirty();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();


             this.setStatus(
             this.setStatus(
                 'Saving preload and config...',
                 'Variable "' +
                 'loading'
                name +
                '" removed from the configuration.',
                 'warning'
             );
             );
        },


            try {
        // =========================================================
                const preloadExists =
        // Select configuration
                    await this.pageExists(title);
        // =========================================================


                 await this.savePage(
        renderSelectConfiguration(
                     title,
            card,
                     this.state.preloadContent,
            field
                     preloadExists
        ) {
                         ? 'Updated preload with Preload Editor'
            const source =
                        : 'Created preload with Preload Editor',
                 this.textInput(
                     !preloadExists
                     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'] || ''
                 );
                 );


                 const configExists =
            sourcePrefix.on(
                    await this.pageExists(
                'input.preloadEditor',
                        configTitle
                 () => {
                    );
                    const value =
                        sourcePrefix.val();


                 await this.savePage(
                    if (value) {
                     configTitle,
                        field['source-prefix'] =
                     this.getConfigJSON(),
                            value;
                     configExists
                    } else {
                         ? 'Updated preload config with Preload Editor'
                        delete field['source-prefix'];
                         : 'Created preload config with Preload Editor',
                    }
                     !configExists
 
                 );
                    this.markDirty();
 
                    this.renderConfigReviewAvailability();
                 this.state.mode = 'edit';
                }
                 this.state.dirty = false;
            );
                 this.state.preloadTitle = title;
 
            card.append(
                this.fieldRow(
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );
 
            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );
 
            excludeCategory.on(
                'input.preloadEditor',
                () => {
                    const value =
                        excludeCategory.val();
 
                    if (value) {
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;
 
                        if (
                            !Object.keys(
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                )
            );
 
            card.append(
                this.createTransformControls(
                    field,
                    'value',
                    'Value transformation'
                ),
 
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );
 
            const optionsValue =
                Array.isArray(field.options)
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }
 
                                return (
                                    String(
                                        option.value || ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';
 
            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            options.on(
                'input.preloadEditor',
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);
 
                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );
 
                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }
 
                                    return {
                                        value:
                                            parts[0],
 
                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
       
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);
 
                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );
 
            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );
 
            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();
 
                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );
 
            const filetext =
                this.textarea(
                    field.filetext || ''
                );
 
            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();
 
                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },
 
        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                $('<div>')
                    .addClass(
                        'preload-editor-transform'
                    );
 
            $('<h4>')
                .text(title)
                .appendTo(wrapper);
 
            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );
 
            const prefix =
                this.textInput(
                    existing.prefix || ''
                );
 
            const suffix =
                this.textInput(
                    existing.suffix || ''
                );
 
            const from =
                this.textInput(
                    existing.from || ''
                );
 
            const to =
                this.textInput(
                    existing.to || ''
                );
 
            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );
 
            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );
 
            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );
 
            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );
 
            const toRow =
                this.fieldRow(
                    'To',
                    to
                );
 
            const renderInputs =
                () => {
                    const type =
                        transform.val();
 
                    prefixRow.toggle(
                        type === 'remove-prefix'
                    );
 
                    suffixRow.toggle(
                        type === 'remove-suffix'
                    );
 
                    fromRow.toggle(
                        type === 'replace'
                    );
 
                    toRow.toggle(
                        type === 'replace'
                    );
                };
 
            const update =
                () => {
                    const type =
                        transform.val();
 
                    let object = null;
 
                    if (
                        type === 'remove-prefix' &&
                        prefix.val()
                    ) {
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                    ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }
 
                    if (object) {
                        field[property] = object;
                    } else {
                        delete field[property];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                };
 
            transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );
 
            controls.append(
                this.fieldRow(
                    'Transformation',
                    transform
                ),
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );
 
            renderInputs();
 
            wrapper.append(controls);
 
            return wrapper;
        },
 
        // =========================================================
        // Config output
        // =========================================================
 
        getCleanConfig() {
            const config =
                JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );
 
            const fields =
                config.fields || {};
 
            const orderedFields = {};
 
            orderedFields.PAGE =
                this.getAutomaticPageField();
 
            Object.keys(fields)
                .filter(
                    name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );
 
            config.fields =
                orderedFields;
 
            return config;
        },
 
        getConfigJSON() {
            return JSON.stringify(
                this.getCleanConfig(),
                null,
                4
            );
        },
 
        renderConfigPreview(container) {
            if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },
 
        renderConfigPreviewBySelector() {
            this.renderAnalysisBySelector();
        },
 
        renderConfigReviewAvailability() {
            this.renderAnalysisBySelector();
        },
 
        // =========================================================
        // Dirty state
        // =========================================================
 
        updateDirtyState() {
            this.state.dirty =
                !!(
                    this.state.dirtyPreload ||
                    this.state.dirtyConfig
                );
        },
 
        markPreloadDirty() {
            this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markConfigDirty() {
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markDirty() {
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        // =========================================================
        // Save
        // =========================================================
 
        async savePreloadOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'preload',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            this.setStatus(
                'Saving preload...',
                'loading'
            );
 
            try {
                const exists =
                    await this.pageExists(title);
 
                 await this.savePage(
                    title,
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyPreload = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveConfigOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'config',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving config...',
                'loading'
            );
 
            try {
                /*
                * This now automatically creates or converts
                * config.json to the JSON content model.
                */
                await this.saveConfigPage(
                     configTitle,
                     this.getConfigJSON(),
                     (
                        await this.pageExists(
                            configTitle
                        )
                    )
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyConfig = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor config save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveAll() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving preload and config...',
                'loading'
            );
 
            try {
                const preloadExists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                     !preloadExists
                );
 
                /*
                * Config is saved through the JSON-aware
                * helper. This means:
                *
                * - new config -> created as JSON
                * - old wikitext config -> converted to JSON
                * - existing JSON config -> simply updated
                */
                const configExists =
                    await this.pageExists(
                        configTitle
                    );
 
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                 );
 
                 this.state.mode = 'edit';
                this.state.dirtyPreload = false;
                this.state.dirtyConfig = false;
                 this.state.dirty = false;
                 this.state.preloadTitle = title;
 
                this.clearDraft(title);
 
                this.setStatus(
                    'Preload and JSON config saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload and config saved. config.json is using the JSON content model.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },


                this.clearDraft(title);
        // =========================================================
 
        // Validation
                this.setStatus(
         // =========================================================
                    'Preload and config saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload and config saved.',
                    {
                        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'
                    }
                );
            }
         },


         validateBeforeSave() {
         validateBeforeSave() {
Line 5,062: Line 6,142:


             let depth = 0;
             let depth = 0;
 
                        analysis.conditions.forEach(
            analysis.conditions.forEach(
                 condition => {
                 condition => {
                     if (
                     if (
Line 5,135: Line 6,214:
         if (
         if (
             mw.config.get('wgPageName') !==
             mw.config.get('wgPageName') !==
             'Petit_Planet:Preload_Editor'
             'Petit_Planet_Wiki:Preload_Editor'
         ) {
         ) {
             return;
             return;