MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

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


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


         state: {
         state: {
Line 33: Line 33:
         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'
         },
         },


Line 47: Line 45:
         getDraftStorage() {
         getDraftStorage() {
             try {
             try {
                 const raw =
                 const raw = window.localStorage.getItem(this.draftStorageKey);
                    window.localStorage.getItem(
                        this.draftStorageKey
                    );


                 if (!raw) {
                 if (!raw) {
Line 59: 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 73: 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 83: 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 97: 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 114: 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 138: 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: 3,
                 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(
                        this.state.selectedVariable ||
                        'PAGE'
                    ),
 
                deletedVariables:
                    Array.isArray(
                        this.state.deletedVariables
                    )
                        ? this.state.deletedVariables.slice()
                        : [],
 
                mode:
                    this.state.mode ||
                    'edit',
 
                dirty:
                    !!this.state.dirty,
 
                dirtyPreload:
                    !!this.state.dirtyPreload,
 
                dirtyConfig:
                    !!this.state.dirtyConfig,
 
                savedAt:
                    Date.now()
            };
        },
 
        updateLocalDraftStatus(
            message,
            type
        ) {
            if (!this.localDraftStatus) {
                return;
            }
 
             this.localDraftStatus.removeClass(
                 'is-saved',
                 'is-saved',
                 'is-warning',
                 'is-warning',
Line 237: Line 153:


             if (type) {
             if (type) {
                 this.localDraftStatus.addClass(
                 this.localDraftStatus.addClass('is-' + type);
                    'is-' + type
                );
             }
             }


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


Line 253: Line 165:


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


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


                 this.updateLocalDraftStatus(
                 this.updateLocalDraftStatus(
                     time
                     time ? 'Saved locally at ' + time : 'Saved locally',
                        ? 'Saved locally at ' + time
                        : 'Saved locally',
                     'saved'
                     'saved'
                 );
                 );
Line 291: Line 191:
             }
             }


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


Line 302: Line 199:
             }
             }


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


            storage.drafts[id] = snapshot;
             storage.active = id;
             storage.active = id;


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


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


Line 345: Line 221:


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


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


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


             this.setDraftStorage(
             this.setDraftStorage(storage);
                storage
            );
 
            this.state.localDraftSavedAt =
                null;


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


             this.updateLocalDraftIndicator();
             this.updateLocalDraftIndicator();
Line 378: Line 241:


         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 408: 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 449: 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 =
                String(
                    draft.preloadTitle || ''
                ).trim();
 
             const displayTitle =
                title ||
                'an untitled preload';


             const savedAt =
             const savedAt = draft.savedAt
                draft.savedAt
                ? new Date(draft.savedAt).toLocaleString()
                    ? 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 502: Line 314:
             }
             }


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


             if (
             if (
Line 511: 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 532: Line 338:


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


                 variables:
                 variables: Array.isArray(draft.variables)
                    Array.isArray(
                     ? draft.variables.slice()
                        draft.variables
                    : [],
                     )
                        ? draft.variables.slice()
                        : [],


                 conditions:
                 conditions: Array.isArray(draft.conditions)
                    Array.isArray(
                     ? draft.conditions.slice()
                        draft.conditions
                    : [],
                     )
                        ? draft.conditions.slice()
                        : [],


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


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


                 dirty:
                 mode: draft.mode || 'edit',
                    hasDirtyFlags
                        ? !!(
                            draft.dirtyPreload ||
                            draft.dirtyConfig
                        )
                        : true,


                 dirtyPreload:
                 dirty: hasDirtyFlags
                     hasDirtyFlags
                     ? !!(draft.dirtyPreload || draft.dirtyConfig)
                        ? !!draft.dirtyPreload
                    : true,
                        : true,


                 dirtyConfig:
                 dirtyPreload: hasDirtyFlags
                     hasDirtyFlags
                     ? !!draft.dirtyPreload
                        ? !!draft.dirtyConfig
                    : true,
                        : true,


                 localDraftSavedAt:
                 dirtyConfig: hasDirtyFlags
                     Number(
                     ? !!draft.dirtyConfig
                        draft.savedAt
                     : true,
                     ) || null,


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


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


Line 626: Line 386:
             );
             );


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


             return true;
             return true;
