Jump to content

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

From The Petit Planet Wiki
ReisuDesign (talk | contribs)
No edit summary
ReisuDesign (talk | contribs)
No edit summary
 
(9 intermediate revisions by the same user not shown)
Line 3: Line 3:


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


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


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


         draftStorageKey:
         draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',
            'PetitPlanet.PreloadEditor.drafts.v1',


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


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


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


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


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


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


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


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


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


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


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


Line 131: Line 103:


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


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


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


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


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


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


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


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


                 selectedVariable:
            this.localDraftStatus.removeClass(
                    String(
                'is-saved',
                        this.state.selectedVariable ||
                 'is-warning',
                        'PAGE'
                'is-error',
                    ),
                'is-empty'
            );
 
            if (type) {
                this.localDraftStatus.addClass('is-' + type);
            }
 
            this.localDraftStatus.text(message || '');
        },
 
        formatLocalDraftTime(timestamp) {
            if (!timestamp) {
                return '';
            }


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


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


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


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


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


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


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


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


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


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


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


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


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


             if (
             if (storage.drafts && storage.drafts[id]) {
                storage.drafts &&
                storage.drafts[id]
            ) {
                 delete storage.drafts[id];
                 delete storage.drafts[id];
             }
             }


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


             if (
             if (
Line 399: Line 322:
             ) {
             ) {
                 try {
                 try {
                     config =
                     config = this.normalizeConfig(
                        this.normalizeConfig(
                        JSON.parse(JSON.stringify(draft.config))
                            JSON.parse(
                    );
                                JSON.stringify(
                                    draft.config
                                )
                            )
                        );
                 } catch (error) {
                 } catch (error) {
                     console.warn(
                     console.warn(
Line 420: Line 338:


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


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


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


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


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


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


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


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


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


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


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


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


             return true;
             return true;
         },
         },


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


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


             const page =
             const page =
Line 545: Line 425:


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


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


             return (
             return (
Line 578: Line 452:
         },
         },


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


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


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


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


             return match
             if (String(page.contentmodel || '').toLowerCase() !== 'json') {
                ? match[1].trim()
                 await this.changeContentModel(
                : String(source || '').trim();
                    title,
        },
                    'json',
 
                     'Changed preload config content model to JSON'
        findVariables(content) {
                 );
            const variables = [];
            const pattern =
                /%%([A-Za-z0-9_-]+)%%/g;
 
            let match;
 
            while (
                 (match = pattern.exec(content)) !== null
            ) {
                const name =
                     match[1].toUpperCase();
 
                 if (!variables.includes(name)) {
                    variables.push(name);
                }
             }
             }


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


        // In-wiki dialogs
                let sourceConfig;


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


            const view =
                    return;
                 this.editorView;
                 }


            const selection =
                if (!field.type) {
                 view.state.selection.main;
                    warnings.push(
                        'Field "' +
                        name +
                        '" has no type.'
                    );
                }
               
                if (
                    field.type === 'file'
                 ) {
                    if (
                        field.accept !== undefined &&
                        !Array.isArray(field.accept)
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" must have "accept" as an array.'
                        );
                    }


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


         getToolVariables() {
         select(options, value) {
             const variables =
             const select = $('<select>')
                 new Set(['PAGE']);
                .addClass('preload-editor-select');
 
            options.forEach(option => {
                 $('<option>')
                    .attr('value', option.value)
                    .text(option.label)
                    .prop(
                        'selected',
                        String(option.value) ===
                        String(value === undefined ? '' : value)
                    )
                    .appendTo(select);
            });


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


            $('<span>')
                const cancel = this.createButton(
                 .addClass(
                    'Cancel',
                     'preload-editor-tool-label'
                    '',
                )
                    () => {
                .text(
                        overlay.remove();
                     'Insert existing variable'
                        resolve(null);
                 )
                    }
                 .appendTo(variableGroup);
                );
 
                 const confirm = this.createButton(
                    'Load',
                     'preload-editor-button-primary',
                    () => {
                        const value =
                            String(
                                input.val() || ''
                            ).trim();
 
                        if (!value) {
                            return;
                        }
 
                        overlay.remove();
                        resolve(value);
                     }
                 );
 
                 buttons.append(cancel, confirm);


            const variableSelect =
                 box.append(
                 this.createToolSelect(
                     input,
                     [],
                     buttons
                     'preload-editor-variable-select'
                 );
                 );


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


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


            const conditionGroup =
                 input.trigger('focus');
                 $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


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


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


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


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


            const insertCondition =
                 $('<h2>')
                 this.createButton(
                     .text('Review config.json')
                    'Insert',
                     .appendTo(box);
                     'preload-editor-tool-button',
 
                     () =>
                $('<p>')
                        this.insertCondition(
                    .text(
                            conditionTypeSelect.val(),
                         'This is the config.json that will be saved for the current preload.'
                            conditionVariableSelect.val()
                    )
                         )
                    .appendTo(box);
                );


            conditionTypeSelect.on(
                const code = $('<pre>')
                'change.preloadEditor',
                    .addClass(
                () =>
                        'preload-editor-config-review'
                     this.updateConditionVariableVisibility()
                    )
            );
                     .text(this.getConfigJSON());


            conditionGroup.append(
                const codeWrap = $('<div>')
                conditionTypeSelect,
                    .addClass(
                conditionVariableWrap,
                        'preload-editor-config-review-wrap'
                insertCondition
                    )
            );
                    .append(code);


            tools.append(
                box.append(codeWrap);
                wrapGroup,
                variableGroup,
                conditionGroup
            );


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


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


            return tools;
                buttons.append(close);
        },
                box.append(buttons);
                overlay.append(box);


        updateEditorTools() {
                $(document.body).append(overlay);
            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();
        },


        // Syntax highlighting
                overlay.attr('tabindex', '-1');
                overlay.trigger('focus');


        getKnownVariables() {
                overlay.on(
            const known =
                    'keydown.preloadEditor',
                new Set(['PAGE']);
                    event => {
                        if (event.key === 'Escape') {
                            close.trigger('click');
                        }
                    }
                );


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


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


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


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


             let match;
             const pages = [];


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


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


                 decorations.push(
                 pages.push(
                     Decoration.mark({
                     'Config content model: JSON'
                        class: [
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                 );
                 );
             }
             }


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


        // Main UI
                    cursorOffset =
                        text.length;


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


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


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


            root.append(this.root);
                    break;


             this.renderShell();
                default:
                    return;
             }


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


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


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


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


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


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


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


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


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


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


             this.status =
             const populate = (
                 $('<div>')
                select,
                    .addClass(
                 value
                        'preload-editor-status'
            ) => {
                    );
                select.empty();


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


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


             this.root.append(this.workspace);
             populate(
                this.editorTools.variableSelect,
                current
            );


             this.renderWelcome();
             populate(
                this.editorTools.conditionVariableSelect,
                currentCondition
            );
         },
         },


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


             const section =
             const type =
                 this.createSection('Get started');
                 this.editorTools
                    .conditionTypeSelect
                    .val();


             $('<p>')
             this.editorTools
                 .text(
                .conditionVariableWrap
                     'Load an existing preload, create a new one, or start from a sample wiki page.'
                 .toggle(
                 )
                     type === 'if'
                .appendTo(section);
                 );
        },


             const tips =
        renderEditorTools() {
                 $('<ul>')
             const tools =
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tips'
                         'preload-editor-tools'
                     );
                     );


             [
             const wrapGroup =
                 'Existing preload: loads the preload and its config.json if available.',
                 $('<div>')
                'New preload: starts with the standard Preload Template structure.',
                    .addClass(
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
             ].forEach(
                    );
                 text => {
 
                     $('<li>')
             wrapGroup.append(
                        .text(text)
                 this.createButton(
                         .appendTo(tips);
                    'Wrap selection',
                 }
                     'preload-editor-tool-button',
                    () =>
                         this.wrapSelectionWithVariable()
                 )
             );
             );


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


        setStatus(
            $('<span>')
            message,
                .addClass(
            type
                    'preload-editor-tool-label'
        ) {
                )
            if (!this.status) {
                .text(
                 return;
                    'Insert existing variable'
            }
                )
                 .appendTo(variableGroup);


             this.status.removeClass(
             const variableSelect =
                'is-error',
                this.createToolSelect(
                'is-success',
                    [],
                'is-warning',
                    'preload-editor-variable-select'
                 'is-loading'
                 );
            );


             if (type) {
             variableGroup.append(
                this.status.addClass(
                 variableSelect,
                    'is-' + type
                 );
            }


            this.status.text(
                this.createButton(
                 message || ''
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                 )
             );
             );
        },


        // Load / create
            const conditionGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                    );


        async loadExisting(title) {
            $('<span>')
            title =
                .addClass(
                 String(title || '').trim();
                    'preload-editor-tool-label'
                )
                 .text('Insert condition')
                .appendTo(conditionGroup);


             if (!title) {
             const conditionTypeSelect =
                 mw.notify(
                 this.createToolSelect(
                     'Enter a preload page title first.',
                     [
                    {
                        {
                         type: 'warn'
                            value: 'if',
                     }
                            label: '@if'
                        },
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                        {
                            value: 'else',
                            label: '@else'
                         },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                     ],
                    'preload-editor-condition-type-select'
                 );
                 );


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


             this.setStatus(
             const conditionVariableWrap =
                'Loading preload...',
                $('<span>')
                'loading'
                    .addClass(
            );
                        'preload-editor-condition-variable'
                    )
                    .append(
                        conditionVariableSelect
                    );


             try {
             const insertCondition =
                const page =
                this.createButton(
                    await this.getPage(title);
                    'Insert',
 
                    'preload-editor-tool-button',
                if (!page) {
                    () =>
                    const suggestions =
                         this.insertCondition(
                         await this.findSimilarPreloads(
                            conditionTypeSelect.val(),
                             title
                             conditionVariableSelect.val()
                         );
                         )
                );


                    this.renderMissingPage(
            conditionTypeSelect.on(
                        title,
                'change.preloadEditor',
                        suggestions
                () =>
                     );
                     this.updateConditionVariableVisibility()
            );


                    this.setStatus(
            conditionGroup.append(
                        'Preload not found.',
                conditionTypeSelect,
                        'warning'
                conditionVariableWrap,
                    );
                insertCondition
            );


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


                await this.loadDefinition(
            this.editorTools = {
                    page.title,
                root: tools,
                    page.content
                variableSelect,
                 );
                 conditionTypeSelect,
 
                conditionVariableSelect,
                 this.setStatus(
                 conditionVariableWrap,
                    'Preload loaded.',
                insertCondition
                    'success'
            };
                );
 
             } catch (error) {
             this.updateEditorToolVariables();
                console.error(
            this.updateConditionVariableVisibility();
                    'Preload Editor:',
                    error
                );


                this.setStatus(
            return tools;
                    error.message ||
                        'Could not load preload.',
                    'error'
                );
            }
         },
         },


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


            if (!query) {
        // =========================================================
                query = title;
        // Syntax highlighting
            }
        // =========================================================


            try {
        getKnownVariables() {
                const results =
            const known =
                    await this.searchPages(query);
                new Set(['PAGE']);


                 return results.filter(
            const fields =
                     result =>
                this.state.config &&
                         /\/Preload$/i.test(
                this.state.config.fields;
                             result.title
 
                         )
            if (
                );
                fields &&
            } catch (error) {
                typeof fields === 'object'
                console.error(
            ) {
                    'Preload Editor search:',
                 Object.keys(fields).forEach(
                    error
                     name => {
                         known.add(
                             String(name).toUpperCase()
                         );
                    }
                 );
                 );
            }


                return [];
            return known;
            }
         },
         },


         renderMissingPage(
         createSyntaxDecorations(
             title,
             state,
             suggestions
             Decoration
         ) {
         ) {
             this.workspace.empty();
             const decorations = [];
            const source =
                state.doc.toString();
 
            const knownVariables =
                this.getKnownVariables();


             const section =
             const variablePattern =
                 this.createSection(
                 /%%([A-Za-z0-9_-]+)%%/g;
                    'Preload not found'
                );


             $('<p>')
             let match;
                .text(
                    'No preload exists at "' +
                    title +
                    '".'
                )
                .appendTo(section);


             if (suggestions.length) {
             while (
                 $('<h3>')
                 (
                     .text('Similar preloads')
                     match =
                     .appendTo(section);
                        variablePattern.exec(source)
                ) !== null
            ) {
                const name =
                     match[1].toUpperCase();


                 const list =
                 const known =
                     $('<div>')
                     knownVariables.has(name);
                        .addClass(
                            'preload-editor-suggestions'
                        );


                 suggestions.forEach(
                 decorations.push(
                     result => {
                     Decoration.mark({
                         list.append(
                         class: [
                             this.createButton(
                            'preload-editor-syntax-variable',
                                 result.title,
                             known
                                 'preload-editor-suggestion',
                                 ? 'preload-editor-syntax-variable-known'
                                () =>
                                 : 'preload-editor-syntax-variable-unknown'
                                    this.loadExisting(
                        ].join(' ')
                                        result.title
                    }).range(
                                    )
                        match.index,
                             )
                        match.index +
                        );
                             match[0].length
                    }
                    )
                 );
                 );
                section.append(list);
             }
             }


             section.append(
             const conditionPattern =
                 this.createButton(
                 /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
                    'Create this preload',
                    'preload-editor-button-primary',
                    () =>
                        this.startNew(title)
                )
            );


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


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


            this.state = {
                decorations.push(
                preloadTitle: title,
                    Decoration.mark({
                preloadSource: '',
                        class:
                 preloadContent:
                            'preload-editor-syntax-directive'
                     this.defaults.preload,
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );
 
                 const type =
                     match[1].toLowerCase();


                 config:
                 if (
                     this.emptyConfig(),
                    type !== 'if' &&
                     type !== 'elseif'
                ) {
                    continue;
                }


                 variables: ['PAGE'],
                 const expression =
                conditions: [],
                    match[2];
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true
            };


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


            this.setStatus(
                 const expressionPattern =
                'Creating a new preload.',
                    /[A-Za-z0-9_-]+/g;
                 'success'
            );
        },


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


            if (!result) {
                while (
                return;
                    (
            }
                        expressionMatch =
                            expressionPattern.exec(
                                expression
                            )
                    ) !== null
                ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


            this.setStatus(
                    if (
                'Loading sample page...',
                        !knownVariables.has(name)
                'loading'
                    ) {
            );
                        continue;
                    }


            try {
                    const start =
                const page =
                        expressionStart +
                    await this.getPage(result);
                        expressionMatch.index;


                if (!page) {
                    decorations.push(
                    throw new Error(
                        Decoration.mark({
                        'Sample page not found: ' +
                            class:
                         result
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                         )
                     );
                     );
                 }
                 }
            }


                const sample =
            return Decoration.set(
                    this.convertSampleToPreload(
                decorations,
                        page.content
                true
                    );
            );
        },


                this.state = {
        async installSyntaxHighlighting(view) {
                    preloadTitle: '',
            await mw.loader.using(
                    preloadSource: '',
                'ext.CodeMirror.v6.lib'
                    preloadContent: sample,
            );


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


                    variables: ['PAGE'],
            const {
                    conditions: [],
                StateField,
                    selectedVariable: 'PAGE',
                StateEffect,
                    deletedVariables: [],
                EditorView,
                    mode: 'new',
                Decoration
                    dirty: true,
            } = require(
                    dirtyPreload: true,
                'ext.CodeMirror.v6.lib'
                    dirtyConfig: true
            );
                };


                this.reanalyze();
            const syntaxField =
                 this.saveDraft();
                 StateField.define({
                this.renderEditor();
                    create: state =>
 
                        this.createSyntaxDecorations(
                this.setStatus(
                            state,
                    'Sample page loaded.',
                            Decoration
                    'success'
                        ),
                );
            } catch (error) {
                console.error(
                    'Preload Editor sample:',
                    error
                );


                this.setStatus(
                    update: (
                     error.message ||
                        decorations,
                        'Could not load sample page.',
                        transaction
                    'error'
                     ) =>
                );
                        transaction.docChanged
            }
                            ? this.createSyntaxDecorations(
        },
                                transaction.state,
                                Decoration
                            )
                            : decorations,


        convertSampleToPreload(source) {
                    provide: field =>
            let content =
                        EditorView.decorations.from(
                 String(source || '').trim();
                            field
                        )
                 });


             const include =
             view.dispatch({
                 content.match(
                 effects:
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                    StateEffect.appendConfig.of(
                );
                        syntaxField
                     )
            });


             if (include) {
             this.editor.syntaxField =
                content =
                 syntaxField;
                    include[1].trim();
            }
 
            content =
                 content
                    .replace(
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                    )
                    .trim();
 
            return (
                '<includeonly>\n' +
                content +
                '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
            );
         },
         },


         async loadDefinition(
         async mountCodeMirror(textarea) {
             title,
             return new Promise(
            source
                (
        ) {
                    resolve,
            const content =
                    reject
                this.extractIncludeonly(source);
                ) => {
                    let settled = false;


            let config =
                    const cleanup = () => {
                this.emptyConfig();
                        mw.hook(
                            'dev.CCM.ready'
                        ).remove(onReady);


            const configTitle =
                        mw.hook(
                title.replace(
                            'dev.CCM.load'
                    /\/+$/,
                        ).remove(onLoad);
                    ''
                    };
                ) +
                '/config.json';


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


            if (configPage) {
                            settled = true;
                try {
                             cleanup();
                    config =
                        JSON.parse(
                             configPage.content
                        );
                } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }


            const analysis =
                            const view =
                this.analyzePreload(content);
                                cm.view;


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


            config =
                                    this.markPreloadDirty();
                this.prepareConfigForVariables(
                    config,
                    analysis
                );


            this.state = {
                                    this.reanalyze();
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,


                variables:
                                    this.renderVariablesBySelector();
                    analysis.variables,
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


                conditions:
                                    this.saveDraft();
                    analysis.conditions,
                                };


                selectedVariable:
                            view.dom.addEventListener(
                    analysis.variables.includes('PAGE')
                                'input',
                        ? 'PAGE'
                                inputHandler
                        : (
                             );
                            analysis.variables[0] ||
                             'PAGE'
                        ),


                deletedVariables: [],
                            view.dom.classList.add(
                                'preload-editor-codemirror'
                            );


                mode: 'edit',
                            const wrapper =
                dirty: false,
                                view.dom.closest(
                dirtyPreload: false,
                                    '.ext-codemirror-wrapper'
                dirtyConfig: false
                                );
            };


            this.clearDraft(title);
                            if (wrapper) {
            this.renderEditor();
                                wrapper.classList.add(
        },
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


        // Editor
                            this.editor = {
 
                                cm,
        renderEditor() {
                                view,
            this.destroyEditor();
                                textarea,
            this.workspace.empty();
                                inputHandler
                            };


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


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


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


            const editorSection =
                                if (
                this.createSection(
                                    this.state.dirty
                    'Preload',
                                ) {
                    'preload-editor-main-section'
                                    this.saveDraft();
                );
                                }


            const meta =
                                resolve(view);
                $('<div>')
                            } catch (error) {
                    .addClass(
                                reject(error);
                         'preload-editor-meta'
                            }
                    );
                         };


            $('<strong>')
                    const onLoad =
                .text(
                        loader => {
                    this.state.preloadTitle ||
                            if (
                    'New preload'
                                settled ||
                )
                                typeof loader !==
                .appendTo(meta);
                                    'function'
                            ) {
                                return;
                            }


            if (
                            try {
                this.state.mode === 'new'
                                loader(textarea);
            ) {
                            } catch (error) {
                $('<span>')
                                settled = true;
                    .addClass(
                                cleanup();
                        'preload-editor-badge'
                                reject(error);
                    )
                            }
                    .text('NEW')
                        };
                    .appendTo(meta);
            }


            editorSection.append(meta);
                    mw.hook(
            editorSection.append(
                        'dev.CCM.ready'
                this.renderEditorTools()
                    ).add(onReady);
            );


            const textarea =
                     mw.hook(
                this.textarea(
                         'dev.CCM.load'
                    this.state.preloadContent
                     ).add(onLoad);
                )
                }
                     .attr(
            );
                         'id',
        },
                        'preload-editor-content'
                     )
                    .addClass(
                        'preload-editor-content'
                    );


            const editorMount =
        // =========================================================
                $('<div>')
        // Main UI
                    .addClass(
        // =========================================================
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);


            editorSection.append(editorMount);
        init() {
             left.append(editorSection);
             const root =
                $('#mw-content-text');


             const analysisSection =
             if (!root.length) {
                 this.createSection('Analysis');
                 return;
            }


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


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


             const variablesSection =
             this.renderShell();
                this.createSection('Variables');


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


             const detectHelp =
             window.addEventListener(
                 $('<div>')
                 'beforeunload',
                    .addClass(
                () => {
                        'preload-editor-help preload-editor-detect-variables-help'
                     if (this.state.dirty) {
                    )
                        this.saveDraft();
                     .text(
                     }
                        'Refresh the variable list after editing the preload.'
                }
                    );
 
            variablesSection.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-detect'
                    )
                     .append(
                        detectVariablesButton,
                        detectHelp
                    )
             );
             );
        },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


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


             variablesSection.append(
             const titleInput =
                variableContainer
                this.textInput(
            );
                    this.state.preloadTitle,
 
                    'Template:Example/Preload'
            const configurationSection =
                 ).attr(
                 this.createSection(
                     'id',
                     'Variable configuration'
                    'preload-editor-title-input'
                 );
                 );


             const configurationContainer =
             titleInput.on(
                 $('<div>')
                 'input.preloadEditor',
                     .addClass(
                () => {
                        'preload-editor-variable-configuration'
                     this.state.preloadTitle =
                    );
                        String(
                            titleInput.val() || ''
                        ).trim();


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


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


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


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


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


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


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


             const savePreloadButton =
             this.root.append(
                this.createButton(
                this.workspace
                    'Save Preload',
            );
                    '',
                    () =>
                        this.savePreloadOnly()
                );


             const saveConfigButton =
            /*
                 this.createButton(
            * Fixed footer
                    'Save Config',
            *
                     '',
            * Local draft status, normal status messages,
                     () =>
            * and save actions live here.
                        this.saveConfigOnly()
            */
                );
             const footer =
                 $('<div>')
                     .addClass(
                        'preload-editor-footer'
                     );


             const saveBothButton =
             this.localDraftStatus =
                 this.createButton(
                 $('<div>')
                    'Save',
                     .addClass(
                     'preload-editor-button-primary',
                        'preload-editor-local-draft-status is-empty'
                     () =>
                     )
                        this.saveAll()
                    .text(
                );
                        'No local draft'
                    );


             actions.append(
             this.status =
                 savePreloadButton,
                 $('<div>')
                saveConfigButton,
                    .addClass(
                saveBothButton
                        'preload-editor-status'
            );
                    );


             right.append(
             footer.append(
                 analysisSection,
                 this.localDraftStatus,
                 variablesSection,
                 this.status
                configurationSection,
                configSection,
                actions
             );
             );


             layout.append(
             this.root.append(
                 left,
                 footer
                right
             );
             );


             this.workspace.append(layout);
             this.updateLocalDraftIndicator();


             this.reanalyze();
             this.renderWelcome();
        },


             this.renderVariables(
        renderWelcome() {
                variableContainer
             this.workspace.empty();
            );


             this.renderAnalysis(
             const section =
                analysisContainer
                this.createSection('Get started');
            );


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


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


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


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


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


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


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


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


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


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


             this.state.preloadContent =
             this.setStatus(
                 source;
                'Loading preload...',
                 'loading'
            );


             this.state.variables =
             try {
                analysis.variables;
                const page =
                    await this.getPage(title);


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


            this.state.config =
                    this.renderMissingPage(
                this.prepareConfigForVariables(
                        title,
                    this.state.config ||
                         suggestions
                         this.emptyConfig(),
                     );
                     analysis
                );


            this.analysis =
                    this.setStatus(
                analysis;
                        'Preload not found.',
                        'warning'
                    );


            const available =
                    return;
                 ['PAGE'].concat(
                }
                     analysis.variables.filter(
 
                        name =>
                 await this.loadDefinition(
                            name !== 'PAGE'
                     page.title,
                     )
                    page.content
                );
 
                this.setStatus(
                    'Preload loaded.',
                    'success'
                );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                     error
                 );
                 );


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


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


             const analysis =
             if (!query) {
                this.analysis ||
                query = title;
                 this.analyzePreload(
            }
                     this.extractIncludeonly(
 
                         this.getEditorContent()
            try {
                     )
                const results =
                    await this.searchPages(query);
 
                 return results.filter(
                     result =>
                        /\/Preload$/i.test(
                            result.title
                         )
                );
            } catch (error) {
                console.error(
                     'Preload Editor search:',
                    error
                 );
                 );


             const variableCount =
                return [];
                analysis.variables.length;
             }
        },


             const conditionCount =
        renderMissingPage(
                analysis.conditions.length;
             title,
            suggestions
        ) {
            this.workspace.empty();


             const configuredCount =
             const section =
                 Object.keys(
                 this.createSection(
                     this.state.config &&
                     'Preload not found'
                    this.state.config.fields
                 );
                        ? this.state.config.fields
                        : {}
                 ).length;


             const summary =
             $('<p>')
                 $('<div>')
                .text(
                     .addClass(
                    'No preload exists at "' +
                        'preload-editor-analysis-summary'
                    title +
                     );
                    '".'
                )
                .appendTo(section);
 
            if (suggestions.length) {
                 $('<h3>')
                     .text('Similar preloads')
                     .appendTo(section);


            const createMetric =
                const list =
                (
                    value,
                    label
                ) =>
                     $('<div>')
                     $('<div>')
                         .addClass(
                         .addClass(
                             'preload-editor-analysis-metric'
                             'preload-editor-suggestions'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),
 
                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                         );
                         );


            summary.append(
                suggestions.forEach(
                createMetric(
                    result => {
                    variableCount,
                        list.append(
                    variableCount === 1
                            this.createButton(
                         ? 'variable'
                                result.title,
                        : 'variables'
                                'preload-editor-suggestion',
                 ),
                                () =>
                                    this.loadExisting(
                                        result.title
                                    )
                            )
                         );
                    }
                 );


                 createMetric(
                 section.append(list);
                    conditionCount,
            }
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),


                 createMetric(
            section.append(
                     configuredCount,
                 this.createButton(
                     configuredCount === 1
                     'Create this preload',
                        ? 'configured field'
                     'preload-editor-button-primary',
                         : 'configured fields'
                    () =>
                         this.startNew(title)
                 )
                 )
             );
             );


             container.append(summary);
             this.workspace.append(section);
        },
 
        async startNew(title) {
            title =
                String(title || '').trim();


             if (
             this.state = {
                analysis.conditionVariables.length
                 preloadTitle: title,
            ) {
                preloadSource: '',
                 container.append(
                preloadContent:
                    $('<div>')
                    this.defaults.preload,
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }


            const validation =
                 config:
                 this.validateConfig(
                     this.emptyConfig(),
                     this.state.config,
                    analysis
                );


            if (validation.errors.length) {
                variables: ['PAGE'],
                 const errors =
                 conditions: [],
                    $('<ul>')
                selectedVariable: 'PAGE',
                        .addClass(
                deletedVariables: [],
                            'preload-editor-validation-errors'
                mode: 'new',
                        );
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,


                 validation.errors.forEach(
                 localDraftSavedAt: null,
                    error => {
                localDraftAvailable: false
                        $('<li>')
            };
                            .text(error)
                            .appendTo(errors);
                    }
                );


                container.append(errors);
            this.saveDraft();
             }
             this.renderEditor();


             if (validation.warnings.length) {
             this.setStatus(
                 const warnings =
                 'Creating a new preload.',
                    $('<ul>')
                'success'
                        .addClass(
            );
                            'preload-editor-validation-warnings'
        },
                        );


                 validation.warnings.forEach(
        async loadSamplePage() {
                     warning => {
            const result =
                        $('<li>')
                 await this.createPromptDialog(
                            .text(warning)
                     'Load Sample Page',
                            .appendTo(warnings);
                    'Enter the title of a normal wiki page to use as the starting point.'
                    }
                 );
                 );


                container.append(warnings);
            if (!result) {
                return;
             }
             }


             if (
             this.setStatus(
                 !validation.errors.length &&
                 'Loading sample page...',
                 !validation.warnings.length
                 'loading'
             ) {
             );
                 container.append(
 
                     $('<div>')
            try {
                        .addClass(
                 const page =
                            'preload-editor-validation-success'
                     await this.getPage(result);
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },


        renderAnalysisBySelector() {
                if (!page) {
            const container =
                    throw new Error(
                this.root &&
                        'Sample page not found: ' +
                this.root.find(
                        result
                    '.preload-editor-analysis'
                    );
                );
                }


            if (
                 const sample =
                 container &&
                    this.convertSampleToPreload(
                container.length
                        page.content
            ) {
                    );
                this.renderAnalysis(container);
            }
        },


        // Variables
                this.state = {
                    preloadTitle: '',
                    preloadSource: '',
                    preloadContent: sample,


        renderVariables(container) {
                    config:
            container.empty();
                        this.emptyConfig(),


            const analysis =
                    variables: ['PAGE'],
                this.analysis ||
                    conditions: [],
                this.analyzePreload(
                    selectedVariable: 'PAGE',
                     this.extractIncludeonly(
                     deletedVariables: [],
                        this.getEditorContent()
                    mode: 'new',
                     )
                     dirty: true,
                );
                    dirtyPreload: true,
                    dirtyConfig: true,


            const variables =
                    localDraftSavedAt: null,
                 analysis.variables.slice();
                    localDraftAvailable: false
                 };


            const ordered =
                this.reanalyze();
                 ['PAGE'];
                this.saveDraft();
                 this.renderEditor();


            variables.forEach(
                this.setStatus(
                name => {
                    'Sample page loaded.',
                     if (
                     'success'
                        name !== 'PAGE' &&
                );
                        !ordered.includes(name)
            } catch (error) {
                    ) {
                console.error(
                        ordered.push(name);
                     'Preload Editor sample:',
                     }
                    error
                 }
                 );
            );


            const configuredFields =
                 this.setStatus(
                 this.state.config &&
                     error.message ||
                this.state.config.fields
                         'Could not load sample page.',
                     ? Object.keys(
                     'error'
                         this.state.config.fields
                );
                     )
            }
                    : [];
        },


            configuredFields.forEach(
        convertSampleToPreload(source) {
                name => {
            let content =
                    const upper =
                String(source || '').trim();
                        name.toUpperCase();


                    if (
            const include =
                        upper !== 'PAGE' &&
                content.match(
                        !ordered.includes(upper)
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                     ) {
                 );
                        ordered.push(upper);
                    }
                 }
            );


             const deleted =
             if (include) {
                Array.isArray(
                 content =
                    this.state.deletedVariables
                     include[1].trim();
                 )
            }
                     ? this.state.deletedVariables
                    : [];


             deleted.forEach(
             content =
                name => {
                content
                     const upper =
                    .replace(
                        String(name).toUpperCase();
                        /<noinclude>[\s\S]*?<\/noinclude>/gi,
                        ''
                     )
                    .trim();


                    if (
            return (
                        upper !== 'PAGE' &&
                '<includeonly>\n' +
                        !ordered.includes(upper)
                content +
                    ) {
                '\n</includeonly>\n' +
                        ordered.push(upper);
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
                    }
                }
             );
             );
        },


             const list =
        async loadDefinition(
                 $('<div>')
            title,
                    .addClass(
            source
                        'preload-editor-variable-list'
        ) {
                    );
             const content =
                 this.extractIncludeonly(source);
 
            let config =
                this.emptyConfig();


             ordered.forEach(
             const configTitle =
                name => {
                title.replace(
                     const isSelected =
                    /\/+$/,
                        name ===
                     ''
                        this.state.selectedVariable;
                ) +
                '/config.json';


                    const isUsed =
            const configPage =
                        analysis.variables.includes(
                await this.getPage(configTitle);
                            name
                        );


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


                    const item =
            const analysis =
                        $('<button>')
                this.analyzePreload(content);
                            .attr({
 
                                type: 'button',
            this.state.deletedVariables = [];
                                'data-variable':
                                    name
                            })
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );


                    $('<span>')
            config =
                        .addClass(
                this.prepareConfigForVariables(
                            'preload-editor-variable-name'
                    config,
                        )
                    analysis
                        .text(name)
                );
                        .appendTo(item);


                    if (name === 'PAGE') {
            this.state = {
                        item.append(
                preloadTitle: title,
                            $('<span>')
                preloadSource: source,
                                .addClass(
                preloadContent: source,
                                    'preload-editor-badge'
                config,
                                )
                                .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);
                variables:
                }
                     analysis.variables,
            );


            container.append(list);
                conditions:
                    analysis.conditions,


            if (!ordered.length) {
                 selectedVariable:
                 container.append(
                     analysis.variables.includes('PAGE')
                     $('<div>')
                         ? 'PAGE'
                         .addClass(
                         : (
                            'preload-editor-empty'
                            analysis.variables[0] ||
                         )
                             'PAGE'
                        .text(
                         ),
                             'No variables found in the preload.'
 
                         )
                deletedVariables: [],
                 );
 
            }
                mode: 'edit',
        },
                 dirty: false,
                dirtyPreload: false,
                dirtyConfig: false,


        renderVariablesBySelector() {
                 localDraftSavedAt: null,
            const container =
                 localDraftAvailable: false
                 this.root &&
            };
                 this.root.find(
                    '.preload-editor-variables'
                );


             if (
             this.clearDraft(title);
                container &&
             this.renderEditor();
                container.length
             ) {
                this.renderVariables(container);
            }
         },
         },


         selectVariable(name) {
         // =========================================================
            name =
        // Editor
                String(name || '')
        // =========================================================
                    .trim()
                    .toUpperCase();


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


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


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


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


             if (!available.includes(name)) {
             const meta =
                return;
                $('<div>')
            }
                    .addClass(
                        'preload-editor-meta'
                    );


             this.state.selectedVariable =
             $('<strong>')
                name;
                .text(
 
                    this.state.preloadTitle ||
            this.renderVariablesBySelector();
                     'New preload'
            this.renderVariableConfigurationBySelector();
                 )
        },
                .appendTo(meta);
 
        renderVariableConfigurationBySelector() {
            const container =
                this.root &&
                this.root.find(
                     '.preload-editor-variable-configuration'
                 );


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


        renderVariableConfiguration(container) {
            editorSection.append(meta);
             container.empty();
             editorSection.append(
                this.renderEditorTools()
            );


             const analysis =
             const textarea =
                 this.analysis ||
                 this.textarea(
                this.analyzePreload(
                    this.state.preloadContent
                     this.extractIncludeonly(
                )
                         this.getEditorContent()
                     .attr(
                         'id',
                        'preload-editor-content'
                     )
                     )
                );
                    .addClass(
                        'preload-editor-content'
                    );


             const name =
             const editorMount =
                 this.state.selectedVariable ||
                 $('<div>')
                'PAGE';
                    .addClass(
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);


             const fields =
             editorSection.append(editorMount);
                this.state.config &&
            left.append(editorSection);
                this.state.config.fields
                    ? this.state.config.fields
                    : {};


             const field =
             const analysisSection =
                 fields[name];
                 this.createSection('Analysis');


             if (name === 'PAGE') {
             const analysisContainer =
                container.append(
                $('<div>')
                    this.createAutomaticPageCard(
                    .addClass(
                        field ||
                        'preload-editor-analysis'
                        this.getAutomaticPageField()
                    );
                    )
 
            analysisSection.append(
                analysisContainer
            );
 
            const variablesSection =
                this.createSection('Variables');
 
            const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                 );
                 );


                return;
             const detectHelp =
            }
                $('<div>')
 
                    .addClass(
             if (!field) {
                        'preload-editor-help preload-editor-detect-variables-help'
                const missing =
                    )
                    $('<div>')
                    .text(
                        .addClass(
                         'Refresh the variable list after editing the preload.'
                            'preload-editor-variable preload-editor-variable-missing'
                    );
                         );


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


                        $('<span>')
            const variableContainer =
                            .addClass(
                $('<div>')
                                'preload-editor-badge is-warning'
                    .addClass(
                            )
                        'preload-editor-variables'
                            .text(
                    );
                                'NOT CONFIGURED'
 
                            )
            variablesSection.append(
                     )
                variableContainer
                    .appendTo(missing);
            );
 
            const configurationSection =
                this.createSection(
                    'Variable configuration'
                );
 
            /*
            * Import button lives at the top of the
            * variable configuration section so the
            * workflow is always easy to find.
            */
            const importDefinitionsButton =
                this.createButton(
                    'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                     () =>
                        this.importVariableDefinitions()
                );


                 $('<p>')
            const importHelp =
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-analysis-note'
                         'preload-editor-help preload-editor-import-definitions-help'
                     )
                     )
                     .text(
                     .text(
                         'This variable is currently not present in config.json.'
                         'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );
 
            const importControls =
                $('<div>')
                    .addClass(
                        'preload-editor-import-definition-controls'
                     )
                     )
                     .appendTo(missing);
                     .append(
                        importDefinitionsButton,
                        importHelp
                    );


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


            container.append(
             const configurationContainer =
                this.createVariableCard(
                    name,
                    field,
                    analysis
                )
            );
        },
 
        createAutomaticPageCard(field) {
             const card =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable preload-editor-variable-automatic'
                         'preload-editor-variable-configuration'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                     );
                     );


             const header =
            configurationSection.append(
                configurationContainer
            );
 
             const configSection =
                this.createSection(
                    'Configuration'
                );
 
            const configHelp =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-variable-header'
                         'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                     );
                     );


             header.append(
             const reviewConfigButton =
                $('<h3>').text('PAGE'),
                this.createButton(
                    'Review config.json',
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );


                $('<span>')
            configSection.append(
                    .addClass(
                configHelp,
                        'preload-editor-badge'
                reviewConfigButton
                    )
                    .text('AUTOMATIC')
             );
             );


             card.append(header);
             right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );


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


             const label =
             const saveBar =
                 this.textInput(
                 $('<div>')
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                );
 
            const description =
                this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                     .addClass(
                     .addClass(
                         'preload-editor-small-textarea'
                         'preload-editor-save-bar'
                    )
                    .prop(
                        'disabled',
                        true
                     );
                     );


             const type =
             saveBar.append(
                 this.textInput(
                 this.createButton(
                     field.type || 'page'
                     'Save Preload',
                ).prop(
                     '',
                     'disabled',
                     () =>
                     true
                        this.savePreloadOnly()
                 );
                 ),


            const required =
                 this.createButton(
                 this.checkbox(
                     'Save Config',
                     field.required !== false
                     '',
                ).prop(
                     () =>
                     'disabled',
                        this.saveConfigOnly()
                     true
                 ),
                 );


            const namespace =
                 this.createButton(
                 this.textInput(
                     'Save',
                     field.namespace || 'Main'
                     'preload-editor-button-primary',
                ).prop(
                     () =>
                     'disabled',
                        this.saveAll()
                     true
                 )
                 );
            );


             const allowNew =
             this.root
                 this.checkbox(
                 .find('.preload-editor-footer')
                    field['allow-new'] === true
                 .append(saveBar);
                 ).prop(
                    'disabled',
                    true
                );


             card.append(
             this.workspace.append(
                 this.fieldRow(
                 layout
                    'Label',
            );
                    label
                ),


                this.fieldRow(
            this.reanalyze();
                    'Description',
                    description
                ),


                this.fieldRow(
            this.renderVariables(
                    'Type',
                variableContainer
                    type
            );
                ),


                this.fieldRow(
            this.renderAnalysis(
                    'Required',
                analysisContainer
                    required
            );
                ),


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


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


        createVariableCard(
            this.mountCodeMirror(
            name,
                textarea.get(0)
            field,
             ).catch(
            analysis
                error => {
        ) {
                     console.error(
             const card =
                         'Preload Editor CodeMirror:',
                $('<div>')
                         error
                    .addClass(
                     );
                        'preload-editor-variable'
                    )
                     .attr(
                         'data-variable',
                         name
                     );


            const header =
                    this.setStatus(
                $('<div>')
                        error.message ||
                    .addClass(
                            'Could not initialize CodeMirror.',
                         'preload-editor-variable-header'
                         'error'
                     );
                     );
                }
            );
        },


            header.append(
        // =========================================================
                $('<h3>').text(name)
        // Variable detection
            );
        // =========================================================


            if (
        detectVariables() {
                !analysis.variables.includes(name)
             const source =
             ) {
                 this.getEditorContent();
                 header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }


             card.append(header);
             this.state.preloadContent =
                source;


             const label =
             const content =
                 this.textInput(
                 this.extractIncludeonly(
                     field.label || ''
                     source
                 );
                 );


             label.on(
             const analysis =
                 'input.preloadEditor',
                 this.analyzePreload(
                () => {
                     content
                     field.label =
                );
                        label.val();


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


            card.append(
                this.state.deletedVariables =
                this.fieldRow(
                    this.state.deletedVariables
                    'Label',
                        .filter(
                    label
                            name =>
                )
                                !detected.has(
             );
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
             } else {
                this.state.deletedVariables = [];
            }


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


             description.on(
             this.reanalyze();
                'input.preloadEditor',
 
                () => {
            this.renderVariablesBySelector();
                    field.description =
            this.renderVariableConfigurationBySelector();
                        description.val();
            this.renderAnalysisBySelector();
            this.updateEditorTools();
 
            this.saveDraft();


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


             card.append(
        reanalyze() {
                 this.fieldRow(
             const source =
                    'Description',
                 this.getEditorContent();
                    description
                )
            );


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


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


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


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


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


             card.append(
             this.state.config =
                 this.fieldRow(
                 this.prepareConfigForVariables(
                     'Type',
                     this.state.config ||
                    typeSelect
                        this.emptyConfig(),
                )
                     analysis
            );
 
            const required =
                this.checkbox(
                     field.required === true
                 );
                 );


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


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


             card.append(
             if (
                 this.fieldRow(
                 !available.includes(
                     'Required',
                     this.state.selectedVariable
                    required
                 )
                 )
             );
             ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },
 
        // =========================================================
        // Analysis
        // =========================================================
 
        renderAnalysis(container) {
            container.empty();


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


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


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


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


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


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


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


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


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


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


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


                maxRows.on(
            const validation =
                    'input.preloadEditor',
                this.validateConfig(
                    () => {
                    this.state.config,
                        const value =
                     analysis
                            parseInt(
                                maxRows.val(),
                                10
                            );
 
                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }
 
                        this.markDirty();
                        this.renderConfigReviewAvailability();
                     }
                 );
                 );


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


             if (
             if (validation.warnings.length) {
                 field.type === 'select' ||
                 const warnings =
                field.type === 'multiselect'
                    $('<ul>')
            ) {
                        .addClass(
                 this.renderSelectConfiguration(
                            'preload-editor-validation-warnings'
                     card,
                        );
                     field
 
                 validation.warnings.forEach(
                     warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                     }
                 );
                 );
                container.append(warnings);
             }
             }


             const deleteButton =
             if (
                 this.createButton(
                !validation.errors.length &&
                     'Delete variable',
                !validation.warnings.length
                    'preload-editor-button-danger preload-editor-delete-variable',
            ) {
                    async () => {
                 container.append(
                         const confirmed =
                     $('<div>')
                            await this.createConfirmDialog(
                        .addClass(
                                'Delete variable',
                            'preload-editor-validation-success'
                                'Delete "' +
                        )
                                name +
                         .text(
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                            'Preload and configuration are in sync.'
                                'Delete variable',
                        )
                                'Cancel'
                );
                            );
            }
        },


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


             card.append(
             if (
                 $('<div>')
                 container &&
                    .addClass(
                container.length
                        'preload-editor-variable-delete'
            ) {
                    )
                this.renderAnalysis(container);
                    .append(deleteButton)
             }
            );
 
             return card;
         },
         },


         async deleteVariable(name) {
         // =========================================================
            name =
        // Variables
                String(name || '')
        // =========================================================
                    .trim()
                    .toUpperCase();


            if (
        renderVariables(container) {
                !name ||
             container.empty();
                name === 'PAGE'
             ) {
                return;
            }


             if (
             const analysis =
                 !this.state.config ||
                 this.analysis ||
                 !this.state.config.fields
                 this.analyzePreload(
            ) {
                    this.extractIncludeonly(
                 return;
                        this.getEditorContent()
            }
                    )
                 );


             delete this.state.config.fields[name];
             const variables =
                analysis.variables.slice();


             if (
             const ordered =
                 !Array.isArray(
                 ['PAGE'];
                    this.state.deletedVariables
                )
            ) {
                this.state.deletedVariables = [];
            }


             if (
             variables.forEach(
                !this.state.deletedVariables.includes(
                name => {
                    name
                    if (
                )
                        name !== 'PAGE' &&
            ) {
                        !ordered.includes(name)
                this.state.deletedVariables.push(
                    ) {
                     name
                        ordered.push(name);
                 );
                     }
            }
                 }
            );


             this.state.selectedVariable =
             const configuredFields =
                 name;
                this.state.config &&
                 this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];


             this.markDirty();
             configuredFields.forEach(
                name => {
                    const upper =
                        name.toUpperCase();


            this.renderVariablesBySelector();
                    if (
            this.renderVariableConfigurationBySelector();
                        upper !== 'PAGE' &&
            this.renderAnalysisBySelector();
                        !ordered.includes(upper)
             this.renderConfigReviewAvailability();
                    ) {
                        ordered.push(upper);
                    }
                }
             );


             this.setStatus(
             const deleted =
                'Variable "' +
                Array.isArray(
                 name +
                    this.state.deletedVariables
                '" removed from the configuration.',
                 )
                'warning'
                    ? this.state.deletedVariables
            );
                    : [];
        },


        renderSelectConfiguration(
            deleted.forEach(
            card,
                name => {
            field
                    const upper =
        ) {
                        String(name).toUpperCase();
            const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                );


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


             card.append(
             const list =
                 this.fieldRow(
                 $('<div>')
                    'Source',
                     .addClass(
                     source,
                        'preload-editor-variable-list'
                    'Currently supported source format: category:Category Name'
                    );
                )
            );


             const sourcePrefix =
             ordered.forEach(
                this.textInput(
                name => {
                    field['source-prefix'] || ''
                    const isSelected =
                );
                        name ===
                        this.state.selectedVariable;


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


                     if (value) {
                     const isConfigured =
                         field['source-prefix'] =
                         !!(
                             value;
                             this.state.config &&
                    } else {
                            this.state.config.fields &&
                        delete field['source-prefix'];
                            this.state.config.fields[name]
                    }
                        );


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


            card.append(
                    $('<span>')
                this.fieldRow(
                        .addClass(
                    'Source prefix',
                            'preload-editor-variable-name'
                    sourcePrefix,
                        )
                    'Only source values beginning with this text are included.'
                        .text(name)
                )
                        .appendTo(item);
            );


            const excludeCategory =
                    if (name === 'PAGE') {
                this.textInput(
                        item.append(
                    field.exclude &&
                            $('<span>')
                     field.exclude.category ||
                                .addClass(
                    ''
                                    'preload-editor-badge'
                );
                                )
 
                                .text('AUTOMATIC')
            excludeCategory.on(
                        );
                'input.preloadEditor',
                     } else if (!isConfigured) {
                () => {
                        item.append(
                     const value =
                            $('<span>')
                        excludeCategory.val();
                                .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);
                }
            );


                    if (value) {
            container.append(list);
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


                        if (
            if (!ordered.length) {
                            !Object.keys(
                container.append(
                                field.exclude
                    $('<div>')
                             ).length
                        .addClass(
                         ) {
                             'preload-editor-empty'
                            delete field.exclude;
                        )
                        }
                        .text(
                    }
                            'No variables found in the preload.'
                         )
                );
            }
        },


                    this.markDirty();
        renderVariablesBySelector() {
                     this.renderConfigReviewAvailability();
            const container =
                 }
                this.root &&
            );
                this.root.find(
                     '.preload-editor-variables'
                 );


             card.append(
             if (
                 this.fieldRow(
                 container &&
                    'Exclude category',
                container.length
                    excludeCategory
            ) {
                 )
                 this.renderVariables(container);
             );
             }
        },


             card.append(
        selectVariable(name) {
                this.createTransformControls(
             name =
                     field,
                String(name || '')
                    'value',
                    .trim()
                    'Value transformation'
                     .toUpperCase();
                 ),
 
            if (!name) {
                 return;
            }


                 this.createTransformControls(
            const available =
                     field,
                 ['PAGE'].concat(
                     'label',
                     (
                     'Label transformation'
                        this.analysis &&
                 )
                        this.analysis.variables
            );
                            ? this.analysis.variables
                            : []
                     ).filter(
                        variable =>
                            variable !== 'PAGE'
                     )
                 );


             const optionsValue =
             const configuredUnused =
                 Array.isArray(field.options)
                 this.state.config &&
                     ? field.options
                this.state.config.fields
                     ? Object.keys(
                        this.state.config.fields
                    )
                         .map(
                         .map(
                             option => {
                             variable =>
                                 if (
                                 variable.toUpperCase()
                                    typeof option ===
                        )
                                    'string'
                    : [];
                                ) {
                                    return option;
                                }


                                return (
            configuredUnused.forEach(
                                    String(
                variable => {
                                        option.value || ''
                    if (
                                    ) +
                        !available.includes(variable) &&
                                    ' | ' +
                        variable !== 'PAGE'
                                    String(
                    ) {
                                        option.label ||
                        available.push(variable);
                                        option.value ||
                    }
                                        ''
                }
                                    )
            );
                                );
 
                            }
            if (!available.includes(name)) {
                        )
                return;
                        .join('\n')
            }
                    : '';
 
            this.state.selectedVariable =
                name;
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },


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


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


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


                                    if (
            const analysis =
                                        parts.length ===
                this.analysis ||
                                        1
                this.analyzePreload(
                                    ) {
                    this.extractIncludeonly(
                                        return parts[0];
                        this.getEditorContent()
                                    }
                    )
                );


                                    return {
            const name =
                                        value:
                this.state.selectedVariable ||
                                            parts[0],
                'PAGE';


                                        label:
            const fields =
                                            parts
                this.state.config &&
                                                .slice(1)
                this.state.config.fields
                                                .join(
                    ? this.state.config.fields
                                                    ' | '
                    : {};
                                                )
                                    };
                                }
                            );
                    }


                    this.markDirty();
            const field =
                    this.renderConfigReviewAvailability();
                 fields[name];
                 }
            );


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


        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                 $('<div>')
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-transform'
                         'preload-editor-variable-header'
                     );
                     )
                    .append(
                        $('<h3>')
                            .text(name),


            $('<h4>')
                        $('<span>')
                .text(title)
                            .addClass(
                .appendTo(wrapper);
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


            const existing =
                $('<p>')
                field[property] &&
                    .addClass(
                typeof field[property] === 'object'
                        'preload-editor-analysis-note'
                     ? field[property]
                    )
                     : {};
                    .text(
                        'This variable is currently not present in config.json.'
                     )
                     .appendTo(missing);


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


             const prefix =
             container.append(
                 this.textInput(
                 this.createVariableCard(
                     existing.prefix || ''
                     name,
                 );
                    field,
                    analysis
                 )
            );
        },


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


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


             const prefixRow =
             header.append(
                 this.fieldRow(
                 $('<h3>').text('PAGE'),
                     'Prefix',
 
                     prefix
                $('<span>')
                );
                     .addClass(
                        'preload-editor-badge'
                     )
                    .text('AUTOMATIC')
            );


             const suffixRow =
             card.append(header);
                this.fieldRow(
                    'Suffix',
                    suffix
                );


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


             const toRow =
             const label =
                 this.fieldRow(
                 this.textInput(
                     'To',
                    field.label ||
                     to
                    'Page Name'
                ).prop(
                     'disabled',
                     true
                 );
                 );


             const renderInputs =
             const description =
                 () => {
                 this.textarea(
                     const type =
                    field.description ||
                         transform.val();
                    'Name of the page.'
 
                )
                     prefixRow.toggle(
                     .addClass(
                         type === 'remove-prefix'
                         'preload-editor-small-textarea'
                    )
                     .prop(
                         'disabled',
                        true
                     );
                     );


                     suffixRow.toggle(
            const type =
                        type === 'remove-suffix'
                this.textInput(
                     );
                     field.type || 'page'
                ).prop(
                    'disabled',
                     true
                );


                    fromRow.toggle(
            const required =
                        type === 'replace'
                this.checkbox(
                     );
                    field.required !== false
                ).prop(
                    'disabled',
                     true
                );


                     toRow.toggle(
            const namespace =
                        type === 'replace'
                this.textInput(
                     );
                     field.namespace || 'Main'
                 };
                ).prop(
                    'disabled',
                     true
                 );


             const update =
             const allowNew =
                 () => {
                 this.checkbox(
                     const type =
                     field['allow-new'] === true
                        transform.val();
                ).prop(
                    'disabled',
                    true
                );


                     let object = null;
            card.append(
                this.fieldRow(
                     'Label',
                    label
                ),


                    if (
                this.fieldRow(
                        type === 'remove-prefix' &&
                     'Description',
                        prefix.val()
                     description
                     ) {
                ),
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                     ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }


                    if (object) {
                this.fieldRow(
                        field[property] = object;
                    'Type',
                     } else {
                     type
                        delete field[property];
                ),
                    }


                    this.markDirty();
                this.fieldRow(
                     this.renderConfigReviewAvailability();
                     'Required',
                 };
                    required
                 ),


            transform.on(
                 this.fieldRow(
                 'change.preloadEditor',
                     'Namespace',
                () => {
                     namespace
                    update();
                 ),
                     renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                     );
                 }
            );


            controls.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Transformation',
                     'Allow new page',
                     transform
                     allowNew
                 ),
                 )
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
             );
             );


            renderInputs();
             return card;
 
            wrapper.append(controls);
 
             return wrapper;
         },
         },


         // Config output
         createVariableCard(
 
            name,
         getCleanConfig() {
            field,
             const config =
            analysis
                 JSON.parse(
         ) {
                     JSON.stringify(
             const card =
                         this.state.config
                 $('<div>')
                     .addClass(
                         'preload-editor-variable'
                     )
                     )
                 );
                    .attr(
                        'data-variable',
                        name
                    );
 
            const header =
                 $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );


             const fields =
             header.append(
                 config.fields || {};
                 $('<h3>').text(name)
            );


             const orderedFields = {};
             if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }


             orderedFields.PAGE =
             card.append(header);
                this.getAutomaticPageField();


             Object.keys(fields)
             const label =
                 .filter(
                 this.textInput(
                     name =>
                     field.label || ''
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                 );
                 );


             config.fields =
             label.on(
                orderedFields;
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();


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


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


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


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


        renderConfigReviewAvailability() {
            card.append(
            /*
                this.fieldRow(
            * The config is generated on demand when the
                    'Description',
            * Review config.json button is pressed.
                    description
            */
                )
             this.renderAnalysisBySelector();
             );
        },


        // Dirty state
            const types = [
                ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];


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


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


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


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


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


        async savePreloadOnly() {
             const required =
             let title =
                 this.checkbox(
                 String(
                     field.required === true
                     this.state.preloadTitle || ''
                 );
                 ).trim();


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


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


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


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


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


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


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


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


             try {
             const defaultInput =
                const exists =
                this.textInput(
                    await this.pageExists(title);
                    field.default === undefined
                        ? ''
                        : field.default
                );


                await this.savePage(
            defaultInput.on(
                    title,
                'input.preloadEditor',
                    this.state.preloadContent,
                () => {
                     exists
                     const value =
                         ? 'Updated preload with Preload Editor'
                         defaultInput.val();
                        : 'Created preload with Preload Editor',
                    !exists
                );


                this.state.mode = 'edit';
                    if (value) {
                this.state.preloadTitle = title;
                        field.default =
                this.state.dirtyPreload = false;
                            value;
                    } else {
                        delete field.default;
                    }


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


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


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


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


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


                mw.notify(
                        this.markDirty();
                    error.message ||
                         this.renderConfigReviewAvailability();
                         'Could not save preload.',
                    {
                        type: 'error'
                     }
                     }
                );
                card.append(
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                 );
                 );
             }
             }
        },


        async saveConfigOnly() {
            if (
            let title =
                field.type === 'select' ||
                 String(
                 field.type === 'multiselect'
                    this.state.preloadTitle || ''
            ) {
                 ).trim();
                 this.renderSelectConfiguration(
                    card,
                    field
                );
            }


             if (!title) {
             if (
                 const result =
                 field.type === 'file'
                    await this.createPromptDialog(
            ) {
                        'Preload title',
                 this.renderFileConfiguration(
                        'Enter the full title for the preload.'
                     card,
                    );
                    field
 
                 );
                 if (!result) {
                     return;
                }
 
                 title = result;
                this.state.preloadTitle =
                    title;
             }
             }


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


             this.reanalyze();
                        if (!confirmed) {
                            return;
                        }
 
                        this.deleteVariable(name);
                    }
                );
 
             card.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );


             const validation =
             return card;
                this.validateBeforeSave();
        },


            if (validation.errors.length) {
        async deleteVariable(name) {
                 this.showValidationErrors(
            name =
                     validation
                 String(name || '')
                );
                    .trim()
                     .toUpperCase();


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


             const confirmed =
             if (
                 await this.confirmSave(
                 !this.state.config ||
                    'config',
                 !this.state.config.fields
                    title
             ) {
                 );
 
             if (!confirmed) {
                 return;
                 return;
             }
             }


             const configTitle =
             delete this.state.config.fields[name];
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';


             this.setStatus(
             if (
                 'Saving config...',
                 !Array.isArray(
                 'loading'
                    this.state.deletedVariables
             );
                 )
             ) {
                this.state.deletedVariables = [];
            }


             try {
             if (
                 const configExists =
                 !this.state.deletedVariables.includes(
                     await this.pageExists(
                     name
                        configTitle
                )
                    );
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }


                await this.savePage(
            this.state.selectedVariable =
                    configTitle,
                name;
                    this.getConfigJSON(),
 
                    configExists
            this.markDirty();
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor',
                    !configExists
                );


                this.state.mode = 'edit';
            this.renderVariablesBySelector();
                this.state.preloadTitle = title;
            this.renderVariableConfigurationBySelector();
                this.state.dirtyConfig = false;
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();


                this.updateDirtyState();
            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },


                if (!this.state.dirty) {
        // =========================================================
                    this.clearDraft(title);
        // Select configuration
                } else {
        // =========================================================
                    this.saveDraft();
                }


                 this.setStatus(
        renderSelectConfiguration(
                     this.state.dirtyPreload
            card,
                        ? 'Config saved. Preload still has unsaved changes.'
            field
                        : 'Config saved successfully.',
        ) {
                     'success'
            const source =
                 this.textInput(
                     field.source || '',
                     'category:Example'
                 );
                 );


                mw.notify(
            source.on(
                    this.state.dirtyPreload
                'input.preloadEditor',
                        ? 'Config saved. Preload still has unsaved changes.'
                () => {
                        : 'Config saved.',
                     const value =
                    {
                        source.val();
                        type: 'success'
 
                     }
                    if (value) {
                );
                        field.source = value;
            } catch (error) {
                     } else {
                console.error(
                        delete field.source;
                     'Preload Editor config save:',
                     }
                     error
                );


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


                 this.setStatus(
            card.append(
                     error.message ||
                 this.fieldRow(
                        'Could not save config.',
                     'Source',
                     'error'
                    source,
                 );
                     'Currently supported source format: category:Category Name'
                 )
            );


                 mw.notify(
            const sourcePrefix =
                     error.message ||
                 this.textInput(
                        'Could not save config.',
                     field['source-prefix'] || ''
                    {
                        type: 'error'
                    }
                 );
                 );
            }
        },


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


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


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


                title = result;
            card.append(
                 this.state.preloadTitle =
                 this.fieldRow(
                    title;
                    'Source prefix',
             }
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
             );


             this.state.preloadContent =
             const excludeCategory =
                 this.getEditorContent();
                 this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );


             this.reanalyze();
             excludeCategory.on(
 
                'input.preloadEditor',
            const validation =
                () => {
                this.validateBeforeSave();
                    const value =
                        excludeCategory.val();


            if (validation.errors.length) {
                    if (value) {
                this.showValidationErrors(
                        field.exclude =
                     validation
                            Object.assign(
                );
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                     ) {
                        delete field.exclude.category;


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


            const confirmed =
                    this.markDirty();
                await this.confirmSave(
                     this.renderConfigReviewAvailability();
                     'both',
                }
                    title
            );
                );


             if (!confirmed) {
             card.append(
                 return;
                 this.fieldRow(
             }
                    'Exclude category',
                    excludeCategory
                )
             );


             const configTitle =
             card.append(
                 title.replace(
                 this.createTransformControls(
                     /\/+$/,
                     field,
                     ''
                     'value',
                 ) +
                    'Value transformation'
                '/config.json';
                 ),


            this.setStatus(
                this.createTransformControls(
                'Saving preload and config...',
                    field,
                'loading'
                    'label',
                    'Label transformation'
                )
             );
             );


             try {
             const optionsValue =
                 const preloadExists =
                 Array.isArray(field.options)
                     await this.pageExists(title);
                     ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


                await this.savePage(
                                return (
                    title,
                                    String(
                    this.state.preloadContent,
                                        option.value || ''
                    preloadExists
                                    ) +
                         ? 'Updated preload with Preload Editor'
                                    ' | ' +
                        : 'Created preload with Preload Editor',
                                    String(
                     !preloadExists
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                         .join('\n')
                    : '';
 
            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                     'preload-editor-small-textarea'
                 );
                 );


                 const configExists =
            options.on(
                     await this.pageExists(
                'input.preloadEditor',
                         configTitle
                () => {
                     );
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);
 
                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );
 
                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }
 
                                    return {
                                        value:
                                            parts[0],
 
                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
       
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );
 
            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);
 
                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );
 
            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );
 
            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();
 
                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );
 
            const filetext =
                this.textarea(
                    field.filetext || ''
                );
 
            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();
 
                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );
 
            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },
 
        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                $('<div>')
                    .addClass(
                        'preload-editor-transform'
                    );
 
            $('<h4>')
                .text(title)
                .appendTo(wrapper);
 
            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );
 
            const prefix =
                this.textInput(
                    existing.prefix || ''
                );
 
            const suffix =
                this.textInput(
                    existing.suffix || ''
                );
 
            const from =
                this.textInput(
                    existing.from || ''
                );
 
            const to =
                this.textInput(
                    existing.to || ''
                );
 
            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );
 
            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );
 
            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );
 
            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );
 
            const toRow =
                this.fieldRow(
                    'To',
                    to
                );
 
            const renderInputs =
                () => {
                    const type =
                        transform.val();
 
                    prefixRow.toggle(
                        type === 'remove-prefix'
                    );
 
                    suffixRow.toggle(
                        type === 'remove-suffix'
                    );
 
                    fromRow.toggle(
                        type === 'replace'
                    );
 
                    toRow.toggle(
                        type === 'replace'
                    );
                };
 
            const update =
                () => {
                    const type =
                        transform.val();
 
                    let object = null;
 
                    if (
                        type === 'remove-prefix' &&
                        prefix.val()
                    ) {
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                    ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }
 
                    if (object) {
                        field[property] = object;
                    } else {
                        delete field[property];
                    }
 
                    this.markDirty();
                    this.renderConfigReviewAvailability();
                };
 
            transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );
 
            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );
 
            controls.append(
                this.fieldRow(
                    'Transformation',
                    transform
                ),
 
                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );
 
            renderInputs();
 
            wrapper.append(controls);
 
            return wrapper;
        },
 
        // =========================================================
        // Config output
        // =========================================================
 
        getCleanConfig() {
            const config =
                 JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );
 
            const fields =
                config.fields || {};
 
            const orderedFields = {};
 
            orderedFields.PAGE =
                this.getAutomaticPageField();
 
            Object.keys(fields)
                .filter(
                    name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );
 
            config.fields =
                orderedFields;
 
            return config;
        },
 
        getConfigJSON() {
            return JSON.stringify(
                this.getCleanConfig(),
                null,
                4
            );
        },
 
        renderConfigPreview(container) {
            if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },
 
        renderConfigPreviewBySelector() {
            this.renderAnalysisBySelector();
        },
 
        renderConfigReviewAvailability() {
            this.renderAnalysisBySelector();
        },
 
        // =========================================================
        // Dirty state
        // =========================================================
 
        updateDirtyState() {
            this.state.dirty =
                !!(
                    this.state.dirtyPreload ||
                    this.state.dirtyConfig
                );
        },
 
        markPreloadDirty() {
            this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markConfigDirty() {
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        markDirty() {
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },
 
        // =========================================================
        // Save
        // =========================================================
 
        async savePreloadOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                     await this.createPromptDialog(
                         'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                     return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'preload',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            this.setStatus(
                'Saving preload...',
                'loading'
            );
 
            try {
                const exists =
                    await this.pageExists(title);


                 await this.savePage(
                 await this.savePage(
                     configTitle,
                    title,
                     this.getConfigJSON(),
                    this.state.preloadContent,
                     configExists
                    exists
                         ? 'Updated preload config with Preload Editor'
                        ? 'Updated preload with Preload Editor'
                         : 'Created preload config with Preload Editor',
                        : 'Created preload with Preload Editor',
                     !configExists
                    !exists
                 );
                );
 
 
                 this.state.mode = 'edit';
                this.state.mode = 'edit';
                 this.state.dirtyPreload = false;
                this.state.preloadTitle = title;
                 this.state.dirtyConfig = false;
                this.state.dirtyPreload = false;
                 this.state.dirty = false;
 
                 this.state.preloadTitle = title;
                this.updateDirtyState();
 
 
                 this.clearDraft(title);
                if (!this.state.dirty) {
 
                    this.clearDraft(title);
                 this.setStatus(
                } else {
                     'Preload and config saved successfully.',
                    this.saveDraft();
                     'success'
                }
                 );
 
 
                this.setStatus(
                 mw.notify(
                    this.state.dirtyConfig
                     'Preload and config saved.',
                        ? 'Preload saved. Config still has unsaved changes.'
                     {
                        : 'Preload saved successfully.',
                         type: 'success'
                    'success'
                     }
                );
                 );
 
             } catch (error) {
                mw.notify(
                 console.error(
                    this.state.dirtyConfig
                     'Preload Editor save:',
                        ? 'Preload saved. Config still has unsaved changes.'
                     error
                        : 'Preload saved.',
                 );
                    {
 
                        type: 'success'
                 this.saveDraft();
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveConfigOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'config',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving config...',
                'loading'
            );
 
            try {
                /*
                * This now automatically creates or converts
                * config.json to the JSON content model.
                */
                await this.saveConfigPage(
                     configTitle,
                     this.getConfigJSON(),
                     (
                        await this.pageExists(
                            configTitle
                        )
                    )
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor'
                );
 
                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyConfig = false;
 
                this.updateDirtyState();
 
                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }
 
                this.setStatus(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON successfully.',
                    'success'
                );
 
                mw.notify(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor config save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                    }
                );
            }
        },
 
        async saveAll() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();
 
            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );
 
                if (!result) {
                    return;
                }
 
                title = result;
                this.state.preloadTitle =
                    title;
            }
 
            this.state.preloadContent =
                this.getEditorContent();
 
            this.reanalyze();
 
            const validation =
                this.validateBeforeSave();
 
            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );
 
                this.saveDraft();
                return;
            }
 
            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );
 
            if (!confirmed) {
                return;
            }
 
            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';
 
            this.setStatus(
                'Saving preload and config...',
                'loading'
            );
 
            try {
                const preloadExists =
                    await this.pageExists(title);
 
                await this.savePage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                     !preloadExists
                );
 
                /*
                * Config is saved through the JSON-aware
                * helper. This means:
                *
                * - new config -> created as JSON
                * - old wikitext config -> converted to JSON
                * - existing JSON config -> simply updated
                */
                const configExists =
                    await this.pageExists(
                        configTitle
                    );
 
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                 );
 
                 this.state.mode = 'edit';
                 this.state.dirtyPreload = false;
                 this.state.dirtyConfig = false;
                 this.state.dirty = false;
                 this.state.preloadTitle = title;
 
                 this.clearDraft(title);
 
                 this.setStatus(
                     'Preload and JSON config saved successfully.',
                     'success'
                 );
 
                 mw.notify(
                     'Preload and config saved. config.json is using the JSON content model.',
                     {
                         type: 'success'
                     }
                 );
             } catch (error) {
                 console.error(
                     'Preload Editor save:',
                     error
                 );
 
                 this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },


                this.setStatus(
        // =========================================================
                    error.message ||
        // Validation
                        'Could not save preload/config.',
         // =========================================================
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
         },


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


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

