MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

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


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


         state: {
         state: {
Line 17: Line 17:
             dirty: false,
             dirty: false,
             dirtyPreload: false,
             dirtyPreload: false,
             dirtyConfig: false
             dirtyConfig: false,
 
            // Local draft state
            localDraftSavedAt: null,
            localDraftAvailable: false
         },
         },


Line 26: 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 52: 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 66: 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 76: 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 90: 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 107: 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 131: 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: 2,
                 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'
            );
 
            if (type) {
                this.localDraftStatus.addClass('is-' + type);
            }
 
            this.localDraftStatus.text(message || '');
        },
 
        formatLocalDraftTime(timestamp) {
            if (!timestamp) {
                return '';
            }


                 deletedVariables:
            try {
                     Array.isArray(
                 return new Date(timestamp).toLocaleTimeString([], {
                        this.state.deletedVariables
                    hour: '2-digit',
                    )
                     minute: '2-digit',
                        ? this.state.deletedVariables.slice()
                    second: '2-digit'
                        : [],
                });
            } catch (error) {
                return '';
            }
        },


                mode:
        updateLocalDraftIndicator() {
                    this.state.mode ||
            if (!this.localDraftStatus) {
                    'edit',
                return;
            }


                 dirty:
            if (this.state.localDraftSavedAt) {
                    !!this.state.dirty,
                 const time = this.formatLocalDraftTime(this.state.localDraftSavedAt);


                 dirtyPreload:
                 this.updateLocalDraftStatus(
                     !!this.state.dirtyPreload,
                    time ? 'Saved locally at ' + time : 'Saved locally',
                     'saved'
                );


                 dirtyConfig:
                 return;
                    !!this.state.dirtyConfig,
            }


                savedAt:
            this.updateLocalDraftStatus('No local draft', 'empty');
                    Date.now()
            };
         },
         },


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


             const snapshot =
             const snapshot = this.getDraftSnapshot();
                this.getDraftSnapshot();
            const id = this.getDraftId(snapshot.preloadTitle);
            const storage = this.getDraftStorage();


             const id =
             storage.drafts[id] = snapshot;
                this.getDraftId(
            storage.active = id;
                    snapshot.preloadTitle
                );


             const storage =
             const saved = this.setDraftStorage(storage);
                this.getDraftStorage();


             storage.drafts[id] =
             if (saved) {
                 snapshot;
                this.state.localDraftSavedAt = snapshot.savedAt;
 
                 this.state.localDraftAvailable = true;
             storage.active = id;
                this.updateLocalDraftIndicator();
             } else {
                this.state.localDraftAvailable = false;
                this.updateLocalDraftStatus('Could not save local draft', 'error');
            }


             this.setDraftStorage(
             return saved;
                storage
            );
         },
         },


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


             if (
             if (storage.drafts && storage.drafts[id]) {
                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 296: 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 337: 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 390: Line 314:
             }
             }


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


             if (
             if (
Line 399: 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 420: Line 338:


             this.state = {
             this.state = {
                 preloadTitle:
                 preloadTitle: title,
                     title,
                preloadSource: String(draft.preloadSource || ''),
                preloadContent: String(draft.preloadContent || ''),
                config,
 
                variables: Array.isArray(draft.variables)
                    ? draft.variables.slice()
                     : [],


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


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


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


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


                 conditions:
                 dirty: hasDirtyFlags
                     Array.isArray(
                     ? !!(draft.dirtyPreload || draft.dirtyConfig)
                        draft.conditions
                    : true,
                    )
                        ? draft.conditions.slice()
                        : [],


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


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


                 mode:
                 localDraftSavedAt: Number(draft.savedAt) || null,
                    draft.mode ||
                 localDraftAvailable: true
                    'edit',
 
                dirty:
                    hasDirtyFlags
                        ? !!(
                            draft.dirtyPreload ||
                            draft.dirtyConfig
                        )
                        : true,
 
                dirtyPreload:
                    hasDirtyFlags
                        ? !!draft.dirtyPreload
                        : true,
 
                 dirtyConfig:
                    hasDirtyFlags
                        ? !!draft.dirtyConfig
                        : true
             };
             };


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


             this.setStatus(
             this.setStatus(
Line 504: 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 545: 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 561: 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 578: 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 598: Line 473:
             }
             }


             return new mw.Api().postWithToken(
            if (contentModel) {
                'csrf',
                params.contentmodel = contentModel;
                params
            }
            );
 
             return new mw.Api().postWithToken('csrf', params);
         },
         },


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


         extractIncludeonly(source) {
         /*
             const match =
        * Save config.json and make sure its content model
                String(source || '').match(
        * is JSON.
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
        *
        * New page:
        *  create directly with contentmodel=json.
        *
        * Existing page:
        *  if not already JSON, change its model first,
        *  then save the JSON normally.
        */
        async saveConfigPage(title, content, summary) {
             const page = await this.getPage(title);
 
            if (!page) {
                return this.savePage(
                     title,
                    content,
                    summary,
                    true,
                    'json'
                 );
                 );
            }


             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'
        findVariables(content) {
                 );
            const variables = [];
            const pattern =
                /%%([A-Za-z0-9_-]+)%%/g;
 
            let match;
 
            while (
                 (match = pattern.exec(content)) !== null
            ) {
                const name =
                     match[1].toUpperCase();
 
                 if (!variables.includes(name)) {
                    variables.push(name);
                }
             }
             }


             return variables;
             return this.savePage(
                title,
                content,
                summary,
                false
            );
         },
         },


         findConditions(content) {
         // =========================================================
            const conditions = [];
        // Config import helpers
            const pattern =
        // =========================================================
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


            let match;
        /*
 
        * Accept either:
            while (
        *
                (match = pattern.exec(content)) !== null
        *  Template:Example/Preload
             ) {
        *
                conditions.push({
        * or:
                    type:
        *
                        match[1].toLowerCase(),
        *  Template:Example/Preload/config.json
        *
        * and always return the config.json title.
        */
        normalizeConfigTitle(title) {
             title = String(title || '').trim();
            title = title.replace(/\/+$/, '');


                    expression:
            if (/\/config\.json$/i.test(title)) {
                        match[2].trim(),
                 return title;
 
                    index:
                        match.index
                 });
             }
             }


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


         findConditionVariables(content) {
         /*
             const variables = [];
        * Return a safe clone of a config field.
        *
        * This is deliberately JSON-based because config
        * definitions are JSON-compatible objects.
        */
        cloneConfigField(field) {
            try {
                return JSON.parse(JSON.stringify(field));
            } catch (error) {
                console.warn(
                    'Preload Editor: Could not clone imported field.',
                    error
                );
 
                return null;
            }
        },
 
        /*
        * Normalize imported field names to the same uppercase
        * convention used throughout the editor.
        */
        getImportableFields(sourceConfig) {
             const fields = sourceConfig && sourceConfig.fields;


             this.findConditions(content).forEach(
             if (
                 condition => {
                 !fields ||
                    if (
                typeof fields !== 'object' ||
                        condition.type !== 'if' &&
                Array.isArray(fields)
                        condition.type !== 'elseif'
            ) {
                    ) {
                return {};
                        return;
            }
                    }


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


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


                            if (
                if (!upper || upper === 'PAGE') {
                                !variables.includes(
                     return;
                                    name
                                )
                            ) {
                                variables.push(
                                    name
                                );
                            }
                        }
                     );
                 }
                 }
            );


            return variables;
                if (
        },
                    !field ||
                    typeof field !== 'object' ||
                    Array.isArray(field)
                ) {
                    return;
                }


        analyzePreload(content) {
                 const clone = this.cloneConfigField(field);
            return {
                 variables:
                    this.findVariables(content),


                 conditions:
                 if (!clone) {
                     this.findConditions(content),
                     return;
                }


                 conditionVariables:
                 result[upper] = clone;
                    this.findConditionVariables(
            });
                        content
 
                    )
             return result;
             };
         },
         },


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


        getAutomaticPageField() {
                const overlay = $('<div>')
            return {
                    .addClass(
                label: 'Page Name',
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                description: 'Name of the page.',
                    );
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


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


                 fields: {
                 $('<h2>')
                     PAGE:
                     .text('Import variable definitions')
                        this.getAutomaticPageField()
                    .appendTo(box);
                }
            };
        },


        normalizeConfig(config) {
                $('<p>')
            if (
                    .text(
                !config ||
                        'Choose which variable definitions to import from "' +
                typeof config !== 'object' ||
                        sourceTitle +
                Array.isArray(config)
                        '". Existing local definitions can be replaced.'
            ) {
                    )
                config =
                     .appendTo(box);
                     this.emptyConfig();
            }


            if (
                if (!names.length) {
                !config.settings ||
                    $('<div>')
                typeof config.settings !== 'object' ||
                        .addClass(
                Array.isArray(config.settings)
                            'preload-editor-empty preload-editor-import-empty'
            ) {
                        )
                config.settings = {};
                        .text(
            }
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);


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


            config.fields.PAGE =
                    const close = this.createButton(
                this.getAutomaticPageField();
                        'Close',
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );


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


        createDefaultField(
                    $(document.body).append(overlay);
            name,
            analysis
        ) {
            return {
                label:
                    this.humanizeName(name),


                description: '',
                    overlay.attr('tabindex', '-1');
                    overlay.trigger('focus');


                type:
                     return;
                    analysis.conditionVariables.includes(
                }
                        name
                     )
                        ? 'boolean'
                        : 'text'
            };
        },


        humanizeName(name) {
                 const search = this.textInput('', 'Search variables...')
            return String(name || '')
                    .addClass('preload-editor-import-search');
                 .replace(
                    /[_-]+/g,
                    ' '
                )
                .replace(
                    /([a-z])([A-Z])/g,
                    '$1 $2'
                )
                .replace(
                    /\s+/g,
                    ' '
                )
                .trim()
                .replace(
                    /\b\w/g,
                    char =>
                        char.toUpperCase()
                );
        },


        prepareConfigForVariables(
                const searchWrap = $('<div>')
            config,
                    .addClass('preload-editor-import-search-wrap')
            analysis
                    .append(search);
        ) {
            config =
                this.normalizeConfig(config);


            const existing =
                box.append(searchWrap);
                 config.fields || {};
 
                const controls = $('<div>')
                    .addClass('preload-editor-import-controls');
 
                 const selectAll = this.createButton(
                    'Select all',
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', true);


            const deleted =
                         updateSummary();
                new Set(
                    }
                    Array.isArray(
                        this.state.deletedVariables
                    )
                         ? this.state.deletedVariables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                        : []
                 );
                 );


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


            fields.PAGE =
                         updateSummary();
                this.getAutomaticPageField();
 
            analysis.variables.forEach(
                name => {
                    if (
                         name === 'PAGE' ||
                        deleted.has(name)
                    ) {
                        return;
                     }
                     }
                );


                    fields[name] =
                controls.append(selectAll, deselectAll);
                        existing[name] ||
                 box.append(controls);
                        this.createDefaultField(
                            name,
                            analysis
                        );
                 }
            );


            Object.keys(existing).forEach(
                 const list = $('<div>')
                 name => {
                     .addClass('preload-editor-import-list');
                     const upper =
                        name.toUpperCase();


                     if (
                const localFields =
                        upper !== 'PAGE' &&
                     this.state.config && this.state.config.fields
                         !fields[upper] &&
                         ? this.state.config.fields
                         !deleted.has(upper)
                         : {};
                    ) {
                        fields[upper] =
                            existing[name];
                    }
                }
            );


            config.fields = fields;
                names.forEach(name => {
                    const existing = !!localFields[name];
                    const field = fields[name];


            return config;
                    const type = field && field.type
        },
                        ? String(field.type)
                        : 'text';


        validateConfig(
                    const label = field && field.label
            config,
                        ? String(field.label)
            analysis
                        : this.humanizeName(name);
        ) {
            const errors = [];
            const warnings = [];


            if (
                    const row = $('<label>')
                !config ||
                        .addClass('preload-editor-import-row')
                typeof config !== 'object' ||
                        .attr('data-variable', name)
                Array.isArray(config)
                        .attr(
            ) {
                            'data-search',
                return {
                            (name + ' ' + label + ' ' + type).toLowerCase()
                    valid: false,
                        );
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                };
            }


            if (
                    const checkbox = this.checkbox(false)
                !config.fields ||
                        .attr('data-import-variable', name)
                typeof config.fields !== 'object' ||
                        .addClass('preload-editor-import-checkbox');
                Array.isArray(config.fields)
            ) {
                return {
                    valid: false,
                    errors: [
                        '"fields" must be an object.'
                    ],
                    warnings
                };
            }


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


            analysis.variables.forEach(
                    const header = $('<span>')
                name => {
                         .addClass('preload-editor-import-header');
                    if (
                        !configured.includes(name)
                    ) {
                         errors.push(
                            'Variable "' +
                            name +
                            '" is not configured.'
                        );
                    }
                }
            );


            configured.forEach(
                    $('<strong>')
                name => {
                         .text(name)
                    if (
                         .appendTo(header);
                         !analysis.variables.includes(
                            name
                        )
                    ) {
                         warnings.push(
                            'Field "' +
                            name +
                            '" is not used by the preload.'
                        );
                    }
                }
            );


            if (
                    $('<span>')
                !configured.includes('PAGE')
                        .addClass('preload-editor-import-type')
            ) {
                        .text(type)
                errors.push(
                        .appendTo(header);
                    'PAGE must always be configured.'
                );
            }


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


                         return;
                    $('<span>')
                    }
                        .text(label)
                         .appendTo(meta);


                     if (!field.type) {
                     const status = $('<span>')
                         warnings.push(
                        .addClass('preload-editor-import-status')
                            'Field "' +
                         .toggleClass('is-existing', existing)
                            name +
                        .toggleClass('is-new', !existing)
                            '" has no type.'
                         .text(existing ? 'REPLACE EXISTING' : 'NEW');
                         );
                    }


                     if (
                     content.append(header, meta, status);
                        (
                    row.append(checkbox, content);
                            field.type === 'select' ||
                     list.append(row);
                            field.type === 'multiselect'
                 });
                        ) &&
                        !field.source &&
                        !Array.isArray(field.options)
                     ) {
                        warnings.push(
                            'Field "' +
                            name +
                            '" is a ' +
                            field.type +
                            ' without a source or manual options.'
                        );
                    }
                 }
            );


            return {
                 box.append(list);
                 valid:
                    !errors.length,
                errors,
                warnings
            };
        },


        // Transformation helpers
                const summary = $('<div>')
                    .addClass('preload-editor-import-summary');


        transformationObject(
                const updateSummary = () => {
            transform,
                    const selected = list.find(
            prefix,
                        'input[type="checkbox"]:checked'
            suffix,
                    ).length;
            from,
 
            to
                    const existingSelected = list
        ) {
                        .find('input[type="checkbox"]:checked')
            if (!transform) {
                        .filter(function () {
                return null;
                            const name = $(this).attr(
            }
                                'data-import-variable'
                            );
 
                            return !!localFields[name];
                        }).length;


            switch (transform) {
                    let text =
                case 'remove-prefix':
                        selected +
                    return prefix
                        ' ' +
                         ? {
                         (selected === 1 ? 'variable' : 'variables') +
                            transform,
                         ' selected.';
                            prefix
                         }
                        : null;


                case 'remove-suffix':
                    if (existingSelected) {
                    return suffix
                        text +=
                        ? {
                            ' ' +
                             transform,
                            existingSelected +
                             suffix
                             ' existing ' +
                        }
                             (existingSelected === 1
                        : null;
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


                case 'replace':
                     summary.text(text);
                     return from === ''
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


                default:
                     importButton.prop('disabled', selected === 0);
                     return null;
                };
            }
        },


        // UI helpers
                const filterRows = () => {
                    const query = String(search.val() || '')
                        .trim()
                        .toLowerCase();


        createSection(
                    list.find('.preload-editor-import-row').each(function () {
            title,
                        const row = $(this);
            className
                        const haystack = String(
        ) {
                            row.attr('data-search') || ''
            const section =
                        );
                $('<section>')
 
                     .addClass(
                        row.toggle(!query || haystack.includes(query));
                        'preload-editor-section'
                     });
                     );
                };
 
                search.on(
                    'input.preloadEditor',
                     filterRows
                );


            if (className) {
                list.on(
                 section.addClass(className);
                    'change.preloadEditor',
            }
                    'input[type="checkbox"]',
                    updateSummary
                 );


            $('<h2>')
                const buttons = $('<div>')
                .addClass(
                    .addClass('preload-editor-prompt-buttons');
                    'preload-editor-section-title'
                )
                .text(title)
                .appendTo(section);


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


        createButton(
                const importButton = this.createButton(
            label,
                     'Import selected',
            className,
                     'preload-editor-button-primary',
            callback
                     () => {
        ) {
                        const selected = [];
            const button =
                $('<button>')
                     .attr(
                        'type',
                        'button'
                     )
                    .addClass(
                        'preload-editor-button'
                     )
                    .text(label);


            if (className) {
                        list
                button.addClass(className);
                            .find('input[type="checkbox"]:checked')
            }
                            .each(function () {
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });


            if (callback) {
                        overlay.remove();
                button.on(
                        resolve(selected);
                     'click.preloadEditor',
                     }
                    callback
                 );
                 );
            }


            return button;
                buttons.append(cancel, importButton);
        },
                box.append(summary, buttons);
                overlay.append(box);


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


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


            if (description) {
                updateSummary();
                 $('<div>')
                 search.trigger('focus');
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(description)
                    .appendTo(row);
            }


            row.append(input);
                const close = event => {
 
                    if (event.key === 'Escape') {
            return row;
                        cancel.trigger('click');
        },
                     }
 
                };
        textInput(
            value,
            placeholder
        ) {
            return $('<input>')
                .attr({
                    type: 'text',
                     value:
                        value == null
                            ? ''
                            : value,


                    placeholder:
                 overlay.on(
                        placeholder || ''
                     'keydown.preloadEditor',
                })
                    close
                 .addClass(
                     'preload-editor-input'
                 );
                 );
        },


        textarea(value) {
                overlay.on(
            return $('<textarea>')
                    'click.preloadEditor',
                .val(
                    event => {
                    value == null
                        if (event.target === overlay.get(0)) {
                        ? ''
                            cancel.trigger('click');
                         : value
                         }
                )
                     }
                .addClass(
                     'preload-editor-textarea'
                 );
                 );
            });
         },
         },


         checkbox(checked) {
         /*
             return $('<input>')
        * Main import workflow.
                 .attr(
        */
                    'type',
        async importVariableDefinitions() {
                    'checkbox'
             const source = await this.createPromptDialog(
                )
                 'Import variable definitions',
                .prop(
                'Enter a preload title or its config.json title.'
                    'checked',
            );
                    !!checked
 
                )
            if (!source) {
                 .addClass(
                 return;
                    'preload-editor-checkbox'
            }
                );
        },


        select(
             const configTitle = this.normalizeConfigTitle(source);
            options,
            value
        ) {
             const select =
                $('<select>')
                    .addClass(
                        'preload-editor-select'
                    );


             options.forEach(
             this.setStatus(
                 option => {
                 'Loading source config...',
                    $('<option>')
                'loading'
                        .attr(
                            'value',
                            option.value
                        )
                        .text(
                            option.label
                        )
                        .prop(
                            'selected',
                            String(
                                option.value
                            ) ===
                            String(
                                value === undefined
                                    ? ''
                                    : value
                            )
                        )
                        .appendTo(select);
                }
             );
             );


             return select;
             try {
        },
                const page = await this.getPage(configTitle);
 
                if (!page) {
                    throw new Error(
                        'No config.json was found at "' +
                        configTitle +
                        '".'
                    );
                }


        // In-wiki dialogs
                let sourceConfig;


        createConfirmDialog(
                try {
            title,
                    sourceConfig = JSON.parse(page.content);
            message,
                 } catch (error) {
            confirmLabel,
                     throw new Error(
            cancelLabel
                         'The source config.json contains invalid JSON: ' +
        ) {
                        error.message
            return new Promise(
                    );
                 resolve => {
                }
                     const overlay =
                         $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                     const box =
                if (
                        $('<div>')
                    !sourceConfig ||
                            .addClass(
                     typeof sourceConfig !== 'object' ||
                                'preload-editor-prompt'
                    Array.isArray(sourceConfig)
                            );
                ) {
                    throw new Error(
                        'The source config.json must contain a JSON object.'
                    );
                }


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


                    const messageLines =
                const fields = this.getImportableFields(sourceConfig);
                        String(message || '')
                            .split('\n');


                     messageLines.forEach(
                const selected =
                         line => {
                     await this.createImportDefinitionsDialog(
                            if (line === '') {
                         configTitle,
                                $('<div>')
                        fields
                                    .addClass(
                    );
                                        'preload-editor-prompt-spacer'
                                    )
                                    .appendTo(box);


                                return;
                if (selected === null) {
                            }
                    this.setStatus(
 
                        'Variable import cancelled.',
                            $('<p>')
                         'warning'
                                .text(line)
                                .appendTo(box);
                         }
                     );
                     );


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


                     const cancel =
                if (!selected.length) {
                        this.createButton(
                     this.setStatus(
                            cancelLabel || 'Cancel',
                        'No variable definitions were imported.',
                            '',
                        'warning'
                            () => {
                    );
                                overlay.remove();
                                resolve(false);
                            }
                        );


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


                     buttons.append(
                if (!this.state.config) {
                        cancel,
                     this.state.config = this.emptyConfig();
                        confirm
                }
                     );
 
                if (!this.state.config.fields) {
                     this.state.config.fields = {};
                }


                    box.append(buttons);
                const imported = [];
                    overlay.append(box);
                const replaced = [];


                     $(document.body)
                selected.forEach(name => {
                         .append(overlay);
                     if (name === 'PAGE') {
                         return;
                    }


                     const close =
                     const field = fields[name];
                        value => {
                            if (value === 'Escape') {
                                cancel.trigger('click');
                            }
                        };


                     overlay.on(
                     if (!field) {
                         'keydown.preloadEditor',
                         return;
                        event => {
                    }
                            close(event.key);
                        }
                    );


                     overlay.attr(
                     if (this.state.config.fields[name]) {
                        'tabindex',
                        replaced.push(name);
                         '-1'
                    } else {
                     );
                         imported.push(name);
                     }


                     overlay.trigger('focus');
                     const clone = this.cloneConfigField(field);


                     overlay.on(
                     if (!clone) {
                        'click.preloadEditor',
                        return;
                        event => {
                     }
                            if (
                                event.target ===
                                overlay.get(0)
                            ) {
                                cancel.trigger('click');
                            }
                        }
                     );
                }
            );
        },


        createPromptDialog(
                     this.state.config.fields[name] = clone;
            title,
            message
        ) {
            return new Promise(
                resolve => {
                     const overlay =
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                     const box =
                     /*
                        $('<div>')
                    * If this variable was previously deleted,
                             .addClass(
                    * importing its definition explicitly should
                                 'preload-editor-prompt'
                    * restore it.
                    */
                    if (Array.isArray(this.state.deletedVariables)) {
                        this.state.deletedVariables =
                             this.state.deletedVariables.filter(
                                 deletedName =>
                                    String(deletedName).toUpperCase() !== name
                             );
                             );
                    }
                });


                    $('<h2>')
                /*
                        .text(title)
                * Keep PAGE automatic regardless of what the
                        .appendTo(box);
                * imported config contained.
                */
                this.state.config.fields.PAGE =
                    this.getAutomaticPageField();


                    $('<p>')
                this.markConfigDirty();
                        .text(message)
                        .appendTo(box);


                    const input =
                /*
                         this.textInput();
                * Keep the current selection when possible.
                * Otherwise select the first imported definition.
                */
                const selectedStillExists = !!(
                    this.state.config.fields[
                         this.state.selectedVariable
                    ]
                );


                     const buttons =
                if (
                        $('<div>')
                    !selectedStillExists ||
                            .addClass(
                     this.state.selectedVariable === 'PAGE'
                                'preload-editor-prompt-buttons'
                ) {
                            );
                    this.state.selectedVariable =
                        selected[0] ||
                        'PAGE';
                }


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


                    const confirm =
                this.renderVariablesBySelector();
                        this.createButton(
                this.renderVariableConfigurationBySelector();
                            'Load',
                this.renderAnalysisBySelector();
                            'preload-editor-button-primary',
                this.updateEditorTools();
                            () => {
                                const value =
                                    String(
                                        input.val() || ''
                                    ).trim();


                                if (!value) {
                this.saveDraft();
                                    return;
                                }


                                overlay.remove();
                let status =
                                resolve(value);
                    'Imported ' +
                            }
                    selected.length +
                         );
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                         : 'definitions') +
                    '.';


                     buttons.append(
                if (replaced.length) {
                        cancel,
                     status +=
                         confirm
                        ' Replaced: ' +
                    );
                        replaced.join(', ') +
                         '.';
                }


                    box.append(
                this.setStatus(status, 'success');
                        input,
                        buttons
                    );


                     overlay.append(box);
                mw.notify(status, {
                     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'
                );


                     input.trigger('focus');
                mw.notify(
                     error.message ||
                        'Could not import variable definitions.',
                    {
                        type: 'error'
                    }
                );
            }
        },


                    input.on(
        // =========================================================
                        'keydown.preloadEditor',
        // Preload parsing
                        event => {
        // =========================================================
                            if (
                                event.key === 'Enter'
                            ) {
                                confirm.trigger('click');
                            }


                            if (
        extractIncludeonly(source) {
                                event.key === 'Escape'
            const match = String(source || '').match(
                            ) {
                /<includeonly>([\s\S]*?)<\/includeonly>/i
                                cancel.trigger('click');
                            }
                        }
                    );
                }
             );
             );
        },


        createConfigReviewDialog() {
             return match
             return new Promise(
                ? match[1].trim()
                 resolve => {
                 : String(source || '').trim();
                    const overlay =
        },
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                            );


                    const box =
        findVariables(content) {
                        $('<div>')
            const variables = [];
                            .addClass(
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                                'preload-editor-prompt preload-editor-code-review'
                            );


                    $('<h2>')
            let match;
                        .text('Review config.json')
                        .appendTo(box);


                    $('<p>')
            while ((match = pattern.exec(content)) !== null) {
                        .text(
                const name = match[1].toUpperCase();
                            'This is the config.json that will be saved for the current preload.'
                        )
                        .appendTo(box);


                    const code =
                if (!variables.includes(name)) {
                        $('<pre>')
                    variables.push(name);
                            .addClass(
                }
                                'preload-editor-config-review'
            }
                            )
                            .text(
                                this.getConfigJSON()
                            );


                    const codeWrap =
            return variables;
                        $('<div>')
        },
                            .addClass(
                                'preload-editor-config-review-wrap'
                            )
                            .append(code);


                    box.append(codeWrap);
        findConditions(content) {
            const conditions = [];
            const pattern =
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;


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


                    const close =
            while ((match = pattern.exec(content)) !== null) {
                        this.createButton(
                conditions.push({
                            'Close',
                    type: match[1].toLowerCase(),
                            'preload-editor-button-primary',
                    expression: match[2].trim(),
                            () => {
                    index: match.index
                                overlay.remove();
                });
                                resolve();
            }
                            }
                        );


                    buttons.append(close);
            return conditions;
                    box.append(buttons);
        },
                    overlay.append(box);
 
        findConditionVariables(content) {
            const variables = [];


                     $(document.body)
            this.findConditions(content).forEach(condition => {
                        .append(overlay);
                if (
                     condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }


                     overlay.attr(
                const matches =
                         'tabindex',
                     condition.expression.match(
                        '-1'
                         /[A-Za-z0-9_-]+/g
                     );
                     ) || [];


                     overlay.trigger('focus');
                matches.forEach(name => {
                     name = name.toUpperCase();


                     overlay.on(
                     if (!variables.includes(name)) {
                        'keydown.preloadEditor',
                        variables.push(name);
                        event => {
                    }
                            if (
                });
                                event.key === 'Escape'
            });
                            ) {
                                close.trigger('click');
                            }
                        }
                    );


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


         async confirmSave(
         analyzePreload(content) {
            mode,
             return {
            title
                 variables: this.findVariables(content),
        ) {
                 conditions: this.findConditions(content),
             const configTitle =
                 conditionVariables:
                 title.replace(
                    this.findConditionVariables(content)
                    /\/+$/,
            };
                    ''
        },
                 ) +
                 '/config.json';


            let saveDescription;
        // =========================================================
        // Config
        // =========================================================


            if (mode === 'preload') {
        getAutomaticPageField() {
                 saveDescription =
            return {
                    'Save the preload page only?';
                 label: 'Page Name',
            } else if (mode === 'config') {
                description: 'Name of the page.',
                 saveDescription =
                type: 'page',
                    'Save the config.json page only?';
                required: true,
             } else {
                 namespace: 'Main',
                 saveDescription =
                'allow-new': true
                     'Save both the preload and config.json?';
            };
            }
        },
 
        emptyConfig() {
             return {
                 settings: {
                     incomplete: 'add-stub'
                },


             let pages = [];
                fields: {
                    PAGE: this.getAutomaticPageField()
                }
             };
        },


        normalizeConfig(config) {
             if (
             if (
                 mode === 'preload' ||
                 !config ||
                 mode === 'both'
                typeof config !== 'object' ||
                 Array.isArray(config)
             ) {
             ) {
                 pages.push(
                 config = this.emptyConfig();
                    'Preload: ' + title
                );
             }
             }


             if (
             if (
                 mode === 'config' ||
                 !config.settings ||
                 mode === 'both'
                 typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
             ) {
             ) {
                 pages.push(
                 config.settings = {};
                    'Config: ' + configTitle
                );
             }
             }


             const message =
             if (
                 saveDescription +
                 !config.fields ||
                 '\n\n' +
                 typeof config.fields !== 'object' ||
                 pages.join('\n') +
                 Array.isArray(config.fields)
                 '\n\nThis will write the changes to the wiki.';
            ) {
                 config.fields = {};
            }
 
            config.fields.PAGE =
                this.getAutomaticPageField();


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


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


         destroyEditor() {
         humanizeName(name) {
             if (!this.editor) {
             return String(name || '')
                 this.editorView = null;
                .replace(/[_-]+/g, ' ')
                 this.editorTools = null;
                .replace(/([a-z])([A-Z])/g, '$1 $2')
                 return;
                 .replace(/\s+/g, ' ')
            }
                 .trim()
                 .replace(/\b\w/g, char => char.toUpperCase());
        },


            const {
        prepareConfigForVariables(config, analysis) {
                view,
             config = this.normalizeConfig(config);
                inputHandler
             } = this.editor;


             if (
             const existing = config.fields || {};
                view &&
                inputHandler
            ) {
                view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }


             if (view) {
             const deleted = new Set(
                view.destroy();
                Array.isArray(this.state.deletedVariables)
             }
                    ? this.state.deletedVariables.map(
                        name => String(name).toUpperCase()
                    )
                    : []
             );


             this.editor = null;
             const fields = {};
            this.editorView = null;
            this.editorTools = null;
        },


        getEditorView() {
            fields.PAGE =
            return this.editorView;
                this.getAutomaticPageField();
        },


        getEditorContent() {
            analysis.variables.forEach(name => {
            if (
                if (
                this.editorView &&
                    name === 'PAGE' ||
                 this.editorView.state
                    deleted.has(name)
            ) {
                 ) {
                return this.editorView.state.doc.toString();
                    return;
            }
                }


            return (
                fields[name] =
                this.state.preloadContent || ''
                    existing[name] ||
            );
                    this.createDefaultField(
        },
                        name,
                        analysis
                    );
            });


        setEditorContent(content) {
            Object.keys(existing).forEach(name => {
            content =
                const upper = name.toUpperCase();
                String(content || '');


            if (!this.editorView) {
                if (
                this.state.preloadContent =
                    upper !== 'PAGE' &&
                    content;
                    !fields[upper] &&
                 return;
                    !deleted.has(upper)
             }
                ) {
                    fields[upper] =
                        existing[name];
                 }
             });


             const current =
             config.fields = fields;
                this.editorView.state.doc.toString();


             if (current === content) {
             return config;
                return;
        },
            }


            this.editorView.dispatch({
        validateConfig(config, analysis) {
                changes: {
            const errors = [];
                    from: 0,
             const warnings = [];
                    to:
                        this.editorView.state.doc.length,
                    insert: content
                }
             });
        },


        getEditorSelection() {
             if (
             if (
                 !this.editorView ||
                 !config ||
                 !this.editorView.state
                 typeof config !== 'object' ||
                Array.isArray(config)
             ) {
             ) {
                 return null;
                 return {
                    valid: false,
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                };
             }
             }


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


             return {
             const configured =
                 from:
                 Object.keys(
                     selection.from,
                    config.fields
                ).map(
                     name =>
                        name.toUpperCase()
                );


                 to:
            analysis.variables.forEach(name => {
                     selection.to,
                 if (!configured.includes(name)) {
                     errors.push(
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                }
            });


                 text:
            configured.forEach(name => {
                     this.editorView.state.doc.sliceString(
                 if (!analysis.variables.includes(name)) {
                         selection.from,
                     warnings.push(
                         selection.to
                         'Field "' +
                     )
                        name +
             };
                         '" is not used by the preload.'
        },
                     );
                }
             });


        focusEditor() {
             if (!configured.includes('PAGE')) {
             if (this.editorView) {
                 errors.push(
                 this.editorView.focus();
                    'PAGE must always be configured.'
                );
             }
             }
        },


        insertEditorText(
            Object.entries(config.fields).forEach(([name, field]) => {
            text,
                if (
            selectionFrom,
                    !field ||
            selectionTo,
                    typeof field !== 'object' ||
            cursorPosition
                    Array.isArray(field)
        ) {
                ) {
            if (!this.editorView) {
                    errors.push(
                return;
                        'Field "' +
            }
                        name +
                        '" must be an object.'
                    );


            const view =
                    return;
                 this.editorView;
                 }


            const selection =
                if (!field.type) {
                 view.state.selection.main;
                    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.'
                        );
                    }


            const from =
                    if (
                selectionFrom === undefined
                        Array.isArray(field.accept) &&
                     ? selection.from
                        field.accept.some(
                     : selectionFrom;
                            value =>
                                !String(
                                    value || ''
                                ).trim()
                        )
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" contains an empty accepted MIME type.'
                        );
                     }


            const to =
                    if (
                selectionTo === undefined
                        field.filename !== undefined &&
                     ? selection.to
                        typeof field.filename !== 'string'
                     : selectionTo;
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                        );
                     }


            const cursor =
                    if (
                cursorPosition === undefined
                        field.filetext !== undefined &&
                     ? from + text.length
                        typeof field.filetext !== 'string'
                     : cursorPosition;
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                     }


            view.dispatch({
                    if (
                changes: {
                        !field.accept ||
                    from,
                        !field.accept.length
                    to,
                    ) {
                     insert: text
                        warnings.push(
                },
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                     }


                selection: {
                    if (
                     anchor: cursor
                        !field.filename
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                     }
                 }
                 }
            });


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


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


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


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


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


         insertVariable(name) {
         // =========================================================
            name =
        // Transformation helpers
                String(name || '')
        // =========================================================
                    .trim()
                    .toUpperCase();


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


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


            if (!selected) {
                case 'remove-suffix':
                return;
                    return suffix
            }
                        ? {
                            transform,
                            suffix
                        }
                        : null;


            this.insertEditorText(
                 case 'replace':
                 '%%' + name + '%%',
                    return from === ''
                selected.from,
                        ? null
                 selected.to
                        : {
             );
                            transform,
                            from,
                            to: to || ''
                        };
 
                 default:
                    return null;
             }
         },
         },


         insertCondition(
         // =========================================================
            type,
        // UI helpers
            variable
         // =========================================================
         ) {
            type =
                String(type || '')
                    .toLowerCase();


             variable =
        createSection(title, className) {
                String(variable || '')
             const section = $('<section>')
                    .trim()
                .addClass('preload-editor-section');
                    .toUpperCase();


            const selected =
             if (className) {
                this.getEditorSelection();
                 section.addClass(className);
 
             if (!selected) {
                 return;
             }
             }


             let text;
             $('<h2>')
            let cursorOffset;
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);


             switch (type) {
             return section;
                case 'if': {
        },
                    if (!variable) {
                        return;
                    }


                    const opening =
        createButton(label, className, callback) {
                        '<!-- @if ' +
            const button = $('<button>')
                        variable +
                .attr('type', 'button')
                        ' -->';
                .addClass('preload-editor-button')
                .text(label);


                    const closing =
            if (className) {
                        '<!-- @endif -->';
                button.addClass(className);
            }


                    if (
            if (callback) {
                        selected.from !==
                button.on(
                        selected.to
                     'click.preloadEditor',
                     ) {
                    callback
                        text =
                );
                            opening +
            }
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                        cursorOffset =
            return button;
                            text.length;
        },
                    } else {
                        text =
                            opening +
                            '\n\n' +
                            closing;


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


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


                 case 'elseif':
            if (description) {
                     text =
                 $('<div>')
                        '<!-- @elseif -->';
                     .addClass('preload-editor-help')
                     cursorOffset =
                     .text(description)
                        text.length;
                    .appendTo(row);
                    break;
            }


                case 'else':
            row.append(input);
                    text =
 
                        '<!-- @else -->';
            return row;
                    cursorOffset =
        },
                        text.length;
                    break;


                 case 'endif':
        textInput(value, placeholder) {
                     text =
            return $('<input>')
                        '<!-- @endif -->';
                 .attr({
                    cursorOffset =
                    type: 'text',
                        text.length;
                     value: value == null ? '' : value,
                    break;
                    placeholder: placeholder || ''
                })
                .addClass('preload-editor-input');
        },


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


             this.insertEditorText(
        checkbox(checked) {
                 text,
             return $('<input>')
                selected.from,
                 .attr('type', 'checkbox')
                 selected.to,
                 .prop('checked', !!checked)
                 selected.from +
                 .addClass('preload-editor-checkbox');
                    cursorOffset
            );
         },
         },


         getToolVariables() {
         select(options, value) {
             const variables =
             const select = $('<select>')
                 new Set(['PAGE']);
                .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);
            });


             if (
             return select;
                this.analysis &&
        },
                this.analysis.variables
            ) {
                this.analysis.variables.forEach(
                    name => {
                        variables.add(
                            String(
                                name
                            ).toUpperCase()
                        );
                    }
                );
            }


            return Array.from(variables);
        // =========================================================
         },
        // In-wiki dialogs
         // =========================================================


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


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


            options.forEach(
                 $('<h2>')
                 option => {
                    .text(title)
                    $('<option>')
                    .appendTo(box);
                        .attr(
                            'value',
                            option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                }
            );


            return select;
                const messageLines =
        },
                    String(message || '').split('\n');


        updateEditorToolVariables() {
                messageLines.forEach(line => {
            if (!this.editorTools) {
                    if (line === '') {
                return;
                        $('<div>')
            }
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);
 
                        return;
                    }
 
                    $('<p>')
                        .text(line)
                        .appendTo(box);
                });


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


            const current =
                const cancel = this.createButton(
                this.editorTools
                    cancelLabel || 'Cancel',
                     .variableSelect
                     '',
                     .val();
                     () => {
                        overlay.remove();
                        resolve(false);
                    }
                );


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


            const populate =
                 buttons.append(cancel, confirm);
                 (
                 box.append(buttons);
                    select,
                overlay.append(box);
                    value
                 ) => {
                    select.empty();


                    variables.forEach(
                $(document.body).append(overlay);
                        name => {
                            $('<option>')
                                .attr(
                                    'value',
                                    name
                                )
                                .text(name)
                                .appendTo(select);
                        }
                    );


                    if (
                const close = value => {
                        value &&
                     if (value === 'Escape') {
                        variables.includes(value)
                         cancel.trigger('click');
                    ) {
                        select.val(value);
                     } else if (
                        variables.length
                    ) {
                         select.val(
                            variables[0]
                        );
                     }
                     }
                 };
                 };


            populate(
                overlay.on(
                 this.editorTools.variableSelect,
                    'keydown.preloadEditor',
                 current
                    event => {
            );
                        close(event.key);
                    }
                 );
 
                overlay.attr('tabindex', '-1');
                 overlay.trigger('focus');


            populate(
                overlay.on(
                this.editorTools.conditionVariableSelect,
                    'click.preloadEditor',
                currentCondition
                    event => {
            );
                        if (event.target === overlay.get(0)) {
        },
                            cancel.trigger('click');
 
                        }
        updateConditionVariableVisibility() {
                     }
            if (!this.editorTools) {
                return;
            }
 
            const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();
 
            this.editorTools
                .conditionVariableWrap
                .toggle(
                     type === 'if'
                 );
                 );
            });
         },
         },


         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',
                    .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 confirm = this.createButton(
                    'Load',
                     'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();
 
                        if (!value) {
                            return;
                        }


            const variableSelect =
                        overlay.remove();
                this.createToolSelect(
                        resolve(value);
                    [],
                     }
                     'preload-editor-variable-select'
                 );
                 );


            variableGroup.append(
                buttons.append(cancel, confirm);
                 variableSelect,
 
                 box.append(
                    input,
                    buttons
                );


                 this.createButton(
                 overlay.append(box);
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                )
            );


            const conditionGroup =
                 $(document.body).append(overlay);
                 $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


            $('<span>')
                input.trigger('focus');
                 .addClass(
 
                     'preload-editor-tool-label'
                 input.on(
                )
                     'keydown.preloadEditor',
                .text('Insert condition')
                    event => {
                .appendTo(conditionGroup);
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


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


             const conditionVariableSelect =
        createConfigReviewDialog() {
                 this.createToolSelect(
             return new Promise(resolve => {
                     [],
                 const overlay = $('<div>')
                    'preload-editor-condition-variable-select'
                     .addClass(
                );
                        'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                    );


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


            const insertCondition =
                 $('<h2>')
                 this.createButton(
                     .text('Review config.json')
                    'Insert',
                    .appendTo(box);
                    'preload-editor-tool-button',
                     () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );


            conditionTypeSelect.on(
                $('<p>')
                'change.preloadEditor',
                    .text(
                () =>
                        'This is the config.json that will be saved for the current preload.'
                     this.updateConditionVariableVisibility()
                    )
            );
                     .appendTo(box);


            conditionGroup.append(
                const code = $('<pre>')
                conditionTypeSelect,
                    .addClass(
                conditionVariableWrap,
                        'preload-editor-config-review'
                insertCondition
                    )
            );
                    .text(this.getConfigJSON());


            tools.append(
                const codeWrap = $('<div>')
                wrapGroup,
                    .addClass(
                variableGroup,
                        'preload-editor-config-review-wrap'
                conditionGroup
                    )
            );
                    .append(code);


            this.editorTools = {
                box.append(codeWrap);
                root: tools,
                variableSelect,
                conditionTypeSelect,
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };


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


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


        updateEditorTools() {
                buttons.append(close);
            this.updateEditorToolVariables();
                box.append(buttons);
            this.updateConditionVariableVisibility();
                overlay.append(box);
        },


        // Syntax highlighting
                $(document.body).append(overlay);


        getKnownVariables() {
                overlay.attr('tabindex', '-1');
            const known =
                 overlay.trigger('focus');
                 new Set(['PAGE']);


            const fields =
                overlay.on(
                this.state.config &&
                    'keydown.preloadEditor',
                 this.state.config.fields;
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                 );


            if (
                overlay.on(
                fields &&
                    'click.preloadEditor',
                typeof fields === 'object'
                     event => {
            ) {
                         if (event.target === overlay.get(0)) {
                Object.keys(fields).forEach(
                             close.trigger('click');
                     name => {
                         }
                         known.add(
                             String(
                                name
                            ).toUpperCase()
                         );
                     }
                     }
                 );
                 );
             }
             });
 
            return known;
         },
         },


         createSyntaxDecorations(
         async confirmSave(mode, title) {
            state,
             const configTitle =
            Decoration
                 title.replace(/\/+$/, '') +
        ) {
                '/config.json';
             const decorations = [];
            const source =
                 state.doc.toString();


             const knownVariables =
             let saveDescription;
                this.getKnownVariables();


             const variablePattern =
             if (mode === 'preload') {
                 /%%([A-Za-z0-9_-]+)%%/g;
                 saveDescription =
                    'Save the preload page only?';
            } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
            } else {
                saveDescription =
                    'Save both the preload and config.json?';
            }


             let match;
             const pages = [];


             while (
             if (mode === 'preload' || mode === 'both') {
                 (
                 pages.push(
                     match =
                     'Preload: ' +
                        variablePattern.exec(
                    title
                            source
                 );
                        )
             }
                 ) !== null
             ) {
                const name =
                    match[1].toUpperCase();


                const known =
            if (mode === 'config' || mode === 'both') {
                    knownVariables.has(name);
                pages.push(
                    'Config: ' +
                    configTitle
                );


                 decorations.push(
                 pages.push(
                     Decoration.mark({
                     'Config content model: JSON'
                        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
                    )
                 );
                 );
             }
             }


             const conditionPattern =
             const message =
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                 saveDescription +
                '\n\n' +
                pages.join('\n') +
                '\n\nThis will write the changes to the wiki.';
 
            return this.createConfirmDialog(
                'Confirm save',
                message,
                'Save',
                'Cancel'
            );
        },


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


                 const directiveStart =
            const {
                    match.index +
                 view,
                    match[0].indexOf('@');
                inputHandler
            } = this.editor;


                 decorations.push(
            if (view && inputHandler) {
                     Decoration.mark({
                 view.dom.removeEventListener(
                        class:
                     'input',
                            'preload-editor-syntax-directive'
                     inputHandler
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                     )
                 );
                 );
            }


                 const type =
            if (view) {
                    match[1].toLowerCase();
                 view.destroy();
            }


                if (
            this.editor = null;
                    type !== 'if' &&
            this.editorView = null;
                    type !== 'elseif'
            this.editorTools = null;
                ) {
        },
                    continue;
                }


                const expression =
        getEditorView() {
                    match[2];
            return this.editorView;
        },


                 const expressionStart =
        getEditorContent() {
                    match.index +
            if (
                    match[0].indexOf(
                 this.editorView &&
                        expression
                this.editorView.state
                    );
            ) {
                return this.editorView.state.doc.toString();
            }


                const expressionPattern =
            return this.state.preloadContent || '';
                    /[A-Za-z0-9_-]+/g;
        },


                let expressionMatch;
        setEditorContent(content) {
            content = String(content || '');


                while (
            if (!this.editorView) {
                    (
                this.state.preloadContent = content;
                        expressionMatch =
                 return;
                            expressionPattern.exec(
            }
                                expression
                            )
                    ) !== null
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


                    if (
            const current =
                        !knownVariables.has(name)
                this.editorView.state.doc.toString();
                    ) {
                        continue;
                    }


                    const start =
            if (current === content) {
                        expressionStart +
                return;
                        expressionMatch.index;
            }


                    decorations.push(
            this.editorView.dispatch({
                        Decoration.mark({
                changes: {
                            class:
                    from: 0,
                                'preload-editor-syntax-condition-variable'
                    to: this.editorView.state.doc.length,
                        }).range(
                     insert: content
                            start,
                            start +
                                expressionMatch[0]
                                    .length
                        )
                     );
                 }
                 }
             }
             });
 
            return Decoration.set(
                decorations,
                true
            );
         },
         },


         async installSyntaxHighlighting(view) {
         getEditorSelection() {
             await mw.loader.using(
             if (
                 'ext.CodeMirror.v6.lib'
                 !this.editorView ||
             );
                !this.editorView.state
             ) {
                return null;
            }


             const require =
             const selection =
                 mw.loader.require;
                 this.editorView.state.selection.main;


             const {
             return {
                 StateField,
                 from: selection.from,
                 StateEffect,
                 to: selection.to,
                 EditorView,
                 text: this.editorView.state.doc.sliceString(
                 Decoration
                    selection.from,
             } = require(
                    selection.to
                'ext.CodeMirror.v6.lib'
                 )
            );
             };
        },


             const syntaxField =
        focusEditor() {
                StateField.define({
             if (this.editorView) {
                    create: state =>
                this.editorView.focus();
                        this.createSyntaxDecorations(
            }
                            state,
        },
                            Decoration
                        ),


                    update: (
        insertEditorText(
                        decorations,
            text,
                        transaction
            selectionFrom,
                    ) =>
            selectionTo,
                        transaction.docChanged
            cursorPosition
                            ? this.createSyntaxDecorations(
        ) {
                                transaction.state,
            if (!this.editorView) {
                                Decoration
                return;
                            )
            }
                            : decorations,
 
            const view = this.editorView;
            const selection = view.state.selection.main;
 
            const from =
                selectionFrom === undefined
                    ? selection.from
                    : selectionFrom;
 
            const to =
                selectionTo === undefined
                    ? selection.to
                    : selectionTo;


                    provide: field =>
            const cursor =
                        EditorView.decorations.from(
                cursorPosition === undefined
                            field
                    ? from + text.length
                        )
                    : cursorPosition;
                });


             view.dispatch({
             view.dispatch({
                 effects:
                 changes: {
                     StateEffect.appendConfig.of(
                     from,
                        syntaxField
                    to,
                     )
                     insert: text
                },
                selection: {
                    anchor: cursor
                }
             });
             });


             this.editor.syntaxField =
             view.focus();
                syntaxField;
         },
         },


         async mountCodeMirror(textarea) {
         // =========================================================
            return new Promise(
        // Editor tools
                (
        // =========================================================
                    resolve,
                    reject
                ) => {
                    let settled = false;


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


                            mw.hook(
            if (
                                'dev.CCM.load'
                !selected ||
                            ).remove(onLoad);
                selected.from === selected.to
                        };
            ) {
                this.focusEditor();
                return;
            }


                    const onReady =
            const replacement =
                        async cm => {
                '%%' +
                            if (
                selected.text +
                                settled ||
                '%%';
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                            settled = true;
            this.insertEditorText(
                            cleanup();
                replacement,
                selected.from,
                selected.to,
                selected.from + replacement.length
            );
        },


                            const view =
        insertVariable(name) {
                                cm.view;
            name = String(name || '')
                .trim()
                .toUpperCase();


                            const inputHandler =
            if (!name) {
                                () => {
                return;
                                    this.state
            }
                                        .preloadContent =
                                        view.state.doc.toString();


                                    this.markPreloadDirty();
            const selected =
                this.getEditorSelection();


                                    this.reanalyze();
            if (!selected) {
                return;
            }


                                    this.renderVariablesBySelector();
            this.insertEditorText(
                                    this.renderVariableConfigurationBySelector();
                '%%' + name + '%%',
                                    this.renderAnalysisBySelector();
                selected.from,
                                    this.updateEditorTools();
                selected.to
            );
        },


                                    this.saveDraft();
        insertCondition(
                                };
            type,
            variable
        ) {
            type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                .toUpperCase();


                            view.dom.addEventListener(
            const selected =
                                'input',
                this.getEditorSelection();
                                inputHandler
                            );


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


                            const wrapper =
            let text;
                                view.dom.closest(
            let cursorOffset;
                                    '.ext-codemirror-wrapper'
                                );


                            if (wrapper) {
            switch (type) {
                                wrapper.classList.add(
                case 'if': {
                                    'preload-editor-codemirror-wrapper'
                    if (!variable) {
                                );
                        return;
                            }
                    }


                            this.editor = {
                    const opening =
                                cm,
                        '<!-- @if ' +
                                view,
                        variable +
                                textarea,
                        ' -->';
                                inputHandler
                            };


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


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


                            try {
                        cursorOffset = text.length;
                                await this.installSyntaxHighlighting(
                    } else {
                                    view
                        text =
                                );
                            opening +
                            '\n\n' +
                            closing;


                                if (
                        cursorOffset =
                                    this.state.dirty
                            opening.length + 1;
                                ) {
                    }
                                    this.saveDraft();
                                }


                                resolve(view);
                    break;
                            } catch (error) {
                }
                                reject(error);
                            }
                        };


                     const onLoad =
                case 'elseif':
                         loader => {
                     text =
                            if (
                         '<!-- @elseif -->';
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                            try {
                    cursorOffset =
                                loader(textarea);
                         text.length;
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                         };


                     mw.hook(
                     break;
                        'dev.CCM.ready'
                    ).add(onReady);


                     mw.hook(
                case 'else':
                         'dev.CCM.load'
                     text =
                    ).add(onLoad);
                         '<!-- @else -->';
                }
            );
        },


        // Main UI
                    cursorOffset =
                        text.length;


        init() {
                    break;
            const root =
                $('#mw-content-text');


            if (!root.length) {
                case 'endif':
                return;
                    text =
            }
                        '<!-- @endif -->';


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


            root.append(this.root);
                    break;


             this.renderShell();
                default:
                    return;
             }


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


             window.addEventListener(
        getToolVariables() {
                 'beforeunload',
             const variables =
                 () => {
                 new Set(['PAGE']);
                    if (this.state.dirty) {
 
                         this.saveDraft();
            if (
                this.analysis &&
                 this.analysis.variables
            ) {
                this.analysis.variables.forEach(
                    name => {
                         variables.add(
                            String(name).toUpperCase()
                        );
                     }
                     }
                 }
                 );
             );
            }
 
             return Array.from(variables);
         },
         },


         renderShell() {
         createToolSelect(
             this.destroyEditor();
            options,
            this.root.empty();
            className
        ) {
             const select =
                $('<select>')
                    .addClass(
                        'preload-editor-tool-select'
                    );


             const loader =
             if (className) {
                 this.createSection('Preload');
                 select.addClass(className);
            }


             const titleInput =
             options.forEach(
                this.textInput(
                option => {
                    this.state.preloadTitle,
                     $('<option>')
                     'Template:Example/Preload'
                        .attr(
                ).attr(
                            'value',
                    'id',
                            option.value
                    'preload-editor-title-input'
                         )
                );
                         .text(option.label)
 
                         .appendTo(select);
            titleInput.on(
                'input.preloadEditor',
                () => {
                    this.state.preloadTitle =
                         String(
                            titleInput.val() || ''
                         ).trim();
 
                    if (
                        this.state.dirty &&
                        this.state.mode === 'new'
                    ) {
                         this.saveDraft();
                    }
                 }
                 }
             );
             );


             const loadButton =
             return select;
                this.createButton(
        },
                    'Load',
                    'preload-editor-button-primary',
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                );


            const newButton =
        updateEditorToolVariables() {
                this.createButton(
            if (!this.editorTools) {
                    'New',
                 return;
                    '',
            }
                    () => this.startNew()
                 );


             const sampleButton =
             const variables =
                 this.createButton(
                 this.getToolVariables();
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );


             loader.append(
             const current =
                 $('<div>')
                 this.editorTools
                     .addClass(
                     .variableSelect
                        'preload-editor-toolbar'
                     .val();
                    )
                     .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );


             this.root.append(loader);
             const currentCondition =
                this.editorTools
                    .conditionVariableSelect
                    .val();


this.workspace =
            const populate = (
    $('<div>')
                select,
        .addClass(
                value
            'preload-editor-workspace'
            ) => {
        );
                select.empty();
this.root.append(this.workspace);
/*
* Fixed footer
*
* Status messages and save actions live here so they
* remain visible while editing.
*/
const footer =
    $('<div>')
        .addClass(
            'preload-editor-footer'
        );
this.status =
    $('<div>')
        .addClass(
            'preload-editor-status'
        );
footer.append(
    this.status
);
this.root.append(footer);


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


        renderWelcome() {
                if (
            this.workspace.empty();
                    value &&
                    variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                        variables[0]
                    );
                }
            };


             const section =
             populate(
                 this.createSection('Get started');
                 this.editorTools.variableSelect,
                current
            );


             $('<p>')
             populate(
                 .text(
                 this.editorTools.conditionVariableSelect,
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                 currentCondition
                )
                .appendTo(section);
 
            const tips =
                $('<ul>')
                    .addClass(
                        'preload-editor-tips'
                    );
 
            [
                'Existing preload: loads the preload and its config.json if available.',
                'New preload: starts with the standard Preload Template structure.',
                 'Sample page: loads normal wiki page content so you can turn it into a preload.'
            ].forEach(
                text => {
                    $('<li>')
                        .text(text)
                        .appendTo(tips);
                }
             );
             );
            section.append(tips);
            this.workspace.append(section);
         },
         },


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


             this.status.removeClass(
             const type =
                'is-error',
                this.editorTools
                'is-success',
                    .conditionTypeSelect
                'is-warning',
                    .val();
                'is-loading'
 
            );
             this.editorTools
 
                 .conditionVariableWrap
             if (type) {
                .toggle(
                 this.status.addClass(
                     type === 'if'
                     'is-' + type
                 );
                 );
            }
            this.status.text(
                message || ''
            );
         },
         },


         // Load / create
         renderEditorTools() {
            const tools =
                $('<div>')
                    .addClass(
                        'preload-editor-tools'
                    );


        async loadExisting(title) {
             const wrapGroup =
             title =
                 $('<div>')
                 String(title || '').trim();
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );


             if (!title) {
             wrapGroup.append(
                 mw.notify(
                 this.createButton(
                     'Enter a preload page title first.',
                     'Wrap selection',
                     {
                     'preload-editor-tool-button',
                        type: 'warn'
                     () =>
                     }
                        this.wrapSelectionWithVariable()
                 );
                 )
            );


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


             this.setStatus(
             $('<span>')
                'Loading preload...',
                .addClass(
                 'loading'
                    'preload-editor-tool-label'
            );
                 )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);


             try {
             const variableSelect =
                const page =
                this.createToolSelect(
                    await this.getPage(title);
                    [],
                    'preload-editor-variable-select'
                );


                if (!page) {
            variableGroup.append(
                    const suggestions =
                variableSelect,
                        await this.findSimilarPreloads(
                            title
                        );


                     this.renderMissingPage(
                this.createButton(
                         title,
                    'Insert',
                        suggestions
                     'preload-editor-tool-button',
                    );
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                         )
                )
            );


                     this.setStatus(
            const conditionGroup =
                         'Preload not found.',
                $('<div>')
                        'warning'
                     .addClass(
                         'preload-editor-tool-group preload-editor-tool-group-condition'
                     );
                     );


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


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


                 this.setStatus(
            const conditionVariableSelect =
                     'Preload loaded.',
                 this.createToolSelect(
                     'success'
                     [],
                );
                     'preload-editor-condition-variable-select'
            } catch (error) {
                console.error(
                    'Preload Editor:',
                    error
                 );
                 );


                 this.setStatus(
            const conditionVariableWrap =
                    error.message ||
                 $('<span>')
                        'Could not load preload.',
                     .addClass(
                    'error'
                         'preload-editor-condition-variable'
                );
            }
        },
 
        async findSimilarPreloads(title) {
            let query =
                title
                     .replace(
                        /\/Preload$/i,
                         ''
                     )
                     )
                     .trim();
                     .append(
                        conditionVariableSelect
                    );


             if (!query) {
             const insertCondition =
                 query = title;
                this.createButton(
            }
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                 );


             try {
             conditionTypeSelect.on(
                 const results =
                 'change.preloadEditor',
                     await this.searchPages(query);
                () =>
                     this.updateConditionVariableVisibility()
            );


                return results.filter(
            conditionGroup.append(
                    result =>
                 conditionTypeSelect,
                        /\/Preload$/i.test(
                 conditionVariableWrap,
                            result.title
                insertCondition
                        )
            );
                 );
            } catch (error) {
                 console.error(
                    'Preload Editor search:',
                    error
                );


                 return [];
            tools.append(
             }
                wrapGroup,
        },
                variableGroup,
                 conditionGroup
             );


        renderMissingPage(
            this.editorTools = {
            title,
                root: tools,
            suggestions
                variableSelect,
        ) {
                conditionTypeSelect,
             this.workspace.empty();
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
             };


             const section =
             this.updateEditorToolVariables();
                this.createSection(
            this.updateConditionVariableVisibility();
                    'Preload not found'
                );


             $('<p>')
             return tools;
                .text(
        },
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


            if (suggestions.length) {
        updateEditorTools() {
                $('<h3>')
            this.updateEditorToolVariables();
                    .text('Similar preloads')
            this.updateConditionVariableVisibility();
                    .appendTo(section);
        },


                const list =
        // =========================================================
                    $('<div>')
        // Syntax highlighting
                        .addClass(
        // =========================================================
                            'preload-editor-suggestions'
                        );


                suggestions.forEach(
        getKnownVariables() {
                    result => {
            const known =
                        list.append(
                new Set(['PAGE']);
                            this.createButton(
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                        );
                    }
                );


                 section.append(list);
            const fields =
            }
                this.state.config &&
                 this.state.config.fields;


             section.append(
             if (
                 this.createButton(
                 fields &&
                    'Create this preload',
                typeof fields === 'object'
                    'preload-editor-button-primary',
            ) {
                    () =>
                Object.keys(fields).forEach(
                         this.startNew(title)
                    name => {
                 )
                         known.add(
             );
                            String(name).toUpperCase()
                        );
                    }
                 );
             }


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


         async startNew(title) {
         createSyntaxDecorations(
             title =
            state,
                 String(title || '').trim();
            Decoration
        ) {
             const decorations = [];
            const source =
                 state.doc.toString();
 
            const knownVariables =
                this.getKnownVariables();


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


                config:
            let match;
                    this.emptyConfig(),


                variables: ['PAGE'],
            while (
                 conditions: [],
                 (
                selectedVariable: 'PAGE',
                    match =
                deletedVariables: [],
                        variablePattern.exec(source)
                 mode: 'new',
                 ) !== null
                dirty: true,
            ) {
                 dirtyPreload: true,
                 const name =
                dirtyConfig: true
                    match[1].toUpperCase();
            };


            this.saveDraft();
                const known =
            this.renderEditor();
                    knownVariables.has(name);


            this.setStatus(
                decorations.push(
                'Creating a new preload.',
                    Decoration.mark({
                'success'
                        class: [
            );
                            'preload-editor-syntax-variable',
        },
                            known
 
                                ? 'preload-editor-syntax-variable-known'
        async loadSamplePage() {
                                : 'preload-editor-syntax-variable-unknown'
            const result =
                        ].join(' ')
                await this.createPromptDialog(
                    }).range(
                    'Load Sample Page',
                        match.index,
                     'Enter the title of a normal wiki page to use as the starting point.'
                        match.index +
                            match[0].length
                     )
                 );
                 );
            if (!result) {
                return;
             }
             }


             this.setStatus(
             const conditionPattern =
                 'Loading sample page...',
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                'loading'
            );


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


                 if (!page) {
                 const directiveStart =
                     throw new Error(
                    match.index +
                        'Sample page not found: ' +
                     match[0].indexOf('@');
                        result
                    );
                }


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


                 this.state = {
                 const type =
                     preloadTitle: '',
                    match[1].toLowerCase();
                     preloadSource: '',
 
                     preloadContent: sample,
                if (
                     type !== 'if' &&
                     type !== 'elseif'
                ) {
                     continue;
                }


                     config:
                const expression =
                        this.emptyConfig(),
                     match[2];


                    variables: ['PAGE'],
                const expressionStart =
                    conditions: [],
                     match.index +
                     selectedVariable: 'PAGE',
                     match[0].indexOf(
                     deletedVariables: [],
                        expression
                    mode: 'new',
                     );
                    dirty: true,
                     dirtyPreload: true,
                    dirtyConfig: true
                };


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


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


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


        convertSampleToPreload(source) {
                    if (
            let content =
                        !knownVariables.has(name)
                String(source || '').trim();
                    ) {
                        continue;
                    }


            const include =
                    const start =
                content.match(
                        expressionStart +
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                        expressionMatch.index;
                );


            if (include) {
                    decorations.push(
                content =
                        Decoration.mark({
                    include[1].trim();
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                }
             }
             }


             content =
             return Decoration.set(
                content
                decorations,
                    .replace(
                 true
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();
 
            return (
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                 '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
             );
             );
         },
         },


         async loadDefinition(
         async installSyntaxHighlighting(view) {
            title,
             await mw.loader.using(
            source
                 'ext.CodeMirror.v6.lib'
        ) {
            );
             const content =
                 this.extractIncludeonly(source);


             let config =
             const require =
                 this.emptyConfig();
                 mw.loader.require;


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


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


            if (configPage) {
                    update: (
                try {
                        decorations,
                     config =
                        transaction
                         JSON.parse(
                     ) =>
                             configPage.content
                         transaction.docChanged
                        );
                             ? this.createSyntaxDecorations(
                } catch (error) {
                                transaction.state,
                    throw new Error(
                                Decoration
                        'The existing config.json contains invalid JSON: ' +
                            )
                        error.message
                            : decorations,
                    );
                }
            }


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


             this.state.deletedVariables = [];
             view.dispatch({
                effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
            });


             config =
             this.editor.syntaxField =
                 this.prepareConfigForVariables(
                 syntaxField;
                    config,
        },
                    analysis
                );


             this.state = {
        async mountCodeMirror(textarea) {
                 preloadTitle: title,
             return new Promise(
                preloadSource: source,
                 (
                 preloadContent: source,
                    resolve,
                config,
                    reject
                 ) => {
                    let settled = false;


                variables:
                    const cleanup = () => {
                    analysis.variables,
                        mw.hook(
                            'dev.CCM.ready'
                        ).remove(onReady);


                conditions:
                        mw.hook(
                     analysis.conditions,
                            'dev.CCM.load'
                        ).remove(onLoad);
                     };


                selectedVariable:
                     const onReady =
                     analysis.variables.includes('PAGE')
                         async cm => {
                         ? 'PAGE'
                            if (
                        : (
                                settled ||
                            analysis.variables[0] ||
                                !cm ||
                             'PAGE'
                                cm.textarea !== textarea ||
                        ),
                                !cm.view
                             ) {
                                return;
                            }


                deletedVariables: [],
                            settled = true;
                            cleanup();


                mode: 'edit',
                            const view =
                dirty: false,
                                cm.view;
                dirtyPreload: false,
                dirtyConfig: false
            };


            this.clearDraft(title);
                            const inputHandler =
            this.renderEditor();
                                () => {
        },
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();
 
                                    this.markPreloadDirty();


        // Editor
                                    this.reanalyze();


        renderEditor() {
                                    this.renderVariablesBySelector();
            this.destroyEditor();
                                    this.renderVariableConfigurationBySelector();
            this.workspace.empty();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


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


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


            const right =
                            view.dom.classList.add(
                $('<div>')
                                'preload-editor-codemirror'
                    .addClass(
                            );
                        'preload-editor-right'
                    );


            const editorSection =
                            const wrapper =
                this.createSection(
                                view.dom.closest(
                    'Preload',
                                    '.ext-codemirror-wrapper'
                    'preload-editor-main-section'
                                );
                );


            const meta =
                            if (wrapper) {
                $('<div>')
                                wrapper.classList.add(
                    .addClass(
                                    'preload-editor-codemirror-wrapper'
                        'preload-editor-meta'
                                );
                    );
                            }


            $('<strong>')
                            this.editor = {
                .text(
                                cm,
                    this.state.preloadTitle ||
                                view,
                    'New preload'
                                textarea,
                )
                                inputHandler
                .appendTo(meta);
                            };


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


            editorSection.append(meta);
                            this.state.preloadContent =
            editorSection.append(
                                view.state.doc.toString();
                this.renderEditorTools()
            );


            const textarea =
                            try {
                this.textarea(
                                await this.installSyntaxHighlighting(
                    this.state.preloadContent
                                    view
                )
                                );
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


            const editorMount =
                                if (
                $('<div>')
                                    this.state.dirty
                    .addClass(
                                ) {
                        'preload-editor-codemirror-mount'
                                    this.saveDraft();
                    )
                                }
                    .append(textarea);


            editorSection.append(editorMount);
                                resolve(view);
            left.append(editorSection);
                            } catch (error) {
                                reject(error);
                            }
                        };


            const analysisSection =
                    const onLoad =
                this.createSection('Analysis');
                        loader => {
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


            const analysisContainer =
                            try {
                $('<div>')
                                loader(textarea);
                     .addClass(
                            } catch (error) {
                         'preload-editor-analysis'
                                settled = true;
                     );
                                cleanup();
                                reject(error);
                            }
                        };
 
                     mw.hook(
                         'dev.CCM.ready'
                     ).add(onReady);


            analysisSection.append(
                    mw.hook(
                 analysisContainer
                        'dev.CCM.load'
                    ).add(onLoad);
                 }
             );
             );
        },
        // =========================================================
        // Main UI
        // =========================================================


             const variablesSection =
        init() {
                 this.createSection('Variables');
             const root =
                 $('#mw-content-text');


             const detectVariablesButton =
             if (!root.length) {
                this.createButton(
                 return;
                    'Detect variables',
            }
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                 );


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


             variablesSection.append(
             root.append(this.root);
                $('<div>')
 
                    .addClass(
            this.renderShell();
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );


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


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


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


             const configurationContainer =
             const titleInput =
                 $('<div>')
                 this.textInput(
                     .addClass(
                    this.state.preloadTitle,
                        'preload-editor-variable-configuration'
                    'Template:Example/Preload'
                     );
                ).attr(
                     'id',
                    'preload-editor-title-input'
                );
 
            titleInput.on(
                'input.preloadEditor',
                () => {
                     this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();


            configurationSection.append(
                    if (
                 configurationContainer
                        this.state.dirty &&
                        this.state.mode === 'new'
                    ) {
                        this.saveDraft();
                    }
                 }
             );
             );


             /*
             const loadButton =
            * CONFIG REVIEW
                this.createButton(
            *
                    'Load',
            * The generated JSON is no longer displayed
                    'preload-editor-button-primary',
            * directly in the page. It can be opened in
                    () =>
            * the custom review dialog instead.
                        this.loadExisting(
            */
                            titleInput.val()
                        )
                );


             const configSection =
             const newButton =
                 this.createSection(
                 this.createButton(
                     'Configuration'
                     'New',
                    '',
                    () => this.startNew()
                 );
                 );


             const configHelp =
             const sampleButton =
                $('<div>')
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );
 
            const reviewConfigButton =
                 this.createButton(
                 this.createButton(
                     'Review config.json',
                     'Load Sample Page',
                     '',
                     '',
                     () =>
                     () => this.loadSamplePage()
                        this.createConfigReviewDialog()
                 );
                 );


             configSection.append(
             loader.append(
                 configHelp,
                 $('<div>')
                reviewConfigButton
                    .addClass(
                        'preload-editor-toolbar'
                    )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
             );
             );


             // Save actions
             this.root.append(loader);


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


             const savePreloadButton =
             this.root.append(
                 this.createButton(
                 this.workspace
                    'Save Preload',
            );
                    '',
 
                     () =>
            /*
                         this.savePreloadOnly()
            * Fixed footer
                );
            *
            * Local draft status, normal status messages,
            * and save actions live here.
            */
            const footer =
                $('<div>')
                     .addClass(
                         'preload-editor-footer'
                    );


             const saveConfigButton =
             this.localDraftStatus =
                 this.createButton(
                 $('<div>')
                    'Save Config',
                     .addClass(
                     '',
                        'preload-editor-local-draft-status is-empty'
                     () =>
                     )
                        this.saveConfigOnly()
                    .text(
                );
                        'No local draft'
                    );


             const saveBothButton =
             this.status =
                 this.createButton(
                 $('<div>')
                    'Save',
                     .addClass(
                     'preload-editor-button-primary',
                        'preload-editor-status'
                     () =>
                     );
                        this.saveAll()
                );


             actions.append(
             footer.append(
                 savePreloadButton,
                 this.localDraftStatus,
                 saveConfigButton,
                 this.status
                saveBothButton
             );
             );


             right.append(
             this.root.append(
    analysisSection,
                footer
    variablesSection,
            );
    configurationSection,
    configSection
);
layout.append(
    left,
    right
);
const saveBar =
    $('<div>')
        .addClass(
            'preload-editor-save-bar'
        );
saveBar.append(
    this.createButton(
        'Save Preload',
        '',
        () => this.savePreloadOnly()
    ),
    this.createButton(
        'Save Config',
        '',
        () => this.saveConfigOnly()
    ),
    this.createButton(
        'Save',
        'preload-editor-button-primary',
        () => this.saveAll()
    )
);
this.root
    .find('.preload-editor-footer')
    .append(saveBar);
this.workspace.append(
    layout
);


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


             this.renderVariables(
             this.renderWelcome();
                variableContainer
        },
            );


             this.renderAnalysis(
        renderWelcome() {
                analysisContainer
             this.workspace.empty();
            );


             this.renderVariableConfiguration(
             const section =
                configurationContainer
                this.createSection('Get started');
            );


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


             this.mountCodeMirror(
             const tips =
                 textarea.get(0)
                 $('<ul>')
            ).catch(
                     .addClass(
                error => {
                         'preload-editor-tips'
                     console.error(
                         'Preload Editor CodeMirror:',
                        error
                     );
                     );


                    this.setStatus(
            [
                        error.message ||
                'Existing preload: loads the preload and its config.json if available.',
                            'Could not initialize CodeMirror.',
                'New preload: starts with the standard Preload Template structure.',
                        'error'
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                     );
            ].forEach(
                text => {
                     $('<li>')
                        .text(text)
                        .appendTo(tips);
                 }
                 }
             );
             );
            section.append(tips);
            this.workspace.append(section);
         },
         },


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


             this.state.preloadContent =
             this.status.removeClass(
                 source;
                 'is-error',
                'is-success',
                'is-warning',
                'is-loading'
            );


             this.markDirty();
             if (type) {
 
                this.status.addClass(
            this.reanalyze();
                    'is-' + type
                );
            }


             this.renderVariablesBySelector();
             this.status.text(
            this.renderVariableConfigurationBySelector();
                 message || ''
            this.renderAnalysisBySelector();
            this.updateEditorTools();
 
            this.saveDraft();
 
            this.setStatus(
                'Variables detected from the current preload.',
                 'success'
             );
             );
         },
         },


         reanalyze() {
         // =========================================================
            const source =
        // Load / create
                this.getEditorContent();
        // =========================================================


             const content =
        async loadExisting(title) {
                 this.extractIncludeonly(source);
             title =
                 String(title || '').trim();


             const analysis =
             if (!title) {
                 this.analyzePreload(content);
                 mw.notify(
                    'Enter a preload page title first.',
                    {
                        type: 'warn'
                    }
                );


            this.state.preloadContent =
                 return;
                 source;
            }


             this.state.variables =
             this.setStatus(
                 analysis.variables;
                'Loading preload...',
                 'loading'
            );


             this.state.conditions =
             try {
                analysis.conditions;
                const page =
                    await this.getPage(title);
 
                if (!page) {
                    const suggestions =
                        await this.findSimilarPreloads(
                            title
                        );
 
                    this.renderMissingPage(
                        title,
                        suggestions
                    );


            this.state.config =
                    this.setStatus(
                this.prepareConfigForVariables(
                        'Preload not found.',
                    this.state.config ||
                         'warning'
                         this.emptyConfig(),
                     );
                     analysis
                );


            this.analysis =
                    return;
                 analysis;
                 }


            const available =
                 await this.loadDefinition(
                 ['PAGE'].concat(
                     page.title,
                     analysis.variables.filter(
                     page.content
                        name =>
                            name !== 'PAGE'
                     )
                 );
                 );


            if (
                 this.setStatus(
                 !available.includes(
                     'Preload loaded.',
                     this.state.selectedVariable
                    'success'
                 )
                 );
             ) {
             } catch (error) {
                 this.state.selectedVariable =
                console.error(
                     available[0] ||
                    'Preload Editor:',
                     'PAGE';
                    error
                );
 
                 this.setStatus(
                     error.message ||
                        'Could not load preload.',
                     'error'
                );
             }
             }
         },
         },


         renderAnalysis(container) {
         async findSimilarPreloads(title) {
             container.empty();
             let query =
 
                 title
            const analysis =
                    .replace(
                 this.analysis ||
                        /\/Preload$/i,
                this.analyzePreload(
                         ''
                    this.extractIncludeonly(
                         this.getEditorContent()
                     )
                     )
                );
                    .trim();


             const variableCount =
             if (!query) {
                 analysis.variables.length;
                 query = title;
            }


             const conditionCount =
             try {
                analysis.conditions.length;
                const results =
                    await this.searchPages(query);


            const configuredCount =
                 return results.filter(
                 Object.keys(
                     result =>
                     this.state.config &&
                        /\/Preload$/i.test(
                    this.state.config.fields
                            result.title
                         ? this.state.config.fields
                         )
                        : {}
                );
                 ).length;
            } catch (error) {
                console.error(
                    'Preload Editor search:',
                    error
                 );


            const summary =
                 return [];
                 $('<div>')
            }
                    .addClass(
        },
                        'preload-editor-analysis-summary'
                    );


            const createMetric =
        renderMissingPage(
                (
            title,
                    value,
            suggestions
                    label
        ) {
                ) =>
            this.workspace.empty();
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                            $('<span>')
            const section =
                                .addClass(
                this.createSection(
                                    'preload-editor-analysis-label'
                    'Preload not found'
                                )
                );
                                .text(label)
                        );


             summary.append(
             $('<p>')
                createMetric(
                 .text(
                    variableCount,
                     'No preload exists at "' +
                    variableCount === 1
                     title +
                        ? 'variable'
                     '".'
                        : 'variables'
                ),
 
                 createMetric(
                     conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),
 
                createMetric(
                     configuredCount,
                     configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                 )
                 )
            );
                .appendTo(section);


             container.append(summary);
             if (suggestions.length) {
                $('<h3>')
                    .text('Similar preloads')
                    .appendTo(section);


            if (
                 const list =
                 analysis.conditionVariables.length
            ) {
                container.append(
                     $('<div>')
                     $('<div>')
                         .addClass(
                         .addClass(
                             'preload-editor-analysis-note'
                             'preload-editor-suggestions'
                         )
                         );
                        .text(
 
                            'Condition variables: ' +
                suggestions.forEach(
                            analysis.conditionVariables.join(', ')
                    result => {
                        )
                        list.append(
                );
                            this.createButton(
            }
                                result.title,
 
                                'preload-editor-suggestion',
            const validation =
                                () =>
                this.validateConfig(
                                    this.loadExisting(
                    this.state.config,
                                        result.title
                    analysis
                                    )
                );
                             )
 
            if (validation.errors.length) {
                const errors =
                    $('<ul>')
                        .addClass(
                             'preload-editor-validation-errors'
                         );
                         );
                validation.errors.forEach(
                    error => {
                        $('<li>')
                            .text(error)
                            .appendTo(errors);
                     }
                     }
                 );
                 );


                 container.append(errors);
                 section.append(list);
             }
             }


             if (validation.warnings.length) {
             section.append(
                 const warnings =
                 this.createButton(
                     $('<ul>')
                     'Create this preload',
                        .addClass(
                    'preload-editor-button-primary',
                            'preload-editor-validation-warnings'
                    () =>
                         );
                         this.startNew(title)
                )
            );


                validation.warnings.forEach(
            this.workspace.append(section);
                    warning => {
        },
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                );


                 container.append(warnings);
        async startNew(title) {
            }
            title =
                 String(title || '').trim();


             if (
             this.state = {
                !validation.errors.length &&
                 preloadTitle: title,
                 !validation.warnings.length
                 preloadSource: '',
            ) {
                preloadContent:
                 container.append(
                    this.defaults.preload,
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },


        renderAnalysisBySelector() {
                config:
            const container =
                    this.emptyConfig(),
                 this.root &&
 
                 this.root.find(
                variables: ['PAGE'],
                    '.preload-editor-analysis'
                conditions: [],
                 );
                 selectedVariable: 'PAGE',
                 deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                 dirtyConfig: true,


            if (
                 localDraftSavedAt: null,
                 container &&
                 localDraftAvailable: false
                 container.length
             };
             ) {
                this.renderAnalysis(container);
            }
        },


        // Variables
            this.saveDraft();
            this.renderEditor();


        renderVariables(container) {
            this.setStatus(
             container.empty();
                'Creating a new preload.',
                'success'
             );
        },


             const analysis =
        async loadSamplePage() {
                 this.analysis ||
             const result =
                this.analyzePreload(
                 await this.createPromptDialog(
                     this.extractIncludeonly(
                     'Load Sample Page',
                        this.getEditorContent()
                    'Enter the title of a normal wiki page to use as the starting point.'
                    )
                 );
                 );


             const variables =
             if (!result) {
                 analysis.variables.slice();
                 return;
            }


             const ordered =
             this.setStatus(
                ['PAGE'];
                 'Loading sample page...',
 
                 'loading'
            variables.forEach(
                 name => {
                    if (
                        name !== 'PAGE' &&
                        !ordered.includes(name)
                    ) {
                        ordered.push(name);
                    }
                 }
             );
             );


             const configuredFields =
             try {
                this.state.config &&
                const page =
                this.state.config.fields
                    await this.getPage(result);
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];


            configuredFields.forEach(
                if (!page) {
                name => {
                     throw new Error(
                     const upper =
                        'Sample page not found: ' +
                         name.toUpperCase();
                         result
                    );
                }


                    if (
                const sample =
                        upper !== 'PAGE' &&
                    this.convertSampleToPreload(
                        !ordered.includes(upper)
                         page.content
                    ) {
                     );
                         ordered.push(upper);
                     }
                }
            );


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


            deleted.forEach(
                     config:
                name => {
                         this.emptyConfig(),
                     const upper =
                         String(name).toUpperCase();


                     if (
                     variables: ['PAGE'],
                        upper !== 'PAGE' &&
                    conditions: [],
                        !ordered.includes(upper)
                    selectedVariable: 'PAGE',
                     ) {
                    deletedVariables: [],
                        ordered.push(upper);
                     mode: 'new',
                     }
                    dirty: true,
                }
                     dirtyPreload: true,
            );
                    dirtyConfig: true,


            const list =
                    localDraftSavedAt: null,
                $('<div>')
                     localDraftAvailable: false
                     .addClass(
                };
                        'preload-editor-variable-list'
                    );


            ordered.forEach(
                this.reanalyze();
                 name => {
                 this.saveDraft();
                    const isSelected =
                this.renderEditor();
                        name ===
                        this.state.selectedVariable;


                     const isUsed =
                this.setStatus(
                        analysis.variables.includes(
                     'Sample page loaded.',
                            name
                    'success'
                         );
                );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                         'Could not load sample page.',
                    'error'
                );
            }
        },
 
        convertSampleToPreload(source) {
            let content =
                String(source || '').trim();


                    const isConfigured =
            const include =
                        !!(
                content.match(
                            this.state.config &&
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                            this.state.config.fields &&
                );
                            this.state.config.fields[name]
                        );


                    const item =
            if (include) {
                        $('<button>')
                content =
                            .attr({
                    include[1].trim();
                                type: 'button',
            }
                                'data-variable':
 
                                    name
            content =
                            })
                content
                            .addClass(
                    .replace(
                                'preload-editor-variable-item'
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                            )
                        ''
                            .toggleClass(
                    )
                                'is-selected',
                    .trim();
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                    $('<span>')
            return (
                        .addClass(
                '<includeonly>\n' +
                            'preload-editor-variable-name'
                content +
                        )
                '\n</includeonly>\n' +
                        .text(name)
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
                        .appendTo(item);
            );
        },


                    if (name === 'PAGE') {
        async loadDefinition(
                        item.append(
            title,
                            $('<span>')
            source
                                .addClass(
        ) {
                                    'preload-editor-badge'
            const content =
                                )
                this.extractIncludeonly(source);
                                .text('AUTOMATIC')
 
                        );
            let config =
                    } else if (!isConfigured) {
                this.emptyConfig();
                        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 configTitle =
                 }
                title.replace(
            );
                    /\/+$/,
                    ''
                ) +
                 '/config.json';


             container.append(list);
             const configPage =
                await this.getPage(configTitle);


             if (!ordered.length) {
             if (configPage) {
                 container.append(
                 try {
                     $('<div>')
                     config =
                         .addClass(
                         JSON.parse(
                             'preload-editor-empty'
                             configPage.content
                         )
                         );
                        .text(
                } catch (error) {
                            'No variables found in the preload.'
                    throw new Error(
                         )
                        'The existing config.json contains invalid JSON: ' +
                 );
                         error.message
                    );
                 }
             }
             }
        },


        renderVariablesBySelector() {
             const analysis =
             const container =
                 this.analyzePreload(content);
                 this.root &&
 
                 this.root.find(
            this.state.deletedVariables = [];
                     '.preload-editor-variables'
 
            config =
                 this.prepareConfigForVariables(
                     config,
                    analysis
                 );
                 );


             if (
             this.state = {
                 container &&
                 preloadTitle: title,
                 container.length
                 preloadSource: source,
            ) {
                preloadContent: source,
                 this.renderVariables(container);
                 config,
            }
        },


        selectVariable(name) {
                 variables:
            name =
                     analysis.variables,
                 String(name || '')
                    .trim()
                     .toUpperCase();


            if (!name) {
                conditions:
                return;
                    analysis.conditions,
            }
 
                selectedVariable:
                    analysis.variables.includes('PAGE')
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),


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


            const configuredUnused =
                mode: 'edit',
                 this.state.config &&
                 dirty: false,
                 this.state.config.fields
                 dirtyPreload: false,
                    ? Object.keys(
                dirtyConfig: false,
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];


            configuredUnused.forEach(
                 localDraftSavedAt: null,
                 variable => {
                 localDraftAvailable: false
                    if (
             };
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                 }
             );


            if (!available.includes(name)) {
             this.clearDraft(title);
                return;
             this.renderEditor();
            }
 
            this.state.selectedVariable =
                name;
 
             this.renderVariablesBySelector();
             this.renderVariableConfigurationBySelector();
         },
         },


         renderVariableConfigurationBySelector() {
         // =========================================================
            const container =
        // Editor
                this.root &&
        // =========================================================
                this.root.find(
                    '.preload-editor-variable-configuration'
                );


            if (
        renderEditor() {
                container &&
            this.destroyEditor();
                container.length
             this.workspace.empty();
            ) {
                this.renderVariableConfiguration(
                    container
                );
             }
        },


        renderVariableConfiguration(container) {
            const layout =
            container.empty();
                $('<div>')
                    .addClass(
                        'preload-editor-layout'
                    );


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


             const name =
             const right =
                 this.state.selectedVariable ||
                 $('<div>')
                'PAGE';
                    .addClass(
                        'preload-editor-right'
                    );


             const fields =
             const editorSection =
                 this.state.config &&
                 this.createSection(
                this.state.config.fields
                     'Preload',
                     ? this.state.config.fields
                     'preload-editor-main-section'
                     : {};
 
            const field =
                fields[name];
 
            if (name === 'PAGE') {
                container.append(
                    this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                 );
                 );


                return;
             const meta =
             }
 
            if (!field) {
                const missing =
                    $('<div>')
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );
 
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor-meta'
                     )
                     );
                    .append(
                        $('<h3>')
                            .text(name),


                        $('<span>')
            $('<strong>')
                            .addClass(
                .text(
                                'preload-editor-badge is-warning'
                    this.state.preloadTitle ||
                            )
                    'New preload'
                            .text(
                )
                                'NOT CONFIGURED'
                .appendTo(meta);
                            )
                    )
                    .appendTo(missing);


                 $('<p>')
            if (
                this.state.mode === 'new'
            ) {
                 $('<span>')
                     .addClass(
                     .addClass(
                         'preload-editor-analysis-note'
                         'preload-editor-badge'
                     )
                     )
                     .text(
                     .text('NEW')
                        'This variable is currently not present in config.json.'
                     .appendTo(meta);
                    )
                     .appendTo(missing);
 
                container.append(missing);
                return;
             }
             }


             container.append(
             editorSection.append(meta);
                 this.createVariableCard(
            editorSection.append(
                    name,
                 this.renderEditorTools()
                    field,
            );
                     analysis
 
            const textarea =
                this.textarea(
                     this.state.preloadContent
                 )
                 )
            );
                    .attr(
        },
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );


        createAutomaticPageCard(field) {
             const editorMount =
             const card =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable preload-editor-variable-automatic'
                         'preload-editor-codemirror-mount'
                     )
                     )
                     .attr(
                     .append(textarea);
                        'data-variable',
 
                        'PAGE'
            editorSection.append(editorMount);
                    );
            left.append(editorSection);
 
            const analysisSection =
                this.createSection('Analysis');


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


             header.append(
             analysisSection.append(
                 $('<h3>').text('PAGE'),
                 analysisContainer
 
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
             );
             );


             card.append(header);
             const variablesSection =
                this.createSection('Variables');


             $('<p>')
             const detectVariablesButton =
                 .addClass(
                 this.createButton(
                     'preload-editor-analysis-note'
                    'Detect variables',
                )
                     'preload-editor-button-primary preload-editor-detect-variables',
                .text(
                     () =>
                     'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                        this.detectVariables()
                )
                .appendTo(card);
 
            const label =
                this.textInput(
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                 );
                 );


             const description =
             const detectHelp =
                 this.textarea(
                 $('<div>')
                    field.description ||
                    'Name of the page.'
                )
                     .addClass(
                     .addClass(
                         'preload-editor-small-textarea'
                         'preload-editor-help preload-editor-detect-variables-help'
                     )
                     )
                     .prop(
                     .text(
                         'disabled',
                         'Refresh the variable list after editing the preload.'
                        true
                     );
                     );


             const type =
             variablesSection.append(
                 this.textInput(
                 $('<div>')
                     field.type || 'page'
                     .addClass(
                ).prop(
                        'preload-editor-variable-detect'
                     'disabled',
                    )
                     true
                    .append(
                );
                        detectVariablesButton,
                        detectHelp
                     )
            );
 
            const variableContainer =
                $('<div>')
                     .addClass(
                        'preload-editor-variables'
                    );


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


             const namespace =
             const configurationSection =
                 this.textInput(
                 this.createSection(
                     field.namespace || 'Main'
                     'Variable configuration'
                ).prop(
                    'disabled',
                    true
                 );
                 );


             const allowNew =
            /*
                 this.checkbox(
            * Import button lives at the top of the
                     field['allow-new'] === true
            * variable configuration section so the
                ).prop(
            * workflow is always easy to find.
                     'disabled',
            */
                     true
             const importDefinitionsButton =
                 this.createButton(
                     'Import definitions',
                     'preload-editor-button-primary preload-editor-import-definitions',
                     () =>
                        this.importVariableDefinitions()
                 );
                 );


             card.append(
             const importHelp =
                this.fieldRow(
                $('<div>')
                    'Label',
                    .addClass(
                     label
                        'preload-editor-help preload-editor-import-definitions-help'
                ),
                    )
                    .text(
                        'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                     );


                 this.fieldRow(
            const importControls =
                    'Description',
                 $('<div>')
                     description
                    .addClass(
                ),
                        'preload-editor-import-definition-controls'
                    )
                    .append(
                        importDefinitionsButton,
                        importHelp
                     );


                this.fieldRow(
            configurationSection.append(
                    'Type',
                importControls
                    type
            );
                ),


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


                this.fieldRow(
            configurationSection.append(
                    'Namespace',
                 configurationContainer
                    namespace
                ),
 
                this.fieldRow(
                    'Allow new page',
                    allowNew
                 )
             );
             );


             return card;
             const configSection =
        },
                this.createSection(
                    'Configuration'
                );


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


             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(name)
                 this.createButton(
            );
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),


            if (
                 this.createButton(
                 !analysis.variables.includes(name)
                     'Save Config',
            ) {
                    '',
                header.append(
                    () =>
                     $('<span>')
                         this.saveConfigOnly()
                        .addClass(
                 ),
                            'preload-editor-badge is-warning'
                        )
                         .text('UNUSED')
                 );
            }


            card.append(header);
                this.createButton(
                    'Save',
                    'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                )
            );


             const label =
             this.root
                 this.textInput(
                 .find('.preload-editor-footer')
                    field.label || ''
                 .append(saveBar);
                 );


             label.on(
             this.workspace.append(
                 'input.preloadEditor',
                 layout
                () => {
            );
                    field.label =
                        label.val();


                    this.markDirty();
            this.reanalyze();
                    this.renderConfigReviewAvailability();
                }
            );


             card.append(
             this.renderVariables(
                this.fieldRow(
                 variableContainer
                    'Label',
                    label
                 )
             );
             );


             const description =
             this.renderAnalysis(
                 this.textarea(
                 analysisContainer
                    field.description || ''
            );
                ).addClass(
 
                    'preload-editor-small-textarea'
            this.renderVariableConfiguration(
                );
                configurationContainer
            );
 
            this.updateEditorTools();
            this.updateLocalDraftIndicator();


             description.on(
             this.mountCodeMirror(
                 'input.preloadEditor',
                 textarea.get(0)
                 () => {
            ).catch(
                     field.description =
                 error => {
                         description.val();
                     console.error(
                        'Preload Editor CodeMirror:',
                         error
                    );


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


            card.append(
        // =========================================================
                this.fieldRow(
        // Variable detection
                    'Description',
        // =========================================================
                    description
                )
            );


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


             const typeSelect =
             const content =
                 this.select(
                 this.extractIncludeonly(
                     types.map(
                     source
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                 );
                 );


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


                     this.markDirty();
            /*
            * If a variable was previously deleted from
            * the configuration, detecting the current
            * preload again should allow it to come back.
            */
            if (
                Array.isArray(
                     this.state.deletedVariables
                )
            ) {
                const detected =
                    new Set(
                        analysis.variables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                    );


                     this.renderVariableConfigurationBySelector();
                this.state.deletedVariables =
                    this.renderConfigReviewAvailability();
                     this.state.deletedVariables
                }
                        .filter(
             );
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                this.state.deletedVariables = [];
            }
 
             this.markDirty();


             card.append(
             this.reanalyze();
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );


             const required =
             this.renderVariablesBySelector();
                this.checkbox(
            this.renderVariableConfigurationBySelector();
                    field.required === true
            this.renderAnalysisBySelector();
                );
            this.updateEditorTools();


             required.on(
             this.saveDraft();
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');


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


             card.append(
        reanalyze() {
                 this.fieldRow(
             const source =
                    'Required',
                 this.getEditorContent();
                    required
 
                 )
            const content =
            );
                 this.extractIncludeonly(source);


             const placeholder =
             const analysis =
                 this.textInput(
                 this.analyzePreload(
                     field.placeholder || ''
                     content
                 );
                 );


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


                    if (value) {
            this.state.variables =
                        field.placeholder =
                analysis.variables;
                            value;
                    } else {
                        delete field.placeholder;
                    }


                    this.markDirty();
            this.state.conditions =
                    this.renderConfigReviewAvailability();
                 analysis.conditions;
                 }
            );


             card.append(
             this.state.config =
                 this.fieldRow(
                 this.prepareConfigForVariables(
                     'Placeholder',
                     this.state.config ||
                     placeholder
                        this.emptyConfig(),
                 )
                     analysis
            );
                 );


             const defaultInput =
            this.analysis =
                 this.textInput(
                analysis;
                     field.default === undefined
 
                        ? ''
             const available =
                        : field.default
                 ['PAGE'].concat(
                     analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                 );
                 );


             defaultInput.on(
             if (
                'input.preloadEditor',
                !available.includes(
                 () => {
                    this.state.selectedVariable
                     const value =
                 )
                        defaultInput.val();
            ) {
                this.state.selectedVariable =
                     available[0] ||
                    'PAGE';
            }
        },


                    if (value) {
        // =========================================================
                        field.default =
        // Analysis
                            value;
        // =========================================================
                    } else {
                        delete field.default;
                    }


                    this.markDirty();
        renderAnalysis(container) {
                    this.renderConfigReviewAvailability();
            container.empty();
                }
            );


             card.append(
             const analysis =
                 this.fieldRow(
                this.analysis ||
                     'Default',
                 this.analyzePreload(
                    defaultInput,
                     this.extractIncludeonly(
                     'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                        this.getEditorContent()
                 )
                     )
             );
                 );
 
             const variableCount =
                analysis.variables.length;


             if (
             const conditionCount =
                field.type === 'textarea'
                 analysis.conditions.length;
            ) {
                 const maxRows =
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );


                 maxRows.on(
            const configuredCount =
                     'input.preloadEditor',
                 Object.keys(
                     () => {
                     this.state.config &&
                         const value =
                     this.state.config.fields
                            parseInt(
                         ? this.state.config.fields
                                maxRows.val(),
                        : {}
                                10
                ).length;
                            );


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


                         this.markDirty();
            const createMetric =
                         this.renderConfigReviewAvailability();
                (
                    }
                    value,
                );
                    label
                ) =>
                    $('<div>')
                         .addClass(
                            'preload-editor-analysis-metric'
                        )
                         .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                card.append(
                            $('<span>')
                    this.fieldRow(
                                .addClass(
                        'Maximum rows',
                                    'preload-editor-analysis-label'
                        maxRows
                                )
                    )
                                .text(label)
                );
                        );
            }


             if (
             summary.append(
                 field.type === 'select' ||
                createMetric(
                 field.type === 'multiselect'
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                 ),
 
                createMetric(
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                 ),
 
                createMetric(
                    configuredCount,
                    configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                )
            );
 
            container.append(summary);
 
            if (
                analysis.conditionVariables.length
             ) {
             ) {
                 this.renderSelectConfiguration(
                 container.append(
                     card,
                     $('<div>')
                    field
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                 );
                 );
             }
             }


             const deleteButton =
             const validation =
                 this.createButton(
                 this.validateConfig(
                     'Delete variable',
                     this.state.config,
                    'preload-editor-button-danger preload-editor-delete-variable',
                    analysis
                    async () => {
                );
                        const confirmed =
                            await this.createConfirmDialog(
                                'Delete variable',
                                'Delete "' +
                                name +
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                                'Delete variable',
                                'Cancel'
                            );


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


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


            card.append(
                 container.append(errors);
                 $('<div>')
             }
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
             );


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


        async deleteVariable(name) {
                validation.warnings.forEach(
            name =
                    warning => {
                String(name || '')
                        $('<li>')
                    .trim()
                            .text(warning)
                    .toUpperCase();
                            .appendTo(warnings);
                    }
                );


            if (
                container.append(warnings);
                !name ||
                name === 'PAGE'
            ) {
                return;
             }
             }


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


             delete this.state.config.fields[name];
        renderAnalysisBySelector() {
             const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );


             if (
             if (
                 !Array.isArray(
                 container &&
                    this.state.deletedVariables
                container.length
                )
             ) {
             ) {
                 this.state.deletedVariables = [];
                 this.renderAnalysis(container);
             }
             }
        },


             if (
        // =========================================================
                 !this.state.deletedVariables.includes(
        // Variables
                     name
        // =========================================================
                )
 
            ) {
        renderVariables(container) {
                this.state.deletedVariables.push(
             container.empty();
                     name
 
            const analysis =
                 this.analysis ||
                this.analyzePreload(
                     this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );
                 );
            }


             this.state.selectedVariable =
             const variables =
                 name;
                 analysis.variables.slice();


             this.markDirty();
             const ordered =
                ['PAGE'];


             this.renderVariablesBySelector();
             variables.forEach(
            this.renderVariableConfigurationBySelector();
                name => {
            this.renderAnalysisBySelector();
                    if (
            this.renderConfigReviewAvailability();
                        name !== 'PAGE' &&
 
                        !ordered.includes(name)
            this.setStatus(
                    ) {
                'Variable "' +
                        ordered.push(name);
                name +
                    }
                '" removed from the configuration.',
                 }
                 'warning'
             );
             );
        },


        renderSelectConfiguration(
             const configuredFields =
            card,
                 this.state.config &&
            field
                this.state.config.fields
        ) {
                    ? Object.keys(
             const source =
                        this.state.config.fields
                 this.textInput(
                     )
                     field.source || '',
                     : [];
                     'category:Example'
                );


             source.on(
             configuredFields.forEach(
                 'input.preloadEditor',
                 name => {
                () => {
                     const upper =
                     const value =
                         name.toUpperCase();
                         source.val();


                     if (value) {
                     if (
                         field.source = value;
                         upper !== 'PAGE' &&
                     } else {
                        !ordered.includes(upper)
                         delete field.source;
                     ) {
                         ordered.push(upper);
                     }
                     }
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             card.append(
             const deleted =
                 this.fieldRow(
                 Array.isArray(
                     'Source',
                     this.state.deletedVariables
                    source,
                    'Currently supported source format: category:Category Name'
                 )
                 )
            );
                    ? this.state.deletedVariables
                    : [];


             const sourcePrefix =
             deleted.forEach(
                this.textInput(
                name => {
                    field['source-prefix'] || ''
                    const upper =
                );
                        String(name).toUpperCase();


            sourcePrefix.on(
                    if (
                'input.preloadEditor',
                        upper !== 'PAGE' &&
                () => {
                         !ordered.includes(upper)
                    const value =
                     ) {
                         sourcePrefix.val();
                         ordered.push(upper);
 
                     if (value) {
                         field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                     }
                     }
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             card.append(
             const list =
                 this.fieldRow(
                 $('<div>')
                    'Source prefix',
                     .addClass(
                     sourcePrefix,
                        'preload-editor-variable-list'
                    'Only source values beginning with this text are included.'
                    );
                )
            );


             const excludeCategory =
             ordered.forEach(
                 this.textInput(
                 name => {
                     field.exclude &&
                     const isSelected =
                    field.exclude.category ||
                        name ===
                    ''
                        this.state.selectedVariable;
                );


            excludeCategory.on(
                     const isUsed =
                'input.preloadEditor',
                         analysis.variables.includes(
                () => {
                            name
                     const value =
                        );
                         excludeCategory.val();


                     if (value) {
                     const isConfigured =
                        field.exclude =
                        !!(
                             Object.assign(
                            this.state.config &&
                                {},
                             this.state.config.fields &&
                                field.exclude || {},
                             this.state.config.fields[name]
                                {
                         );
                                    category: value
                                }
                             );
                    } else if (
                         field.exclude
                    ) {
                        delete field.exclude.category;


                         if (
                    const item =
                             !Object.keys(
                         $('<button>')
                                 field.exclude
                             .attr({
                             ).length
                                type: 'button',
                        ) {
                                 'data-variable':
                             delete field.exclude;
                                    name
                        }
                            })
                    }
                            .addClass(
                                'preload-editor-variable-item'
                             )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                             .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


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


            card.append(
                    if (name === 'PAGE') {
                this.fieldRow(
                        item.append(
                    'Exclude category',
                            $('<span>')
                    excludeCategory
                                .addClass(
                )
                                    'preload-editor-badge'
            );
                                )
 
                                .text('AUTOMATIC')
            card.append(
                        );
                this.createTransformControls(
                    } else if (!isConfigured) {
                     field,
                        item.append(
                    'value',
                            $('<span>')
                    'Value transformation'
                                .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')
                        );
                    }


                this.createTransformControls(
                    list.append(item);
                    field,
                 }
                    'label',
                    'Label transformation'
                 )
             );
             );


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


                                return (
            if (!ordered.length) {
                                    String(
                container.append(
                                        option.value || ''
                    $('<div>')
                                    ) +
                        .addClass(
                                    ' | ' +
                            'preload-editor-empty'
                                    String(
                        )
                                        option.label ||
                        .text(
                                        option.value ||
                             'No variables found in the preload.'
                                        ''
                                    )
                                );
                             }
                         )
                         )
                        .join('\n')
                );
                    : '';
            }
        },


             const options =
        renderVariablesBySelector() {
                 this.textarea(
             const container =
                    optionsValue
                 this.root &&
                 ).addClass(
                 this.root.find(
                     'preload-editor-small-textarea'
                     '.preload-editor-variables'
                 );
                 );


             options.on(
             if (
                 'input.preloadEditor',
                 container &&
                 () => {
                 container.length
                    const lines =
            ) {
                        options
                this.renderVariables(container);
                            .val()
            }
                            .split('\n')
        },
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                    if (!lines.length) {
        selectVariable(name) {
                        delete field.options;
            name =
                     } else {
                String(name || '')
                        field.options =
                     .trim()
                            lines.map(
                    .toUpperCase();
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );


                                    if (
            if (!name) {
                                        parts.length ===
                return;
                                        1
            }
                                    ) {
                                        return parts[0];
                                    }


                                    return {
            const available =
                                        value:
                ['PAGE'].concat(
                                            parts[0],
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );


                                        label:
            const configuredUnused =
                                            parts
                this.state.config &&
                                                .slice(1)
                this.state.config.fields
                                                .join(
                    ? Object.keys(
                                                    ' | '
                        this.state.config.fields
                                                )
                    )
                                    };
                        .map(
                                }
                            variable =>
                            );
                                variable.toUpperCase()
                        )
                    : [];
 
            configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                     }
                     }
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             card.append(
             if (!available.includes(name)) {
                 this.fieldRow(
                 return;
                    'Manual options',
            }
                    options,
 
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
            this.state.selectedVariable =
                 )
                 name;
             );
 
            this.renderVariablesBySelector();
             this.renderVariableConfigurationBySelector();
         },
         },


         createTransformControls(
         renderVariableConfigurationBySelector() {
             field,
             const container =
             property,
                this.root &&
            title
                this.root.find(
         ) {
                    '.preload-editor-variable-configuration'
             const wrapper =
                );
                 $('<div>')
 
                     .addClass(
            if (
                         'preload-editor-transform'
                container &&
                     );
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
             }
        },
 
         renderVariableConfiguration(container) {
            container.empty();
 
             const analysis =
                 this.analysis ||
                this.analyzePreload(
                     this.extractIncludeonly(
                         this.getEditorContent()
                     )
                );


             $('<h4>')
             const name =
                 .text(title)
                 this.state.selectedVariable ||
                 .appendTo(wrapper);
                 'PAGE';


             const existing =
             const fields =
                 field[property] &&
                 this.state.config &&
                 typeof field[property] === 'object'
                 this.state.config.fields
                     ? field[property]
                     ? this.state.config.fields
                     : {};
                     : {};


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


             const prefix =
             if (name === 'PAGE') {
                 this.textInput(
                 container.append(
                     existing.prefix || ''
                     this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                 );
                 );


            const suffix =
                 return;
                 this.textInput(
            }
                    existing.suffix || ''
                );


             const from =
             if (!field) {
                this.textInput(
                const missing =
                    existing.from || ''
                    $('<div>')
                );
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );


            const to =
                this.textInput(
                    existing.to || ''
                );
            const controls =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-transform-controls'
                         'preload-editor-variable-header'
                     );
                     )
                    .append(
                        $('<h3>')
                            .text(name),


            const prefixRow =
                        $('<span>')
                this.fieldRow(
                            .addClass(
                    'Prefix',
                                'preload-editor-badge is-warning'
                     prefix
                            )
                );
                            .text(
                                'NOT CONFIGURED'
                            )
                     )
                    .appendTo(missing);


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


            const fromRow =
                 container.append(missing);
                 this.fieldRow(
                 return;
                    'From',
            }
                    from
                 );


             const toRow =
             container.append(
                 this.fieldRow(
                 this.createVariableCard(
                     'To',
                     name,
                     to
                     field,
                 );
                    analysis
                 )
            );
        },


             const renderInputs =
        createAutomaticPageCard(field) {
                 () => {
             const card =
                     const type =
                 $('<div>')
                         transform.val();
                     .addClass(
 
                         'preload-editor-variable preload-editor-variable-automatic'
                     prefixRow.toggle(
                    )
                         type === 'remove-prefix'
                     .attr(
                         'data-variable',
                        'PAGE'
                     );
                     );


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


                     fromRow.toggle(
            header.append(
                         type === 'replace'
                $('<h3>').text('PAGE'),
                     );
 
                $('<span>')
                     .addClass(
                         'preload-editor-badge'
                     )
                    .text('AUTOMATIC')
            );


                    toRow.toggle(
            card.append(header);
                        type === 'replace'
                    );
                };


             const update =
             $('<p>')
                 () => {
                 .addClass(
                     const type =
                    'preload-editor-analysis-note'
                        transform.val();
                )
                .text(
                     'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);


                     let object = null;
            const label =
                this.textInput(
                     field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                );


                    if (
            const description =
                        type === 'remove-prefix' &&
                this.textarea(
                        prefix.val()
                     field.description ||
                     ) {
                    'Name of the page.'
                        object = {
                )
                            transform: type,
                     .addClass(
                            prefix:
                         'preload-editor-small-textarea'
                                prefix.val()
                    )
                        };
                     .prop(
                     } else if (
                         'disabled',
                         type === 'remove-suffix' &&
                         true
                        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) {
            const type =
                        field[property] = object;
                this.textInput(
                     } else {
                     field.type || 'page'
                        delete field[property];
                ).prop(
                    }
                    'disabled',
                     true
                );


                    this.markDirty();
            const required =
                     this.renderConfigReviewAvailability();
                this.checkbox(
                 };
                     field.required !== false
                ).prop(
                    'disabled',
                    true
                 );


             transform.on(
             const namespace =
                'change.preloadEditor',
                this.textInput(
                 () => {
                    field.namespace || 'Main'
                     update();
                 ).prop(
                     renderInputs();
                     'disabled',
                 }
                     true
            );
                 );


             [
             const allowNew =
                prefix,
                 this.checkbox(
                suffix,
                    field['allow-new'] === true
                 from,
                ).prop(
                to
                    'disabled',
            ].forEach(
                     true
                input => {
                 );
                    input.on(
                        'input.preloadEditor',
                        update
                     );
                 }
            );


             controls.append(
             card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Transformation',
                     'Label',
                     transform
                     label
                 ),
                 ),


                 prefixRow,
                 this.fieldRow(
                suffixRow,
                    'Description',
                fromRow,
                    description
                 toRow
                 ),
            );


            renderInputs();
                this.fieldRow(
                    'Type',
                    type
                ),


            wrapper.append(controls);
                this.fieldRow(
                    'Required',
                    required
                ),


            return wrapper;
                this.fieldRow(
        },
                    'Namespace',
                    namespace
                ),


        // Config output
                this.fieldRow(
                    'Allow new page',
                    allowNew
                )
            );


        getCleanConfig() {
             return card;
             const config =
        },
                JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );


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


             const orderedFields = {};
             const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );


             orderedFields.PAGE =
             header.append(
                 this.getAutomaticPageField();
                 $('<h3>').text(name)
            );


             Object.keys(fields)
             if (
                 .filter(
                !analysis.variables.includes(name)
                     name =>
            ) {
                         name.toUpperCase() !== 'PAGE'
                 header.append(
                )
                     $('<span>')
                .forEach(
                         .addClass(
                    name => {
                            'preload-editor-badge is-warning'
                        orderedFields[name] =
                        )
                            fields[name];
                        .text('UNUSED')
                    }
                 );
                 );
            }


             config.fields =
             card.append(header);
                 orderedFields;
 
            const label =
                 this.textInput(
                    field.label || ''
                );
 
            label.on(
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();


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


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


        /*
            const description =
        * Kept as a compatibility helper in case CSS or
                this.textarea(
        * another part of the gadget expects the method.
                    field.description || ''
        * There is no longer a permanently rendered
                ).addClass(
        * config preview.
                     'preload-editor-small-textarea'
        */
        renderConfigPreview(container) {
            if (container) {
                container.text(
                     this.getConfigJSON()
                 );
                 );
            }
        },


        renderConfigPreviewBySelector() {
            description.on(
            /*
                'input.preloadEditor',
            * The old generated configuration <pre> no
                () => {
            * longer exists in the editor UI.
                    field.description =
            *
                        description.val();
            * Keep this method so existing calls do not
            * break.
            */
            this.renderAnalysisBySelector();
        },


        renderConfigReviewAvailability() {
                    this.markDirty();
            /*
                    this.renderConfigReviewAvailability();
            * The config is generated on demand when the
                }
            * Review config.json button is pressed.
            );
            */
            this.renderAnalysisBySelector();
        },


        // Dirty state
            card.append(
                this.fieldRow(
                    'Description',
                    description
                )
            );


        updateDirtyState() {
             const types = [
             this.state.dirty =
                ['text', 'Text'],
                 !!(
                ['textarea', 'Textarea'],
                    this.state.dirtyPreload ||
                ['number', 'Number'],
                    this.state.dirtyConfig
                ['boolean', 'Boolean'],
                 );
                ['select', 'Select'],
        },
                 ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                 ['date', 'Date'],
                ['file', 'File']
            ];


        markPreloadDirty() {
             const typeSelect =
             this.state.dirtyPreload = true;
                this.select(
            this.updateDirtyState();
                    types.map(
            this.saveDraft();
                        ([value, label]) => ({
        },
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                );


        markConfigDirty() {
            typeSelect.on(
            this.state.dirtyConfig = true;
                'change.preloadEditor',
            this.updateDirtyState();
                () => {
            this.saveDraft();
                    field.type =
        },
                        typeSelect.val();


        markDirty() {
                    this.markDirty();
            /*
            * Existing configuration controls call
            * markDirty(), so keep it conservative:
            * both parts are considered locally dirty.
            */
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },


        // Save
                    this.renderVariableConfigurationBySelector();
                    this.renderConfigReviewAvailability();
                }
            );


        async savePreloadOnly() {
            card.append(
            let title =
                 this.fieldRow(
                 String(
                     'Type',
                     this.state.preloadTitle || ''
                    typeSelect
                 ).trim();
                 )
            );


             if (!title) {
             const required =
                const result =
                this.checkbox(
                    await this.createPromptDialog(
                    field.required === true
                        'Preload title',
                );
                         'Enter the full title for the preload.'
 
                    );
            required.on(
                'change.preloadEditor',
                () => {
                    field.required =
                         required.prop('checked');


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


                title = result;
            card.append(
                 this.state.preloadTitle =
                 this.fieldRow(
                     title;
                    'Required',
             }
                     required
                )
             );


            this.state.preloadContent =
             const placeholder =
                this.getEditorContent();
                 this.textInput(
 
                    field.placeholder || ''
             const validation =
                 this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                 );
                 );


                 this.saveDraft();
            placeholder.on(
                return;
                 'input.preloadEditor',
            }
                () => {
                    const value =
                        placeholder.val();


            const confirmed =
                    if (value) {
                await this.confirmSave(
                        field.placeholder =
                    'preload',
                            value;
                     title
                     } else {
                );
                        delete field.placeholder;
                    }


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


             this.setStatus(
             card.append(
                'Saving preload...',
                this.fieldRow(
                 'loading'
                    'Placeholder',
                    placeholder
                 )
             );
             );


             try {
             const defaultInput =
                const exists =
                 this.textInput(
                    await this.pageExists(title);
                     field.default === undefined
 
                         ? ''
                 await this.savePage(
                         : field.default
                     title,
                    this.state.preloadContent,
                    exists
                         ? 'Updated preload with Preload Editor'
                         : 'Created preload with Preload Editor',
                    !exists
                 );
                 );


                 this.state.mode = 'edit';
            defaultInput.on(
                 this.state.preloadTitle = title;
                 'input.preloadEditor',
                this.state.dirtyPreload = false;
                 () => {
                    const value =
                        defaultInput.val();


                this.updateDirtyState();
                    if (value) {
                        field.default =
                            value;
                    } else {
                        delete field.default;
                    }


                if (!this.state.dirty) {
                     this.markDirty();
                     this.clearDraft(title);
                     this.renderConfigReviewAvailability();
                } else {
                     this.saveDraft();
                 }
                 }
            );


                 this.setStatus(
            card.append(
                     this.state.dirtyConfig
                 this.fieldRow(
                        ? 'Preload saved. Config still has unsaved changes.'
                     'Default',
                        : 'Preload saved successfully.',
                    defaultInput,
                     'success'
                     'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                 );
                 )
            );


                mw.notify(
            if (
                    this.state.dirtyConfig
                field.type === 'textarea'
                        ? 'Preload saved. Config still has unsaved changes.'
            ) {
                        : 'Preload saved.',
                const maxRows =
                     {
                     this.textInput(
                         type: 'success'
                         field.maxRows || ''
                     }
                     ).attr(
                );
                        'type',
            } catch (error) {
                        'number'
                console.error(
                     );
                    'Preload Editor save:',
                     error
                );


                 this.saveDraft();
                 maxRows.on(
                    'input.preloadEditor',
                    () => {
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );


                this.setStatus(
                        if (
                    error.message ||
                            Number.isFinite(value) &&
                         'Could not save preload.',
                            value > 0
                    'error'
                         ) {
                );
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }


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


        async saveConfigOnly() {
                 card.append(
            let title =
                     this.fieldRow(
                 String(
                         'Maximum rows',
                    this.state.preloadTitle || ''
                         maxRows
                ).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 =
             if (
                 this.getEditorContent();
                 field.type === 'select' ||
 
                 field.type === 'multiselect'
            this.reanalyze();
             ) {
 
                 this.renderSelectConfiguration(
            const validation =
                     card,
                 this.validateBeforeSave();
                    field
 
             if (validation.errors.length) {
                 this.showValidationErrors(
                     validation
                 );
                 );
                this.saveDraft();
                return;
             }
             }


             const confirmed =
             if (
                 await this.confirmSave(
                field.type === 'file'
                     'config',
            ) {
                     title
                 this.renderFileConfiguration(
                     card,
                     field
                 );
                 );
            if (!confirmed) {
                return;
             }
             }


             const configTitle =
             const deleteButton =
                 title.replace(
                 this.createButton(
                     /\/+$/,
                     'Delete variable',
                     ''
                     'preload-editor-button-danger preload-editor-delete-variable',
                ) +
                    async () => {
                '/config.json';
                        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.setStatus(
                        if (!confirmed) {
                'Saving config...',
                            return;
                'loading'
                        }
            );


            try {
                        this.deleteVariable(name);
                const configExists =
                    }
                    await this.pageExists(
                );
                        configTitle
                    );


                await this.savePage(
            card.append(
                    configTitle,
                $('<div>')
                     this.getConfigJSON(),
                     .addClass(
                    configExists
                         'preload-editor-variable-delete'
                         ? 'Updated preload config with Preload Editor'
                    )
                        : 'Created preload config with Preload Editor',
                     .append(deleteButton)
                     !configExists
            );
                );
 
            return card;
        },


                 this.state.mode = 'edit';
        async deleteVariable(name) {
                this.state.preloadTitle = title;
            name =
                this.state.dirtyConfig = false;
                 String(name || '')
                    .trim()
                    .toUpperCase();


                 this.updateDirtyState();
            if (
                !name ||
                 name === 'PAGE'
            ) {
                return;
            }


                if (!this.state.dirty) {
            if (
                    this.clearDraft(title);
                !this.state.config ||
                 } else {
                !this.state.config.fields
                    this.saveDraft();
            ) {
                }
                 return;
            }


                this.setStatus(
            delete this.state.config.fields[name];
                    this.state.dirtyPreload
                        ? 'Config saved. Preload still has unsaved changes.'
                        : 'Config saved successfully.',
                    'success'
                );


                 mw.notify(
            if (
                     this.state.dirtyPreload
                 !Array.isArray(
                        ? 'Config saved. Preload still has unsaved changes.'
                     this.state.deletedVariables
                        : 'Config saved.',
                 )
                    {
             ) {
                        type: 'success'
                 this.state.deletedVariables = [];
                    }
            }
                 );
             } catch (error) {
                 console.error(
                    'Preload Editor config save:',
                    error
                );


                this.saveDraft();
            if (
 
                 !this.state.deletedVariables.includes(
                 this.setStatus(
                     name
                    error.message ||
                 )
                        'Could not save config.',
            ) {
                     'error'
                 this.state.deletedVariables.push(
                 );
                     name
 
                 mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                     }
                 );
                 );
             }
             }
        },


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


             if (!title) {
             this.markDirty();
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );


                if (!result) {
            this.renderVariablesBySelector();
                    return;
            this.renderVariableConfigurationBySelector();
                }
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();


                 title = result;
            this.setStatus(
                 this.state.preloadTitle =
                 'Variable "' +
                    title;
                name +
            }
                 '" removed from the configuration.',
                'warning'
            );
        },


            this.state.preloadContent =
        // =========================================================
                this.getEditorContent();
        // Select configuration
        // =========================================================


             this.reanalyze();
        renderSelectConfiguration(
 
            card,
             const validation =
             field
                 this.validateBeforeSave();
        ) {
 
             const source =
            if (validation.errors.length) {
                 this.textInput(
                this.showValidationErrors(
                    field.source || '',
                     validation
                     'category:Example'
                 );
                 );


                 this.saveDraft();
            source.on(
                return;
                 'input.preloadEditor',
            }
                () => {
                    const value =
                        source.val();


            const confirmed =
                    if (value) {
                await this.confirmSave(
                        field.source = value;
                     'both',
                     } else {
                     title
                        delete field.source;
                );
                     }


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


             const configTitle =
             card.append(
                 title.replace(
                 this.fieldRow(
                     /\/+$/,
                     'Source',
                     ''
                    source,
                 ) +
                     'Currently supported source format: category:Category Name'
                '/config.json';
                 )
 
            this.setStatus(
                'Saving preload and config...',
                'loading'
             );
             );


             try {
             const sourcePrefix =
                const preloadExists =
                this.textInput(
                    await this.pageExists(title);
                    field['source-prefix'] || ''
                );


                 await this.savePage(
            sourcePrefix.on(
                     title,
                 'input.preloadEditor',
                     this.state.preloadContent,
                () => {
                     preloadExists
                    const value =
                        ? 'Updated preload with Preload Editor'
                        sourcePrefix.val();
                        : 'Created preload with Preload Editor',
 
                    !preloadExists
                     if (value) {
                        field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                    }
 
                     this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source prefix',
                     sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );
 
            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                 );
                 );


                 const configExists =
            excludeCategory.on(
                     await this.pageExists(
                'input.preloadEditor',
                         configTitle
                () => {
                     );
                    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(
                 await this.savePage(
                     configTitle,
                    title,
                     this.getConfigJSON(),
                    this.state.preloadContent,
                     configExists
                    exists
                         ? 'Updated preload config with Preload Editor'
                        ? 'Updated preload with Preload Editor'
                         : 'Created preload config with Preload Editor',
                        : 'Created preload with Preload Editor',
                     !configExists
                    !exists
                 );
                );
 
 
                 this.state.mode = 'edit';
                this.state.mode = 'edit';
                 this.state.dirtyPreload = false;
                this.state.preloadTitle = title;
                 this.state.dirtyConfig = false;
                this.state.dirtyPreload = false;
                 this.state.dirty = false;
 
                 this.state.preloadTitle = title;
                this.updateDirtyState();
 
 
                 this.clearDraft(title);
                if (!this.state.dirty) {
 
                    this.clearDraft(title);
                 this.setStatus(
                } else {
                     'Preload and config saved successfully.',
                    this.saveDraft();
                     'success'
                }
                 );
 
 
                this.setStatus(
                 mw.notify(
                    this.state.dirtyConfig
                     'Preload and config saved.',
                        ? 'Preload saved. Config still has unsaved changes.'
                     {
                        : 'Preload saved successfully.',
                         type: 'success'
                    'success'
                     }
                );
                 );
 
             } catch (error) {
                mw.notify(
                 console.error(
                    this.state.dirtyConfig
                     'Preload Editor save:',
                        ? 'Preload saved. Config still has unsaved changes.'
                     error
                        : 'Preload saved.',
                 );
                    {
 
                        type: 'success'
                 this.saveDraft();
                    }
                );
            } 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.setStatus(
        // =========================================================
                    error.message ||
        // Validation
                        'Could not save preload/config.',
         // =========================================================
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
         },


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


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