Line 641: Line 398:


         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 669: 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 685: 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 702: 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 722: 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'
            });
        },
 
         /*
        * Save config.json and make sure its content model
        * is JSON.
        *
        * New page:
        *  create directly with contentmodel=json.
        *
        * Existing page:
        *  if not already JSON, change its model first,
        *  then save the JSON normally.
        */
        async saveConfigPage(title, content, summary) {
            const page = await this.getPage(title);
 
            if (!page) {
                return this.savePage(
                    title,
                    content,
                    summary,
                    true,
                    'json'
                );
            }


        extractIncludeonly(source) {
            if (String(page.contentmodel || '').toLowerCase() !== 'json') {
            const match =
                await this.changeContentModel(
                String(source || '').match(
                     title,
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                    'json',
                    'Changed preload config content model to JSON'
                 );
                 );
            }


             return match
             return this.savePage(
                 ? match[1].trim()
                title,
                 : String(source || '').trim();
                content,
                 summary,
                 false
            );
         },
         },


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


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


                if (!variables.includes(name)) {
            if (/\/config\.json$/i.test(title)) {
                    variables.push(name);
                return title;
                }
             }
             }


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


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


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


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


             return conditions;
             const result = {};
        },


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


            this.findConditions(content).forEach(
                 if (!upper || upper === 'PAGE') {
                 condition => {
                    return;
                    if (
                }
                        condition.type !== 'if' &&
                        condition.type !== 'elseif'
                    ) {
                        return;
                    }


                     const matches =
                if (
                        condition.expression.match(
                     !field ||
                            /[A-Za-z0-9_-]+/g
                    typeof field !== 'object' ||
                        ) || [];
                    Array.isArray(field)
                ) {
                    return;
                }


                    matches.forEach(
                const clone = this.cloneConfigField(field);
                        name => {
                            name =
                                name.toUpperCase();


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


             return variables;
                result[upper] = clone;
            });
 
             return result;
         },
         },


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


                 conditions:
                 const overlay = $('<div>')
                     this.findConditions(content),
                     .addClass(
                        'preload-editor-prompt-overlay preload-editor-import-overlay'
                    );


                 conditionVariables:
                 const box = $('<div>')
                     this.findConditionVariables(
                     .addClass(
                         content
                         'preload-editor-prompt preload-editor-import-dialog'
                    );
 
                $('<h2>')
                    .text('Import variable definitions')
                    .appendTo(box);
 
                $('<p>')
                    .text(
                        'Choose which variable definitions to import from "' +
                        sourceTitle +
                        '". Existing local definitions can be replaced.'
                     )
                     )
            };
                    .appendTo(box);
        },
 
                if (!names.length) {
                    $('<div>')
                        .addClass(
                            'preload-editor-empty preload-editor-import-empty'
                        )
                        .text(
                            'This config.json does not contain any importable variable definitions.'
                        )
                        .appendTo(box);
 
                    const emptyButtons = $('<div>')
                        .addClass('preload-editor-prompt-buttons');
 
                    const close = this.createButton(
                        'Close',
                        'preload-editor-button-primary',
                        () => {
                            overlay.remove();
                            resolve(null);
                        }
                    );


        // =========================================================
                    emptyButtons.append(close);
        // Config
                    box.append(emptyButtons);
        // =========================================================
                    overlay.append(box);


        getAutomaticPageField() {
                    $(document.body).append(overlay);
            return {
                label: 'Page Name',
                description: 'Name of the page.',
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


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


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


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


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


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


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


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


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


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


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


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


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


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


            const deleted =
                    const label = field && field.label
                new Set(
                         ? String(field.label)
                    Array.isArray(
                         : this.humanizeName(name);
                         this.state.deletedVariables
                    )
                         ? this.state.deletedVariables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                        : []
                );


            const fields = {};
                    const row = $('<label>')
                        .addClass('preload-editor-import-row')
                        .attr('data-variable', name)
                        .attr(
                            'data-search',
                            (name + ' ' + label + ' ' + type).toLowerCase()
                        );


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


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


                     fields[name] =
                     const header = $('<span>')
                         existing[name] ||
                         .addClass('preload-editor-import-header');
                        this.createDefaultField(
                            name,
                            analysis
                        );
                }
            );


            Object.keys(existing).forEach(
                    $('<strong>')
                name => {
                        .text(name)
                    const upper =
                         .appendTo(header);
                         name.toUpperCase();


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


            config.fields = fields;
                    const meta = $('<span>')
                        .addClass('preload-editor-import-meta');


            return config;
                    $('<span>')
        },
                        .text(label)
                        .appendTo(meta);
 
                    const status = $('<span>')
                        .addClass('preload-editor-import-status')
                        .toggleClass('is-existing', existing)
                        .toggleClass('is-new', !existing)
                        .text(existing ? 'REPLACE EXISTING' : 'NEW');
 
                    content.append(header, meta, status);
                    row.append(checkbox, content);
                    list.append(row);
                });
 
                box.append(list);
 
                const summary = $('<div>')
                    .addClass('preload-editor-import-summary');
 
                const updateSummary = () => {
                    const selected = list.find(
                        'input[type="checkbox"]:checked'
                    ).length;
 
                    const existingSelected = list
                        .find('input[type="checkbox"]:checked')
                        .filter(function () {
                            const name = $(this).attr(
                                'data-import-variable'
                            );
 
                            return !!localFields[name];
                        }).length;
 
                    let text =
                        selected +
                        ' ' +
                        (selected === 1 ? 'variable' : 'variables') +
                        ' selected.';
 
                    if (existingSelected) {
                        text +=
                            ' ' +
                            existingSelected +
                            ' existing ' +
                            (existingSelected === 1
                                ? 'definition'
                                : 'definitions') +
                            ' will be replaced.';
                    }


        validateConfig(
                    summary.text(text);
            config,
            analysis
        ) {
            const errors = [];
            const warnings = [];


            if (
                    importButton.prop('disabled', selected === 0);
                !config ||
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                return {
                    valid: false,
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                 };
                 };
            }


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


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


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


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


            Object.entries(
                 const importButton = this.createButton(
                 config.fields
                    'Import selected',
            ).forEach(
                     'preload-editor-button-primary',
                ([name, field]) => {
                    () => {
                     if (
                         const selected = [];
                        !field ||
                        typeof field !== 'object' ||
                        Array.isArray(field)
                    ) {
                         errors.push(
                            'Field "' +
                            name +
                            '" must be an object.'
                        );


                         return;
                         list
                            .find('input[type="checkbox"]:checked')
                            .each(function () {
                                selected.push(
                                    String(
                                        $(this).attr(
                                            'data-import-variable'
                                        )
                                    )
                                );
                            });
 
                        overlay.remove();
                        resolve(selected);
                     }
                     }
                );
                buttons.append(cancel, importButton);
                box.append(summary, buttons);
                overlay.append(box);
                $(document.body).append(overlay);
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');
                updateSummary();
                search.trigger('focus');


                     if (!field.type) {
                const close = event => {
                         warnings.push(
                     if (event.key === 'Escape') {
                            'Field "' +
                         cancel.trigger('click');
                            name +
                            '" has no type.'
                        );
                     }
                     }
                };


                    if (
                overlay.on(
                        (
                    'keydown.preloadEditor',
                            field.type === 'select' ||
                    close
                            field.type === 'multiselect'
                );
                        ) &&
 
                        !field.source &&
                overlay.on(
                        !Array.isArray(field.options)
                    'click.preloadEditor',
                     ) {
                     event => {
                         warnings.push(
                         if (event.target === overlay.get(0)) {
                             'Field "' +
                             cancel.trigger('click');
                            name +
                         }
                            '" is a ' +
                            field.type +
                            ' without a source or manual options.'
                         );
                     }
                     }
                 }
                 );
            );
             });
 
            return {
                valid:
                    !errors.length,
                errors,
                warnings
             };
         },
         },


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


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


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


                case 'remove-suffix':
            try {
                    return suffix
                const page = await this.getPage(configTitle);
                        ? {
                            transform,
                            suffix
                        }
                        : null;


                 case 'replace':
                 if (!page) {
                     return from === ''
                     throw new Error(
                         ? null
                        'No config.json was found at "' +
                         : {
                         configTitle +
                            transform,
                         '".'
                            from,
                    );
                            to: to || ''
                }
                        };


                 default:
                 let sourceConfig;
                    return null;
            }
        },


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


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


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


            $('<h2>')
                 const fields = this.getImportableFields(sourceConfig);
                .addClass(
                    'preload-editor-section-title'
                )
                .text(title)
                 .appendTo(section);


            return section;
                const selected =
        },
                    await this.createImportDefinitionsDialog(
                        configTitle,
                        fields
                    );


        createButton(
                if (selected === null) {
            label,
                     this.setStatus(
            className,
                         'Variable import cancelled.',
            callback
                         'warning'
        ) {
                     );
            const button =
                $('<button>')
                     .attr(
                         'type',
                         'button'
                     )
                    .addClass(
                        'preload-editor-button'
                    )
                    .text(label);


            if (className) {
                    return;
                 button.addClass(className);
                 }
            }


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


            return button;
                    return;
        },
                }
 
                if (!this.state.config) {
                    this.state.config = this.emptyConfig();
                }


        fieldRow(
                if (!this.state.config.fields) {
            label,
                    this.state.config.fields = {};
            input,
                 }
            description
        ) {
            const row =
                 $('<div>')
                    .addClass(
                        'preload-editor-field'
                    );


            $('<label>')
                 const imported = [];
                .addClass(
                 const replaced = [];
                    'preload-editor-label'
                )
                 .text(label)
                 .appendTo(row);


            if (description) {
                 selected.forEach(name => {
                 $('<div>')
                     if (name === 'PAGE') {
                     .addClass(
                        return;
                        'preload-editor-help'
                     }
                    )
                    .text(description)
                     .appendTo(row);
            }


            row.append(input);
                    const field = fields[name];


            return row;
                    if (!field) {
        },
                        return;
                    }


        textInput(
                    if (this.state.config.fields[name]) {
            value,
                        replaced.push(name);
            placeholder
                    } else {
        ) {
                        imported.push(name);
            return $('<input>')
                     }
                .attr({
                    type: 'text',
                     value:
                        value == null
                            ? ''
                            : value,


                     placeholder:
                     const clone = this.cloneConfigField(field);
                        placeholder || ''
                })
                .addClass(
                    'preload-editor-input'
                );
        },


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


        checkbox(checked) {
                    this.state.config.fields[name] = clone;
            return $('<input>')
                .attr(
                    'type',
                    'checkbox'
                )
                .prop(
                    'checked',
                    !!checked
                )
                .addClass(
                    'preload-editor-checkbox'
                );
        },


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


            options.forEach(
                 /*
                 option => {
                * Keep PAGE automatic regardless of what the
                    $('<option>')
                * imported config contained.
                        .attr(
                */
                            'value',
                this.state.config.fields.PAGE =
                            option.value
                    this.getAutomaticPageField();
                        )
                        .text(
                            option.label
                        )
                        .prop(
                            'selected',
                            String(
                                option.value
                            ) ===
                            String(
                                value === undefined
                                    ? ''
                                    : value
                            )
                        )
                        .appendTo(select);
                }
            );


            return select;
                this.markConfigDirty();
        },


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


        createConfirmDialog(
                if (
            title,
                    !selectedStillExists ||
            message,
                    this.state.selectedVariable === 'PAGE'
            confirmLabel,
                ) {
            cancelLabel
                     this.state.selectedVariable =
        ) {
                         selected[0] ||
            return new Promise(
                        'PAGE';
                resolve => {
                }
                     const overlay =
                         $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


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


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


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


                     messageLines.forEach(
                let status =
                        line => {
                    'Imported ' +
                            if (line === '') {
                     selected.length +
                                $('<div>')
                    ' variable ' +
                                    .addClass(
                    (selected.length === 1
                                        'preload-editor-prompt-spacer'
                        ? 'definition'
                                    )
                        : 'definitions') +
                                    .appendTo(box);
                    '.';


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


                            $('<p>')
                this.setStatus(status, 'success');
                                .text(line)
                                .appendTo(box);
                        }
                    );


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


                    const cancel =
                this.setStatus(
                        this.createButton(
                    error.message ||
                            cancelLabel || 'Cancel',
                        'Could not import variable definitions.',
                            '',
                    'error'
                            () => {
                );
                                overlay.remove();
                                resolve(false);
                            }
                        );


                    const confirm =
                mw.notify(
                        this.createButton(
                    error.message ||
                            confirmLabel || 'Confirm',
                        'Could not import variable definitions.',
                            'preload-editor-button-primary',
                    {
                            () => {
                        type: 'error'
                                overlay.remove();
                    }
                                resolve(true);
                );
                            }
            }
                        );
        },
 
                    buttons.append(
                        cancel,
                        confirm
                    );


                    box.append(buttons);
        // =========================================================
                    overlay.append(box);
        // Preload parsing
        // =========================================================


                    $(document.body)
        extractIncludeonly(source) {
                        .append(overlay);
            const match = String(source || '').match(
                /<includeonly>([\s\S]*?)<\/includeonly>/i
            );


                    const close =
            return match
                        value => {
                ? match[1].trim()
                            if (value === 'Escape') {
                : String(source || '').trim();
                                cancel.trigger('click');
        },
                            }
                        };


                    overlay.on(
        findVariables(content) {
                        'keydown.preloadEditor',
            const variables = [];
                        event => {
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                            close(event.key);
                        }
                    );


                    overlay.attr(
            let match;
                        'tabindex',
                        '-1'
                    );


                    overlay.trigger('focus');
            while ((match = pattern.exec(content)) !== null) {
                const name = match[1].toUpperCase();


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


         createPromptDialog(
         findConditions(content) {
            title,
             const conditions = [];
            message
            const pattern =
        ) {
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
             return new Promise(
 
                resolve => {
            let match;
                    const overlay =
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                    const box =
            while ((match = pattern.exec(content)) !== null) {
                        $('<div>')
                conditions.push({
                            .addClass(
                    type: match[1].toLowerCase(),
                                'preload-editor-prompt'
                    expression: match[2].trim(),
                            );
                    index: match.index
                });
            }


                    $('<h2>')
            return conditions;
                        .text(title)
        },
                        .appendTo(box);


                    $('<p>')
        findConditionVariables(content) {
                        .text(message)
            const variables = [];
                        .appendTo(box);


                     const input =
            this.findConditions(content).forEach(condition => {
                        this.textInput();
                if (
                     condition.type !== 'if' &&
                    condition.type !== 'elseif'
                ) {
                    return;
                }


                    const buttons =
                const matches =
                        $('<div>')
                    condition.expression.match(
                            .addClass(
                        /[A-Za-z0-9_-]+/g
                                'preload-editor-prompt-buttons'
                    ) || [];
                            );


                    const cancel =
                matches.forEach(name => {
                        this.createButton(
                    name = name.toUpperCase();
                            'Cancel',
                            '',
                            () => {
                                overlay.remove();
                                resolve(null);
                            }
                        );


                     const confirm =
                     if (!variables.includes(name)) {
                        this.createButton(
                        variables.push(name);
                            'Load',
                    }
                            'preload-editor-button-primary',
                });
                            () => {
            });
                                const value =
                                    String(
                                        input.val() || ''
                                    ).trim();


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


                                overlay.remove();
        analyzePreload(content) {
                                resolve(value);
            return {
                            }
                variables: this.findVariables(content),
                        );
                conditions: this.findConditions(content),
                conditionVariables:
                    this.findConditionVariables(content)
            };
        },


                    buttons.append(
        // =========================================================
                        cancel,
        // Config
                        confirm
        // =========================================================
                    );


                    box.append(
        getAutomaticPageField() {
                        input,
            return {
                        buttons
                label: 'Page Name',
                    );
                description: 'Name of the page.',
 
                type: 'page',
                    overlay.append(box);
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


                    $(document.body)
        emptyConfig() {
                        .append(overlay);
            return {
                settings: {
                    incomplete: 'add-stub'
                },


                    input.trigger('focus');
                fields: {
 
                     PAGE: this.getAutomaticPageField()
                     input.on(
                        'keydown.preloadEditor',
                        event => {
                            if (
                                event.key === 'Enter'
                            ) {
                                confirm.trigger('click');
                            }
 
                            if (
                                event.key === 'Escape'
                            ) {
                                cancel.trigger('click');
                            }
                        }
                    );
                 }
                 }
             );
             };
         },
         },


         createConfigReviewDialog() {
         normalizeConfig(config) {
             return new Promise(
             if (
                 resolve => {
                 !config ||
                    const overlay =
                typeof config !== 'object' ||
                        $('<div>')
                Array.isArray(config)
                            .addClass(
            ) {
                                'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                config = this.emptyConfig();
                            );
            }


                    const box =
            if (
                        $('<div>')
                !config.settings ||
                            .addClass(
                typeof config.settings !== 'object' ||
                                'preload-editor-prompt preload-editor-code-review'
                Array.isArray(config.settings)
                            );
            ) {
 
                config.settings = {};
                    $('<h2>')
            }
                        .text('Review config.json')
                        .appendTo(box);


                    $('<p>')
            if (
                        .text(
                !config.fields ||
                            'This is the config.json that will be saved for the current preload.'
                typeof config.fields !== 'object' ||
                        )
                Array.isArray(config.fields)
                        .appendTo(box);
            ) {
                config.fields = {};
            }


                    const code =
            config.fields.PAGE =
                        $('<pre>')
                this.getAutomaticPageField();
                            .addClass(
                                'preload-editor-config-review'
                            )
                            .text(
                                this.getConfigJSON()
                            );


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


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


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


                    const close =
        prepareConfigForVariables(config, analysis) {
                        this.createButton(
            config = this.normalizeConfig(config);
                            'Close',
                            'preload-editor-button-primary',
                            () => {
                                overlay.remove();
                                resolve();
                            }
                        );


                    buttons.append(close);
            const existing = config.fields || {};
                    box.append(buttons);
                    overlay.append(box);


                    $(document.body)
            const deleted = new Set(
                         .append(overlay);
                Array.isArray(this.state.deletedVariables)
                    ? this.state.deletedVariables.map(
                         name => String(name).toUpperCase()
                    )
                    : []
            );


                    overlay.attr(
            const fields = {};
                        'tabindex',
                        '-1'
                    );


                    overlay.trigger('focus');
            fields.PAGE =
                this.getAutomaticPageField();


                    overlay.on(
            analysis.variables.forEach(name => {
                        'keydown.preloadEditor',
                if (
                        event => {
                    name === 'PAGE' ||
                            if (
                    deleted.has(name)
                                event.key === 'Escape'
                ) {
                            ) {
                    return;
                                close.trigger('click');
                }
                            }
 
                         }
                fields[name] =
                    existing[name] ||
                    this.createDefaultField(
                        name,
                         analysis
                     );
                     );
            });


                    overlay.on(
            Object.keys(existing).forEach(name => {
                        'click.preloadEditor',
                const upper = name.toUpperCase();
                        event => {
 
                            if (
                if (
                                event.target ===
                    upper !== 'PAGE' &&
                                overlay.get(0)
                    !fields[upper] &&
                            ) {
                    !deleted.has(upper)
                                close.trigger('click');
                ) {
                            }
                    fields[upper] =
                         }
                         existing[name];
                    );
                 }
                 }
             );
             });
        },


        async confirmSave(
             config.fields = fields;
             mode,
            title
        ) {
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';


             let saveDescription;
             return config;
        },


            if (mode === 'preload') {
        validateConfig(config, analysis) {
                saveDescription =
             const errors = [];
                    'Save the preload page only?';
             const warnings = [];
            } else if (mode === 'config') {
                saveDescription =
                    'Save the config.json page only?';
             } else {
                saveDescription =
                    'Save both the preload and config.json?';
             }
 
            let pages = [];


             if (
             if (
                 mode === 'preload' ||
                 !config ||
                 mode === 'both'
                typeof config !== 'object' ||
                 Array.isArray(config)
             ) {
             ) {
                 pages.push(
                 return {
                     'Preload: ' + title
                    valid: false,
                 );
                    errors: [
                        'Config must be an object.'
                    ],
                     warnings: []
                 };
             }
             }


             if (
             if (
                 mode === 'config' ||
                 !config.fields ||
                 mode === 'both'
                 typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
             ) {
             ) {
                 pages.push(
                 return {
                     'Config: ' + configTitle
                    valid: false,
                 );
                     errors: [
                        '"fields" must be an object.'
                    ],
                    warnings
                 };
             }
             }


             const message =
             const configured =
                 saveDescription +
                 Object.keys(
                 '\n\n' +
                    config.fields
                pages.join('\n') +
                 ).map(
                 '\n\nThis will write the changes to the wiki.';
                    name =>
                        name.toUpperCase()
                 );


             return this.createConfirmDialog(
             analysis.variables.forEach(name => {
                 'Confirm save',
                 if (!configured.includes(name)) {
                message,
                    errors.push(
                'Save',
                        'Variable "' +
                 'Cancel'
                        name +
             );
                        '" is not configured.'
        },
                    );
                 }
             });


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


        destroyEditor() {
             if (!configured.includes('PAGE')) {
             if (!this.editor) {
                 errors.push(
                this.editorView = null;
                     'PAGE must always be configured.'
                this.editorTools = null;
                return;
            }
 
            const {
                view,
                inputHandler
            } = this.editor;
 
            if (
                view &&
                inputHandler
            ) {
                 view.dom.removeEventListener(
                     'input',
                    inputHandler
                 );
                 );
             }
             }


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


            this.editor = null;
                    return;
            this.editorView = null;
                }
            this.editorTools = null;
        },


        getEditorView() {
                if (!field.type) {
            return this.editorView;
                    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.'
                        );
                    }


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


            return (
                    if (
                this.state.preloadContent || ''
                        field.filename !== undefined &&
            );
                        typeof field.filename !== 'string'
        },
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filename" as a string.'
                        );
                    }


        setEditorContent(content) {
                    if (
            content =
                        field.filetext !== undefined &&
                String(content || '');
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "filetext" as a string.'
                        );
                    }


            if (!this.editorView) {
                    if (
                this.state.preloadContent =
                        !field.accept ||
                    content;
                        !field.accept.length
                return;
                    ) {
            }
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


            const current =
                    if (
                this.editorView.state.doc.toString();
                        !field.filename
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no filename template.'
                        );
                    }
                }


            if (current === content) {
                if (
                return;
                    (
            }
                        field.type === 'select' ||
 
                        field.type === 'multiselect'
            this.editorView.dispatch({
                    ) &&
                 changes: {
                    !field.source &&
                     from: 0,
                    !Array.isArray(field.options)
                    to:
                 ) {
                         this.editorView.state.doc.length,
                     warnings.push(
                     insert: content
                        'Field "' +
                        name +
                        '" is a ' +
                         field.type +
                        ' without a source or manual options.'
                     );
                 }
                 }
            });
        },


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


            const selection =
                    if (
                this.editorView.state
                        field.filetext !== undefined &&
                     .selection.main;
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                    }
 
                    if (
                        field.accept !== undefined &&
                        (
                            !Array.isArray(field.accept) ||
                            field.accept.some(
                                value =>
                                    typeof value !== 'string' ||
                                    !value.trim()
                            )
                        )
                     ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array of MIME types.'
                        );
                    }
                }
            });


             return {
             return {
                 from:
                 valid: !errors.length,
                    selection.from,
                 errors,
 
                 warnings
                 to:
                    selection.to,
 
                 text:
                    this.editorView.state.doc.sliceString(
                        selection.from,
                        selection.to
                    )
             };
             };
         },
         },


         focusEditor() {
         // =========================================================
            if (this.editorView) {
        // Transformation helpers
                this.editorView.focus();
         // =========================================================
            }
         },


         insertEditorText(
         transformationObject(
             text,
             transform,
             selectionFrom,
             prefix,
             selectionTo,
             suffix,
             cursorPosition
             from,
            to
         ) {
         ) {
             if (!this.editorView) {
             if (!transform) {
                 return;
                 return null;
             }
             }


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


            const selection =
                case 'remove-suffix':
                view.state.selection.main;
                    return suffix
                        ? {
                            transform,
                            suffix
                        }
                        : null;


            const from =
                case 'replace':
                selectionFrom === undefined
                    return from === ''
                    ? selection.from
                        ? null
                    : selectionFrom;
                        : {
                            transform,
                            from,
                            to: to || ''
                        };


            const to =
                 default:
                 selectionTo === undefined
                     return null;
                     ? selection.to
            }
                    : selectionTo;
        },


            const cursor =
        // =========================================================
                cursorPosition === undefined
        // UI helpers
                    ? from + text.length
        // =========================================================
                    : cursorPosition;


            view.dispatch({
        createSection(title, className) {
                changes: {
            const section = $('<section>')
                    from,
                 .addClass('preload-editor-section');
                    to,
                    insert: text
                 },


                selection: {
            if (className) {
                    anchor: cursor
                section.addClass(className);
                }
            }
             });
 
             $('<h2>')
                .addClass('preload-editor-section-title')
                .text(title)
                .appendTo(section);


             view.focus();
             return section;
         },
         },


         // =========================================================
         createButton(label, className, callback) {
        // Editor tools
            const button = $('<button>')
        // =========================================================
                .attr('type', 'button')
                .addClass('preload-editor-button')
                .text(label);


        wrapSelectionWithVariable() {
            if (className) {
            const selected =
                 button.addClass(className);
                 this.getEditorSelection();
            }


             if (
             if (callback) {
                 !selected ||
                 button.on(
                selected.from === selected.to
                    'click.preloadEditor',
            ) {
                    callback
                 this.focusEditor();
                 );
                return;
             }
             }


             const replacement =
             return button;
                '%%' +
                selected.text +
                '%%';
 
            this.insertEditorText(
                replacement,
                selected.from,
                selected.to,
                selected.from +
                    replacement.length
            );
         },
         },


         insertVariable(name) {
         fieldRow(label, input, description) {
             name =
             const row = $('<div>')
                String(name || '')
                .addClass('preload-editor-field');
                    .trim()
                    .toUpperCase();


             if (!name) {
            $('<label>')
                 return;
                .addClass('preload-editor-label')
                .text(label)
                .appendTo(row);
 
             if (description) {
                 $('<div>')
                    .addClass('preload-editor-help')
                    .text(description)
                    .appendTo(row);
             }
             }


             const selected =
             row.append(input);
                this.getEditorSelection();


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


             this.insertEditorText(
        textInput(value, placeholder) {
                '%%' + name + '%%',
             return $('<input>')
                 selected.from,
                .attr({
                 selected.to
                    type: 'text',
            );
                    value: value == null ? '' : value,
                    placeholder: placeholder || ''
                 })
                 .addClass('preload-editor-input');
         },
         },


         insertCondition(
         textarea(value) {
            type,
             return $('<textarea>')
            variable
                 .val(value == null ? '' : value)
        ) {
                .addClass('preload-editor-textarea');
             type =
        },
                 String(type || '')
                    .toLowerCase();


             variable =
        checkbox(checked) {
                 String(variable || '')
             return $('<input>')
                    .trim()
                 .attr('type', 'checkbox')
                    .toUpperCase();
                .prop('checked', !!checked)
                .addClass('preload-editor-checkbox');
        },


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


             if (!selected) {
             options.forEach(option => {
                return;
                $('<option>')
             }
                    .attr('value', option.value)
                    .text(option.label)
                    .prop(
                        'selected',
                        String(option.value) ===
                        String(value === undefined ? '' : value)
                    )
                    .appendTo(select);
             });


             let text;
             return select;
            let cursorOffset;
        },
 
        // =========================================================
        // In-wiki dialogs
        // =========================================================


             switch (type) {
        createConfirmDialog(
                 case 'if': {
            title,
                     if (!variable) {
             message,
                        return;
            confirmLabel,
                    }
            cancelLabel
        ) {
            return new Promise(resolve => {
                 const overlay = $('<div>')
                     .addClass('preload-editor-prompt-overlay');


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


                    const closing =
                $('<h2>')
                        '<!-- @endif -->';
                    .text(title)
                    .appendTo(box);


                    if (
                const messageLines =
                        selected.from !==
                     String(message || '').split('\n');
                        selected.to
                     ) {
                        text =
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                        cursorOffset =
                messageLines.forEach(line => {
                            text.length;
                     if (line === '') {
                     } else {
                         $('<div>')
                         text =
                             .addClass(
                             opening +
                                'preload-editor-prompt-spacer'
                            '\n\n' +
                             )
                             closing;
                            .appendTo(box);


                         cursorOffset =
                         return;
                            opening.length + 1;
                     }
                     }


                     break;
                     $('<p>')
                 }
                        .text(line)
                        .appendTo(box);
                 });


                 case 'elseif':
                 const buttons = $('<div>')
                     text =
                     .addClass(
                         '<!-- @elseif -->';
                         'preload-editor-prompt-buttons'
                    cursorOffset =
                     );
                        text.length;
                     break;


                 case 'else':
                 const cancel = this.createButton(
                     text =
                    cancelLabel || 'Cancel',
                        '<!-- @else -->';
                     '',
                     cursorOffset =
                     () => {
                         text.length;
                         overlay.remove();
                     break;
                        resolve(false);
                     }
                );


                 case 'endif':
                 const confirm = this.createButton(
                     text =
                    confirmLabel || 'Confirm',
                        '<!-- @endif -->';
                     'preload-editor-button-primary',
                     cursorOffset =
                     () => {
                         text.length;
                         overlay.remove();
                     break;
                        resolve(true);
                     }
                );


                 default:
                 buttons.append(cancel, confirm);
                    return;
                box.append(buttons);
            }
                overlay.append(box);


            this.insertEditorText(
                $(document.body).append(overlay);
                text,
                selected.from,
                selected.to,
                selected.from +
                    cursorOffset
            );
        },


        getToolVariables() {
                const close = value => {
            const variables =
                    if (value === 'Escape') {
                new Set(['PAGE']);
                        cancel.trigger('click');
                    }
                };


            if (
                 overlay.on(
                 this.analysis &&
                    'keydown.preloadEditor',
                this.analysis.variables
                     event => {
            ) {
                         close(event.key);
                this.analysis.variables.forEach(
                     name => {
                         variables.add(
                            String(
                                name
                            ).toUpperCase()
                        );
                     }
                     }
                 );
                 );
            }


            return Array.from(variables);
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');
 
                overlay.on(
                    'click.preloadEditor',
                    event => {
                        if (event.target === overlay.get(0)) {
                            cancel.trigger('click');
                        }
                    }
                );
            });
         },
         },


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


            if (className) {
                $('<h2>')
                select.addClass(className);
                    .text(title)
            }
                    .appendTo(box);


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


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


        updateEditorToolVariables() {
                const buttons = $('<div>')
            if (!this.editorTools) {
                    .addClass(
                return;
                        'preload-editor-prompt-buttons'
            }
                    );


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


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


            const currentCondition =
                        if (!value) {
                this.editorTools
                            return;
                    .conditionVariableSelect
                        }
                    .val();


            const populate =
                        overlay.remove();
                (
                        resolve(value);
                     select,
                     }
                    value
                 );
                 ) => {
                    select.empty();


                    variables.forEach(
                buttons.append(cancel, confirm);
                        name => {
                            $('<option>')
                                .attr(
                                    'value',
                                    name
                                )
                                .text(name)
                                .appendTo(select);
                        }
                    );


                    if (
                box.append(
                        value &&
                     input,
                        variables.includes(value)
                     buttons
                     ) {
                );
                        select.val(value);
                     } else if (
                        variables.length
                    ) {
                        select.val(
                            variables[0]
                        );
                    }
                };


            populate(
                 overlay.append(box);
                 this.editorTools.variableSelect,
                current
            );


            populate(
                $(document.body).append(overlay);
                this.editorTools.conditionVariableSelect,
                currentCondition
            );
        },


        updateConditionVariableVisibility() {
                input.trigger('focus');
            if (!this.editorTools) {
                return;
            }


            const type =
                 input.on(
                 this.editorTools
                     'keydown.preloadEditor',
                     .conditionTypeSelect
                     event => {
                     .val();
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }


            this.editorTools
                        if (event.key === 'Escape') {
                .conditionVariableWrap
                            cancel.trigger('click');
                .toggle(
                        }
                     type === 'if'
                     }
                 );
                 );
            });
         },
         },


         renderEditorTools() {
         createConfigReviewDialog() {
             const tools =
             return new Promise(resolve => {
                 $('<div>')
                 const overlay = $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tools'
                         'preload-editor-prompt-overlay preload-editor-code-review-overlay'
                     );
                     );


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


            wrapGroup.append(
                $('<h2>')
                this.createButton(
                    .text('Review config.json')
                    'Wrap selection',
                    .appendTo(box);
                     'preload-editor-tool-button',
 
                     () =>
                $('<p>')
                        this.wrapSelectionWithVariable()
                     .text(
                )
                        'This is the config.json that will be saved for the current preload.'
            );
                     )
                    .appendTo(box);


            const variableGroup =
                const code = $('<pre>')
                $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tool-group preload-editor-tool-group-variable'
                         'preload-editor-config-review'
                     );
                     )
                    .text(this.getConfigJSON());


            $('<span>')
                const codeWrap = $('<div>')
                .addClass(
                    .addClass(
                    'preload-editor-tool-label'
                        'preload-editor-config-review-wrap'
                )
                    )
                 .text(
                    .append(code);
                    'Insert existing variable'
 
                )
                 box.append(codeWrap);
                .appendTo(variableGroup);
 
                const buttons = $('<div>')
                    .addClass(
                        'preload-editor-prompt-buttons'
                    );


            const variableSelect =
                const close = this.createButton(
                this.createToolSelect(
                     'Close',
                     [],
                     'preload-editor-button-primary',
                     'preload-editor-variable-select'
                    () => {
                        overlay.remove();
                        resolve();
                    }
                 );
                 );


            variableGroup.append(
                buttons.append(close);
                 variableSelect,
                 box.append(buttons);
                overlay.append(box);


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


            const conditionGroup =
                 overlay.attr('tabindex', '-1');
                 $('<div>')
                overlay.trigger('focus');
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


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


            const conditionTypeSelect =
                 overlay.on(
                 this.createToolSelect(
                     'click.preloadEditor',
                     [
                    event => {
                        {
                         if (event.target === overlay.get(0)) {
                            value: 'if',
                             close.trigger('click');
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                         {
                             value: 'else',
                            label: '@else'
                        },
                        {
                            value: 'endif',
                            label: '@endif'
                         }
                         }
                     ],
                     }
                    'preload-editor-condition-type-select'
                 );
                 );
            });
        },


             const conditionVariableSelect =
        async confirmSave(mode, title) {
                 this.createToolSelect(
             const configTitle =
                    [],
                 title.replace(/\/+$/, '') +
                    'preload-editor-condition-variable-select'
                 '/config.json';
                 );


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


             const insertCondition =
             if (mode === 'preload') {
                 this.createButton(
                 saveDescription =
                     'Insert',
                    'Save the preload page only?';
                     'preload-editor-tool-button',
            } else if (mode === 'config') {
                    () =>
                saveDescription =
                        this.insertCondition(
                     'Save the config.json page only?';
                            conditionTypeSelect.val(),
            } else {
                            conditionVariableSelect.val()
                saveDescription =
                        )
                     'Save both the preload and config.json?';
            }
 
            const pages = [];
 
            if (mode === 'preload' || mode === 'both') {
                pages.push(
                    'Preload: ' +
                    title
                 );
                 );
            }


             conditionTypeSelect.on(
             if (mode === 'config' || mode === 'both') {
                'change.preloadEditor',
                 pages.push(
                 () =>
                     'Config: ' +
                     this.updateConditionVariableVisibility()
                    configTitle
            );
                );


            conditionGroup.append(
                pages.push(
                conditionTypeSelect,
                    'Config content model: JSON'
                 conditionVariableWrap,
                 );
                insertCondition
             }
             );


             tools.append(
             const message =
                 wrapGroup,
                 saveDescription +
                 variableGroup,
                 '\n\n' +
                 conditionGroup
                 pages.join('\n') +
            );
                '\n\nThis will write the changes to the wiki.';


             this.editorTools = {
             return this.createConfirmDialog(
                root: tools,
                 'Confirm save',
                 variableSelect,
                 message,
                 conditionTypeSelect,
                 'Save',
                 conditionVariableSelect,
                 'Cancel'
                 conditionVariableWrap,
             );
                insertCondition
            };
 
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
 
             return tools;
        },
 
        updateEditorTools() {
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
         },
         },


         // =========================================================
         // =========================================================
         // Syntax highlighting
         // CodeMirror
         // =========================================================
         // =========================================================
                destroyEditor() {
            if (!this.editor) {
                this.editorView = null;
                this.editorTools = null;
                return;
            }


        getKnownVariables() {
            const {
             const known =
                view,
                new Set(['PAGE']);
                inputHandler
             } = this.editor;


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


             if (
             if (view) {
                fields &&
                 view.destroy();
                typeof fields === 'object'
            ) {
                 Object.keys(fields).forEach(
                    name => {
                        known.add(
                            String(
                                name
                            ).toUpperCase()
                        );
                    }
                );
             }
             }


             return known;
            this.editor = null;
            this.editorView = null;
            this.editorTools = null;
        },
 
        getEditorView() {
             return this.editorView;
         },
         },


         createSyntaxDecorations(
         getEditorContent() {
             state,
             if (
             Decoration
                this.editorView &&
        ) {
                this.editorView.state
            const decorations = [];
             ) {
            const source =
                 return this.editorView.state.doc.toString();
                 state.doc.toString();
            }


             const knownVariables =
             return this.state.preloadContent || '';
                this.getKnownVariables();
        },


             const variablePattern =
        setEditorContent(content) {
                /%%([A-Za-z0-9_-]+)%%/g;
             content = String(content || '');


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


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


                 const known =
            this.editorView.dispatch({
                     knownVariables.has(name);
                 changes: {
                    from: 0,
                     to: this.editorView.state.doc.length,
                    insert: content
                }
            });
        },


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


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


             while (
             return {
                 (
                 from: selection.from,
                    match =
                 to: selection.to,
                        conditionPattern.exec(
                 text: this.editorView.state.doc.sliceString(
                            source
                     selection.from,
                        )
                    selection.to
                 ) !== null
                )
            ) {
            };
                 decorations.push(
        },
                    Decoration.mark({
                        class:
                            'preload-editor-syntax-condition'
                     }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


                const directiveStart =
        focusEditor() {
                    match.index +
            if (this.editorView) {
                    match[0].indexOf('@');
                this.editorView.focus();
            }
        },


                decorations.push(
        insertEditorText(
                    Decoration.mark({
            text,
                        class:
            selectionFrom,
                            'preload-editor-syntax-directive'
            selectionTo,
                    }).range(
            cursorPosition
                        directiveStart,
        ) {
                        directiveStart +
            if (!this.editorView) {
                            match[1].length +
                 return;
                            1
            }
                    )
                 );


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


                 if (
            const from =
                    type !== 'if' &&
                 selectionFrom === undefined
                     type !== 'elseif'
                     ? selection.from
                ) {
                     : selectionFrom;
                     continue;
                }


                 const expression =
            const to =
                     match[2];
                 selectionTo === undefined
                    ? selection.to
                     : selectionTo;


                 const expressionStart =
            const cursor =
                     match.index +
                 cursorPosition === undefined
                    match[0].indexOf(
                     ? from + text.length
                        expression
                     : cursorPosition;
                     );


                 const expressionPattern =
            view.dispatch({
                     /[A-Za-z0-9_-]+/g;
                changes: {
                    from,
                    to,
                    insert: text
                },
                 selection: {
                     anchor: cursor
                }
            });


                let expressionMatch;
            view.focus();
        },


                while (
        // =========================================================
                    (
        // Editor tools
                        expressionMatch =
        // =========================================================
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


                    if (
        wrapSelectionWithVariable() {
                        !knownVariables.has(name)
            const selected =
                    ) {
                this.getEditorSelection();
                        continue;
                    }


                    const start =
            if (
                        expressionStart +
                !selected ||
                        expressionMatch.index;
                selected.from === selected.to
 
            ) {
                    decorations.push(
                this.focusEditor();
                        Decoration.mark({
                 return;
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0]
                                    .length
                        )
                    );
                 }
             }
             }


             return Decoration.set(
             const replacement =
                 decorations,
                 '%%' +
                 true
                 selected.text +
            );
                '%%';
        },


        async installSyntaxHighlighting(view) {
            this.insertEditorText(
            await mw.loader.using(
                replacement,
                 'ext.CodeMirror.v6.lib'
                selected.from,
                selected.to,
                 selected.from + replacement.length
             );
             );
        },


             const require =
        insertVariable(name) {
                 mw.loader.require;
             name = String(name || '')
                 .trim()
                .toUpperCase();


             const {
             if (!name) {
                 StateField,
                 return;
                StateEffect,
             }
                EditorView,
                Decoration
             } = require(
                'ext.CodeMirror.v6.lib'
            );


             const syntaxField =
             const selected =
                 StateField.define({
                 this.getEditorSelection();
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


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


                    provide: field =>
            this.insertEditorText(
                        EditorView.decorations.from(
                '%%' + name + '%%',
                            field
                selected.from,
                        )
                selected.to
                });
            );
        },


             view.dispatch({
        insertCondition(
                 effects:
            type,
                    StateEffect.appendConfig.of(
             variable
                        syntaxField
        ) {
                    )
            type = String(type || '').toLowerCase();
            });
            variable = String(variable || '')
                 .trim()
                .toUpperCase();


             this.editor.syntaxField =
             const selected =
                 syntaxField;
                 this.getEditorSelection();
        },


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


                    const cleanup =
            let text;
                        () => {
            let cursorOffset;
                            mw.hook(
                                'dev.CCM.ready'
                            ).remove(onReady);


                            mw.hook(
            switch (type) {
                                'dev.CCM.load'
                case 'if': {
                            ).remove(onLoad);
                    if (!variable) {
                        };
                        return;
                    }


                     const onReady =
                     const opening =
                         async cm => {
                         '<!-- @if ' +
                            if (
                        variable +
                                settled ||
                        ' -->';
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                            settled = true;
                    const closing =
                            cleanup();
                        '<!-- @endif -->';


                             const view =
                    if (
                                cm.view;
                        selected.from !==
                        selected.to
                    ) {
                        text =
                             opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;


                            const inputHandler =
                        cursorOffset = text.length;
                                () => {
                    } else {
                                    this.state
                        text =
                                        .preloadContent =
                            opening +
                                        view.state.doc.toString();
                            '\n\n' +
                            closing;


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


                                    this.reanalyze();
                    break;
                }


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


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


                            view.dom.addEventListener(
                    break;
                                'input',
                                inputHandler
                            );


                            view.dom.classList.add(
                case 'else':
                                'preload-editor-codemirror'
                    text =
                            );
                        '<!-- @else -->';


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


                            if (wrapper) {
                    break;
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


                            this.editor = {
                case 'endif':
                                cm,
                    text =
                                view,
                        '<!-- @endif -->';
                                textarea,
                                inputHandler
                            };


                            this.editorView =
                    cursorOffset =
                                view;
                        text.length;


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


                            try {
                default:
                                await this.installSyntaxHighlighting(
                    return;
                                    view
            }
                                );


                                if (
            this.insertEditorText(
                                    this.state.dirty
                text,
                                ) {
                selected.from,
                                    this.saveDraft();
                selected.to,
                                }
                selected.from + cursorOffset
            );
        },


                                resolve(view);
        getToolVariables() {
                            } catch (error) {
            const variables =
                                reject(error);
                new Set(['PAGE']);
                            }
                        };


                     const onLoad =
            if (
                         loader => {
                this.analysis &&
                             if (
                this.analysis.variables
                                settled ||
            ) {
                                typeof loader !==
                this.analysis.variables.forEach(
                                    'function'
                     name => {
                            ) {
                         variables.add(
                                return;
                             String(name).toUpperCase()
                            }
                        );
                    }
                );
            }
 
            return Array.from(variables);
        },


                            try {
        createToolSelect(
                                loader(textarea);
            options,
                            } catch (error) {
            className
                                settled = true;
        ) {
                                cleanup();
            const select =
                                reject(error);
                $('<select>')
                            }
                    .addClass(
                        };
                        'preload-editor-tool-select'
                    );


                    mw.hook(
            if (className) {
                        'dev.CCM.ready'
                select.addClass(className);
                    ).add(onReady);
            }


                     mw.hook(
            options.forEach(
                         'dev.CCM.load'
                option => {
                    ).add(onLoad);
                     $('<option>')
                        .attr(
                            'value',
                            option.value
                        )
                         .text(option.label)
                        .appendTo(select);
                 }
                 }
             );
             );
            return select;
         },
         },


         // =========================================================
         updateEditorToolVariables() {
        // Main UI
             if (!this.editorTools) {
        // =========================================================
 
        init() {
            const root =
                $('#mw-content-text');
 
             if (!root.length) {
                 return;
                 return;
             }
             }


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


             root.append(this.root);
             const current =
                this.editorTools
                    .variableSelect
                    .val();


             this.renderShell();
             const currentCondition =
                this.editorTools
                    .conditionVariableSelect
                    .val();


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


            window.addEventListener(
                variables.forEach(
                'beforeunload',
                    name => {
                () => {
                        $('<option>')
                    if (this.state.dirty) {
                            .attr(
                        this.saveDraft();
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                     }
                     }
                 }
                 );
            );
        },


        renderShell() {
                if (
            this.destroyEditor();
                    value &&
             this.root.empty();
                    variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                    select.val(
                        variables[0]
                    );
                }
            };
 
             populate(
                this.editorTools.variableSelect,
                current
            );


             const loader =
             populate(
                 this.createSection('Preload');
                 this.editorTools.conditionVariableSelect,
                currentCondition
            );
        },


             const titleInput =
        updateConditionVariableVisibility() {
                this.textInput(
             if (!this.editorTools) {
                    this.state.preloadTitle,
                 return;
                    'Template:Example/Preload'
            }
                ).attr(
                    'id',
                    'preload-editor-title-input'
                 );


             titleInput.on(
             const type =
                 'input.preloadEditor',
                 this.editorTools
                () => {
                     .conditionTypeSelect
                     this.state.preloadTitle =
                    .val();
                        String(
                            titleInput.val() || ''
                        ).trim();


                    if (
            this.editorTools
                        this.state.dirty &&
                .conditionVariableWrap
                        this.state.mode === 'new'
                .toggle(
                    ) {
                     type === 'if'
                        this.saveDraft();
                     }
                }
            );
 
            const loadButton =
                this.createButton(
                    'Load',
                    'preload-editor-button-primary',
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                 );
                 );
        },


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


             const sampleButton =
             const wrapGroup =
                this.createButton(
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );
 
            loader.append(
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-toolbar'
                         'preload-editor-tool-group preload-editor-tool-group-wrap'
                     )
                     );
                    .append(
 
                        titleInput,
            wrapGroup.append(
                        loadButton,
                this.createButton(
                        newButton,
                    'Wrap selection',
                         sampleButton
                    'preload-editor-tool-button',
                    )
                    () =>
                         this.wrapSelectionWithVariable()
                )
             );
             );


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


             this.root.append(
             $('<span>')
                 this.workspace
                .addClass(
            );
                    'preload-editor-tool-label'
                )
                .text(
                    'Insert existing variable'
                )
                .appendTo(variableGroup);
 
            const variableSelect =
                 this.createToolSelect(
                    [],
                    'preload-editor-variable-select'
                );


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


            this.localDraftStatus =
                this.createButton(
                $('<div>')
                    'Insert',
                     .addClass(
                     'preload-editor-tool-button',
                        'preload-editor-local-draft-status is-empty'
                     () =>
                     )
                        this.insertVariable(
                    .text(
                            variableSelect.val()
                         'No local draft'
                         )
                    );
                )
            );


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


             footer.append(
             $('<span>')
                 this.localDraftStatus,
                .addClass(
                 this.status
                    'preload-editor-tool-label'
            );
                )
                 .text('Insert condition')
                 .appendTo(conditionGroup);


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


        renderWelcome() {
            const conditionVariableSelect =
            this.workspace.empty();
                this.createToolSelect(
                    [],
                    'preload-editor-condition-variable-select'
                );


             const section =
             const conditionVariableWrap =
                this.createSection('Get started');
                 $('<span>')
 
            $('<p>')
                .text(
                    'Load an existing preload, create a new one, or start from a sample wiki page.'
                )
                .appendTo(section);
 
            const tips =
                 $('<ul>')
                     .addClass(
                     .addClass(
                         'preload-editor-tips'
                         'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                     );
                     );


             [
             const insertCondition =
                 'Existing preload: loads the preload and its config.json if available.',
                 this.createButton(
                'New preload: starts with the standard Preload Template structure.',
                    'Insert',
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                    'preload-editor-tool-button',
            ].forEach(
                    () =>
                 text => {
                        this.insertCondition(
                    $('<li>')
                            conditionTypeSelect.val(),
                        .text(text)
                            conditionVariableSelect.val()
                        .appendTo(tips);
                        )
                }
                 );
 
            conditionTypeSelect.on(
                'change.preloadEditor',
                () =>
                    this.updateConditionVariableVisibility()
             );
             );


             section.append(tips);
             conditionGroup.append(
             this.workspace.append(section);
                conditionTypeSelect,
        },
                conditionVariableWrap,
                insertCondition
             );


        setStatus(
             tools.append(
            message,
                 wrapGroup,
             type
                 variableGroup,
        ) {
                 conditionGroup
            if (!this.status) {
                return;
            }
 
            this.status.removeClass(
                 'is-error',
                'is-success',
                 'is-warning',
                 'is-loading'
             );
             );


             if (type) {
             this.editorTools = {
                 this.status.addClass(
                 root: tools,
                    'is-' + type
                variableSelect,
                );
                conditionTypeSelect,
            }
                conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
            };
 
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
 
            return tools;
        },


             this.status.text(
        updateEditorTools() {
                message || ''
             this.updateEditorToolVariables();
             );
             this.updateConditionVariableVisibility();
         },
         },


         // =========================================================
         // =========================================================
         // Load / create
         // Syntax highlighting
         // =========================================================
         // =========================================================


         async loadExisting(title) {
         getKnownVariables() {
             title =
             const known =
                 String(title || '').trim();
                 new Set(['PAGE']);


             if (!title) {
             const fields =
                 mw.notify(
                 this.state.config &&
                    'Enter a preload page title first.',
                 this.state.config.fields;
                    {
                        type: 'warn'
                    }
                 );


                 return;
            if (
             }
                 fields &&
                typeof fields === 'object'
            ) {
                Object.keys(fields).forEach(
                    name => {
                        known.add(
                            String(name).toUpperCase()
                        );
                    }
                );
             }


             this.setStatus(
             return known;
                'Loading preload...',
        },
                'loading'
            );


             try {
        createSyntaxDecorations(
                const page =
            state,
                    await this.getPage(title);
             Decoration
        ) {
            const decorations = [];
            const source =
                state.doc.toString();


                if (!page) {
            const knownVariables =
                    const suggestions =
                this.getKnownVariables();
                        await this.findSimilarPreloads(
                            title
                        );


                    this.renderMissingPage(
            const variablePattern =
                        title,
                /%%([A-Za-z0-9_-]+)%%/g;
                        suggestions
                    );


                    this.setStatus(
            let match;
                        'Preload not found.',
                        'warning'
                    );


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


                 await this.loadDefinition(
                 const known =
                     page.title,
                     knownVariables.has(name);
                    page.content
                );


                 this.setStatus(
                 decorations.push(
                     'Preload loaded.',
                     Decoration.mark({
                    'success'
                        class: [
                );
                            'preload-editor-syntax-variable',
            } catch (error) {
                            known
                console.error(
                                ? 'preload-editor-syntax-variable-known'
                    'Preload Editor:',
                                : 'preload-editor-syntax-variable-unknown'
                     error
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                     )
                 );
                 );
            }


                 this.setStatus(
            const conditionPattern =
                    error.message ||
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                        'Could not load preload.',
                    'error'
                );
            }
        },


        async findSimilarPreloads(title) {
            while (
             let query =
                (
                 title
                    match =
                     .replace(
                        conditionPattern.exec(source)
                         /\/Preload$/i,
                ) !== null
                         ''
             ) {
                 decorations.push(
                     Decoration.mark({
                         class:
                            'preload-editor-syntax-condition'
                    }).range(
                        match.index,
                         match.index +
                            match[0].length
                     )
                     )
                    .trim();
                );


            if (!query) {
                const directiveStart =
                query = title;
                    match.index +
            }
                    match[0].indexOf('@');


            try {
                decorations.push(
                const results =
                    Decoration.mark({
                     await this.searchPages(query);
                        class:
                            'preload-editor-syntax-directive'
                     }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


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


                 return [];
                 if (
            }
                    type !== 'if' &&
        },
                    type !== 'elseif'
                ) {
                    continue;
                }


        renderMissingPage(
                const expression =
            title,
                    match[2];
            suggestions
        ) {
            this.workspace.empty();


            const section =
                const expressionStart =
                this.createSection(
                    match.index +
                     'Preload not found'
                    match[0].indexOf(
                );
                        expression
                     );


            $('<p>')
                 const expressionPattern =
                 .text(
                     /[A-Za-z0-9_-]+/g;
                     'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


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


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


                suggestions.forEach(
                    if (
                    result => {
                         !knownVariables.has(name)
                         list.append(
                    ) {
                            this.createButton(
                         continue;
                                result.title,
                                'preload-editor-suggestion',
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                         );
                     }
                     }
                );


                section.append(list);
                    const start =
                        expressionStart +
                        expressionMatch.index;
 
                    decorations.push(
                        Decoration.mark({
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                    );
                }
             }
             }


             section.append(
             return Decoration.set(
                 this.createButton(
                 decorations,
                    'Create this preload',
                 true
                    'preload-editor-button-primary',
                    () =>
                        this.startNew(title)
                 )
             );
             );
            this.workspace.append(section);
         },
         },


         async startNew(title) {
         async installSyntaxHighlighting(view) {
             title =
             await mw.loader.using(
                 String(title || '').trim();
                 'ext.CodeMirror.v6.lib'
            );


             this.state = {
             const require =
                preloadTitle: title,
                 mw.loader.require;
                preloadSource: '',
                 preloadContent:
                    this.defaults.preload,


                 config:
            const {
                    this.emptyConfig(),
                StateField,
                StateEffect,
                EditorView,
                 Decoration
            } = require(
                'ext.CodeMirror.v6.lib'
            );


                 variables: ['PAGE'],
            const syntaxField =
                conditions: [],
                 StateField.define({
                selectedVariable: 'PAGE',
                    create: state =>
                deletedVariables: [],
                        this.createSyntaxDecorations(
                mode: 'new',
                            state,
                dirty: true,
                            Decoration
                dirtyPreload: true,
                        ),
                dirtyConfig: true,
 
                    update: (
                        decorations,
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                localDraftSavedAt: null,
                    provide: field =>
                 localDraftAvailable: false
                        EditorView.decorations.from(
            };
                            field
                        )
                 });


             this.saveDraft();
             view.dispatch({
             this.renderEditor();
                effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                    )
             });


             this.setStatus(
             this.editor.syntaxField =
                'Creating a new preload.',
                 syntaxField;
                 'success'
            );
         },
         },


         async loadSamplePage() {
         async mountCodeMirror(textarea) {
             const result =
             return new Promise(
                 await this.createPromptDialog(
                 (
                     'Load Sample Page',
                     resolve,
                     'Enter the title of a normal wiki page to use as the starting point.'
                     reject
                 );
                 ) => {
                    let settled = false;


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


            this.setStatus(
                        mw.hook(
                'Loading sample page...',
                            'dev.CCM.load'
                'loading'
                        ).remove(onLoad);
            );
                    };


            try {
                    const onReady =
                const page =
                        async cm => {
                    await this.getPage(result);
                            if (
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                if (!page) {
                            settled = true;
                    throw new Error(
                            cleanup();
                        'Sample page not found: ' +
                        result
                    );
                }


                const sample =
                            const view =
                    this.convertSampleToPreload(
                                cm.view;
                        page.content
                    );


                this.state = {
                            const inputHandler =
                    preloadTitle: '',
                                () => {
                    preloadSource: '',
                                    this.state
                    preloadContent: sample,
                                        .preloadContent =
                                        view.state.doc.toString();
 
                                    this.markPreloadDirty();


                    config:
                                    this.reanalyze();
                        this.emptyConfig(),


                    variables: ['PAGE'],
                                    this.renderVariablesBySelector();
                    conditions: [],
                                    this.renderVariableConfigurationBySelector();
                    selectedVariable: 'PAGE',
                                    this.renderAnalysisBySelector();
                    deletedVariables: [],
                                    this.updateEditorTools();
                    mode: 'new',
                    dirty: true,
                    dirtyPreload: true,
                    dirtyConfig: true,


                    localDraftSavedAt: null,
                                    this.saveDraft();
                    localDraftAvailable: false
                                };
                };


                this.reanalyze();
                            view.dom.addEventListener(
                this.saveDraft();
                                'input',
                this.renderEditor();
                                inputHandler
                            );


                this.setStatus(
                            view.dom.classList.add(
                    'Sample page loaded.',
                                'preload-editor-codemirror'
                    'success'
                            );
                );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );


                this.setStatus(
                            const wrapper =
                    error.message ||
                                view.dom.closest(
                        'Could not load sample page.',
                                    '.ext-codemirror-wrapper'
                    'error'
                                );
                );
            }
        },


        convertSampleToPreload(source) {
                            if (wrapper) {
            let content =
                                wrapper.classList.add(
                String(source || '').trim();
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


            const include =
                            this.editor = {
                content.match(
                                cm,
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                                view,
                );
                                textarea,
                                inputHandler
                            };


            if (include) {
                            this.editorView =
                content =
                                view;
                    include[1].trim();
            }


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


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


        async loadDefinition(
                                if (
            title,
                                    this.state.dirty
            source
                                ) {
        ) {
                                    this.saveDraft();
            const content =
                                }
                this.extractIncludeonly(source);


            let config =
                                resolve(view);
                this.emptyConfig();
                            } catch (error) {
                                reject(error);
                            }
                        };


            const configTitle =
                    const onLoad =
                title.replace(
                        loader => {
                    /\/+$/,
                            if (
                    ''
                                settled ||
                ) +
                                typeof loader !==
                '/config.json';
                                    'function'
                            ) {
                                return;
                            }


            const configPage =
                            try {
                await this.getPage(configTitle);
                                loader(textarea);
 
                            } catch (error) {
            if (configPage) {
                                settled = true;
                try {
                                cleanup();
                    config =
                                reject(error);
                        JSON.parse(
                             }
                             configPage.content
                         };
                         );
 
                } catch (error) {
                     mw.hook(
                     throw new Error(
                         'dev.CCM.ready'
                         'The existing config.json contains invalid JSON: ' +
                    ).add(onReady);
                         error.message
 
                     );
                    mw.hook(
                         'dev.CCM.load'
                     ).add(onLoad);
                 }
                 }
             }
             );
        },


            const analysis =
        // =========================================================
                this.analyzePreload(content);
        // Main UI
        // =========================================================


             this.state.deletedVariables = [];
        init() {
             const root =
                $('#mw-content-text');


             config =
             if (!root.length) {
                this.prepareConfigForVariables(
                 return;
                    config,
            }
                    analysis
                 );


             this.state = {
             this.root =
                 preloadTitle: title,
                 $('<div>')
                preloadSource: source,
                    .attr(
                preloadContent: source,
                        'id',
                config,
                        'preload-editor'
                    )
                    .addClass(
                        'preload-editor'
                    );


                variables:
            root.append(this.root);
                    analysis.variables,


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


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


                 deletedVariables: [],
            window.addEventListener(
                 'beforeunload',
                () => {
                    if (this.state.dirty) {
                        this.saveDraft();
                    }
                }
            );
        },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


                 mode: 'edit',
            const loader =
                dirty: false,
                 this.createSection('Preload');
                dirtyPreload: false,
                dirtyConfig: false,


                 localDraftSavedAt: null,
            const titleInput =
                 localDraftAvailable: false
                 this.textInput(
            };
                    this.state.preloadTitle,
                    'Template:Example/Preload'
                ).attr(
                    'id',
                    'preload-editor-title-input'
                 );


             this.clearDraft(title);
             titleInput.on(
            this.renderEditor();
                'input.preloadEditor',
        },
                () => {
                    this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();


        // =========================================================
                    if (
        // Editor
                        this.state.dirty &&
        // =========================================================
                        this.state.mode === 'new'
                    ) {
                        this.saveDraft();
                    }
                }
            );


        renderEditor() {
            const loadButton =
            this.destroyEditor();
                this.createButton(
            this.workspace.empty();
                    'Load',
                    'preload-editor-button-primary',
                    () =>
                        this.loadExisting(
                            titleInput.val()
                        )
                );


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


             const left =
             const sampleButton =
                 $('<div>')
                 this.createButton(
                     .addClass(
                    'Load Sample Page',
                        'preload-editor-left'
                     '',
                     );
                     () => this.loadSamplePage()
                );


             const right =
             loader.append(
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-right'
                         'preload-editor-toolbar'
                     );
                     )
                    .append(
                        titleInput,
                        loadButton,
                        newButton,
                        sampleButton
                    )
            );


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


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


             $('<strong>')
             this.root.append(
                .text(
                this.workspace
                    this.state.preloadTitle ||
            );
                    'New preload'
 
                )
            /*
                .appendTo(meta);
            * Fixed footer
            *
            * Local draft status, normal status messages,
            * and save actions live here.
            */
            const footer =
                $('<div>')
                    .addClass(
                        'preload-editor-footer'
                    );


             if (
             this.localDraftStatus =
                this.state.mode === 'new'
                 $('<div>')
            ) {
                 $('<span>')
                     .addClass(
                     .addClass(
                         'preload-editor-badge'
                         'preload-editor-local-draft-status is-empty'
                     )
                     )
                     .text('NEW')
                     .text(
                     .appendTo(meta);
                        'No local draft'
            }
                     );


             editorSection.append(meta);
             this.status =
            editorSection.append(
                 $('<div>')
                this.renderEditorTools()
            );
 
            const textarea =
                 this.textarea(
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                     .addClass(
                     .addClass(
                         'preload-editor-content'
                         'preload-editor-status'
                     );
                     );


             const editorMount =
             footer.append(
                 $('<div>')
                 this.localDraftStatus,
                    .addClass(
                this.status
                        'preload-editor-codemirror-mount'
            );
                    )
                    .append(textarea);


             editorSection.append(editorMount);
             this.root.append(
             left.append(editorSection);
                footer
             );


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


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


             analysisSection.append(
        renderWelcome() {
                analysisContainer
             this.workspace.empty();
            );


             const variablesSection =
             const section =
                 this.createSection('Variables');
                 this.createSection('Get started');


             const detectVariablesButton =
             $('<p>')
                 this.createButton(
                 .text(
                     'Detect variables',
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                    'preload-editor-button-primary preload-editor-detect-variables',
                )
                    () =>
                .appendTo(section);
                        this.detectVariables()
                );


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


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


             const variableContainer =
             section.append(tips);
                $('<div>')
            this.workspace.append(section);
                    .addClass(
        },
                        'preload-editor-variables'
                    );


             variablesSection.append(
        setStatus(
                 variableContainer
            message,
             );
            type
        ) {
             if (!this.status) {
                 return;
             }


             const configurationSection =
             this.status.removeClass(
                 this.createSection(
                'is-error',
                     'Variable configuration'
                'is-success',
                'is-warning',
                'is-loading'
            );
 
            if (type) {
                 this.status.addClass(
                     'is-' + type
                 );
                 );
            }


             const configurationContainer =
             this.status.text(
                 $('<div>')
                 message || ''
                    .addClass(
            );
                        'preload-editor-variable-configuration'
        },
                    );
 
        // =========================================================
        // Load / create
        // =========================================================


             configurationSection.append(
        async loadExisting(title) {
                configurationContainer
             title =
            );
                String(title || '').trim();


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


            const configHelp =
                 return;
                 $('<div>')
            }
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );


             const reviewConfigButton =
             this.setStatus(
                this.createButton(
                'Loading preload...',
                    'Review config.json',
                'loading'
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );
 
            configSection.append(
                configHelp,
                reviewConfigButton
             );
             );


             right.append(
             try {
                 analysisSection,
                 const page =
                variablesSection,
                    await this.getPage(title);
                configurationSection,
                configSection
            );


            layout.append(
                if (!page) {
                left,
                    const suggestions =
                right
                        await this.findSimilarPreloads(
            );
                            title
                        );


            const saveBar =
                     this.renderMissingPage(
                $('<div>')
                         title,
                     .addClass(
                        suggestions
                         'preload-editor-save-bar'
                     );
                     );


            saveBar.append(
                    this.setStatus(
                this.createButton(
                        'Preload not found.',
                    'Save Preload',
                        'warning'
                    '',
                     );
                     () =>
                        this.savePreloadOnly()
                ),


                this.createButton(
                     return;
                    'Save Config',
                 }
                     '',
                    () =>
                        this.saveConfigOnly()
                 ),


                 this.createButton(
                 await this.loadDefinition(
                     'Save',
                     page.title,
                     'preload-editor-button-primary',
                     page.content
                    () =>
                 );
                        this.saveAll()
                 )
            );


            this.root
                this.setStatus(
                .find('.preload-editor-footer')
                    'Preload loaded.',
                 .append(saveBar);
                    'success'
                );
            } catch (error) {
                 console.error(
                    'Preload Editor:',
                    error
                );


            this.workspace.append(
                this.setStatus(
                 layout
                    error.message ||
             );
                        'Could not load preload.',
                    'error'
                 );
             }
        },


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


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


             this.renderAnalysis(
             try {
                analysisContainer
                const results =
            );
                    await this.searchPages(query);


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


            this.updateEditorTools();
                return [];
             this.updateLocalDraftIndicator();
             }
        },


            this.mountCodeMirror(
        renderMissingPage(
                textarea.get(0)
            title,
             ).catch(
             suggestions
                error => {
        ) {
                    console.error(
            this.workspace.empty();
                        'Preload Editor CodeMirror:',
                        error
                    );


                    this.setStatus(
            const section =
                        error.message ||
                this.createSection(
                            'Could not initialize CodeMirror.',
                    'Preload not found'
                        'error'
                 );
                    );
                 }
            );
        },


        // =========================================================
            $('<p>')
        // Variable detection
                .text(
        // =========================================================
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


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


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


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


            const analysis =
                 section.append(list);
                 this.analyzePreload(
            }
                    content
                );


             /*
             section.append(
            * IMPORTANT:
                this.createButton(
            *
                    'Create this preload',
            * If a variable was previously deleted from
                    'preload-editor-button-primary',
            * the configuration, detecting the current
                    () =>
            * preload again should allow it to come back.
                        this.startNew(title)
            *
            * Example:
            *
            *  delete FOO
            *  edit preload -> %%FOO%%
            *  Detect variables
            *
            * FOO is removed from deletedVariables here,
            * allowing prepareConfigForVariables() to
            * recreate/restore its configuration.
            */
            if (
                Array.isArray(
                    this.state.deletedVariables
                 )
                 )
             ) {
             );
                const detected =
 
                    new Set(
            this.workspace.append(section);
                        analysis.variables
        },
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                    );


                this.state.deletedVariables =
        async startNew(title) {
                    this.state.deletedVariables
            title =
                        .filter(
                String(title || '').trim();
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                this.state.deletedVariables = [];
            }


             this.markDirty();
             this.state = {
                preloadTitle: title,
                preloadSource: '',
                preloadContent:
                    this.defaults.preload,


            this.reanalyze();
                config:
 
                    this.emptyConfig(),
            this.renderVariablesBySelector();
 
            this.renderVariableConfigurationBySelector();
                variables: ['PAGE'],
            this.renderAnalysisBySelector();
                conditions: [],
             this.updateEditorTools();
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                localDraftAvailable: false
             };


             this.saveDraft();
             this.saveDraft();
            this.renderEditor();


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


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


             this.state.preloadContent =
             if (!result) {
                 source;
                 return;
            }


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


             this.state.conditions =
             try {
                analysis.conditions;
                const page =
                    await this.getPage(result);


            this.state.config =
                if (!page) {
                 this.prepareConfigForVariables(
                    throw new Error(
                     this.state.config ||
                        'Sample page not found: ' +
                         this.emptyConfig(),
                        result
                     analysis
                    );
                );
                }
 
                 const sample =
                     this.convertSampleToPreload(
                         page.content
                     );


            this.analysis =
                this.state = {
                analysis;
                    preloadTitle: '',
                    preloadSource: '',
                    preloadContent: sample,


            const available =
                    config:
                ['PAGE'].concat(
                        this.emptyConfig(),
                    analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );


            if (
                    variables: ['PAGE'],
                !available.includes(
                    conditions: [],
                     this.state.selectedVariable
                     selectedVariable: 'PAGE',
                )
                     deletedVariables: [],
            ) {
                     mode: 'new',
                this.state.selectedVariable =
                    dirty: true,
                     available[0] ||
                    dirtyPreload: true,
                     'PAGE';
                    dirtyConfig: true,
            }
        },


        // =========================================================
                    localDraftSavedAt: null,
        // Analysis
                    localDraftAvailable: false
        // =========================================================
                };


        renderAnalysis(container) {
                this.reanalyze();
            container.empty();
                this.saveDraft();
                this.renderEditor();


            const analysis =
                 this.setStatus(
                 this.analysis ||
                    'Sample page loaded.',
                this.analyzePreload(
                     'success'
                     this.extractIncludeonly(
                );
                        this.getEditorContent()
            } catch (error) {
                     )
                console.error(
                     'Preload Editor sample:',
                    error
                 );
                 );


            const variableCount =
                this.setStatus(
                analysis.variables.length;
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
        },


             const conditionCount =
        convertSampleToPreload(source) {
                 analysis.conditions.length;
             let content =
                 String(source || '').trim();


             const configuredCount =
             const include =
                 Object.keys(
                 content.match(
                     this.state.config &&
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                    this.state.config.fields
                 );
                        ? this.state.config.fields
                        : {}
                 ).length;


             const summary =
             if (include) {
                 $('<div>')
                 content =
                     .addClass(
                     include[1].trim();
                        'preload-editor-analysis-summary'
            }
                    );


             const createMetric =
             content =
                 (
                 content
                    value,
                     .replace(
                     label
                         /<noinclude>[\s\S]*?<\/noinclude>/gi,
                ) =>
                        ''
                    $('<div>')
                    )
                        .addClass(
                    .trim();
                            'preload-editor-analysis-metric'
                         )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


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


            summary.append(
        async loadDefinition(
                createMetric(
            title,
                    variableCount,
            source
                    variableCount === 1
        ) {
                        ? 'variable'
            const content =
                        : 'variables'
                 this.extractIncludeonly(source);
                 ),


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


                 createMetric(
            const configTitle =
                     configuredCount,
                 title.replace(
                     configuredCount === 1
                     /\/+$/,
                        ? 'configured field'
                     ''
                        : 'configured fields'
                 ) +
                 )
                '/config.json';
            );


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


             if (
             if (configPage) {
                analysis.conditionVariables.length
                 try {
            ) {
                     config =
                 container.append(
                         JSON.parse(
                     $('<div>')
                             configPage.content
                         .addClass(
                         );
                             'preload-editor-analysis-note'
                } catch (error) {
                         )
                    throw new Error(
                        .text(
                        'The existing config.json contains invalid JSON: ' +
                            'Condition variables: ' +
                        error.message
                            analysis.conditionVariables.join(', ')
                    );
                        )
                 }
                 );
             }
             }


             const validation =
             const analysis =
                 this.validateConfig(
                 this.analyzePreload(content);
                    this.state.config,
 
            this.state.deletedVariables = [];
 
            config =
                this.prepareConfigForVariables(
                    config,
                     analysis
                     analysis
                 );
                 );


             if (validation.errors.length) {
             this.state = {
                 const errors =
                 preloadTitle: title,
                    $('<ul>')
                preloadSource: source,
                        .addClass(
                preloadContent: source,
                            'preload-editor-validation-errors'
                config,
                        );


                 validation.errors.forEach(
                 variables:
                     error => {
                     analysis.variables,
                        $('<li>')
 
                            .text(error)
                conditions:
                            .appendTo(errors);
                    analysis.conditions,
                    }
                );


                 container.append(errors);
                 selectedVariable:
            }
                    analysis.variables.includes('PAGE')
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),


            if (validation.warnings.length) {
                 deletedVariables: [],
                 const warnings =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );


                 validation.warnings.forEach(
                 mode: 'edit',
                    warning => {
                dirty: false,
                        $('<li>')
                dirtyPreload: false,
                            .text(warning)
                 dirtyConfig: false,
                            .appendTo(warnings);
                    }
                 );


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


             if (
             this.clearDraft(title);
                !validation.errors.length &&
             this.renderEditor();
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },
 
        renderAnalysisBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );
 
             if (
                container &&
                container.length
            ) {
                this.renderAnalysis(container);
            }
         },
         },


         // =========================================================
         // =========================================================
         // Variables
         // Editor
         // =========================================================
         // =========================================================


         renderVariables(container) {
         renderEditor() {
             container.empty();
             this.destroyEditor();
            this.workspace.empty();


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


             const variables =
             const left =
                 analysis.variables.slice();
                 $('<div>')
                    .addClass(
                        'preload-editor-left'
                    );


             const ordered =
             const right =
                 ['PAGE'];
                 $('<div>')
                    .addClass(
                        'preload-editor-right'
                    );


             variables.forEach(
             const editorSection =
                name => {
                this.createSection(
                     if (
                     'Preload',
                        name !== 'PAGE' &&
                     'preload-editor-main-section'
                        !ordered.includes(name)
                 );
                     ) {
                        ordered.push(name);
                    }
                 }
            );


             const configuredFields =
             const meta =
                 this.state.config &&
                 $('<div>')
                this.state.config.fields
                     .addClass(
                     ? Object.keys(
                         'preload-editor-meta'
                         this.state.config.fields
                     );
                     )
                    : [];


             configuredFields.forEach(
             $('<strong>')
                 name => {
                .text(
                     const upper =
                    this.state.preloadTitle ||
                         name.toUpperCase();
                    'New preload'
                 )
                .appendTo(meta);
 
            if (
                this.state.mode === 'new'
            ) {
                $('<span>')
                     .addClass(
                         'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
            }


                    if (
            editorSection.append(meta);
                        upper !== 'PAGE' &&
            editorSection.append(
                        !ordered.includes(upper)
                this.renderEditorTools()
                    ) {
                        ordered.push(upper);
                    }
                }
             );
             );


             const deleted =
             const textarea =
                 Array.isArray(
                 this.textarea(
                     this.state.deletedVariables
                     this.state.preloadContent
                 )
                 )
                     ? this.state.deletedVariables
                     .attr(
                     : [];
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                     );


             deleted.forEach(
             const editorMount =
                 name => {
                 $('<div>')
                     const upper =
                     .addClass(
                         String(name).toUpperCase();
                         'preload-editor-codemirror-mount'
                    )
                    .append(textarea);
 
            editorSection.append(editorMount);
            left.append(editorSection);


                    if (
            const analysisSection =
                        upper !== 'PAGE' &&
                this.createSection('Analysis');
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );


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


             ordered.forEach(
             analysisSection.append(
                 name => {
                 analysisContainer
                    const isSelected =
            );
                        name ===
                        this.state.selectedVariable;


                    const isUsed =
            const variablesSection =
                        analysis.variables.includes(
                this.createSection('Variables');
                            name
                        );


                    const isConfigured =
            const detectVariablesButton =
                        !!(
                this.createButton(
                            this.state.config &&
                    'Detect variables',
                            this.state.config.fields &&
                    'preload-editor-button-primary preload-editor-detect-variables',
                            this.state.config.fields[name]
                    () =>
                        );
                        this.detectVariables()
                );


                    const item =
            const detectHelp =
                        $('<button>')
                $('<div>')
                            .attr({
                    .addClass(
                                type: 'button',
                        'preload-editor-help preload-editor-detect-variables-help'
                                'data-variable':
                    )
                                    name
                    .text(
                            })
                        'Refresh the variable list after editing the preload.'
                            .addClass(
                    );
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                    $('<span>')
            variablesSection.append(
                        .addClass(
                $('<div>')
                            'preload-editor-variable-name'
                    .addClass(
                        )
                        'preload-editor-variable-detect'
                        .text(name)
                    )
                        .appendTo(item);
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );


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


                    list.append(item);
            variablesSection.append(
                 }
                 variableContainer
             );
             );


             container.append(list);
             const configurationSection =
                this.createSection(
                    'Variable configuration'
                );


             if (!ordered.length) {
             /*
                 container.append(
            * Import button lives at the top of the
                     $('<div>')
            * variable configuration section so the
                        .addClass(
            * workflow is always easy to find.
                            'preload-editor-empty'
            */
                        )
            const importDefinitionsButton =
                         .text(
                 this.createButton(
                            'No variables found in the preload.'
                     'Import definitions',
                        )
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                         this.importVariableDefinitions()
                 );
                 );
            }
        },


        renderVariablesBySelector() {
             const importHelp =
             const container =
                 $('<div>')
                 this.root &&
                    .addClass(
                this.root.find(
                        'preload-editor-help preload-editor-import-definitions-help'
                    '.preload-editor-variables'
                    )
                );
                    .text(
                        'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );


             if (
             const importControls =
                 container &&
                 $('<div>')
                container.length
                    .addClass(
            ) {
                        'preload-editor-import-definition-controls'
                this.renderVariables(container);
                    )
            }
                    .append(
        },
                        importDefinitionsButton,
                        importHelp
                    );


        selectVariable(name) {
            configurationSection.append(
            name =
                 importControls
                 String(name || '')
            );
                    .trim()
                    .toUpperCase();


             if (!name) {
             const configurationContainer =
                 return;
                $('<div>')
             }
                    .addClass(
                        'preload-editor-variable-configuration'
                    );
 
            configurationSection.append(
                 configurationContainer
             );


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


             const configuredUnused =
             const configHelp =
                 this.state.config &&
                 $('<div>')
                this.state.config.fields
                     .addClass(
                     ? Object.keys(
                         'preload-editor-help'
                         this.state.config.fields
                     )
                     )
                        .map(
                    .text(
                            variable =>
                        'Review the exact config.json that will be uploaded to the wiki.'
                                variable.toUpperCase()
                    );
                        )
                    : [];


             configuredUnused.forEach(
             const reviewConfigButton =
                variable => {
                this.createButton(
                     if (
                     'Review config.json',
                        !available.includes(variable) &&
                    '',
                        variable !== 'PAGE'
                     () =>
                     ) {
                         this.createConfigReviewDialog()
                         available.push(variable);
                );
                    }
 
                 }
            configSection.append(
                configHelp,
                 reviewConfigButton
             );
             );


             if (!available.includes(name)) {
             right.append(
                 return;
                 analysisSection,
             }
                variablesSection,
                configurationSection,
                configSection
             );


             this.state.selectedVariable =
             layout.append(
                 name;
                left,
                 right
            );


             this.renderVariablesBySelector();
             const saveBar =
            this.renderVariableConfigurationBySelector();
                $('<div>')
        },
                    .addClass(
                        'preload-editor-save-bar'
                    );


        renderVariableConfigurationBySelector() {
            saveBar.append(
            const container =
                this.createButton(
                this.root &&
                    'Save Preload',
                 this.root.find(
                    '',
                     '.preload-editor-variable-configuration'
                    () =>
                 );
                        this.savePreloadOnly()
                ),
 
                 this.createButton(
                     'Save Config',
                    '',
                    () =>
                        this.saveConfigOnly()
                 ),


            if (
                this.createButton(
                container &&
                    'Save',
                container.length
                    'preload-editor-button-primary',
            ) {
                    () =>
                this.renderVariableConfiguration(
                        this.saveAll()
                    container
                 )
                 );
             );
             }
        },


        renderVariableConfiguration(container) {
            this.root
            container.empty();
                .find('.preload-editor-footer')
                .append(saveBar);


             const analysis =
             this.workspace.append(
                this.analysis ||
                layout
                this.analyzePreload(
            );
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


             const name =
             this.reanalyze();
                this.state.selectedVariable ||
                'PAGE';


             const fields =
             this.renderVariables(
                this.state.config &&
                 variableContainer
                 this.state.config.fields
            );
                    ? this.state.config.fields
                    : {};


             const field =
             this.renderAnalysis(
                 fields[name];
                 analysisContainer
            );


             if (name === 'PAGE') {
             this.renderVariableConfiguration(
                container.append(
                configurationContainer
                    this.createAutomaticPageCard(
            );
                        field ||
                        this.getAutomaticPageField()
                    )
                );


                return;
            this.updateEditorTools();
             }
             this.updateLocalDraftIndicator();


             if (!field) {
             this.mountCodeMirror(
                 const missing =
                textarea.get(0)
                     $('<div>')
            ).catch(
                         .addClass(
                 error => {
                            'preload-editor-variable preload-editor-variable-missing'
                     console.error(
                         );
                         'Preload Editor CodeMirror:',
                         error
                    );


                $('<div>')
                    this.setStatus(
                    .addClass(
                        error.message ||
                         'preload-editor-variable-header'
                            'Could not initialize CodeMirror.',
                     )
                         'error'
                    .append(
                     );
                        $('<h3>')
                }
                            .text(name),
            );
        },
 
        // =========================================================
        // Variable detection
        // =========================================================


                        $('<span>')
        detectVariables() {
                            .addClass(
            const source =
                                'preload-editor-badge is-warning'
                this.getEditorContent();
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


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


                 container.append(missing);
            const content =
                 return;
                 this.extractIncludeonly(
            }
                    source
                 );


             container.append(
             const analysis =
                 this.createVariableCard(
                 this.analyzePreload(
                     name,
                     content
                    field,
                );
                     analysis
 
            /*
            * 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(
        createAutomaticPageCard(field) {
                        analysis.variables
            const card =
                            .map(
                $('<div>')
                                name =>
                    .addClass(
                                    String(
                        'preload-editor-variable preload-editor-variable-automatic'
                                        name
                    )
                                    ).toUpperCase()
                    .attr(
                            )
                        'data-variable',
                        'PAGE'
                     );
                     );


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


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


             card.append(header);
             this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.updateEditorTools();


             $('<p>')
             this.saveDraft();
                .addClass(
                    'preload-editor-analysis-note'
                )
                .text(
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);


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


             const description =
        reanalyze() {
                 this.textarea(
             const source =
                    field.description ||
                 this.getEditorContent();
                    'Name of the page.'
 
                 )
            const content =
                    .addClass(
                 this.extractIncludeonly(source);
                        'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                    );


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


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


             const namespace =
             this.state.variables =
                this.textInput(
                 analysis.variables;
                    field.namespace || 'Main'
                 ).prop(
                    'disabled',
                    true
                );


             const allowNew =
             this.state.conditions =
                 this.checkbox(
                 analysis.conditions;
                    field['allow-new'] === true
 
                 ).prop(
            this.state.config =
                     'disabled',
                 this.prepareConfigForVariables(
                     true
                     this.state.config ||
                        this.emptyConfig(),
                     analysis
                 );
                 );


             card.append(
             this.analysis =
                this.fieldRow(
                 analysis;
                    'Label',
                    label
                 ),


                 this.fieldRow(
            const available =
                     'Description',
                 ['PAGE'].concat(
                     description
                     analysis.variables.filter(
                 ),
                        name =>
                            name !== 'PAGE'
                     )
                 );


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


                 this.fieldRow(
        // =========================================================
                     'Required',
        // Analysis
                     required
        // =========================================================
                 ),
 
        renderAnalysis(container) {
            container.empty();
 
            const analysis =
                this.analysis ||
                 this.analyzePreload(
                     this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );


                 this.fieldRow(
            const variableCount =
                    'Namespace',
                 analysis.variables.length;
                    namespace
                ),


                 this.fieldRow(
            const conditionCount =
                    'Allow new page',
                 analysis.conditions.length;
                    allowNew
                )
            );


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


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


             const header =
             const createMetric =
                 $('<div>')
                 (
                     .addClass(
                     value,
                        'preload-editor-variable-header'
                     label
                     );
                 ) =>
 
                     $('<div>')
            header.append(
                 $('<h3>').text(name)
            );
 
            if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                     $('<span>')
                         .addClass(
                         .addClass(
                             'preload-editor-badge is-warning'
                             'preload-editor-analysis-metric'
                         )
                         )
                         .text('UNUSED')
                         .append(
                );
                            $('<strong>')
            }
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


            card.append(header);
                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                        );


             const label =
             summary.append(
                 this.textInput(
                 createMetric(
                     field.label || ''
                     variableCount,
                 );
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                 ),


            label.on(
                createMetric(
                'input.preloadEditor',
                    conditionCount,
                () => {
                    conditionCount === 1
                    field.label =
                        ? 'condition marker'
                         label.val();
                         : 'condition markers'
                ),


                    this.markDirty();
                createMetric(
                     this.renderConfigReviewAvailability();
                     configuredCount,
                }
                    configuredCount === 1
            );
                        ? 'configured field'
 
                        : 'configured fields'
            card.append(
                this.fieldRow(
                    'Label',
                    label
                 )
                 )
             );
             );


             const description =
             container.append(summary);
                this.textarea(
                    field.description || ''
                ).addClass(
                    'preload-editor-small-textarea'
                );


             description.on(
             if (
                 'input.preloadEditor',
                 analysis.conditionVariables.length
                 () => {
            ) {
                    field.description =
                 container.append(
                         description.val();
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                         .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }


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


             card.append(
             if (validation.errors.length) {
                 this.fieldRow(
                 const errors =
                     'Description',
                     $('<ul>')
                    description
                        .addClass(
                )
                            'preload-editor-validation-errors'
            );
                        );


            const types = [
                 validation.errors.forEach(
                 ['text', 'Text'],
                    error => {
                ['textarea', 'Textarea'],
                        $('<li>')
                ['number', 'Number'],
                            .text(error)
                ['boolean', 'Boolean'],
                            .appendTo(errors);
                ['select', 'Select'],
                    }
                ['multiselect', 'Multi-select'],
                 );
                ['page', 'Page'],
                ['user', 'User'],
                 ['date', 'Date']
            ];


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


             typeSelect.on(
             if (validation.warnings.length) {
                'change.preloadEditor',
                 const warnings =
                 () => {
                     $('<ul>')
                     field.type =
                         .addClass(
                         typeSelect.val();
                            'preload-editor-validation-warnings'
                        );


                     this.markDirty();
                validation.warnings.forEach(
                     warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                );


                    this.renderVariableConfigurationBySelector();
                container.append(warnings);
                    this.renderConfigReviewAvailability();
            }
                }
            );


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


             const required =
        renderAnalysisBySelector() {
                 this.checkbox(
             const container =
                     field.required === true
                 this.root &&
                this.root.find(
                     '.preload-editor-analysis'
                 );
                 );


             required.on(
             if (
                 'change.preloadEditor',
                 container &&
                () => {
                container.length
                    field.required =
            ) {
                        required.prop('checked');
                this.renderAnalysis(container);
            }
        },


                    this.markDirty();
        // =========================================================
                    this.renderConfigReviewAvailability();
        // Variables
                }
        // =========================================================
            );


            card.append(
        renderVariables(container) {
                this.fieldRow(
            container.empty();
                    'Required',
                    required
                )
            );


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


             placeholder.on(
             const variables =
                 'input.preloadEditor',
                 analysis.variables.slice();
                () => {
 
                    const value =
            const ordered =
                        placeholder.val();
                ['PAGE'];


                     if (value) {
            variables.forEach(
                         field.placeholder =
                name => {
                            value;
                     if (
                     } else {
                         name !== 'PAGE' &&
                         delete field.placeholder;
                        !ordered.includes(name)
                     ) {
                         ordered.push(name);
                     }
                     }
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             card.append(
             const configuredFields =
                 this.fieldRow(
                this.state.config &&
                    'Placeholder',
                 this.state.config.fields
                     placeholder
                    ? Object.keys(
                )
                        this.state.config.fields
            );
                     )
                    : [];


             const defaultInput =
             configuredFields.forEach(
                 this.textInput(
                 name => {
                     field.default === undefined
                     const upper =
                        ? ''
                         name.toUpperCase();
                         : field.default
                );


            defaultInput.on(
                    if (
                'input.preloadEditor',
                        upper !== 'PAGE' &&
                () => {
                         !ordered.includes(upper)
                    const value =
                     ) {
                         defaultInput.val();
                         ordered.push(upper);
 
                     if (value) {
                         field.default =
                            value;
                    } else {
                        delete field.default;
                     }
                     }
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                 }
                 }
             );
             );


             card.append(
             const deleted =
                 this.fieldRow(
                 Array.isArray(
                     'Default',
                     this.state.deletedVariables
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                 )
                 )
                    ? this.state.deletedVariables
                    : [];
            deleted.forEach(
                name => {
                    const upper =
                        String(name).toUpperCase();
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
             );
             );


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


                maxRows.on(
            ordered.forEach(
                    'input.preloadEditor',
                name => {
                    () => {
                    const isSelected =
                        const value =
                        name ===
                            parseInt(
                        this.state.selectedVariable;
                                maxRows.val(),
                                10
                            );


                         if (
                    const isUsed =
                            Number.isFinite(value) &&
                         analysis.variables.includes(
                             value > 0
                             name
                         ) {
                         );
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }


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


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


            if (
                    $('<span>')
                field.type === 'select' ||
                        .addClass(
                field.type === 'multiselect'
                            'preload-editor-variable-name'
            ) {
                        )
                this.renderSelectConfiguration(
                        .text(name)
                    card,
                        .appendTo(item);
                    field
                );
            }


            const deleteButton =
                    if (name === 'PAGE') {
                this.createButton(
                        item.append(
                    'Delete variable',
                            $('<span>')
                    'preload-editor-button-danger preload-editor-delete-variable',
                                .addClass(
                     async () => {
                                    'preload-editor-badge'
                         const confirmed =
                                )
                             await this.createConfirmDialog(
                                .text('AUTOMATIC')
                                'Delete variable',
                        );
                                 'Delete "' +
                     } else if (!isConfigured) {
                                 name +
                         item.append(
                                 '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                             $('<span>')
                                'Delete variable',
                                 .addClass(
                                 'Cancel'
                                    'preload-editor-badge is-warning'
                            );
                                 )
 
                                 .text(
                        if (!confirmed) {
                                    isUsed
                             return;
                                        ? 'NOT CONFIGURED'
                        }
                                        : 'DELETED'
 
                                 )
                        this.deleteVariable(name);
                        );
                    } else if (!isUsed) {
                        item.append(
                             $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                     }
                     }
                );


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


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


         async deleteVariable(name) {
         renderVariablesBySelector() {
             name =
             const container =
                 String(name || '')
                 this.root &&
                    .trim()
                this.root.find(
                     .toUpperCase();
                     '.preload-editor-variables'
                );


             if (
             if (
                 !name ||
                 container &&
                 name === 'PAGE'
                 container.length
             ) {
             ) {
                 return;
                 this.renderVariables(container);
             }
             }
        },


             if (
        selectVariable(name) {
                 !this.state.config ||
             name =
                !this.state.config.fields
                 String(name || '')
             ) {
                    .trim()
                    .toUpperCase();
 
             if (!name) {
                 return;
                 return;
             }
             }


             delete this.state.config.fields[name];
             const available =
                ['PAGE'].concat(
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );


             if (
             const configuredUnused =
                 !Array.isArray(
                 this.state.config &&
                    this.state.deletedVariables
                this.state.config.fields
                )
                    ? Object.keys(
            ) {
                        this.state.config.fields
                this.state.deletedVariables = [];
                    )
             }
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];
 
             configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                }
            );


             if (
             if (!available.includes(name)) {
                !this.state.deletedVariables.includes(
                 return;
                    name
                )
            ) {
                 this.state.deletedVariables.push(
                    name
                );
             }
             }


             this.state.selectedVariable =
             this.state.selectedVariable =
                 name;
                 name;
            this.markDirty();


             this.renderVariablesBySelector();
             this.renderVariablesBySelector();
             this.renderVariableConfigurationBySelector();
             this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();
            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
         },
         },


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


        renderSelectConfiguration(
            if (
            card,
                container &&
             field
                container.length
        ) {
             ) {
            const source =
                 this.renderVariableConfiguration(
                 this.textInput(
                     container
                     field.source || '',
                    'category:Example'
                 );
                 );
            }
        },


            source.on(
        renderVariableConfiguration(container) {
                'input.preloadEditor',
            container.empty();
                () => {
                    const value =
                        source.val();


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


                    this.markDirty();
            const name =
                    this.renderConfigReviewAvailability();
                this.state.selectedVariable ||
                 }
                 'PAGE';
            );


             card.append(
             const fields =
                 this.fieldRow(
                this.state.config &&
                     'Source',
                 this.state.config.fields
                    source,
                     ? this.state.config.fields
                     'Currently supported source format: category:Category Name'
                     : {};
                )
 
             );
             const field =
                fields[name];


             const sourcePrefix =
             if (name === 'PAGE') {
                 this.textInput(
                 container.append(
                    field['source-prefix'] || ''
                    this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                 );
                 );


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


                    if (value) {
            if (!field) {
                        field['source-prefix'] =
                const missing =
                            value;
                     $('<div>')
                     } else {
                         .addClass(
                         delete field['source-prefix'];
                            'preload-editor-variable preload-editor-variable-missing'
                    }
                        );


                     this.markDirty();
                $('<div>')
                     this.renderConfigReviewAvailability();
                    .addClass(
                 }
                        'preload-editor-variable-header'
             );
                    )
                     .append(
                        $('<h3>')
                            .text(name),
 
                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);
 
                $('<p>')
                    .addClass(
                        'preload-editor-analysis-note'
                    )
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                     .appendTo(missing);
 
                 container.append(missing);
                return;
             }


             card.append(
             container.append(
                 this.fieldRow(
                 this.createVariableCard(
                     'Source prefix',
                     name,
                     sourcePrefix,
                     field,
                     'Only source values beginning with this text are included.'
                     analysis
                 )
                 )
             );
             );
        },


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


             excludeCategory.on(
             const header =
                 'input.preloadEditor',
                 $('<div>')
                () => {
                     .addClass(
                     const value =
                         'preload-editor-variable-header'
                         excludeCategory.val();
                    );


                    if (value) {
            header.append(
                        field.exclude =
                $('<h3>').text('PAGE'),
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
                $('<span>')
                            !Object.keys(
                    .addClass(
                                field.exclude
                        'preload-editor-badge'
                            ).length
                    )
                        ) {
                    .text('AUTOMATIC')
                            delete field.exclude;
            );
                        }
                    }


                    this.markDirty();
            card.append(header);
                    this.renderConfigReviewAvailability();
                }
            );


             card.append(
             $('<p>')
                 this.fieldRow(
                 .addClass(
                     'Exclude category',
                     'preload-editor-analysis-note'
                     excludeCategory
                )
                .text(
                     'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                 )
                 )
            );
                .appendTo(card);


             card.append(
             const label =
                 this.createTransformControls(
                 this.textInput(
                     field,
                     field.label ||
                     'value',
                     'Page Name'
                     'Value transformation'
                ).prop(
                 ),
                     'disabled',
                    true
                 );


                 this.createTransformControls(
            const description =
                     field,
                 this.textarea(
                     'label',
                     field.description ||
                    'Label transformation'
                     'Name of the page.'
                 )
                 )
            );
                    .addClass(
 
                        'preload-editor-small-textarea'
            const optionsValue =
                    )
                Array.isArray(field.options)
                     .prop(
                     ? field.options
                         'disabled',
                         .map(
                        true
                            option => {
                    );
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


                                return (
            const type =
                                    String(
                this.textInput(
                                        option.value || ''
                    field.type || 'page'
                                    ) +
                ).prop(
                                    ' | ' +
                     'disabled',
                                    String(
                     true
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                     : '';
 
            const options =
                this.textarea(
                     optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                 );
                 );


             options.on(
             const required =
                 'input.preloadEditor',
                 this.checkbox(
                () => {
                     field.required !== false
                     const lines =
                ).prop(
                        options
                    'disabled',
                            .val()
                    true
                            .split('\n')
                );
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                    if (!lines.length) {
            const namespace =
                        delete field.options;
                this.textInput(
                     } else {
                     field.namespace || 'Main'
                        field.options =
                ).prop(
                            lines.map(
                    'disabled',
                                line => {
                    true
                                    const parts =
                );
                                        line.split(
                                            /\s*\|\s*/
                                        );


                                    if (
            const allowNew =
                                        parts.length ===
                this.checkbox(
                                        1
                    field['allow-new'] === true
                                    ) {
                ).prop(
                                        return parts[0];
                    'disabled',
                                    }
                    true
                );


                                    return {
            card.append(
                                        value:
                this.fieldRow(
                                            parts[0],
                    'Label',
                    label
                ),
 
                this.fieldRow(
                    'Description',
                    description
                ),
 
                this.fieldRow(
                    'Type',
                    type
                ),


                                        label:
                this.fieldRow(
                                            parts
                    'Required',
                                                .slice(1)
                    required
                                                .join(
                ),
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }


                    this.markDirty();
                this.fieldRow(
                     this.renderConfigReviewAvailability();
                     'Namespace',
                 }
                    namespace
            );
                 ),


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


         createTransformControls(
            return card;
             field,
        },
             property,
 
             title
        createVariableCard(
         ) {
            name,
             const wrapper =
            field,
                 $('<div>')
            analysis
                     .addClass(
        ) {
                         'preload-editor-transform'
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );
 
            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );
 
            header.append(
                $('<h3>').text(name)
            );
 
            if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }
 
            card.append(header);
 
            const label =
                this.textInput(
                    field.label || ''
                );
 
            label.on(
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                )
            );
 
            const description =
                this.textarea(
                    field.description || ''
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            description.on(
                'input.preloadEditor',
                () => {
                    field.description =
                        description.val();
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Description',
                    description
                )
            );
 
            const types = [
                ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];
 
            const typeSelect =
                this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                );
 
            typeSelect.on(
                'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();
 
                    this.markDirty();
 
                    this.renderVariableConfigurationBySelector();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );
 
            const required =
                this.checkbox(
                    field.required === true
                );
 
            required.on(
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Required',
                    required
                )
            );
 
            const placeholder =
                this.textInput(
                    field.placeholder || ''
                );
 
            placeholder.on(
                'input.preloadEditor',
                () => {
                    const value =
                        placeholder.val();
 
                    if (value) {
                        field.placeholder =
                            value;
                    } else {
                        delete field.placeholder;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );
 
            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                );
 
            defaultInput.on(
                'input.preloadEditor',
                () => {
                    const value =
                        defaultInput.val();
 
                    if (value) {
                        field.default =
                            value;
                    } else {
                        delete field.default;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Default',
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
            );
 
            if (
                field.type === 'textarea'
            ) {
                const maxRows =
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );
 
                maxRows.on(
                    'input.preloadEditor',
                    () => {
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );
 
                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }
 
                        this.markDirty();
                        this.renderConfigReviewAvailability();
                    }
                );
 
                card.append(
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                );
            }
 
            if (
                field.type === 'select' ||
                field.type === 'multiselect'
            ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }
 
            if (
                field.type === 'file'
            ) {
                this.renderFileConfiguration(
                    card,
                    field
                );
            }
 
            const deleteButton =
                this.createButton(
                    'Delete variable',
                    'preload-editor-button-danger preload-editor-delete-variable',
                    async () => {
                        const confirmed =
                            await this.createConfirmDialog(
                                'Delete variable',
                                'Delete "' +
                                name +
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                                'Delete variable',
                                'Cancel'
                            );
 
                        if (!confirmed) {
                            return;
                        }
 
                        this.deleteVariable(name);
                    }
                );
 
            card.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );
 
            return card;
        },
 
        async deleteVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();
 
            if (
                !name ||
                name === 'PAGE'
            ) {
                return;
            }
 
            if (
                !this.state.config ||
                !this.state.config.fields
            ) {
                return;
            }
 
            delete this.state.config.fields[name];
 
            if (
                !Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                this.state.deletedVariables = [];
            }
 
            if (
                !this.state.deletedVariables.includes(
                    name
                )
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }
 
            this.state.selectedVariable =
                name;
 
            this.markDirty();
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();
 
            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },
 
        // =========================================================
        // Select configuration
        // =========================================================
 
        renderSelectConfiguration(
            card,
            field
        ) {
            const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                );
 
            source.on(
                'input.preloadEditor',
                () => {
                    const value =
                        source.val();
 
                    if (value) {
                        field.source = value;
                    } else {
                        delete field.source;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source',
                    source,
                    'Currently supported source format: category:Category Name'
                )
            );
 
            const sourcePrefix =
                this.textInput(
                    field['source-prefix'] || ''
                );
 
            sourcePrefix.on(
                'input.preloadEditor',
                () => {
                    const value =
                        sourcePrefix.val();
 
                    if (value) {
                        field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );
 
            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );
 
            excludeCategory.on(
                'input.preloadEditor',
                () => {
                    const value =
                        excludeCategory.val();
 
                    if (value) {
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;
 
                        if (
                            !Object.keys(
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                )
            );
 
            card.append(
                this.createTransformControls(
                    field,
                    'value',
                    'Value transformation'
                ),
 
                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );
 
            const optionsValue =
                Array.isArray(field.options)
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }
 
                                return (
                                    String(
                                        option.value || ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';
 
            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            options.on(
                'input.preloadEditor',
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);
 
                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );
 
                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }
 
                                    return {
                                        value:
                                            parts[0],
 
                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
       
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);
 
                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );
 
            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );
 
            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();
 
                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );
 
            const filetext =
                this.textarea(
                    field.filetext || ''
                );
 
            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();
 
                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },
 
         createTransformControls(
             field,
             property,
             title
         ) {
             const wrapper =
                 $('<div>')
                     .addClass(
                         'preload-editor-transform'
                    );
 
            $('<h4>')
                .text(title)
                .appendTo(wrapper);
 
            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );
 
            const prefix =
                this.textInput(
                    existing.prefix || ''
                );
 
            const suffix =
                this.textInput(
                    existing.suffix || ''
                );
 
            const from =
                this.textInput(
                    existing.from || ''
                );
 
            const to =
                this.textInput(
                    existing.to || ''
                );
 
            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );
 
            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );
 
            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );
 
            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );
 
            const toRow =
                this.fieldRow(
                    'To',
                    to
                );
 
            const renderInputs =
                () => {
                    const type =
                        transform.val();
 
                    prefixRow.toggle(
                        type === 'remove-prefix'
                     );
                     );


            $('<h4>')
                    suffixRow.toggle(
                .text(title)
                        type === 'remove-suffix'
                .appendTo(wrapper);
                    );


            const existing =
                    fromRow.toggle(
                field[property] &&
                        type === 'replace'
                typeof field[property] === 'object'
                     );
                     ? field[property]
                    : {};


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


             const prefix =
             const update =
                 this.textInput(
                 () => {
                     existing.prefix || ''
                     const type =
                );
                        transform.val();


            const suffix =
                    let object = null;
                this.textInput(
                    existing.suffix || ''
                );


            const from =
                    if (
                this.textInput(
                        type === 'remove-prefix' &&
                     existing.from || ''
                        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()
                        };
                    }


            const to =
                    if (object) {
                this.textInput(
                        field[property] = object;
                     existing.to || ''
                     } else {
                );
                        delete field[property];
                    }


             const controls =
                    this.markDirty();
                 $('<div>')
                    this.renderConfigReviewAvailability();
                     .addClass(
                };
                         'preload-editor-transform-controls'
 
             transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                 to
            ].forEach(
                input => {
                     input.on(
                         'input.preloadEditor',
                        update
                     );
                     );
                }
            );


             const prefixRow =
             controls.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Prefix',
                     'Transformation',
                     prefix
                     transform
                 );
                 ),


            const suffixRow =
                prefixRow,
                 this.fieldRow(
                suffixRow,
                    'Suffix',
                 fromRow,
                    suffix
                toRow
                );
            );


             const fromRow =
             renderInputs();
                this.fieldRow(
                    'From',
                    from
                );


             const toRow =
             wrapper.append(controls);
                this.fieldRow(
                    'To',
                    to
                );


             const renderInputs =
             return wrapper;
                () => {
        },
                    const type =
                        transform.val();


                    prefixRow.toggle(
        // =========================================================
                        type === 'remove-prefix'
        // Config output
                    );
        // =========================================================


                     suffixRow.toggle(
        getCleanConfig() {
                         type === 'remove-suffix'
            const config =
                     );
                JSON.parse(
                     JSON.stringify(
                         this.state.config
                     )
                );


                    fromRow.toggle(
            const fields =
                        type === 'replace'
                config.fields || {};
                    );


                    toRow.toggle(
            const orderedFields = {};
                        type === 'replace'
                    );
                };


             const update =
             orderedFields.PAGE =
                 () => {
                 this.getAutomaticPageField();
                    const type =
                        transform.val();


                     let object = null;
            Object.keys(fields)
                .filter(
                     name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );


                    if (
            config.fields =
                        type === 'remove-prefix' &&
                orderedFields;
                        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) {
            return config;
                        field[property] = object;
        },
                    } else {
                        delete field[property];
                    }


                    this.markDirty();
        getConfigJSON() {
                    this.renderConfigReviewAvailability();
            return JSON.stringify(
                 };
                 this.getCleanConfig(),
 
                 null,
            transform.on(
                 4
                 'change.preloadEditor',
                 () => {
                    update();
                    renderInputs();
                }
             );
             );
        },


             [
        renderConfigPreview(container) {
                prefix,
             if (container) {
                 suffix,
                 container.text(
                from,
                     this.getConfigJSON()
                to
                );
            ].forEach(
            }
                input => {
        },
                     input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );


            controls.append(
        renderConfigPreviewBySelector() {
                this.fieldRow(
            this.renderAnalysisBySelector();
                    'Transformation',
        },
                    transform
                ),


                prefixRow,
        renderConfigReviewAvailability() {
                suffixRow,
             this.renderAnalysisBySelector();
                fromRow,
                toRow
            );
 
            renderInputs();
 
             wrapper.append(controls);
 
            return wrapper;
         },
         },


         // =========================================================
         // =========================================================
         // Config output
         // Dirty state
         // =========================================================
         // =========================================================


         getCleanConfig() {
         updateDirtyState() {
             const config =
             this.state.dirty =
                 JSON.parse(
                 !!(
                     JSON.stringify(
                     this.state.dirtyPreload ||
                        this.state.config
                    this.state.dirtyConfig
                    )
                 );
                 );
        },


             const fields =
        markPreloadDirty() {
                config.fields || {};
             this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },


             const orderedFields = {};
        markConfigDirty() {
             this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },


             orderedFields.PAGE =
        markDirty() {
                this.getAutomaticPageField();
             this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },


            Object.keys(fields)
        // =========================================================
                .filter(
        // Save
                    name =>
        // =========================================================
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );


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


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


        getConfigJSON() {
                if (!result) {
            return JSON.stringify(
                    return;
                 this.getCleanConfig(),
                 }
                null,
                4
            );
        },


        renderConfigPreview(container) {
                title = result;
            if (container) {
                 this.state.preloadTitle =
                 container.text(
                     title;
                     this.getConfigJSON()
                );
             }
             }
        },


        renderConfigPreviewBySelector() {
            this.state.preloadContent =
             this.renderAnalysisBySelector();
                this.getEditorContent();
        },
 
             const validation =
                this.validateBeforeSave();


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


        // =========================================================
                this.saveDraft();
        // Dirty state
                return;
        // =========================================================
            }


        updateDirtyState() {
             const confirmed =
             this.state.dirty =
                 await this.confirmSave(
                 !!(
                     'preload',
                     this.state.dirtyPreload ||
                     title
                     this.state.dirtyConfig
                 );
                 );
        },


        markPreloadDirty() {
            if (!confirmed) {
            this.state.dirtyPreload = true;
                return;
             this.updateDirtyState();
             }
            this.saveDraft();
        },


        markConfigDirty() {
            this.setStatus(
            this.state.dirtyConfig = true;
                'Saving preload...',
            this.updateDirtyState();
                'loading'
             this.saveDraft();
             );
        },


        markDirty() {
            try {
            this.state.dirtyPreload = true;
                const exists =
            this.state.dirtyConfig = true;
                    await this.pageExists(title);
            this.updateDirtyState();
            this.saveDraft();
        },


        // =========================================================
                await this.savePage(
        // Save
                    title,
        // =========================================================
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );


        async savePreloadOnly() {
                this.state.mode = 'edit';
            let title =
                 this.state.preloadTitle = title;
                 String(
                 this.state.dirtyPreload = false;
                    this.state.preloadTitle || ''
                 ).trim();


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


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


                 title = result;
                 this.setStatus(
                this.state.preloadTitle =
                    this.state.dirtyConfig
                     title;
                        ? 'Preload saved. Config still has unsaved changes.'
            }
                        : 'Preload saved successfully.',
                     'success'
                );


            this.state.preloadContent =
                mw.notify(
                this.getEditorContent();
                    this.state.dirtyConfig
 
                        ? 'Preload saved. Config still has unsaved changes.'
            const validation =
                        : 'Preload saved.',
                 this.validateBeforeSave();
                    {
 
                        type: 'success'
             if (validation.errors.length) {
                    }
                 this.showValidationErrors(
                 );
                     validation
             } catch (error) {
                 console.error(
                     'Preload Editor save:',
                    error
                 );
                 );


                 this.saveDraft();
                 this.saveDraft();
                return;
            }


            const confirmed =
                 this.setStatus(
                 await this.confirmSave(
                     error.message ||
                     'preload',
                        'Could not save preload.',
                     title
                     'error'
                 );
                 );


            if (!confirmed) {
                mw.notify(
                 return;
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                 );
             }
             }
        },


             this.setStatus(
        async saveConfigOnly() {
                'Saving preload...',
             let title =
                 'loading'
                String(
            );
                    this.state.preloadTitle || ''
                 ).trim();


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


                 await this.savePage(
                 if (!result) {
                     title,
                     return;
                    this.state.preloadContent,
                 }
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                 );


                 this.state.mode = 'edit';
                 title = result;
                 this.state.preloadTitle = title;
                 this.state.preloadTitle =
                this.state.dirtyPreload = false;
                    title;
            }


                 this.updateDirtyState();
            this.state.preloadContent =
                 this.getEditorContent();


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


                 this.setStatus(
            const validation =
                    this.state.dirtyConfig
                 this.validateBeforeSave();
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved successfully.',
                    'success'
                );


                mw.notify(
            if (validation.errors.length) {
                    this.state.dirtyConfig
                 this.showValidationErrors(
                        ? 'Preload saved. Config still has unsaved changes.'
                     validation
                        : 'Preload saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                 console.error(
                     'Preload Editor save:',
                    error
                 );
                 );


                 this.saveDraft();
                 this.saveDraft();
                return;
            }


                 this.setStatus(
            const confirmed =
                     error.message ||
                 await this.confirmSave(
                        'Could not save preload.',
                     'config',
                     'error'
                     title
                 );
                 );


                mw.notify(
            if (!confirmed) {
                    error.message ||
                 return;
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                 );
             }
             }
        },


        async saveConfigOnly() {
             const configTitle =
             let title =
                 title.replace(
                 String(
                     /\/+$/,
                     this.state.preloadTitle || ''
                    ''
                 ).trim();
                 ) +
                '/config.json';


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


                if (!result) {
            try {
                    return;
                 /*
                 }
                * This now automatically creates or converts
 
                * config.json to the JSON content model.
                title = result;
                */
                this.state.preloadTitle =
                 await this.saveConfigPage(
                    title;
                     configTitle,
            }
                     this.getConfigJSON(),
 
                     (
            this.state.preloadContent =
                         await this.pageExists(
                this.getEditorContent();
                            configTitle
 
                        )
            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 {
                const configExists =
                     await this.pageExists(
                         configTitle
                    );
 
                await this.savePage(
                    configTitle,
                    this.getConfigJSON(),
                     configExists
                         ? 'Updated preload config with Preload Editor'
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor',
                         : 'Created preload config with Preload Editor'
                    !configExists
                 );
                 );


Line 5,461: Line 5,882:
                 this.setStatus(
                 this.setStatus(
                     this.state.dirtyPreload
                     this.state.dirtyPreload
                         ? 'Config saved. Preload still has unsaved changes.'
                         ? 'Config saved as JSON. Preload still has unsaved changes.'
                         : 'Config saved successfully.',
                         : 'Config saved as JSON successfully.',
                     'success'
                     'success'
                 );
                 );
Line 5,468: Line 5,889:
                 mw.notify(
                 mw.notify(
                     this.state.dirtyPreload
                     this.state.dirtyPreload
                         ? 'Config saved. Preload still has unsaved changes.'
                         ? 'Config saved as JSON. Preload still has unsaved changes.'
                         : 'Config saved.',
                         : 'Config saved as JSON.',
                     {
                     {
                         type: 'success'
                         type: 'success'
Line 5,572: Line 5,993:
                 );
                 );


                /*
                * 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 =
                 const configExists =
                     await this.pageExists(
                     await this.pageExists(
Line 5,577: Line 6,006:
                     );
                     );


                 await this.savePage(
                 await this.saveConfigPage(
                     configTitle,
                     configTitle,
                     this.getConfigJSON(),
                     this.getConfigJSON(),
                     configExists
                     configExists
                         ? 'Updated preload config with Preload Editor'
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor',
                         : 'Created preload config with Preload Editor'
                    !configExists
                 );
                 );


Line 5,595: Line 6,023:


                 this.setStatus(
                 this.setStatus(
                     'Preload and config saved successfully.',
                     'Preload and JSON config saved successfully.',
                     'success'
                     'success'
                 );
                 );


                 mw.notify(
                 mw.notify(
                     'Preload and config saved.',
                     'Preload and config saved. config.json is using the JSON content model.',
                     {
                     {
                         type: 'success'
                         type: 'success'
Line 5,714: Line 6,142:


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