Latest revision as of 22:07, 14 October 2026

(function (mw, $) {
    'use strict';

    const PreloadEditor = {
        version: '1.2.0',

        state: {
            preloadTitle: '',
            preloadSource: '',
            preloadContent: '',
            config: null,
            variables: [],
            conditions: [],
            selectedVariable: 'PAGE',
            deletedVariables: [],
            mode: 'idle',
            dirty: false,
            dirtyPreload: false,
            dirtyConfig: false,

            // Local draft state
            localDraftSavedAt: null,
            localDraftAvailable: false
        },

        editor: null,
        editorView: null,
        analysis: null,
        root: null,
        workspace: null,
        status: null,
        localDraftStatus: null,
        editorTools: null,

        draftStorageKey: 'PetitPlanet.PreloadEditor.drafts.v1',

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

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

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

                if (!raw) {
                    return {
                        active: null,
                        drafts: {}
                    };
                }

                const parsed = JSON.parse(raw);

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

                if (!parsed.drafts || typeof parsed.drafts !== 'object' || Array.isArray(parsed.drafts)) {
                    parsed.drafts = {};
                }

                return parsed;
            } catch (error) {
                console.warn('Preload Editor: Could not read local drafts.', error);

                return {
                    active: null,
                    drafts: {}
                };
            }
        },

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

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

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

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

            let config = null;

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

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

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

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

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

                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-warning',
                'is-error',
                'is-empty'
            );

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

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

        formatLocalDraftTime(timestamp) {
            if (!timestamp) {
                return '';
            }

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

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

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

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

                return;
            }

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

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

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

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

            const saved = this.setDraftStorage(storage);

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

            return saved;
        },

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

            if (storage.drafts && storage.drafts[id]) {
                delete storage.drafts[id];
            }

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

            this.setDraftStorage(storage);

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

            this.updateLocalDraftIndicator();
        },

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

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

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

            let latestId = null;
            let latestDraft = null;

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

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

            if (!latestDraft) {
                return null;
            }

            return {
                id: latestId,
                draft: latestDraft
            };
        },

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

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

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

            const savedAt = draft.savedAt
                ? new Date(draft.savedAt).toLocaleString()
                : '';

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

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

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

            let config = this.emptyConfig();

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

            const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';

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

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

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

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

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

                mode: draft.mode || 'edit',

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

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

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

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

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

            this.setStatus(
                'Restored unsaved local work from this browser.',
                'warning'
            );

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

            return true;
        },

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

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

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

            if (!page || page.missing) {
                return null;
            }

            const content =
                page.revisions &&
                page.revisions[0] &&
                page.revisions[0].slots &&
                page.revisions[0].slots.main &&
                page.revisions[0].slots.main.content;

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

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

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

            return (
                response &&
                response.query &&
                response.query.search
            ) || [];
        },

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

            if (createOnly) {
                params.createonly = true;
            }

            if (contentModel) {
                params.contentmodel = contentModel;
            }

            return new mw.Api().postWithToken('csrf', params);
        },

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

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

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

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

        // =========================================================
        // Config import helpers
        // =========================================================

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

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

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

        /*
         * Return a safe clone of a config field.
         *
         * This is deliberately JSON-based because config
         * definitions are JSON-compatible objects.
         */
        cloneConfigField(field) {
            try {
                return JSON.parse(JSON.stringify(field));
            } catch (error) {
                console.warn(
                    'Preload Editor: Could not clone imported field.',
                    error
                );

                return null;
            }
        },

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

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

            const result = {};

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

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

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

                const clone = this.cloneConfigField(field);

                if (!clone) {
                    return;
                }

                result[upper] = clone;
            });

            return result;
        },

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

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

                const box = $('<div>')
                    .addClass(
                        '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);
                    box.append(emptyButtons);
                    overlay.append(box);

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

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

                    return;
                }

                const search = this.textInput('', 'Search variables...')
                    .addClass('preload-editor-import-search');

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

                box.append(searchWrap);

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

                const selectAll = this.createButton(
                    'Select all',
                    '',
                    () => {
                        list
                            .find('input[type="checkbox"]:visible')
                            .prop('checked', true);

                        updateSummary();
                    }
                );

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

                        updateSummary();
                    }
                );

                controls.append(selectAll, deselectAll);
                box.append(controls);

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

                const localFields =
                    this.state.config && this.state.config.fields
                        ? this.state.config.fields
                        : {};

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

                    const type = field && field.type
                        ? String(field.type)
                        : 'text';

                    const label = field && field.label
                        ? String(field.label)
                        : this.humanizeName(name);

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

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

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

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

                    $('<strong>')
                        .text(name)
                        .appendTo(header);

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

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

                    $('<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.';
                    }

                    summary.text(text);

                    importButton.prop('disabled', selected === 0);
                };

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

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

                        row.toggle(!query || haystack.includes(query));
                    });
                };

                search.on(
                    'input.preloadEditor',
                    filterRows
                );

                list.on(
                    'change.preloadEditor',
                    'input[type="checkbox"]',
                    updateSummary
                );

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

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

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

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

                        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');

                const close = event => {
                    if (event.key === 'Escape') {
                        cancel.trigger('click');
                    }
                };

                overlay.on(
                    'keydown.preloadEditor',
                    close
                );

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

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

            if (!source) {
                return;
            }

            const configTitle = this.normalizeConfigTitle(source);

            this.setStatus(
                'Loading source config...',
                'loading'
            );

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

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

                let sourceConfig;

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

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

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

                const fields = this.getImportableFields(sourceConfig);

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

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

                    return;
                }

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

                    return;
                }

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

                if (!this.state.config.fields) {
                    this.state.config.fields = {};
                }

                const imported = [];
                const replaced = [];

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

                    const field = fields[name];

                    if (!field) {
                        return;
                    }

                    if (this.state.config.fields[name]) {
                        replaced.push(name);
                    } else {
                        imported.push(name);
                    }

                    const clone = this.cloneConfigField(field);

                    if (!clone) {
                        return;
                    }

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

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

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

                this.markConfigDirty();

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

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

                this.reanalyze();

                this.renderVariablesBySelector();
                this.renderVariableConfigurationBySelector();
                this.renderAnalysisBySelector();
                this.updateEditorTools();

                this.saveDraft();

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

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

                this.setStatus(status, 'success');

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

                this.setStatus(
                    error.message ||
                        'Could not import variable definitions.',
                    'error'
                );

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

        // =========================================================
        // Preload parsing
        // =========================================================

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

            return match
                ? match[1].trim()
                : String(source || '').trim();
        },

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

            let match;

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

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

            return variables;
        },

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

            let match;

            while ((match = pattern.exec(content)) !== null) {
                conditions.push({
                    type: match[1].toLowerCase(),
                    expression: match[2].trim(),
                    index: match.index
                });
            }

            return conditions;
        },

        findConditionVariables(content) {
            const variables = [];

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

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

                matches.forEach(name => {
                    name = name.toUpperCase();

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

            return variables;
        },

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

        // =========================================================
        // Config
        // =========================================================

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

        emptyConfig() {
            return {
                settings: {
                    incomplete: 'add-stub'
                },

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

        normalizeConfig(config) {
            if (
                !config ||
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                config = this.emptyConfig();
            }

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

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

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

            return config;
        },

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

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

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

            const existing = config.fields || {};

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

            const fields = {};

            fields.PAGE =
                this.getAutomaticPageField();

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

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

            Object.keys(existing).forEach(name => {
                const upper = name.toUpperCase();

                if (
                    upper !== 'PAGE' &&
                    !fields[upper] &&
                    !deleted.has(upper)
                ) {
                    fields[upper] =
                        existing[name];
                }
            });

            config.fields = fields;

            return config;
        },

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

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

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

            const configured =
                Object.keys(
                    config.fields
                ).map(
                    name =>
                        name.toUpperCase()
                );

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

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

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

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

                    return;
                }

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

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

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

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

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

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

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

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

                    if (
                        field.filetext !== undefined &&
                        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 {
                valid: !errors.length,
                errors,
                warnings
            };
        },

        // =========================================================
        // Transformation helpers
        // =========================================================

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

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

                case 'remove-suffix':
                    return suffix
                        ? {
                            transform,
                            suffix
                        }
                        : null;

                case 'replace':
                    return from === ''
                        ? null
                        : {
                            transform,
                            from,
                            to: to || ''
                        };

                default:
                    return null;
            }
        },

        // =========================================================
        // UI helpers
        // =========================================================

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

            if (className) {
                section.addClass(className);
            }

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

            return section;
        },

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

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

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

            return button;
        },

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

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

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

            row.append(input);

            return row;
        },

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

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

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

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

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

            return select;
        },

        // =========================================================
        // In-wiki dialogs
        // =========================================================

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

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

                $('<h2>')
                    .text(title)
                    .appendTo(box);

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

                messageLines.forEach(line => {
                    if (line === '') {
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-spacer'
                            )
                            .appendTo(box);

                        return;
                    }

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

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

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

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

                buttons.append(cancel, confirm);
                box.append(buttons);
                overlay.append(box);

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

                const close = value => {
                    if (value === 'Escape') {
                        cancel.trigger('click');
                    }
                };

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

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

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

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

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

                $('<h2>')
                    .text(title)
                    .appendTo(box);

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

                const input = this.textInput();

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

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

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

                        if (!value) {
                            return;
                        }

                        overlay.remove();
                        resolve(value);
                    }
                );

                buttons.append(cancel, confirm);

                box.append(
                    input,
                    buttons
                );

                overlay.append(box);

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

                input.trigger('focus');

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

                        if (event.key === 'Escape') {
                            cancel.trigger('click');
                        }
                    }
                );
            });
        },

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

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

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

                $('<p>')
                    .text(
                        'This is the config.json that will be saved for the current preload.'
                    )
                    .appendTo(box);

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

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

                box.append(codeWrap);

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

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

                buttons.append(close);
                box.append(buttons);
                overlay.append(box);

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

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

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

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

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

            let saveDescription;

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

            const pages = [];

            if (mode === 'preload' || mode === 'both') {
                pages.push(
                    'Preload: ' +
                    title
                );
            }

            if (mode === 'config' || mode === 'both') {
                pages.push(
                    'Config: ' +
                    configTitle
                );

                pages.push(
                    'Config content model: JSON'
                );
            }

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

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

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

            const {
                view,
                inputHandler
            } = this.editor;

            if (view && inputHandler) {
                view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }

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

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

        getEditorView() {
            return this.editorView;
        },

        getEditorContent() {
            if (
                this.editorView &&
                this.editorView.state
            ) {
                return this.editorView.state.doc.toString();
            }

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

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

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

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

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

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

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

            const selection =
                this.editorView.state.selection.main;

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

        focusEditor() {
            if (this.editorView) {
                this.editorView.focus();
            }
        },

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

            const view = this.editorView;
            const selection = view.state.selection.main;

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

            const to =
                selectionTo === undefined
                    ? selection.to
                    : selectionTo;

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

            view.dispatch({
                changes: {
                    from,
                    to,
                    insert: text
                },
                selection: {
                    anchor: cursor
                }
            });

            view.focus();
        },

        // =========================================================
        // Editor tools
        // =========================================================

        wrapSelectionWithVariable() {
            const selected =
                this.getEditorSelection();

            if (
                !selected ||
                selected.from === selected.to
            ) {
                this.focusEditor();
                return;
            }

            const replacement =
                '%%' +
                selected.text +
                '%%';

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

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

            if (!name) {
                return;
            }

            const selected =
                this.getEditorSelection();

            if (!selected) {
                return;
            }

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

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

            const selected =
                this.getEditorSelection();

            if (!selected) {
                return;
            }

            let text;
            let cursorOffset;

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

                    const opening =
                        '<!-- @if ' +
                        variable +
                        ' -->';

                    const closing =
                        '<!-- @endif -->';

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

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

                        cursorOffset =
                            opening.length + 1;
                    }

                    break;
                }

                case 'elseif':
                    text =
                        '<!-- @elseif -->';

                    cursorOffset =
                        text.length;

                    break;

                case 'else':
                    text =
                        '<!-- @else -->';

                    cursorOffset =
                        text.length;

                    break;

                case 'endif':
                    text =
                        '<!-- @endif -->';

                    cursorOffset =
                        text.length;

                    break;

                default:
                    return;
            }

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

        getToolVariables() {
            const variables =
                new Set(['PAGE']);

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

            return Array.from(variables);
        },

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

            if (className) {
                select.addClass(className);
            }

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

            return select;
        },

        updateEditorToolVariables() {
            if (!this.editorTools) {
                return;
            }

            const variables =
                this.getToolVariables();

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

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

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

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

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

            populate(
                this.editorTools.variableSelect,
                current
            );

            populate(
                this.editorTools.conditionVariableSelect,
                currentCondition
            );
        },

        updateConditionVariableVisibility() {
            if (!this.editorTools) {
                return;
            }

            const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();

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

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

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

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

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

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

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

            variableGroup.append(
                variableSelect,

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

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

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

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

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

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

            const insertCondition =
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                );

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

            conditionGroup.append(
                conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );

            tools.append(
                wrapGroup,
                variableGroup,
                conditionGroup
            );

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

            this.updateEditorToolVariables();
            this.updateConditionVariableVisibility();

            return tools;
        },

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

        // =========================================================
        // Syntax highlighting
        // =========================================================

        getKnownVariables() {
            const known =
                new Set(['PAGE']);

            const fields =
                this.state.config &&
                this.state.config.fields;

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

            return known;
        },

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

            const knownVariables =
                this.getKnownVariables();

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

            let match;

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

                const known =
                    knownVariables.has(name);

                decorations.push(
                    Decoration.mark({
                        class: [
                            'preload-editor-syntax-variable',
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );
            }

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

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

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

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

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

                if (
                    type !== 'if' &&
                    type !== 'elseif'
                ) {
                    continue;
                }

                const expression =
                    match[2];

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

                const expressionPattern =
                    /[A-Za-z0-9_-]+/g;

                let expressionMatch;

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

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

                    const start =
                        expressionStart +
                        expressionMatch.index;

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

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

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

            const require =
                mw.loader.require;

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

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

                    update: (
                        decorations,
                        transaction
                    ) =>
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,

                    provide: field =>
                        EditorView.decorations.from(
                            field
                        )
                });

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

            this.editor.syntaxField =
                syntaxField;
        },

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

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

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

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

                            settled = true;
                            cleanup();

                            const view =
                                cm.view;

                            const inputHandler =
                                () => {
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();

                                    this.markPreloadDirty();

                                    this.reanalyze();

                                    this.renderVariablesBySelector();
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();

                                    this.saveDraft();
                                };

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

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

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

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

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

                            this.editorView =
                                view;

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

                            try {
                                await this.installSyntaxHighlighting(
                                    view
                                );

                                if (
                                    this.state.dirty
                                ) {
                                    this.saveDraft();
                                }

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

                    const onLoad =
                        loader => {
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }

                            try {
                                loader(textarea);
                            } catch (error) {
                                settled = true;
                                cleanup();
                                reject(error);
                            }
                        };

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

                    mw.hook(
                        'dev.CCM.load'
                    ).add(onLoad);
                }
            );
        },

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

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

            if (!root.length) {
                return;
            }

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

            root.append(this.root);

            this.renderShell();

            this.restoreDraft();

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

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

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

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

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

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

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

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

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

            this.root.append(loader);

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

            this.root.append(
                this.workspace
            );

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

            this.localDraftStatus =
                $('<div>')
                    .addClass(
                        'preload-editor-local-draft-status is-empty'
                    )
                    .text(
                        'No local draft'
                    );

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

            footer.append(
                this.localDraftStatus,
                this.status
            );

            this.root.append(
                footer
            );

            this.updateLocalDraftIndicator();

            this.renderWelcome();
        },

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

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

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

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

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

            section.append(tips);
            this.workspace.append(section);
        },

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

            this.status.removeClass(
                'is-error',
                'is-success',
                'is-warning',
                'is-loading'
            );

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

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

        // =========================================================
        // Load / create
        // =========================================================

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

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

                return;
            }

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

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

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

                    this.renderMissingPage(
                        title,
                        suggestions
                    );

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

                    return;
                }

                await this.loadDefinition(
                    page.title,
                    page.content
                );

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

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

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

            if (!query) {
                query = title;
            }

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

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

                return [];
            }
        },

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

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

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

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

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

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

                section.append(list);
            }

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

            this.workspace.append(section);
        },

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

            this.state = {
                preloadTitle: title,
                preloadSource: '',
                preloadContent:
                    this.defaults.preload,

                config:
                    this.emptyConfig(),

                variables: ['PAGE'],
                conditions: [],
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,

                localDraftSavedAt: null,
                localDraftAvailable: false
            };

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

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

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

            if (!result) {
                return;
            }

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

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

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

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

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

                    config:
                        this.emptyConfig(),

                    variables: ['PAGE'],
                    conditions: [],
                    selectedVariable: 'PAGE',
                    deletedVariables: [],
                    mode: 'new',
                    dirty: true,
                    dirtyPreload: true,
                    dirtyConfig: true,

                    localDraftSavedAt: null,
                    localDraftAvailable: false
                };

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

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

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

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

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

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

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

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

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

            let config =
                this.emptyConfig();

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

            const configPage =
                await this.getPage(configTitle);

            if (configPage) {
                try {
                    config =
                        JSON.parse(
                            configPage.content
                        );
                } catch (error) {
                    throw new Error(
                        'The existing config.json contains invalid JSON: ' +
                        error.message
                    );
                }
            }

            const analysis =
                this.analyzePreload(content);

            this.state.deletedVariables = [];

            config =
                this.prepareConfigForVariables(
                    config,
                    analysis
                );

            this.state = {
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,

                variables:
                    analysis.variables,

                conditions:
                    analysis.conditions,

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

                deletedVariables: [],

                mode: 'edit',
                dirty: false,
                dirtyPreload: false,
                dirtyConfig: false,

                localDraftSavedAt: null,
                localDraftAvailable: false
            };

            this.clearDraft(title);
            this.renderEditor();
        },

        // =========================================================
        // Editor
        // =========================================================

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

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

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

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

            const editorSection =
                this.createSection(
                    'Preload',
                    'preload-editor-main-section'
                );

            const meta =
                $('<div>')
                    .addClass(
                        'preload-editor-meta'
                    );

            $('<strong>')
                .text(
                    this.state.preloadTitle ||
                    'New preload'
                )
                .appendTo(meta);

            if (
                this.state.mode === 'new'
            ) {
                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
            }

            editorSection.append(meta);
            editorSection.append(
                this.renderEditorTools()
            );

            const textarea =
                this.textarea(
                    this.state.preloadContent
                )
                    .attr(
                        'id',
                        'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                    );

            const editorMount =
                $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);

            editorSection.append(editorMount);
            left.append(editorSection);

            const analysisSection =
                this.createSection('Analysis');

            const analysisContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis'
                    );

            analysisSection.append(
                analysisContainer
            );

            const variablesSection =
                this.createSection('Variables');

            const detectVariablesButton =
                this.createButton(
                    'Detect variables',
                    'preload-editor-button-primary preload-editor-detect-variables',
                    () =>
                        this.detectVariables()
                );

            const detectHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                        'Refresh the variable list after editing the preload.'
                    );

            variablesSection.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-detect'
                    )
                    .append(
                        detectVariablesButton,
                        detectHelp
                    )
            );

            const variableContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variables'
                    );

            variablesSection.append(
                variableContainer
            );

            const configurationSection =
                this.createSection(
                    'Variable configuration'
                );

            /*
             * Import button lives at the top of the
             * variable configuration section so the
             * workflow is always easy to find.
             */
            const importDefinitionsButton =
                this.createButton(
                    'Import definitions',
                    'preload-editor-button-primary preload-editor-import-definitions',
                    () =>
                        this.importVariableDefinitions()
                );

            const importHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help preload-editor-import-definitions-help'
                    )
                    .text(
                        'Import variable definitions from another preload config.json. Existing definitions can be replaced.'
                    );

            const importControls =
                $('<div>')
                    .addClass(
                        'preload-editor-import-definition-controls'
                    )
                    .append(
                        importDefinitionsButton,
                        importHelp
                    );

            configurationSection.append(
                importControls
            );

            const configurationContainer =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-configuration'
                    );

            configurationSection.append(
                configurationContainer
            );

            const configSection =
                this.createSection(
                    'Configuration'
                );

            const configHelp =
                $('<div>')
                    .addClass(
                        'preload-editor-help'
                    )
                    .text(
                        'Review the exact config.json that will be uploaded to the wiki.'
                    );

            const reviewConfigButton =
                this.createButton(
                    'Review config.json',
                    '',
                    () =>
                        this.createConfigReviewDialog()
                );

            configSection.append(
                configHelp,
                reviewConfigButton
            );

            right.append(
                analysisSection,
                variablesSection,
                configurationSection,
                configSection
            );

            layout.append(
                left,
                right
            );

            const saveBar =
                $('<div>')
                    .addClass(
                        'preload-editor-save-bar'
                    );

            saveBar.append(
                this.createButton(
                    'Save Preload',
                    '',
                    () =>
                        this.savePreloadOnly()
                ),

                this.createButton(
                    'Save Config',
                    '',
                    () =>
                        this.saveConfigOnly()
                ),

                this.createButton(
                    'Save',
                    'preload-editor-button-primary',
                    () =>
                        this.saveAll()
                )
            );

            this.root
                .find('.preload-editor-footer')
                .append(saveBar);

            this.workspace.append(
                layout
            );

            this.reanalyze();

            this.renderVariables(
                variableContainer
            );

            this.renderAnalysis(
                analysisContainer
            );

            this.renderVariableConfiguration(
                configurationContainer
            );

            this.updateEditorTools();
            this.updateLocalDraftIndicator();

            this.mountCodeMirror(
                textarea.get(0)
            ).catch(
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                    );

                    this.setStatus(
                        error.message ||
                            'Could not initialize CodeMirror.',
                        'error'
                    );
                }
            );
        },

        // =========================================================
        // Variable detection
        // =========================================================

        detectVariables() {
            const source =
                this.getEditorContent();

            this.state.preloadContent =
                source;

            const content =
                this.extractIncludeonly(
                    source
                );

            const analysis =
                this.analyzePreload(
                    content
                );

            /*
             * If a variable was previously deleted from
             * the configuration, detecting the current
             * preload again should allow it to come back.
             */
            if (
                Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                const detected =
                    new Set(
                        analysis.variables
                            .map(
                                name =>
                                    String(
                                        name
                                    ).toUpperCase()
                            )
                    );

                this.state.deletedVariables =
                    this.state.deletedVariables
                        .filter(
                            name =>
                                !detected.has(
                                    String(
                                        name
                                    ).toUpperCase()
                                )
                        );
            } else {
                this.state.deletedVariables = [];
            }

            this.markDirty();

            this.reanalyze();

            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.updateEditorTools();

            this.saveDraft();

            this.setStatus(
                'Variables detected from the current preload.',
                'success'
            );
        },

        reanalyze() {
            const source =
                this.getEditorContent();

            const content =
                this.extractIncludeonly(source);

            const analysis =
                this.analyzePreload(
                    content
                );

            this.state.preloadContent =
                source;

            this.state.variables =
                analysis.variables;

            this.state.conditions =
                analysis.conditions;

            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );

            this.analysis =
                analysis;

            const available =
                ['PAGE'].concat(
                    analysis.variables.filter(
                        name =>
                            name !== 'PAGE'
                    )
                );

            if (
                !available.includes(
                    this.state.selectedVariable
                )
            ) {
                this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
            }
        },

        // =========================================================
        // Analysis
        // =========================================================

        renderAnalysis(container) {
            container.empty();

            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );

            const variableCount =
                analysis.variables.length;

            const conditionCount =
                analysis.conditions.length;

            const configuredCount =
                Object.keys(
                    this.state.config &&
                    this.state.config.fields
                        ? this.state.config.fields
                        : {}
                ).length;

            const summary =
                $('<div>')
                    .addClass(
                        'preload-editor-analysis-summary'
                    );

            const createMetric =
                (
                    value,
                    label
                ) =>
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),

                            $('<span>')
                                .addClass(
                                    'preload-editor-analysis-label'
                                )
                                .text(label)
                        );

            summary.append(
                createMetric(
                    variableCount,
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),

                createMetric(
                    conditionCount,
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                ),

                createMetric(
                    configuredCount,
                    configuredCount === 1
                        ? 'configured field'
                        : 'configured fields'
                )
            );

            container.append(summary);

            if (
                analysis.conditionVariables.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-note'
                        )
                        .text(
                            'Condition variables: ' +
                            analysis.conditionVariables.join(', ')
                        )
                );
            }

            const validation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );

            if (validation.errors.length) {
                const errors =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-errors'
                        );

                validation.errors.forEach(
                    error => {
                        $('<li>')
                            .text(error)
                            .appendTo(errors);
                    }
                );

                container.append(errors);
            }

            if (validation.warnings.length) {
                const warnings =
                    $('<ul>')
                        .addClass(
                            'preload-editor-validation-warnings'
                        );

                validation.warnings.forEach(
                    warning => {
                        $('<li>')
                            .text(warning)
                            .appendTo(warnings);
                    }
                );

                container.append(warnings);
            }

            if (
                !validation.errors.length &&
                !validation.warnings.length
            ) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-validation-success'
                        )
                        .text(
                            'Preload and configuration are in sync.'
                        )
                );
            }
        },

        renderAnalysisBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );

            if (
                container &&
                container.length
            ) {
                this.renderAnalysis(container);
            }
        },

        // =========================================================
        // Variables
        // =========================================================

        renderVariables(container) {
            container.empty();

            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );

            const variables =
                analysis.variables.slice();

            const ordered =
                ['PAGE'];

            variables.forEach(
                name => {
                    if (
                        name !== 'PAGE' &&
                        !ordered.includes(name)
                    ) {
                        ordered.push(name);
                    }
                }
            );

            const configuredFields =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                    : [];

            configuredFields.forEach(
                name => {
                    const upper =
                        name.toUpperCase();

                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );

            const deleted =
                Array.isArray(
                    this.state.deletedVariables
                )
                    ? this.state.deletedVariables
                    : [];

            deleted.forEach(
                name => {
                    const upper =
                        String(name).toUpperCase();

                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
            );

            const list =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-list'
                    );

            ordered.forEach(
                name => {
                    const isSelected =
                        name ===
                        this.state.selectedVariable;

                    const isUsed =
                        analysis.variables.includes(
                            name
                        );

                    const isConfigured =
                        !!(
                            this.state.config &&
                            this.state.config.fields &&
                            this.state.config.fields[name]
                        );

                    const item =
                        $('<button>')
                            .attr({
                                type: 'button',
                                'data-variable':
                                    name
                            })
                            .addClass(
                                'preload-editor-variable-item'
                            )
                            .toggleClass(
                                'is-selected',
                                isSelected
                            )
                            .on(
                                'click.preloadEditor',
                                () =>
                                    this.selectVariable(
                                        name
                                    )
                            );

                    $('<span>')
                        .addClass(
                            'preload-editor-variable-name'
                        )
                        .text(name)
                        .appendTo(item);

                    if (name === 'PAGE') {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge'
                                )
                                .text('AUTOMATIC')
                        );
                    } else if (!isConfigured) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text(
                                    isUsed
                                        ? 'NOT CONFIGURED'
                                        : 'DELETED'
                                )
                        );
                    } else if (!isUsed) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                    }

                    list.append(item);
                }
            );

            container.append(list);

            if (!ordered.length) {
                container.append(
                    $('<div>')
                        .addClass(
                            'preload-editor-empty'
                        )
                        .text(
                            'No variables found in the preload.'
                        )
                );
            }
        },

        renderVariablesBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variables'
                );

            if (
                container &&
                container.length
            ) {
                this.renderVariables(container);
            }
        },

        selectVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();

            if (!name) {
                return;
            }

            const available =
                ['PAGE'].concat(
                    (
                        this.analysis &&
                        this.analysis.variables
                            ? this.analysis.variables
                            : []
                    ).filter(
                        variable =>
                            variable !== 'PAGE'
                    )
                );

            const configuredUnused =
                this.state.config &&
                this.state.config.fields
                    ? Object.keys(
                        this.state.config.fields
                    )
                        .map(
                            variable =>
                                variable.toUpperCase()
                        )
                    : [];

            configuredUnused.forEach(
                variable => {
                    if (
                        !available.includes(variable) &&
                        variable !== 'PAGE'
                    ) {
                        available.push(variable);
                    }
                }
            );

            if (!available.includes(name)) {
                return;
            }

            this.state.selectedVariable =
                name;

            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },

        renderVariableConfigurationBySelector() {
            const container =
                this.root &&
                this.root.find(
                    '.preload-editor-variable-configuration'
                );

            if (
                container &&
                container.length
            ) {
                this.renderVariableConfiguration(
                    container
                );
            }
        },

        renderVariableConfiguration(container) {
            container.empty();

            const analysis =
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );

            const name =
                this.state.selectedVariable ||
                'PAGE';

            const fields =
                this.state.config &&
                this.state.config.fields
                    ? this.state.config.fields
                    : {};

            const field =
                fields[name];

            if (name === 'PAGE') {
                container.append(
                    this.createAutomaticPageCard(
                        field ||
                        this.getAutomaticPageField()
                    )
                );

                return;
            }

            if (!field) {
                const missing =
                    $('<div>')
                        .addClass(
                            'preload-editor-variable preload-editor-variable-missing'
                        );

                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    )
                    .append(
                        $('<h3>')
                            .text(name),

                        $('<span>')
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);

                $('<p>')
                    .addClass(
                        'preload-editor-analysis-note'
                    )
                    .text(
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);

                container.append(missing);
                return;
            }

            container.append(
                this.createVariableCard(
                    name,
                    field,
                    analysis
                )
            );
        },

        createAutomaticPageCard(field) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );

            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );

            header.append(
                $('<h3>').text('PAGE'),

                $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
            );

            card.append(header);

            $('<p>')
                .addClass(
                    'preload-editor-analysis-note'
                )
                .text(
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                )
                .appendTo(card);

            const label =
                this.textInput(
                    field.label ||
                    'Page Name'
                ).prop(
                    'disabled',
                    true
                );

            const description =
                this.textarea(
                    field.description ||
                    'Name of the page.'
                )
                    .addClass(
                        'preload-editor-small-textarea'
                    )
                    .prop(
                        'disabled',
                        true
                    );

            const type =
                this.textInput(
                    field.type || 'page'
                ).prop(
                    'disabled',
                    true
                );

            const required =
                this.checkbox(
                    field.required !== false
                ).prop(
                    'disabled',
                    true
                );

            const namespace =
                this.textInput(
                    field.namespace || 'Main'
                ).prop(
                    'disabled',
                    true
                );

            const allowNew =
                this.checkbox(
                    field['allow-new'] === true
                ).prop(
                    'disabled',
                    true
                );

            card.append(
                this.fieldRow(
                    'Label',
                    label
                ),

                this.fieldRow(
                    'Description',
                    description
                ),

                this.fieldRow(
                    'Type',
                    type
                ),

                this.fieldRow(
                    'Required',
                    required
                ),

                this.fieldRow(
                    'Namespace',
                    namespace
                ),

                this.fieldRow(
                    'Allow new page',
                    allowNew
                )
            );

            return card;
        },

        createVariableCard(
            name,
            field,
            analysis
        ) {
            const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );

            const header =
                $('<div>')
                    .addClass(
                        'preload-editor-variable-header'
                    );

            header.append(
                $('<h3>').text(name)
            );

            if (
                !analysis.variables.includes(name)
            ) {
                header.append(
                    $('<span>')
                        .addClass(
                            'preload-editor-badge is-warning'
                        )
                        .text('UNUSED')
                );
            }

            card.append(header);

            const label =
                this.textInput(
                    field.label || ''
                );

            label.on(
                'input.preloadEditor',
                () => {
                    field.label =
                        label.val();

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Label',
                    label
                )
            );

            const description =
                this.textarea(
                    field.description || ''
                ).addClass(
                    'preload-editor-small-textarea'
                );

            description.on(
                'input.preloadEditor',
                () => {
                    field.description =
                        description.val();

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Description',
                    description
                )
            );

            const types = [
                ['text', 'Text'],
                ['textarea', 'Textarea'],
                ['number', 'Number'],
                ['boolean', 'Boolean'],
                ['select', 'Select'],
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date'],
                ['file', 'File']
            ];

            const typeSelect =
                this.select(
                    types.map(
                        ([value, label]) => ({
                            value,
                            label
                        })
                    ),
                    field.type || 'text'
                );

            typeSelect.on(
                'change.preloadEditor',
                () => {
                    field.type =
                        typeSelect.val();

                    this.markDirty();

                    this.renderVariableConfigurationBySelector();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );

            const required =
                this.checkbox(
                    field.required === true
                );

            required.on(
                'change.preloadEditor',
                () => {
                    field.required =
                        required.prop('checked');

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Required',
                    required
                )
            );

            const placeholder =
                this.textInput(
                    field.placeholder || ''
                );

            placeholder.on(
                'input.preloadEditor',
                () => {
                    const value =
                        placeholder.val();

                    if (value) {
                        field.placeholder =
                            value;
                    } else {
                        delete field.placeholder;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );

            const defaultInput =
                this.textInput(
                    field.default === undefined
                        ? ''
                        : field.default
                );

            defaultInput.on(
                'input.preloadEditor',
                () => {
                    const value =
                        defaultInput.val();

                    if (value) {
                        field.default =
                            value;
                    } else {
                        delete field.default;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Default',
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
            );

            if (
                field.type === 'textarea'
            ) {
                const maxRows =
                    this.textInput(
                        field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                    );

                maxRows.on(
                    'input.preloadEditor',
                    () => {
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );

                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }

                        this.markDirty();
                        this.renderConfigReviewAvailability();
                    }
                );

                card.append(
                    this.fieldRow(
                        'Maximum rows',
                        maxRows
                    )
                );
            }

            if (
                field.type === 'select' ||
                field.type === 'multiselect'
            ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }

            if (
                field.type === 'file'
            ) {
                this.renderFileConfiguration(
                    card,
                    field
                );
            }

            const deleteButton =
                this.createButton(
                    'Delete variable',
                    'preload-editor-button-danger preload-editor-delete-variable',
                    async () => {
                        const confirmed =
                            await this.createConfirmDialog(
                                'Delete variable',
                                'Delete "' +
                                name +
                                '" from the configuration?\n\nThe variable will remain in the preload, but its config.json field will be removed.',
                                'Delete variable',
                                'Cancel'
                            );

                        if (!confirmed) {
                            return;
                        }

                        this.deleteVariable(name);
                    }
                );

            card.append(
                $('<div>')
                    .addClass(
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
            );

            return card;
        },

        async deleteVariable(name) {
            name =
                String(name || '')
                    .trim()
                    .toUpperCase();

            if (
                !name ||
                name === 'PAGE'
            ) {
                return;
            }

            if (
                !this.state.config ||
                !this.state.config.fields
            ) {
                return;
            }

            delete this.state.config.fields[name];

            if (
                !Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                this.state.deletedVariables = [];
            }

            if (
                !this.state.deletedVariables.includes(
                    name
                )
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }

            this.state.selectedVariable =
                name;

            this.markDirty();

            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();

            this.setStatus(
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },

        // =========================================================
        // Select configuration
        // =========================================================

        renderSelectConfiguration(
            card,
            field
        ) {
            const source =
                this.textInput(
                    field.source || '',
                    'category:Example'
                );

            source.on(
                'input.preloadEditor',
                () => {
                    const value =
                        source.val();

                    if (value) {
                        field.source = value;
                    } else {
                        delete field.source;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Source',
                    source,
                    'Currently supported source format: category:Category Name'
                )
            );

            const sourcePrefix =
                this.textInput(
                    field['source-prefix'] || ''
                );

            sourcePrefix.on(
                'input.preloadEditor',
                () => {
                    const value =
                        sourcePrefix.val();

                    if (value) {
                        field['source-prefix'] =
                            value;
                    } else {
                        delete field['source-prefix'];
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
            );

            const excludeCategory =
                this.textInput(
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );

            excludeCategory.on(
                'input.preloadEditor',
                () => {
                    const value =
                        excludeCategory.val();

                    if (value) {
                        field.exclude =
                            Object.assign(
                                {},
                                field.exclude || {},
                                {
                                    category: value
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;

                        if (
                            !Object.keys(
                                field.exclude
                            ).length
                        ) {
                            delete field.exclude;
                        }
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Exclude category',
                    excludeCategory
                )
            );

            card.append(
                this.createTransformControls(
                    field,
                    'value',
                    'Value transformation'
                ),

                this.createTransformControls(
                    field,
                    'label',
                    'Label transformation'
                )
            );

            const optionsValue =
                Array.isArray(field.options)
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }

                                return (
                                    String(
                                        option.value || ''
                                    ) +
                                    ' | ' +
                                    String(
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';

            const options =
                this.textarea(
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );

            options.on(
                'input.preloadEditor',
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);

                    if (!lines.length) {
                        delete field.options;
                    } else {
                        field.options =
                            lines.map(
                                line => {
                                    const parts =
                                        line.split(
                                            /\s*\|\s*/
                                        );

                                    if (
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }

                                    return {
                                        value:
                                            parts[0],

                                        label:
                                            parts
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Manual options',
                    options,
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                )
            );
        },
        
                renderFileConfiguration(
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                    ? field.accept.join('\n')
                    : '';

            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                    'preload-editor-small-textarea'
                );

            accept.on(
                'input.preloadEditor',
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);

                    if (values.length) {
                        field.accept = values;
                    } else {
                        delete field.accept;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Accepted MIME types',
                    accept,
                    'One MIME type per line. Example: image/png'
                )
            );

            const filename =
                this.textInput(
                    field.filename ||
                    '%%PAGE%%.%%EXT%%'
                );

            filename.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filename.val();

                    if (value) {
                        field.filename = value;
                    } else {
                        delete field.filename;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'Filename',
                    filename,
                    'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                )
            );

            const filetext =
                this.textarea(
                    field.filetext || ''
                );

            filetext.on(
                'input.preloadEditor',
                () => {
                    const value =
                        filetext.val();

                    if (value) {
                        field.filetext = value;
                    } else {
                        delete field.filetext;
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                }
            );

            card.append(
                this.fieldRow(
                    'File page text',
                    filetext,
                    'Wikitext used for the uploaded File: page.'
                )
            );
        },

        createTransformControls(
            field,
            property,
            title
        ) {
            const wrapper =
                $('<div>')
                    .addClass(
                        'preload-editor-transform'
                    );

            $('<h4>')
                .text(title)
                .appendTo(wrapper);

            const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};

            const transform =
                this.select(
                    [
                        {
                            value: '',
                            label:
                                'No transformation'
                        },
                        {
                            value:
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                            value:
                                'remove-suffix',
                            label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                        }
                    ],
                    existing.transform || ''
                );

            const prefix =
                this.textInput(
                    existing.prefix || ''
                );

            const suffix =
                this.textInput(
                    existing.suffix || ''
                );

            const from =
                this.textInput(
                    existing.from || ''
                );

            const to =
                this.textInput(
                    existing.to || ''
                );

            const controls =
                $('<div>')
                    .addClass(
                        'preload-editor-transform-controls'
                    );

            const prefixRow =
                this.fieldRow(
                    'Prefix',
                    prefix
                );

            const suffixRow =
                this.fieldRow(
                    'Suffix',
                    suffix
                );

            const fromRow =
                this.fieldRow(
                    'From',
                    from
                );

            const toRow =
                this.fieldRow(
                    'To',
                    to
                );

            const renderInputs =
                () => {
                    const type =
                        transform.val();

                    prefixRow.toggle(
                        type === 'remove-prefix'
                    );

                    suffixRow.toggle(
                        type === 'remove-suffix'
                    );

                    fromRow.toggle(
                        type === 'replace'
                    );

                    toRow.toggle(
                        type === 'replace'
                    );
                };

            const update =
                () => {
                    const type =
                        transform.val();

                    let object = null;

                    if (
                        type === 'remove-prefix' &&
                        prefix.val()
                    ) {
                        object = {
                            transform: type,
                            prefix:
                                prefix.val()
                        };
                    } else if (
                        type === 'remove-suffix' &&
                        suffix.val()
                    ) {
                        object = {
                            transform: type,
                            suffix:
                                suffix.val()
                        };
                    } else if (
                        type === 'replace' &&
                        from.val()
                    ) {
                        object = {
                            transform: type,
                            from:
                                from.val(),
                            to:
                                to.val()
                        };
                    }

                    if (object) {
                        field[property] = object;
                    } else {
                        delete field[property];
                    }

                    this.markDirty();
                    this.renderConfigReviewAvailability();
                };

            transform.on(
                'change.preloadEditor',
                () => {
                    update();
                    renderInputs();
                }
            );

            [
                prefix,
                suffix,
                from,
                to
            ].forEach(
                input => {
                    input.on(
                        'input.preloadEditor',
                        update
                    );
                }
            );

            controls.append(
                this.fieldRow(
                    'Transformation',
                    transform
                ),

                prefixRow,
                suffixRow,
                fromRow,
                toRow
            );

            renderInputs();

            wrapper.append(controls);

            return wrapper;
        },

        // =========================================================
        // Config output
        // =========================================================

        getCleanConfig() {
            const config =
                JSON.parse(
                    JSON.stringify(
                        this.state.config
                    )
                );

            const fields =
                config.fields || {};

            const orderedFields = {};

            orderedFields.PAGE =
                this.getAutomaticPageField();

            Object.keys(fields)
                .filter(
                    name =>
                        name.toUpperCase() !== 'PAGE'
                )
                .forEach(
                    name => {
                        orderedFields[name] =
                            fields[name];
                    }
                );

            config.fields =
                orderedFields;

            return config;
        },

        getConfigJSON() {
            return JSON.stringify(
                this.getCleanConfig(),
                null,
                4
            );
        },

        renderConfigPreview(container) {
            if (container) {
                container.text(
                    this.getConfigJSON()
                );
            }
        },

        renderConfigPreviewBySelector() {
            this.renderAnalysisBySelector();
        },

        renderConfigReviewAvailability() {
            this.renderAnalysisBySelector();
        },

        // =========================================================
        // Dirty state
        // =========================================================

        updateDirtyState() {
            this.state.dirty =
                !!(
                    this.state.dirtyPreload ||
                    this.state.dirtyConfig
                );
        },

        markPreloadDirty() {
            this.state.dirtyPreload = true;
            this.updateDirtyState();
            this.saveDraft();
        },

        markConfigDirty() {
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },

        markDirty() {
            this.state.dirtyPreload = true;
            this.state.dirtyConfig = true;
            this.updateDirtyState();
            this.saveDraft();
        },

        // =========================================================
        // Save
        // =========================================================

        async savePreloadOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();

            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );

                if (!result) {
                    return;
                }

                title = result;
                this.state.preloadTitle =
                    title;
            }

            this.state.preloadContent =
                this.getEditorContent();

            const validation =
                this.validateBeforeSave();

            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );

                this.saveDraft();
                return;
            }

            const confirmed =
                await this.confirmSave(
                    'preload',
                    title
                );

            if (!confirmed) {
                return;
            }

            this.setStatus(
                'Saving preload...',
                'loading'
            );

            try {
                const exists =
                    await this.pageExists(title);

                await this.savePage(
                    title,
                    this.state.preloadContent,
                    exists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !exists
                );

                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyPreload = false;

                this.updateDirtyState();

                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }

                this.setStatus(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved successfully.',
                    'success'
                );

                mw.notify(
                    this.state.dirtyConfig
                        ? 'Preload saved. Config still has unsaved changes.'
                        : 'Preload saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );

                this.saveDraft();

                this.setStatus(
                    error.message ||
                        'Could not save preload.',
                    'error'
                );

                mw.notify(
                    error.message ||
                        'Could not save preload.',
                    {
                        type: 'error'
                    }
                );
            }
        },

        async saveConfigOnly() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();

            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );

                if (!result) {
                    return;
                }

                title = result;
                this.state.preloadTitle =
                    title;
            }

            this.state.preloadContent =
                this.getEditorContent();

            this.reanalyze();

            const validation =
                this.validateBeforeSave();

            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );

                this.saveDraft();
                return;
            }

            const confirmed =
                await this.confirmSave(
                    'config',
                    title
                );

            if (!confirmed) {
                return;
            }

            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';

            this.setStatus(
                'Saving config...',
                'loading'
            );

            try {
                /*
                 * This now automatically creates or converts
                 * config.json to the JSON content model.
                 */
                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    (
                        await this.pageExists(
                            configTitle
                        )
                    )
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );

                this.state.mode = 'edit';
                this.state.preloadTitle = title;
                this.state.dirtyConfig = false;

                this.updateDirtyState();

                if (!this.state.dirty) {
                    this.clearDraft(title);
                } else {
                    this.saveDraft();
                }

                this.setStatus(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON successfully.',
                    'success'
                );

                mw.notify(
                    this.state.dirtyPreload
                        ? 'Config saved as JSON. Preload still has unsaved changes.'
                        : 'Config saved as JSON.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor config save:',
                    error
                );

                this.saveDraft();

                this.setStatus(
                    error.message ||
                        'Could not save config.',
                    'error'
                );

                mw.notify(
                    error.message ||
                        'Could not save config.',
                    {
                        type: 'error'
                    }
                );
            }
        },

        async saveAll() {
            let title =
                String(
                    this.state.preloadTitle || ''
                ).trim();

            if (!title) {
                const result =
                    await this.createPromptDialog(
                        'Preload title',
                        'Enter the full title for the preload.'
                    );

                if (!result) {
                    return;
                }

                title = result;
                this.state.preloadTitle =
                    title;
            }

            this.state.preloadContent =
                this.getEditorContent();

            this.reanalyze();

            const validation =
                this.validateBeforeSave();

            if (validation.errors.length) {
                this.showValidationErrors(
                    validation
                );

                this.saveDraft();
                return;
            }

            const confirmed =
                await this.confirmSave(
                    'both',
                    title
                );

            if (!confirmed) {
                return;
            }

            const configTitle =
                title.replace(
                    /\/+$/,
                    ''
                ) +
                '/config.json';

            this.setStatus(
                'Saving preload and config...',
                'loading'
            );

            try {
                const preloadExists =
                    await this.pageExists(title);

                await this.savePage(
                    title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );

                /*
                 * Config is saved through the JSON-aware
                 * helper. This means:
                 *
                 * - new config -> created as JSON
                 * - old wikitext config -> converted to JSON
                 * - existing JSON config -> simply updated
                 */
                const configExists =
                    await this.pageExists(
                        configTitle
                    );

                await this.saveConfigPage(
                    configTitle,
                    this.getConfigJSON(),
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor'
                );

                this.state.mode = 'edit';
                this.state.dirtyPreload = false;
                this.state.dirtyConfig = false;
                this.state.dirty = false;
                this.state.preloadTitle = title;

                this.clearDraft(title);

                this.setStatus(
                    'Preload and JSON config saved successfully.',
                    'success'
                );

                mw.notify(
                    'Preload and config saved. config.json is using the JSON content model.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );

                this.saveDraft();

                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );

                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },

        // =========================================================
        // Validation
        // =========================================================

        validateBeforeSave() {
            const errors = [];
            const warnings = [];

            const title =
                String(
                    this.state.preloadTitle || ''
                ).trim();

            if (!title) {
                errors.push(
                    'A preload title is required.'
                );
            }

            if (
                title &&
                !/\/Preload$/i.test(title)
            ) {
                warnings.push(
                    'The title does not end with "/Preload".'
                );
            }

            const content =
                this.getEditorContent();

            this.state.preloadContent =
                content;

            if (!content.trim()) {
                errors.push(
                    'The preload cannot be empty.'
                );
            }

            if (
                !/<includeonly>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain an <includeonly> section.'
                );
            }

            if (
                !/<noinclude>/i.test(content)
            ) {
                warnings.push(
                    'The preload does not contain a <noinclude> section.'
                );
            }

            const analysis =
                this.analyzePreload(
                    this.extractIncludeonly(
                        content
                    )
                );

            this.state.config =
                this.prepareConfigForVariables(
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );

            const configValidation =
                this.validateConfig(
                    this.state.config,
                    analysis
                );

            errors.push(
                ...configValidation.errors
            );

            warnings.push(
                ...configValidation.warnings
            );

            let depth = 0;
                        analysis.conditions.forEach(
                condition => {
                    if (
                        condition.type === 'if'
                    ) {
                        depth++;
                    } else if (
                        condition.type === 'endif'
                    ) {
                        depth--;

                        if (depth < 0) {
                            errors.push(
                                'Found @endif without a matching @if.'
                            );

                            depth = 0;
                        }
                    } else if (
                        condition.type === 'elseif' ||
                        condition.type === 'else'
                    ) {
                        if (depth === 0) {
                            errors.push(
                                '@' +
                                condition.type +
                                ' exists outside an @if block.'
                            );
                        }
                    }
                }
            );

            if (depth > 0) {
                errors.push(
                    'One or more @if blocks are missing @endif.'
                );
            }

            return {
                errors,
                warnings,
                valid:
                    errors.length === 0
            };
        },

        showValidationErrors(validation) {
            this.renderAnalysisBySelector();

            this.saveDraft();

            this.setStatus(
                validation.errors.join(' '),
                'error'
            );

            mw.notify(
                validation.errors.join('\n'),
                {
                    type: 'error'
                }
            );
        }
    };

    mw.PreloadEditor =
        PreloadEditor;

    $(function () {
        if (
            mw.config.get('wgPageName') !==
            'Petit_Planet_Wiki:Preload_Editor'
        ) {
            return;
        }

        PreloadEditor.init();
    });

}(mediaWiki, jQuery));