Jump to content
Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
If you make an edit, a temporary account will be created for you.

MediaWiki:Gadget-PreloadEditor.js: Difference between revisions

MediaWiki interface page
ReisuDesign (talk | contribs)
No edit summary
ReisuDesign (talk | contribs)
No edit summary
 
(11 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 15: Line 15:
             deletedVariables: [],
             deletedVariables: [],
             mode: 'idle',
             mode: 'idle',
            dirty: false,
            dirtyPreload: false,
            dirtyConfig: false,


             /*
             // Local draft state
            * Keep preload and config dirty independently.
             localDraftSavedAt: null,
            * This is important because "Save Config" must not
             localDraftAvailable: false
            * accidentally mark an unsaved preload as saved.
            */
             preloadDirty: false,
             configDirty: false,
 
            dirty: false
         },
         },


Line 33: Line 30:
         workspace: null,
         workspace: null,
         status: null,
         status: null,
        localDraftStatus: null,
         editorTools: null,
         editorTools: null,
        pageResizeHandler: 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 62: 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 76: 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 86: 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 100: 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 117: 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 141: 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;
            }


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


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


                 dirty: true,
                 return;
            }


                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;
                this.updateLocalDraftIndicator();
            } else {
                this.state.localDraftAvailable = false;
                 this.updateLocalDraftStatus('Could not save local draft', 'error');
            }


             storage.active = id;
             return saved;
 
            this.setDraftStorage(
                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 &&
                 return {
                storage.drafts[
                    storage.active
                ]
            ) {
                 return {
                     id: storage.active,
                     id: storage.active,
                     draft:
                     draft: storage.drafts[storage.active]
                        storage.drafts[
                            storage.active
                        ]
                 };
                 };
             }
             }
Line 305: 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 346: 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 399: Line 314:
             }
             }


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


             if (
             if (
Line 408: 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 423: Line 332:
                 }
                 }
             }
             }
            const hasDirtyFlags =
                typeof draft.dirtyPreload === 'boolean' ||
                typeof draft.dirtyConfig === 'boolean';


             this.state = {
             this.state = {
                 preloadTitle:
                 preloadTitle: title,
                     title,
                preloadSource: String(draft.preloadSource || ''),
                preloadContent: String(draft.preloadContent || ''),
                config,
 
                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',
 
                preloadDirty:
                    draft.preloadDirty !== undefined
                        ? !!draft.preloadDirty
                        : true,
 
                configDirty:
                    draft.configDirty !== undefined
                        ? !!draft.configDirty
                        : true,
 
                 dirty: true
             };
             };


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


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


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


             return true;
             return true;
         },
         },


         // ------------------------------------------------------------
         // =========================================================
         // Page / viewport mode
         // API
         // ------------------------------------------------------------
         // =========================================================


         applyPageMode() {
         async getPage(title) {
             $('body')
             const response = await new mw.Api().get({
                .addClass(
                action: 'query',
                    'preload-editor-page'
                 prop: 'info|revisions',
                 );
                 titles: title,
 
                 rvprop: 'content',
            /*
                 rvslots: 'main',
            * Hide the normal MediaWiki page heading.
                 formatversion: 2
            * The editor supplies its own internal headings.
            */
            $(
                 '#firstHeading, ' +
                 '.firstHeading'
            ).hide();
 
            /*
            * Remove the normal heading spacing.
            */
            $(
                 '#mw-content-text'
            ).css({
                 marginTop: 0
             });
             });


            /*
             const page =
            * Make the editor occupy the remaining viewport
                 response &&
            * and keep the outer page from scrolling.
                 response.query &&
            */
                 response.query.pages &&
            this.updatePageHeight();
                 response.query.pages[0];
 
            if (!this.pageResizeHandler) {
                this.pageResizeHandler =
                    () =>
                        this.updatePageHeight();
 
                window.addEventListener(
                    'resize',
                    this.pageResizeHandler
                );
            }
        },
 
        updatePageHeight() {
            if (!this.root || !this.root.length) {
                return;
            }
 
            const element =
                this.root.get(0);
 
            if (!element) {
                return;
            }
 
            const rect =
                element.getBoundingClientRect();
 
            const height =
                Math.max(
                    300,
                    window.innerHeight -
                    rect.top
                );
 
            this.root.css({
                height:
                    height + 'px',
 
                maxHeight:
                    height + 'px'
            });
        },
 
        // ------------------------------------------------------------
        // API
        // ------------------------------------------------------------
 
        async getPage(title) {
            const response =
                await new mw.Api().get({
                    action: 'query',
                    prop: '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) {
             if (!page || page.missing) {
Line 623: 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 639: 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 656: 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 676: Line 473:
             }
             }


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


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


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


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


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


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


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


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


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


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


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


             return conditions;
             const result = {};
        },


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


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


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


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


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


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


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


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


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


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


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


        emptyConfig() {
                    const close = this.createButton(
            return {
                        'Close',
                settings: {
                        'preload-editor-button-primary',
                    incomplete: 'add-stub'
                        () => {
                },
                            overlay.remove();
                            resolve(null);
                        }
                    );


                fields: {
                    emptyButtons.append(close);
                     PAGE:
                     box.append(emptyButtons);
                        this.getAutomaticPageField()
                    overlay.append(box);
                }
            };
        },


        normalizeConfig(config) {
                    $(document.body).append(overlay);
            if (
                !config ||
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                config =
                    this.emptyConfig();
            }


            if (
                    overlay.attr('tabindex', '-1');
                !config.settings ||
                    overlay.trigger('focus');
                typeof config.settings !== 'object' ||
                Array.isArray(config.settings)
            ) {
                config.settings = {};
            }


            if (
                    return;
                !config.fields ||
                 }
                typeof config.fields !== 'object' ||
                 Array.isArray(config.fields)
            ) {
                config.fields = {};
            }


            config.fields.PAGE =
                const search = this.textInput('', 'Search variables...')
                this.getAutomaticPageField();
                    .addClass('preload-editor-import-search');


            return config;
                const searchWrap = $('<div>')
        },
                    .addClass('preload-editor-import-search-wrap')
                    .append(search);


        createDefaultField(
                 box.append(searchWrap);
            name,
            analysis
        ) {
            return {
                 label:
                    this.humanizeName(name),


                 description: '',
                 const controls = $('<div>')
                    .addClass('preload-editor-import-controls');


                 type:
                 const selectAll = this.createButton(
                     analysis.conditionVariables.includes(
                     'Select all',
                        name
                    '',
                     )
                     () => {
                         ? 'boolean'
                         list
                        : 'text'
                            .find('input[type="checkbox"]:visible')
            };
                            .prop('checked', true);
        },


        humanizeName(name) {
                        updateSummary();
            return String(name || '')
                    }
                 .replace(
                );
                     /[_-]+/g,
 
                     ' '
                 const deselectAll = this.createButton(
                )
                     'Deselect all',
                .replace(
                     '',
                    /([a-z])([A-Z])/g,
                    () => {
                    '$1 $2'
                        list
                )
                            .find('input[type="checkbox"]:visible')
                .replace(
                            .prop('checked', false);
                    /\s+/g,
 
                    ' '
                        updateSummary();
                )
                     }
                .trim()
                .replace(
                    /\b\w/g,
                     char =>
                        char.toUpperCase()
                 );
                 );
        },


        prepareConfigForVariables(
                controls.append(selectAll, deselectAll);
            config,
                 box.append(controls);
            analysis
        ) {
            config =
                 this.normalizeConfig(config);


            const existing =
                const list = $('<div>')
                config.fields || {};
                    .addClass('preload-editor-import-list');


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


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


            fields.PAGE =
                    const type = field && field.type
                this.getAutomaticPageField();
                        ? String(field.type)
                        : 'text';


            analysis.variables.forEach(
                    const label = field && field.label
                name => {
                        ? String(field.label)
                    if (
                         : this.humanizeName(name);
                         name === 'PAGE' ||
                        deleted.has(name)
                    ) {
                        return;
                    }


                     fields[name] =
                     const row = $('<label>')
                         existing[name] ||
                         .addClass('preload-editor-import-row')
                         this.createDefaultField(
                        .attr('data-variable', name)
                             name,
                         .attr(
                             analysis
                             'data-search',
                             (name + ' ' + label + ' ' + type).toLowerCase()
                         );
                         );
                }
            );


            Object.keys(existing).forEach(
                    const checkbox = this.checkbox(false)
                name => {
                        .attr('data-import-variable', name)
                     const upper =
                        .addClass('preload-editor-import-checkbox');
                         name.toUpperCase();
 
                    const content = $('<span>')
                        .addClass('preload-editor-import-content');
 
                     const header = $('<span>')
                         .addClass('preload-editor-import-header');


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


            config.fields = fields;
                    summary.text(text);
 
                    importButton.prop('disabled', selected === 0);
                };


            return config;
                const filterRows = () => {
        },
                    const query = String(search.val() || '')
                        .trim()
                        .toLowerCase();


        validateConfig(
                    list.find('.preload-editor-import-row').each(function () {
            config,
                        const row = $(this);
            analysis
                        const haystack = String(
        ) {
                            row.attr('data-search') || ''
            const errors = [];
                        );
            const warnings = [];


            if (
                        row.toggle(!query || haystack.includes(query));
                !config ||
                     });
                typeof config !== 'object' ||
                Array.isArray(config)
            ) {
                return {
                     valid: false,
                    errors: [
                        'Config must be an object.'
                    ],
                    warnings: []
                 };
                 };
            }


            if (
                 search.on(
                !config.fields ||
                     'input.preloadEditor',
                typeof config.fields !== 'object' ||
                     filterRows
                 Array.isArray(config.fields)
                 );
            ) {
                return {
                    valid: false,
                     errors: [
                        '"fields" must be an object.'
                    ],
                     warnings
                 };
            }


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


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


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


            Object.entries(
                const importButton = this.createButton(
                config.fields
                    'Import selected',
            ).forEach(
                    'preload-editor-button-primary',
                ([name, field]) => {
                    () => {
                    if (
                        const selected = [];
                         !field ||
 
                        typeof field !== 'object' ||
                         list
                        Array.isArray(field)
                            .find('input[type="checkbox"]:checked')
                    ) {
                            .each(function () {
                        errors.push(
                                selected.push(
                            'Field "' +
                                    String(
                            name +
                                        $(this).attr(
                             '" must be an object.'
                                            'data-import-variable'
                        );
                                        )
                                    )
                                );
                             });


                         return;
                         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');


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


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


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


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


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


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


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


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


        // ------------------------------------------------------------
                let sourceConfig;
        // UI helpers
        // ------------------------------------------------------------


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


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


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


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


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


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


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


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


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


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


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


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


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


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


                     placeholder:
                     if (!field) {
                         placeholder || ''
                         return;
                })
                    }
                .addClass(
 
                     'preload-editor-input'
                    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();


        textarea(value) {
                /*
            return $('<textarea>')
                * Keep the current selection when possible.
                 .val(
                * Otherwise select the first imported definition.
                     value == null
                */
                         ? ''
                 const selectedStillExists = !!(
                        : value
                     this.state.config.fields[
                )
                         this.state.selectedVariable
                .addClass(
                     ]
                     'preload-editor-textarea'
                 );
                 );
        },


        checkbox(checked) {
                 if (
            return $('<input>')
                     !selectedStillExists ||
                 .attr(
                     this.state.selectedVariable === 'PAGE'
                     'type',
                 ) {
                     'checkbox'
                    this.state.selectedVariable =
                 )
                        selected[0] ||
                .prop(
                        'PAGE';
                    'checked',
                 }
                    !!checked
                )
                .addClass(
                    'preload-editor-checkbox'
                 );
        },


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


            options.forEach(
                 this.renderVariablesBySelector();
                 option => {
                this.renderVariableConfigurationBySelector();
                    $('<option>')
                this.renderAnalysisBySelector();
                        .attr(
                 this.updateEditorTools();
                            'value',
                            option.value
                        )
                        .text(
                            option.label
                        )
                        .prop(
                            'selected',
                            String(
                                option.value
                            ) ===
                            String(
                                value === undefined
                                    ? ''
                                    : value
                            )
                        )
                        .appendTo(select);
                 }
            );


            return select;
                this.saveDraft();
        },


        // ------------------------------------------------------------
                let status =
        // In-wiki dialogs
                    'Imported ' +
        // ------------------------------------------------------------
                    selected.length +
                    ' variable ' +
                    (selected.length === 1
                        ? 'definition'
                        : 'definitions') +
                    '.';


        createConfirmDialog(
                if (replaced.length) {
            title,
                     status +=
            message,
                         ' Replaced: ' +
            confirmLabel,
                        replaced.join(', ') +
            cancelLabel
                        '.';
        ) {
                }
            return new Promise(
                resolve => {
                     const overlay =
                         $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                    const box =
                this.setStatus(status, 'success');
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt'
                            );


                     $('<h2>')
                mw.notify(status, {
                        .text(title)
                     type: 'success'
                        .appendTo(box);
                });
            } catch (error) {
                console.error(
                    'Preload Editor variable import:',
                    error
                );


                     const messageLines =
                this.setStatus(
                        String(message || '')
                     error.message ||
                            .split('\n');
                        'Could not import variable definitions.',
                    'error'
                );


                     messageLines.forEach(
                mw.notify(
                         line => {
                     error.message ||
                            $('<p>')
                         'Could not import variable definitions.',
                                .text(line)
                    {
                                .appendTo(box);
                        type: 'error'
                        }
                    }
                    );
                );
            }
        },
 
        // =========================================================
        // Preload parsing
        // =========================================================


                    const buttons =
        extractIncludeonly(source) {
                        $('<div>')
            const match = String(source || '').match(
                            .addClass(
                /<includeonly>([\s\S]*?)<\/includeonly>/i
                                'preload-editor-prompt-buttons'
            );
                            );


                    const cancel =
            return match
                        this.createButton(
                ? match[1].trim()
                            cancelLabel || 'Cancel',
                : String(source || '').trim();
                            '',
        },
                            () => {
                                overlay.remove();
                                resolve(false);
                            }
                        );


                    const confirm =
        findVariables(content) {
                        this.createButton(
            const variables = [];
                            confirmLabel || 'Confirm',
            const pattern = /%%([A-Za-z0-9_-]+)%%/g;
                            'preload-editor-button-primary',
                            () => {
                                overlay.remove();
                                resolve(true);
                            }
                        );


                    buttons.append(
            let match;
                        cancel,
                        confirm
                    );


                    box.append(buttons);
            while ((match = pattern.exec(content)) !== null) {
                    overlay.append(box);
                const name = match[1].toUpperCase();


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


                    overlay.attr(
            return variables;
                        'tabindex',
        },
                        '-1'
                    );


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


                    overlay.on(
            let match;
                        'keydown.preloadEditor',
                        event => {
                            if (
                                event.key === 'Escape'
                            ) {
                                cancel.trigger('click');
                            }


                            if (
            while ((match = pattern.exec(content)) !== null) {
                                event.key === 'Enter'
                conditions.push({
                            ) {
                    type: match[1].toLowerCase(),
                                confirm.trigger('click');
                    expression: match[2].trim(),
                            }
                    index: match.index
                        }
                });
                    );
            }


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


         createPromptDialog(
         findConditionVariables(content) {
            title,
             const variables = [];
            message
        ) {
             return new Promise(
                resolve => {
                    const overlay =
                        $('<div>')
                            .addClass(
                                'preload-editor-prompt-overlay'
                            );


                    const box =
            this.findConditions(content).forEach(condition => {
                        $('<div>')
                if (
                            .addClass(
                    condition.type !== 'if' &&
                                'preload-editor-prompt'
                    condition.type !== 'elseif'
                            );
                ) {
                    return;
                }


                     $('<h2>')
                const matches =
                         .text(title)
                     condition.expression.match(
                        .appendTo(box);
                         /[A-Za-z0-9_-]+/g
                    ) || [];


                    $('<p>')
                matches.forEach(name => {
                        .text(message)
                    name = name.toUpperCase();
                        .appendTo(box);


                     const input =
                     if (!variables.includes(name)) {
                         this.textInput();
                         variables.push(name);
                    }
                });
            });


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


                    const cancel =
        analyzePreload(content) {
                        this.createButton(
            return {
                            'Cancel',
                variables: this.findVariables(content),
                            '',
                conditions: this.findConditions(content),
                            () => {
                conditionVariables:
                                overlay.remove();
                     this.findConditionVariables(content)
                                resolve(null);
            };
                            }
        },
                        );
 
                     const confirm =
                        this.createButton(
                            'Load',
                            'preload-editor-button-primary',
                            () => {
                                const value =
                                    String(
                                        input.val() || ''
                                    ).trim();


                                if (!value) {
        // =========================================================
                                    return;
        // Config
                                }
        // =========================================================


                                overlay.remove();
        getAutomaticPageField() {
                                resolve(value);
            return {
                            }
                label: 'Page Name',
                        );
                description: 'Name of the page.',
                type: 'page',
                required: true,
                namespace: 'Main',
                'allow-new': true
            };
        },


                    buttons.append(
        emptyConfig() {
                        cancel,
            return {
                        confirm
                settings: {
                     );
                     incomplete: 'add-stub'
                },


                    box.append(
                fields: {
                        input,
                     PAGE: this.getAutomaticPageField()
                        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() {
         normalizeConfig(config) {
             return new Promise(
             if (
                 resolve => {
                 !config ||
                    const overlay =
                typeof config !== 'object' ||
                        $('<div>')
                Array.isArray(config)
                            .addClass(
            ) {
                                'preload-editor-prompt-overlay preload-editor-config-review-overlay'
                config = this.emptyConfig();
                            );
            }


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


                    $('<h2>')
            if (
                        .text(
                !config.fields ||
                            'Generated configuration'
                typeof config.fields !== 'object' ||
                        )
                Array.isArray(config.fields)
                        .appendTo(box);
            ) {
                config.fields = {};
            }


                    $('<p>')
            config.fields.PAGE =
                        .text(
                this.getAutomaticPageField();
                            'This is the JSON that will be uploaded to the preload\'s config.json page.'
                        )
                        .appendTo(box);


                    const preview =
            return config;
                        $('<pre>')
        },
                            .addClass(
                                'preload-editor-config-review-preview'
                            )
                            .text(
                                this.getConfigJSON()
                            );


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


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


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


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


                    $(document.body)
            const fields = {};
                        .append(overlay);


                    overlay.attr(
            fields.PAGE =
                        'tabindex',
                this.getAutomaticPageField();
                        '-1'
                    );


                    overlay.trigger('focus');
            analysis.variables.forEach(name => {
                if (
                    name === 'PAGE' ||
                    deleted.has(name)
                ) {
                    return;
                }


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


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


         // ------------------------------------------------------------
         validateConfig(config, analysis) {
        // CodeMirror
            const errors = [];
        // ------------------------------------------------------------
            const warnings = [];


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


             if (
             if (
                 view &&
                 !config.fields ||
                 inputHandler
                 typeof config.fields !== 'object' ||
                Array.isArray(config.fields)
             ) {
             ) {
                 view.dom.removeEventListener(
                 return {
                     'input',
                    valid: false,
                     inputHandler
                     errors: [
                 );
                        '"fields" must be an object.'
                    ],
                     warnings
                 };
             }
             }


             if (view) {
             const configured =
                view.destroy();
                Object.keys(
            }
                    config.fields
                ).map(
                    name =>
                        name.toUpperCase()
                );


             this.editor = null;
             analysis.variables.forEach(name => {
            this.editorView = null;
                if (!configured.includes(name)) {
            this.editorTools = null;
                    errors.push(
        },
                        'Variable "' +
                        name +
                        '" is not configured.'
                    );
                }
            });


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


        getEditorContent() {
            if (!configured.includes('PAGE')) {
            if (
                 errors.push(
                 this.editorView &&
                    'PAGE must always be configured.'
                this.editorView.state
                 );
            ) {
                 return this.editorView.state.doc.toString();
             }
             }


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


        setEditorContent(content) {
                    return;
            content =
                 }
                 String(content || '');


            if (!this.editorView) {
                if (!field.type) {
                 this.state.preloadContent =
                    warnings.push(
                     content;
                        'Field "' +
                return;
                        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 current =
                    if (
                this.editorView.state.doc.toString();
                        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 (current === content) {
                    if (
                return;
                        !field.accept ||
            }
                        !field.accept.length
                    ) {
                        warnings.push(
                            'File field "' +
                            name +
                            '" has no accepted MIME types.'
                        );
                    }


            this.editorView.dispatch({
                    if (
                changes: {
                        !field.filename
                    from: 0,
                    ) {
                    to:
                        warnings.push(
                         this.editorView.state.doc.length,
                            'File field "' +
                     insert: content
                            name +
                            '" has no filename template.'
                         );
                     }
                 }
                 }
            });
        },


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


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


            return {
                    if (
                from:
                        field.filetext !== undefined &&
                     selection.from,
                        typeof field.filetext !== 'string'
                    ) {
                        errors.push(
                            'File field "' +
                            name +
                            '" has an invalid "filetext" value.'
                        );
                     }


                to:
                    if (
                     selection.to,
                        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.'
                        );
                    }
                }
            });


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


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


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


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


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


            const to =
        // =========================================================
                selectionTo === undefined
        // UI helpers
                    ? selection.to
        // =========================================================
                    : selectionTo;


             const cursor =
        createSection(title, className) {
                 cursorPosition === undefined
             const section = $('<section>')
                    ? from + text.length
                 .addClass('preload-editor-section');
                    : cursorPosition;


             view.dispatch({
             if (className) {
                 changes: {
                 section.addClass(className);
                    from,
            }
                    to,
                    insert: text
                },


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


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


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


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


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


             const replacement =
             return button;
                '%%' +
        },
                selected.text +
                '%%';


            this.insertEditorText(
        fieldRow(label, input, description) {
                replacement,
            const row = $('<div>')
                selected.from,
                 .addClass('preload-editor-field');
                selected.to,
                 selected.from +
                    replacement.length
            );
        },


        insertVariable(name) {
            $('<label>')
            name =
                 .addClass('preload-editor-label')
                 String(name || '')
                .text(label)
                    .trim()
                .appendTo(row);
                    .toUpperCase();


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


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


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


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


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


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


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


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


             let text;
             return select;
            let cursorOffset;
        },


            switch (type) {
        // =========================================================
                case 'if': {
        // In-wiki dialogs
                    if (!variable) {
        // =========================================================
                        return;
                    }


                    const opening =
        createConfirmDialog(
                        '<!-- @if ' +
            title,
                        variable +
            message,
                        ' -->';
            confirmLabel,
            cancelLabel
        ) {
            return new Promise(resolve => {
                const overlay = $('<div>')
                    .addClass('preload-editor-prompt-overlay');
 
                const box = $('<div>')
                    .addClass('preload-editor-prompt');


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


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


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


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


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


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


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


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


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


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


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


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


            return Array.from(variables);
                overlay.attr('tabindex', '-1');
        },
                overlay.trigger('focus');


        createToolSelect(
                overlay.on(
             options,
                    'click.preloadEditor',
            className
                    event => {
         ) {
                        if (event.target === overlay.get(0)) {
             const select =
                            cancel.trigger('click');
                 $('<select>')
                        }
                    }
                );
             });
        },
 
         createPromptDialog(title, message) {
             return new Promise(resolve => {
                 const overlay = $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-tool-select'
                         'preload-editor-prompt-overlay'
                     );
                     );


            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;
                $('<p>')
        },
                    .text(message)
                    .appendTo(box);


        updateEditorToolVariables() {
                const input = this.textInput();
            if (!this.editorTools) {
                return;
            }


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


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


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


            const populate =
                        if (!value) {
                (
                             return;
                    select,
                    value
                ) => {
                    select.empty();
 
                    variables.forEach(
                        name => {
                             $('<option>')
                                .attr(
                                    'value',
                                    name
                                )
                                .text(name)
                                .appendTo(select);
                         }
                         }
                    );


                    if (
                         overlay.remove();
                         value &&
                         resolve(value);
                        variables.includes(value)
                    ) {
                         select.val(value);
                    } else if (
                        variables.length
                    ) {
                        select.val(
                            variables[0]
                        );
                     }
                     }
                 };
                 );
 
                buttons.append(cancel, confirm);


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


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


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


            const type =
                 input.trigger('focus');
                 this.editorTools
                    .conditionTypeSelect
                    .val();


            this.editorTools
                input.on(
                .conditionVariableWrap
                    'keydown.preloadEditor',
                .toggle(
                    event => {
                    type === 'if'
                        if (event.key === 'Enter') {
                            confirm.trigger('click');
                        }
 
                        if (event.key === 'Escape') {
                            cancel.trigger('click');
                        }
                    }
                 );
                 );
            });
         },
         },


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


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


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


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


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


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


            variableGroup.append(
                const buttons = $('<div>')
                 variableSelect,
                    .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);


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


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


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


            const conditionTypeSelect =
                 overlay.on(
                 this.createToolSelect(
                     'click.preloadEditor',
                     [
                    event => {
                        {
                         if (event.target === overlay.get(0)) {
                            value: 'if',
                             close.trigger('click');
                            label: '@if'
                         }
                        },
                    }
                        {
                            value: 'elseif',
                            label: '@elseif'
                        },
                         {
                             value: 'else',
                            label: '@else'
                         },
                        {
                            value: 'endif',
                            label: '@endif'
                        }
                    ],
                    'preload-editor-condition-type-select'
                 );
                 );
            });
        },
        async confirmSave(mode, title) {
            const configTitle =
                title.replace(/\/+$/, '') +
                '/config.json';


             const conditionVariableSelect =
             let saveDescription;
                 this.createToolSelect(
 
                     [],
            if (mode === 'preload') {
                     'preload-editor-condition-variable-select'
                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
                 );
                 );
            }


             const conditionVariableWrap =
             if (mode === 'config' || mode === 'both') {
                $('<span>')
                pages.push(
                    .addClass(
                    'Config: ' +
                        'preload-editor-condition-variable'
                     configTitle
                     )
                );
                    .append(
                        conditionVariableSelect
                    );


            const insertCondition =
                 pages.push(
                 this.createButton(
                     'Config content model: JSON'
                     'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                        )
                 );
                 );
            }


             conditionTypeSelect.on(
             const message =
                 'change.preloadEditor',
                saveDescription +
                 () =>
                 '\n\n' +
                    this.updateConditionVariableVisibility()
                 pages.join('\n') +
            );
                '\n\nThis will write the changes to the wiki.';


             conditionGroup.append(
             return this.createConfirmDialog(
                 conditionTypeSelect,
                 'Confirm save',
                 conditionVariableWrap,
                 message,
                 insertCondition
                 'Save',
                'Cancel'
             );
             );
        },


             tools.append(
        // =========================================================
                 wrapGroup,
        // CodeMirror
                 variableGroup,
        // =========================================================
                 conditionGroup
                destroyEditor() {
             );
             if (!this.editor) {
                 this.editorView = null;
                 this.editorTools = null;
                 return;
             }


             this.editorTools = {
             const {
                 root: tools,
                 view,
                variableSelect,
                 inputHandler
                conditionTypeSelect,
             } = this.editor;
                 conditionVariableSelect,
                conditionVariableWrap,
                insertCondition
             };


             this.updateEditorToolVariables();
             if (view && inputHandler) {
            this.updateConditionVariableVisibility();
                view.dom.removeEventListener(
                    'input',
                    inputHandler
                );
            }


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


        updateEditorTools() {
            this.editor = null;
             this.updateEditorToolVariables();
             this.editorView = null;
             this.updateConditionVariableVisibility();
             this.editorTools = null;
         },
         },


         // ------------------------------------------------------------
         getEditorView() {
        // Syntax highlighting
             return this.editorView;
        // ------------------------------------------------------------
        },
 
        getKnownVariables() {
             const known =
                new Set(['PAGE']);
 
            const fields =
                this.state.config &&
                this.state.config.fields;


        getEditorContent() {
             if (
             if (
                 fields &&
                 this.editorView &&
                 typeof fields === 'object'
                 this.editorView.state
             ) {
             ) {
                 Object.keys(fields).forEach(
                 return this.editorView.state.doc.toString();
                    name => {
                        known.add(
                            String(
                                name
                            ).toUpperCase()
                        );
                    }
                );
             }
             }


             return known;
             return this.state.preloadContent || '';
         },
         },


         createSyntaxDecorations(
         setEditorContent(content) {
            state,
             content = String(content || '');
            Decoration
        ) {
             const decorations = [];
            const source =
                state.doc.toString();


             const knownVariables =
            if (!this.editorView) {
                 this.getKnownVariables();
                this.state.preloadContent = content;
                return;
            }
 
             const current =
                 this.editorView.state.doc.toString();


             const variablePattern =
             if (current === content) {
                 /%%([A-Za-z0-9_-]+)%%/g;
                 return;
            }


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


             while (
        getEditorSelection() {
                 (
             if (
                    match =
                 !this.editorView ||
                        variablePattern.exec(
                 !this.editorView.state
                            source
                        )
                 ) !== null
             ) {
             ) {
                 const name =
                 return null;
                    match[1].toUpperCase();
            }
 
            const selection =
                this.editorView.state.selection.main;


                 const known =
            return {
                     knownVariables.has(name);
                from: selection.from,
                to: selection.to,
                 text: this.editorView.state.doc.sliceString(
                    selection.from,
                     selection.to
                )
            };
        },


                decorations.push(
        focusEditor() {
                    Decoration.mark({
            if (this.editorView) {
                        class: [
                this.editorView.focus();
                            '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 =
        insertEditorText(
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
            text,
            selectionFrom,
             selectionTo,
            cursorPosition
        ) {
            if (!this.editorView) {
                return;
            }


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


                 const directiveStart =
            const from =
                     match.index +
                 selectionFrom === undefined
                     match[0].indexOf('@');
                     ? selection.from
                     : selectionFrom;


                 decorations.push(
            const to =
                     Decoration.mark({
                 selectionTo === undefined
                        class:
                     ? selection.to
                            'preload-editor-syntax-directive'
                    : selectionTo;
                    }).range(
                        directiveStart,
                        directiveStart +
                            match[1].length +
                            1
                    )
                );


                 const type =
            const cursor =
                     match[1].toLowerCase();
                 cursorPosition === undefined
                     ? from + text.length
                    : cursorPosition;


                 if (
            view.dispatch({
                     type !== 'if' &&
                 changes: {
                     type !== 'elseif'
                    from,
                 ) {
                     to,
                     continue;
                     insert: text
                },
                 selection: {
                     anchor: cursor
                 }
                 }
            });


                const expression =
            view.focus();
                    match[2];
        },
 
        // =========================================================
        // Editor tools
        // =========================================================


                const expressionStart =
        wrapSelectionWithVariable() {
                    match.index +
            const selected =
                    match[0].indexOf(
                this.getEditorSelection();
                        expression
                    );


                 const expressionPattern =
            if (
                    /[A-Za-z0-9_-]+/g;
                !selected ||
                 selected.from === selected.to
            ) {
                this.focusEditor();
                return;
            }


                 let expressionMatch;
            const replacement =
                 '%%' +
                selected.text +
                '%%';


                while (
            this.insertEditorText(
                    (
                replacement,
                        expressionMatch =
                selected.from,
                            expressionPattern.exec(
                selected.to,
                                expression
                 selected.from + replacement.length
                            )
            );
                    ) !== null
        },
                 ) {
                    const name =
                        expressionMatch[0]
                            .toUpperCase();


                    if (
        insertVariable(name) {
                        !knownVariables.has(name)
            name = String(name || '')
                    ) {
                .trim()
                        continue;
                .toUpperCase();
                    }


                    const start =
            if (!name) {
                        expressionStart +
                return;
                        expressionMatch.index;
            }
 
            const selected =
                this.getEditorSelection();


                    decorations.push(
            if (!selected) {
                        Decoration.mark({
                return;
                            class:
                                'preload-editor-syntax-condition-variable'
                        }).range(
                            start,
                            start +
                                expressionMatch[0]
                                    .length
                        )
                    );
                }
             }
             }


             return Decoration.set(
             this.insertEditorText(
                 decorations,
                 '%%' + name + '%%',
                 true
                 selected.from,
                selected.to
             );
             );
         },
         },


         async installSyntaxHighlighting(view) {
         insertCondition(
             await mw.loader.using(
            type,
                 'ext.CodeMirror.v6.lib'
            variable
            );
        ) {
             type = String(type || '').toLowerCase();
            variable = String(variable || '')
                .trim()
                 .toUpperCase();


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


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


             const syntaxField =
             switch (type) {
                 StateField.define({
                 case 'if': {
                     create: state =>
                     if (!variable) {
                         this.createSyntaxDecorations(
                         return;
                            state,
                    }
                            Decoration
                        ),


                     update: (
                     const opening =
                         decorations,
                         '<!-- @if ' +
                         transaction
                         variable +
                    ) =>
                        ' -->';
                        transaction.docChanged
                            ? this.createSyntaxDecorations(
                                transaction.state,
                                Decoration
                            )
                            : decorations,


                     provide: field =>
                     const closing =
                         EditorView.decorations.from(
                         '<!-- @endif -->';
                            field
                        )
                });


            view.dispatch({
                    if (
                effects:
                        selected.from !==
                    StateEffect.appendConfig.of(
                        selected.to
                         syntaxField
                    ) {
                    )
                        text =
            });
                            opening +
                            '\n' +
                            selected.text +
                            '\n' +
                            closing;
 
                        cursorOffset = text.length;
                    } else {
                         text =
                            opening +
                            '\n\n' +
                            closing;


            this.editor.syntaxField =
                        cursorOffset =
                syntaxField;
                            opening.length + 1;
        },
                    }


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


                     const cleanup =
                case 'elseif':
                         () => {
                     text =
                            mw.hook(
                         '<!-- @elseif -->';
                                'dev.CCM.ready'
                            ).remove(onReady);


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


                     const onReady =
                     break;
                        async cm => {
                            if (
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                            settled = true;
                case 'else':
                            cleanup();
                    text =
                        '<!-- @else -->';


                            const view =
                    cursorOffset =
                                cm.view;
                        text.length;


                            const inputHandler =
                    break;
                                () => {
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();


                                    this.state.preloadDirty =
                case 'endif':
                                        true;
                    text =
                        '<!-- @endif -->';


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


                                    this.reanalyze();
                    break;


                                    this.renderVariablesBySelector();
                default:
                                    this.renderVariableConfigurationBySelector();
                    return;
                                    this.renderAnalysisBySelector();
            }
                                    this.updateEditorTools();


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


                            view.dom.addEventListener(
        getToolVariables() {
                                'input',
            const variables =
                                inputHandler
                new Set(['PAGE']);
                            );


                            view.dom.classList.add(
            if (
                                'preload-editor-codemirror'
                this.analysis &&
                            );
                this.analysis.variables
            ) {
                this.analysis.variables.forEach(
                    name => {
                        variables.add(
                            String(name).toUpperCase()
                        );
                    }
                );
            }


                            const wrapper =
            return Array.from(variables);
                                view.dom.closest(
        },
                                    '.ext-codemirror-wrapper'
                                );


                            if (wrapper) {
        createToolSelect(
                                wrapper.classList.add(
            options,
                                    'preload-editor-codemirror-wrapper'
            className
                                );
        ) {
                            }
            const select =
                $('<select>')
                    .addClass(
                        'preload-editor-tool-select'
                    );


                            this.editor = {
            if (className) {
                                cm,
                select.addClass(className);
                                view,
            }
                                textarea,
                                inputHandler
                            };


                             this.editorView =
            options.forEach(
                                view;
                option => {
                    $('<option>')
                        .attr(
                            'value',
                             option.value
                        )
                        .text(option.label)
                        .appendTo(select);
                }
            );


                            this.state.preloadContent =
            return select;
                                view.state.doc.toString();
        },


                            try {
        updateEditorToolVariables() {
                                await this.installSyntaxHighlighting(
            if (!this.editorTools) {
                                    view
                return;
                                );
            }


                                if (
            const variables =
                                    this.state.dirty
                this.getToolVariables();
                                ) {
                                    this.saveDraft();
                                }


                                resolve(view);
            const current =
                            } catch (error) {
                this.editorTools
                                reject(error);
                    .variableSelect
                            }
                    .val();
                        };


                    const onLoad =
            const currentCondition =
                        loader => {
                this.editorTools
                            if (
                    .conditionVariableSelect
                                settled ||
                    .val();
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                            try {
            const populate = (
                                loader(textarea);
                select,
                            } catch (error) {
                value
                                settled = true;
            ) => {
                                cleanup();
                select.empty();
                                reject(error);
                            }
                        };


                    mw.hook(
                variables.forEach(
                         'dev.CCM.ready'
                    name => {
                    ).add(onReady);
                         $('<option>')
                            .attr(
                                'value',
                                name
                            )
                            .text(name)
                            .appendTo(select);
                    }
                );


                     mw.hook(
                if (
                        'dev.CCM.load'
                    value &&
                     ).add(onLoad);
                     variables.includes(value)
                ) {
                    select.val(value);
                } else if (
                    variables.length
                ) {
                     select.val(
                        variables[0]
                    );
                 }
                 }
            };
            populate(
                this.editorTools.variableSelect,
                current
             );
             );
        },


        // ------------------------------------------------------------
            populate(
        // Main UI
                this.editorTools.conditionVariableSelect,
         // ------------------------------------------------------------
                currentCondition
            );
         },


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


             this.root =
             const type =
                this.editorTools
                    .conditionTypeSelect
                    .val();
 
            this.editorTools
                .conditionVariableWrap
                .toggle(
                    type === 'if'
                );
        },
 
        renderEditorTools() {
            const tools =
                 $('<div>')
                 $('<div>')
                    .attr(
                        'id',
                        'preload-editor'
                    )
                     .addClass(
                     .addClass(
                         'preload-editor'
                         'preload-editor-tools'
                     );
                     );


             root.append(this.root);
             const wrapGroup =
                $('<div>')
                    .addClass(
                        'preload-editor-tool-group preload-editor-tool-group-wrap'
                    );


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


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


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


             window.addEventListener(
             const variableSelect =
                'beforeunload',
                 this.createToolSelect(
                 () => {
                     [],
                     if (this.state.dirty) {
                     'preload-editor-variable-select'
                        this.saveDraft();
                 );
                     }
                 }
            );
        },


        renderShell() {
             variableGroup.append(
             this.destroyEditor();
                variableSelect,
            this.root.empty();


            const loader =
                 this.createButton(
                 this.createSection('Preload');
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                        this.insertVariable(
                            variableSelect.val()
                        )
                )
            );


             const titleInput =
             const conditionGroup =
                 this.textInput(
                 $('<div>')
                    this.state.preloadTitle,
                    .addClass(
                    'Template:Example/Preload'
                        'preload-editor-tool-group preload-editor-tool-group-condition'
                ).attr(
                    );
                    'id',
                    'preload-editor-title-input'
                );


             titleInput.on(
             $('<span>')
                'input.preloadEditor',
                 .addClass(
                 () => {
                     'preload-editor-tool-label'
                     this.state.preloadTitle =
                )
                        String(
                .text('Insert condition')
                            titleInput.val() || ''
                .appendTo(conditionGroup);
                        ).trim();


                     if (
            const conditionTypeSelect =
                         this.state.dirty &&
                this.createToolSelect(
                         this.state.mode === 'new'
                     [
                    ) {
                        {
                        this.saveDraft();
                            value: 'if',
                    }
                            label: '@if'
                }
                         },
            );
                         {
 
                            value: 'elseif',
            const loadButton =
                            label: '@elseif'
                this.createButton(
                        },
                     'Load',
                        {
                     'preload-editor-button-primary',
                            value: 'else',
                    () =>
                            label: '@else'
                        this.loadExisting(
                        },
                            titleInput.val()
                        {
                        )
                            value: 'endif',
                            label: '@endif'
                        }
                     ],
                     'preload-editor-condition-type-select'
                 );
                 );


             const newButton =
             const conditionVariableSelect =
                 this.createButton(
                 this.createToolSelect(
                     'New',
                     [],
                     '',
                     'preload-editor-condition-variable-select'
                    () => this.startNew()
                 );
                 );


             const sampleButton =
             const conditionVariableWrap =
                this.createButton(
                 $('<span>')
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );
 
            loader.append(
                 $('<div>')
                     .addClass(
                     .addClass(
                         'preload-editor-toolbar'
                         'preload-editor-condition-variable'
                     )
                     )
                     .append(
                     .append(
                         titleInput,
                         conditionVariableSelect
                         loadButton,
                    );
                         newButton,
 
                        sampleButton
            const insertCondition =
                     )
                this.createButton(
                    'Insert',
                    'preload-editor-tool-button',
                    () =>
                         this.insertCondition(
                            conditionTypeSelect.val(),
                            conditionVariableSelect.val()
                         )
                );
 
            conditionTypeSelect.on(
                'change.preloadEditor',
                () =>
                     this.updateConditionVariableVisibility()
             );
             );


             this.root.append(loader);
             conditionGroup.append(
                conditionTypeSelect,
                conditionVariableWrap,
                insertCondition
            );


             this.status =
             tools.append(
                 $('<div>')
                 wrapGroup,
                    .addClass(
                variableGroup,
                        'preload-editor-status'
                conditionGroup
                    );
            );


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


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


             this.root.append(this.workspace);
             return tools;
        },


             this.renderWelcome();
        updateEditorTools() {
 
             this.updateEditorToolVariables();
             this.updatePageHeight();
             this.updateConditionVariableVisibility();
         },
         },


         renderWelcome() {
         // =========================================================
            this.workspace.empty();
        // Syntax highlighting
        // =========================================================


             const section =
        getKnownVariables() {
                 this.createSection('Get started');
             const known =
                 new Set(['PAGE']);


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


             const tips =
             if (
                 $('<ul>')
                fields &&
                     .addClass(
                typeof fields === 'object'
                         'preload-editor-tips'
            ) {
                     );
                 Object.keys(fields).forEach(
                     name => {
                        known.add(
                            String(name).toUpperCase()
                         );
                     }
                );
            }


             [
             return known;
                '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);
        createSyntaxDecorations(
             this.workspace.append(section);
            state,
        },
             Decoration
        ) {
            const decorations = [];
             const source =
                state.doc.toString();


        setStatus(
             const knownVariables =
             message,
                this.getKnownVariables();
            type
        ) {
            if (!this.status) {
                return;
            }


             this.status.removeClass(
             const variablePattern =
                 'is-error',
                 /%%([A-Za-z0-9_-]+)%%/g;
                'is-success',
                'is-warning',
                'is-loading'
            );


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


             this.status.text(
             while (
                 message || ''
                (
             );
                    match =
        },
                        variablePattern.exec(source)
                 ) !== null
             ) {
                const name =
                    match[1].toUpperCase();
 
                const known =
                    knownVariables.has(name);


        updateDirtyState() {
                decorations.push(
            this.state.dirty =
                    Decoration.mark({
                !!(
                        class: [
                     this.state.preloadDirty ||
                            'preload-editor-syntax-variable',
                    this.state.configDirty
                            known
                                ? 'preload-editor-syntax-variable-known'
                                : 'preload-editor-syntax-variable-unknown'
                        ].join(' ')
                     }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                 );
                 );
        },
            }


        markPreloadDirty() {
             const conditionPattern =
             this.state.preloadDirty = true;
                /<!--\s*@(if|elseif|else|endif)\b([\s\S]*?)-->/gi;
            this.updateDirtyState();
            this.saveDraft();
        },


        markConfigDirty() {
            while (
            this.state.configDirty = true;
                (
             this.updateDirtyState();
                    match =
            this.saveDraft();
                        conditionPattern.exec(source)
        },
                ) !== null
             ) {
                decorations.push(
                    Decoration.mark({
                        class:
                            'preload-editor-syntax-condition'
                    }).range(
                        match.index,
                        match.index +
                            match[0].length
                    )
                );


        markDirty() {
                const directiveStart =
            /*
                    match.index +
            * Existing callers generally modify config fields,
                    match[0].indexOf('@');
            * so markDirty() means the configuration changed.
            */
            this.markConfigDirty();
        },


        // ------------------------------------------------------------
                decorations.push(
        // Load / create
                    Decoration.mark({
        // ------------------------------------------------------------
                        class:
 
                            'preload-editor-syntax-directive'
        async loadExisting(title) {
                    }).range(
            title =
                        directiveStart,
                String(title || '').trim();
                        directiveStart +
 
                            match[1].length +
            if (!title) {
                            1
                mw.notify(
                     )
                    'Enter a preload page title first.',
                    {
                        type: 'warn'
                     }
                 );
                 );


                 return;
                 const type =
            }
                    match[1].toLowerCase();


            this.setStatus(
                if (
                'Loading preload...',
                    type !== 'if' &&
                'loading'
                    type !== 'elseif'
            );
                ) {
                    continue;
                }


            try {
                 const expression =
                 const page =
                     match[2];
                     await this.getPage(title);


                 if (!page) {
                 const expressionStart =
                    const suggestions =
                    match.index +
                        await this.findSimilarPreloads(
                     match[0].indexOf(
                            title
                         expression
                        );
 
                     this.renderMissingPage(
                         title,
                        suggestions
                     );
                     );


                    this.setStatus(
                const expressionPattern =
                        'Preload not found.',
                     /[A-Za-z0-9_-]+/g;
                        'warning'
                     );


                    return;
                let expressionMatch;
                }


                 await this.loadDefinition(
                 while (
                     page.title,
                     (
                     page.content
                        expressionMatch =
                 );
                            expressionPattern.exec(
 
                                expression
                this.setStatus(
                            )
                     'Preload loaded.',
                     ) !== null
                     'success'
                 ) {
                );
                    const name =
            } catch (error) {
                        expressionMatch[0]
                console.error(
                            .toUpperCase();
                     'Preload Editor:',
 
                    error
                     if (
                );
                        !knownVariables.has(name)
                     ) {
                        continue;
                    }
 
                     const start =
                        expressionStart +
                        expressionMatch.index;


                this.setStatus(
                    decorations.push(
                    error.message ||
                        Decoration.mark({
                        'Could not load preload.',
                            class:
                     'error'
                                'preload-editor-syntax-condition-variable'
                 );
                        }).range(
                            start,
                            start +
                                expressionMatch[0].length
                        )
                     );
                 }
             }
             }
            return Decoration.set(
                decorations,
                true
            );
         },
         },


         async findSimilarPreloads(title) {
         async installSyntaxHighlighting(view) {
             let query =
             await mw.loader.using(
                title
                'ext.CodeMirror.v6.lib'
                    .replace(
            );
                        /\/Preload$/i,
 
                        ''
            const require =
                    )
                mw.loader.require;
                    .trim();


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


             try {
             const syntaxField =
                const results =
                StateField.define({
                    await this.searchPages(query);
                    create: state =>
                        this.createSyntaxDecorations(
                            state,
                            Decoration
                        ),


                return results.filter(
                    update: (
                     result =>
                        decorations,
                         /\/Preload$/i.test(
                        transaction
                             result.title
                    ) =>
                         )
                        transaction.docChanged
                 );
                            ? this.createSyntaxDecorations(
             } catch (error) {
                                transaction.state,
                 console.error(
                                Decoration
                    'Preload Editor search:',
                            )
                     error
                            : decorations,
                );
 
                     provide: field =>
                         EditorView.decorations.from(
                             field
                         )
                 });
 
             view.dispatch({
                 effects:
                    StateEffect.appendConfig.of(
                        syntaxField
                     )
            });


                 return [];
            this.editor.syntaxField =
            }
                 syntaxField;
         },
         },


         renderMissingPage(
         async mountCodeMirror(textarea) {
             title,
             return new Promise(
            suggestions
                (
        ) {
                    resolve,
            this.workspace.empty();
                    reject
                ) => {
                    let settled = false;


            const section =
                    const cleanup = () => {
                this.createSection(
                        mw.hook(
                    'Preload not found'
                            'dev.CCM.ready'
                );
                        ).remove(onReady);


            $('<p>')
                        mw.hook(
                .text(
                            'dev.CCM.load'
                    'No preload exists at "' +
                        ).remove(onLoad);
                    title +
                    };
                    '".'
                )
                .appendTo(section);


            if (suggestions.length) {
                    const onReady =
                $('<h3>')
                        async cm => {
                    .text('Similar preloads')
                            if (
                    .appendTo(section);
                                settled ||
                                !cm ||
                                cm.textarea !== textarea ||
                                !cm.view
                            ) {
                                return;
                            }


                const list =
                            settled = true;
                    $('<div>')
                            cleanup();
                        .addClass(
                            'preload-editor-suggestions'
                        );


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


                section.append(list);
                            const inputHandler =
            }
                                () => {
                                    this.state
                                        .preloadContent =
                                        view.state.doc.toString();
 
                                    this.markPreloadDirty();


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


            this.workspace.append(section);
                                    this.renderVariablesBySelector();
        },
                                    this.renderVariableConfigurationBySelector();
                                    this.renderAnalysisBySelector();
                                    this.updateEditorTools();


        async startNew(title) {
                                    this.saveDraft();
            title =
                                };
                String(title || '').trim();


            this.state = {
                            view.dom.addEventListener(
                preloadTitle: title,
                                'input',
                preloadSource: '',
                                inputHandler
                preloadContent:
                            );
                    this.defaults.preload,


                config:
                            view.dom.classList.add(
                    this.emptyConfig(),
                                'preload-editor-codemirror'
                            );


                variables: ['PAGE'],
                            const wrapper =
                conditions: [],
                                view.dom.closest(
                selectedVariable: 'PAGE',
                                    '.ext-codemirror-wrapper'
                deletedVariables: [],
                                );
                mode: 'new',


                preloadDirty: true,
                            if (wrapper) {
                configDirty: true,
                                wrapper.classList.add(
                                    'preload-editor-codemirror-wrapper'
                                );
                            }


                dirty: true
                            this.editor = {
            };
                                cm,
                                view,
                                textarea,
                                inputHandler
                            };


            this.saveDraft();
                            this.editorView =
            this.renderEditor();
                                view;


            this.setStatus(
                            this.state.preloadContent =
                'Creating a new preload.',
                                view.state.doc.toString();
                'success'
            );
        },


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


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


            this.setStatus(
                                resolve(view);
                'Loading sample page...',
                            } catch (error) {
                'loading'
                                reject(error);
            );
                            }
                        };


            try {
                    const onLoad =
                const page =
                        loader => {
                    await this.getPage(result);
                            if (
                                settled ||
                                typeof loader !==
                                    'function'
                            ) {
                                return;
                            }


                if (!page) {
                            try {
                    throw new Error(
                                loader(textarea);
                        'Sample page not found: ' +
                            } catch (error) {
                        result
                                settled = true;
                    );
                                cleanup();
                }
                                reject(error);
                            }
                        };


                const sample =
                     mw.hook(
                     this.convertSampleToPreload(
                         'dev.CCM.ready'
                         page.content
                     ).add(onReady);
                     );


                this.state = {
                    mw.hook(
                    preloadTitle: '',
                        'dev.CCM.load'
                    preloadSource: '',
                    ).add(onLoad);
                    preloadContent: sample,
                }
            );
        },
 
        // =========================================================
        // Main UI
        // =========================================================
 
        init() {
            const root =
                $('#mw-content-text');


                    config:
            if (!root.length) {
                        this.emptyConfig(),
                return;
            }


                    variables: ['PAGE'],
            this.root =
                     conditions: [],
                $('<div>')
                    selectedVariable: 'PAGE',
                     .attr(
                     deletedVariables: [],
                        'id',
                     mode: 'new',
                        'preload-editor'
                     )
                     .addClass(
                        'preload-editor'
                    );


                    preloadDirty: true,
            root.append(this.root);
                    configDirty: true,


                    dirty: true
            this.renderShell();
                };


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


                this.setStatus(
            window.addEventListener(
                    'Sample page loaded.',
                'beforeunload',
                    'success'
                 () => {
                 );
                    if (this.state.dirty) {
            } catch (error) {
                         this.saveDraft();
                console.error(
                     }
                    'Preload Editor sample:',
                 }
                    error
            );
                );
 
                this.setStatus(
                    error.message ||
                         'Could not load sample page.',
                     'error'
                 );
            }
         },
         },
                renderShell() {
            this.destroyEditor();
            this.root.empty();


        convertSampleToPreload(source) {
             const loader =
             let content =
                 this.createSection('Preload');
                 String(source || '').trim();


             const include =
             const titleInput =
                 content.match(
                 this.textInput(
                     /<includeonly>([\s\S]*?)<\/includeonly>/i
                     this.state.preloadTitle,
                    'Template:Example/Preload'
                ).attr(
                    'id',
                    'preload-editor-title-input'
                 );
                 );


             if (include) {
             titleInput.on(
                content =
                'input.preloadEditor',
                    include[1].trim();
                () => {
            }
                    this.state.preloadTitle =
                        String(
                            titleInput.val() || ''
                        ).trim();


            content =
                     if (
                content
                         this.state.dirty &&
                     .replace(
                         this.state.mode === 'new'
                         /<noinclude>[\s\S]*?<\/noinclude>/gi,
                     ) {
                         ''
                        this.saveDraft();
                     )
                    }
                    .trim();
                 }
 
            return (
                '<includeonly>\n' +
                content +
                 '\n</includeonly>\n' +
                '<noinclude>{{Documentation|type=Preload|content={{Preload Template}}}}</noinclude>\n'
             );
             );
        },


        async loadDefinition(
            const loadButton =
            title,
                this.createButton(
            source
                    'Load',
        ) {
                    'preload-editor-button-primary',
            const content =
                    () =>
                this.extractIncludeonly(source);
                        this.loadExisting(
                            titleInput.val()
                        )
                );


             let config =
             const newButton =
                 this.emptyConfig();
                 this.createButton(
 
                     'New',
            const configTitle =
                     '',
                title.replace(
                    () => this.startNew()
                     /\/+$/,
                 );
                     ''
                ) +
                 '/config.json';


             const configPage =
             const sampleButton =
                 await this.getPage(configTitle);
                 this.createButton(
                    'Load Sample Page',
                    '',
                    () => this.loadSamplePage()
                );


             if (configPage) {
             loader.append(
                 try {
                 $('<div>')
                     config =
                     .addClass(
                        JSON.parse(
                         'preload-editor-toolbar'
                            configPage.content
                    )
                         );
                     .append(
                } catch (error) {
                         titleInput,
                     throw new Error(
                        loadButton,
                         'The existing config.json contains invalid JSON: ' +
                        newButton,
                         error.message
                         sampleButton
                     );
                     )
                }
             );
             }


             const analysis =
             this.root.append(loader);
                this.analyzePreload(content);


             this.state.deletedVariables = [];
             this.workspace =
                $('<div>')
                    .addClass(
                        'preload-editor-workspace'
                    );


             config =
             this.root.append(
                 this.prepareConfigForVariables(
                 this.workspace
                    config,
            );
                    analysis
                );


             this.state = {
             /*
                 preloadTitle: title,
            * Fixed footer
                preloadSource: source,
            *
                preloadContent: source,
            * Local draft status, normal status messages,
                config,
            * and save actions live here.
            */
            const footer =
                 $('<div>')
                    .addClass(
                        'preload-editor-footer'
                    );


                 variables:
            this.localDraftStatus =
                     analysis.variables,
                 $('<div>')
                     .addClass(
                        'preload-editor-local-draft-status is-empty'
                    )
                    .text(
                        'No local draft'
                    );


                 conditions:
            this.status =
                     analysis.conditions,
                 $('<div>')
                     .addClass(
                        'preload-editor-status'
                    );


                selectedVariable:
            footer.append(
                    analysis.variables.includes('PAGE')
                this.localDraftStatus,
                        ? 'PAGE'
                this.status
                        : (
            );
                            analysis.variables[0] ||
                            'PAGE'
                        ),


                 deletedVariables: [],
            this.root.append(
 
                 footer
                mode: 'edit',
            );


                preloadDirty: false,
            this.updateLocalDraftIndicator();
                configDirty: false,


                dirty: false
             this.renderWelcome();
            };
 
            this.clearDraft(title);
             this.renderEditor();
         },
         },


         // ------------------------------------------------------------
         renderWelcome() {
        // Editor
        // ------------------------------------------------------------
 
        renderEditor() {
            this.destroyEditor();
             this.workspace.empty();
             this.workspace.empty();


             const layout =
             const section =
                 $('<div>')
                 this.createSection('Get started');
                    .addClass(
                        'preload-editor-layout'
                    );


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


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


             const editorSection =
             [
                 this.createSection(
                 'Existing preload: loads the preload and its config.json if available.',
                    'Preload',
                'New preload: starts with the standard Preload Template structure.',
                     'preload-editor-main-section'
                'Sample page: loads normal wiki page content so you can turn it into a preload.'
                 );
            ].forEach(
                text => {
                     $('<li>')
                        .text(text)
                        .appendTo(tips);
                 }
            );


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


            $('<strong>')
        setStatus(
                .text(
            message,
                    this.state.preloadTitle ||
            type
                    'New preload'
        ) {
                )
             if (!this.status) {
                .appendTo(meta);
                 return;
 
             if (
                this.state.mode === 'new'
            ) {
                 $('<span>')
                    .addClass(
                        'preload-editor-badge'
                    )
                    .text('NEW')
                    .appendTo(meta);
             }
             }


             editorSection.append(meta);
             this.status.removeClass(
            editorSection.append(
                'is-error',
                 this.renderEditorTools()
                'is-success',
                'is-warning',
                 'is-loading'
             );
             );


             const textarea =
             if (type) {
                 this.textarea(
                 this.status.addClass(
                    this.state.preloadContent
                     'is-' + type
                )
                );
                    .attr(
            }
                        'id',
                        'preload-editor-content'
                    )
                     .addClass(
                        'preload-editor-content'
                    );


             const editorMount =
             this.status.text(
                $('<div>')
                message || ''
                    .addClass(
            );
                        'preload-editor-codemirror-mount'
        },
                    )
                    .append(textarea);


            editorSection.append(editorMount);
        // =========================================================
            left.append(editorSection);
        // Load / create
        // =========================================================


             // Analysis
        async loadExisting(title) {
             title =
                String(title || '').trim();


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


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


             analysisSection.append(
             this.setStatus(
                 analysisContainer
                 'Loading preload...',
                'loading'
             );
             );


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


            const variablesSection =
                if (!page) {
                this.createSection('Variables');
                    const suggestions =
                        await this.findSimilarPreloads(
                            title
                        );


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


            const detectHelp =
                     this.setStatus(
                $('<div>')
                         'Preload not found.',
                     .addClass(
                         'warning'
                         'preload-editor-help preload-editor-detect-variables-help'
                    )
                    .text(
                         'Refresh the variable list after editing the preload.'
                     );
                     );


            variablesSection.append(
                    return;
                 $('<div>')
                 }
                    .addClass(
 
                        'preload-editor-variable-detect'
                await this.loadDefinition(
                    )
                     page.title,
                     .append(
                     page.content
                        detectVariablesButton,
                );
                        detectHelp
                     )
            );


            const variableContainer =
                 this.setStatus(
                 $('<div>')
                    'Preload loaded.',
                    .addClass(
                    'success'
                        'preload-editor-variables'
                );
                     );
            } catch (error) {
                console.error(
                    'Preload Editor:',
                     error
                );


            variablesSection.append(
                this.setStatus(
                variableContainer
                    error.message ||
            );
                        'Could not load preload.',
 
                     'error'
            // Configuration
 
            const configurationSection =
                this.createSection(
                     'Variable configuration'
                 );
                 );
            }
        },


             const configurationContainer =
        async findSimilarPreloads(title) {
                 $('<div>')
             let query =
                     .addClass(
                 title
                         'preload-editor-variable-configuration'
                     .replace(
                     );
                        /\/Preload$/i,
                         ''
                     )
                    .trim();


             configurationSection.append(
             if (!query) {
                 configurationContainer
                 query = title;
             );
             }


             /*
             try {
            * --------------------------------------------------------
                const results =
            * Generated configuration
                    await this.searchPages(query);
            * --------------------------------------------------------
            *
            * The giant JSON preview is gone from the main workspace.
            * We now have one compact button which opens a review
            * dialog.
            */


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


            const configReview =
                 return [];
                 $('<div>')
            }
                    .addClass(
        },
                        'preload-editor-config-review-trigger'
                    );


             $('<p>')
        renderMissingPage(
                 .addClass(
            title,
                     'preload-editor-analysis-note'
            suggestions
                 )
        ) {
             this.workspace.empty();
 
            const section =
                 this.createSection(
                     'Preload not found'
                 );
 
            $('<p>')
                 .text(
                 .text(
                     'Review the generated config.json before saving it.'
                     'No preload exists at "' +
                    title +
                    '".'
                 )
                 )
                 .appendTo(configReview);
                 .appendTo(section);


             configReview.append(
             if (suggestions.length) {
                 this.createButton(
                 $('<h3>')
                    'Review generated JSON',
                     .text('Similar preloads')
                     'preload-editor-button-primary preload-editor-review-config',
                     .appendTo(section);
                     () =>
                        this.createConfigReviewDialog()
                )
            );


            configSection.append(
                const list =
                configReview
                    $('<div>')
            );
                        .addClass(
                            'preload-editor-suggestions'
                        );


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


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


             actions.append(
             section.append(
                 this.createButton(
                 this.createButton(
                     'Save Preload',
                     'Create this preload',
                     'preload-editor-button-primary preload-editor-save-preload',
                     'preload-editor-button-primary',
                     () =>
                     () =>
                         this.savePreloadOnly()
                         this.startNew(title)
                ),
 
                this.createButton(
                    'Save Config',
                    'preload-editor-button-primary preload-editor-save-config',
                    () =>
                        this.saveConfigOnly()
                ),
 
                this.createButton(
                    'Save',
                    'preload-editor-button-primary preload-editor-save-all',
                    () =>
                        this.saveAll()
                 )
                 )
             );
             );


             right.append(
             this.workspace.append(section);
                analysisSection,
        },
                variablesSection,
                configurationSection,
                configSection,
                actions
            );


            layout.append(
        async startNew(title) {
                left,
            title =
                 right
                 String(title || '').trim();
            );


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


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


            this.renderVariables(
                variables: ['PAGE'],
                 variableContainer
                conditions: [],
             );
                selectedVariable: 'PAGE',
                deletedVariables: [],
                mode: 'new',
                dirty: true,
                dirtyPreload: true,
                dirtyConfig: true,
 
                localDraftSavedAt: null,
                 localDraftAvailable: false
             };


             this.renderAnalysis(
             this.saveDraft();
                analysisContainer
             this.renderEditor();
             );


             this.renderVariableConfiguration(
             this.setStatus(
                 configurationContainer
                 'Creating a new preload.',
                'success'
             );
             );
        },


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


             this.mountCodeMirror(
             if (!result) {
                 textarea.get(0)
                 return;
             ).catch(
             }
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                    );


                    this.setStatus(
            this.setStatus(
                        error.message ||
                'Loading sample page...',
                            'Could not initialize CodeMirror.',
                'loading'
                         'error'
            );
 
            try {
                const page =
                    await this.getPage(result);
 
                if (!page) {
                    throw new Error(
                         'Sample page not found: ' +
                        result
                     );
                     );
                 }
                 }
            );


            this.updatePageHeight();
                const sample =
        },
                    this.convertSampleToPreload(
                        page.content
                    );


        detectVariables() {
                this.state = {
            const source =
                    preloadTitle: '',
                this.getEditorContent();
                    preloadSource: '',
                    preloadContent: sample,


            this.state.preloadContent =
                    config:
                source;
                        this.emptyConfig(),


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


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


            this.renderVariablesBySelector();
                this.reanalyze();
            this.renderVariableConfigurationBySelector();
                this.saveDraft();
            this.renderAnalysisBySelector();
                this.renderEditor();
            this.updateEditorTools();


             this.saveDraft();
                this.setStatus(
 
                    'Sample page loaded.',
            this.setStatus(
                    'success'
                'Variables detected from the current preload.',
                );
                'success'
             } catch (error) {
            );
                console.error(
                    'Preload Editor sample:',
                    error
                );
 
                this.setStatus(
                    error.message ||
                        'Could not load sample page.',
                    'error'
                );
            }
         },
         },


         reanalyze() {
         convertSampleToPreload(source) {
             const source =
             let content =
                 this.getEditorContent();
                 String(source || '').trim();


             const content =
             const include =
                 this.extractIncludeonly(source);
                 content.match(
                    /<includeonly>([\s\S]*?)<\/includeonly>/i
                );


             const analysis =
             if (include) {
                this.analyzePreload(content);
                content =
                    include[1].trim();
            }


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


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


             const beforeConfig =
        async loadDefinition(
                 this.state.config
            title,
                    ? JSON.stringify(
            source
                        this.state.config
        ) {
                    )
             const content =
                    : '';
                 this.extractIncludeonly(source);


             this.state.config =
             let config =
                 this.prepareConfigForVariables(
                 this.emptyConfig();
                    this.state.config ||
                        this.emptyConfig(),
                    analysis
                );


             const afterConfig =
             const configTitle =
                 JSON.stringify(
                 title.replace(
                     this.state.config
                     /\/+$/,
                 );
                    ''
                 ) +
                '/config.json';


             /*
             const configPage =
            * If analysis automatically created a new field,
                 await this.getPage(configTitle);
            * that is a real config change and should be saved.
            */
            if (
                beforeConfig &&
                beforeConfig !== afterConfig
            ) {
                this.state.configDirty = true;
                 this.updateDirtyState();
            }


             this.analysis =
             if (configPage) {
                 analysis;
                 try {
 
                    config =
            const available =
                        JSON.parse(
                ['PAGE'].concat(
                            configPage.content
                    analysis.variables.filter(
                         );
                         name =>
                 } catch (error) {
                            name !== 'PAGE'
                    throw new Error(
                    )
                        'The existing config.json contains invalid JSON: ' +
                 );
                        error.message
 
                    );
            if (
                 }
                !available.includes(
                    this.state.selectedVariable
                )
            ) {
                 this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
             }
             }
        },


        // ------------------------------------------------------------
            const analysis =
        // Analysis
                this.analyzePreload(content);
        // ------------------------------------------------------------


        renderAnalysis(container) {
             this.state.deletedVariables = [];
             container.empty();


             const analysis =
             config =
                 this.analysis ||
                 this.prepareConfigForVariables(
                 this.analyzePreload(
                    config,
                    this.extractIncludeonly(
                    analysis
                        this.getEditorContent()
                 );
                    )
 
                 );
            this.state = {
                preloadTitle: title,
                preloadSource: source,
                preloadContent: source,
                config,
 
                 variables:
                    analysis.variables,


            const variableCount =
                conditions:
                analysis.variables.length;
                    analysis.conditions,


            const conditionCount =
                selectedVariable:
                analysis.conditions.length;
                    analysis.variables.includes('PAGE')
                        ? 'PAGE'
                        : (
                            analysis.variables[0] ||
                            'PAGE'
                        ),


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


            const summary =
                 mode: 'edit',
                 $('<div>')
                dirty: false,
                    .addClass(
                dirtyPreload: false,
                        'preload-editor-analysis-summary'
                dirtyConfig: false,
                    );


            const createMetric =
                 localDraftSavedAt: null,
                 (
                 localDraftAvailable: false
                    value,
            };
                    label
                 ) =>
                    $('<div>')
                        .addClass(
                            'preload-editor-analysis-metric'
                        )
                        .append(
                            $('<strong>')
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


                            $('<span>')
            this.clearDraft(title);
                                .addClass(
            this.renderEditor();
                                    'preload-editor-analysis-label'
        },
                                )
                                .text(label)
                        );


            summary.append(
        // =========================================================
                createMetric(
        // Editor
                    variableCount,
        // =========================================================
                    variableCount === 1
                        ? 'variable'
                        : 'variables'
                ),


                createMetric(
        renderEditor() {
                    conditionCount,
            this.destroyEditor();
                    conditionCount === 1
            this.workspace.empty();
                        ? 'condition marker'
                        : 'condition markers'
                ),


                 createMetric(
            const layout =
                     configuredCount,
                 $('<div>')
                    configuredCount === 1
                     .addClass(
                         ? 'configured field'
                         'preload-editor-layout'
                        : 'configured fields'
                    );
                )
            );


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


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


             const validation =
             const editorSection =
                 this.validateConfig(
                 this.createSection(
                     this.state.config,
                     'Preload',
                     analysis
                     'preload-editor-main-section'
                 );
                 );


             if (validation.errors.length) {
             const meta =
                const errors =
                $('<div>')
                    $('<ul>')
                    .addClass(
                        .addClass(
                        'preload-editor-meta'
                            'preload-editor-validation-errors'
                    );
                        );


                validation.errors.forEach(
            $('<strong>')
                    error => {
                .text(
                        $('<li>')
                    this.state.preloadTitle ||
                            .text(error)
                     'New preload'
                            .appendTo(errors);
                 )
                     }
                .appendTo(meta);
                 );


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


             if (validation.warnings.length) {
             editorSection.append(meta);
                const warnings =
            editorSection.append(
                    $('<ul>')
                this.renderEditorTools()
                        .addClass(
            );
                            'preload-editor-validation-warnings'
                        );


                 validation.warnings.forEach(
            const textarea =
                    warning => {
                 this.textarea(
                         $('<li>')
                    this.state.preloadContent
                            .text(warning)
                )
                            .appendTo(warnings);
                    .attr(
                     }
                        'id',
                );
                         'preload-editor-content'
                    )
                    .addClass(
                        'preload-editor-content'
                     );


                 container.append(warnings);
            const editorMount =
            }
                 $('<div>')
                    .addClass(
                        'preload-editor-codemirror-mount'
                    )
                    .append(textarea);


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


        renderAnalysisBySelector() {
             const analysisSection =
             const container =
                 this.createSection('Analysis');
                 this.root &&
                this.root.find(
                    '.preload-editor-analysis'
                );


             if (
             const analysisContainer =
                 container &&
                 $('<div>')
                container.length
                    .addClass(
            ) {
                        'preload-editor-analysis'
                this.renderAnalysis(container);
                    );
            }
        },


        // ------------------------------------------------------------
            analysisSection.append(
        // Variables
                analysisContainer
        // ------------------------------------------------------------
            );


        renderVariables(container) {
            const variablesSection =
            container.empty();
                this.createSection('Variables');


             const analysis =
             const detectVariablesButton =
                 this.analysis ||
                 this.createButton(
                this.analyzePreload(
                    'Detect variables',
                     this.extractIncludeonly(
                    'preload-editor-button-primary preload-editor-detect-variables',
                         this.getEditorContent()
                     () =>
                    )
                         this.detectVariables()
                 );
                 );


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


             const ordered =
             variablesSection.append(
                ['PAGE'];
                 $('<div>')
 
                     .addClass(
            variables.forEach(
                         'preload-editor-variable-detect'
                 name => {
                    )
                     if (
                    .append(
                         name !== 'PAGE' &&
                        detectVariablesButton,
                        !ordered.includes(name)
                         detectHelp
                    ) {
                     )
                         ordered.push(name);
                     }
                }
             );
             );


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


             configuredFields.forEach(
             variablesSection.append(
                 name => {
                 variableContainer
                    const upper =
                        name.toUpperCase();
 
                    if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                }
             );
             );


             const deleted =
             const configurationSection =
                 Array.isArray(
                 this.createSection(
                     this.state.deletedVariables
                     'Variable configuration'
                 )
                );
                     ? this.state.deletedVariables
 
                     : [];
            /*
            * 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.'
                     );


             deleted.forEach(
             const importControls =
                 name => {
                 $('<div>')
                     const upper =
                     .addClass(
                         String(name).toUpperCase();
                         'preload-editor-import-definition-controls'
                    )
                    .append(
                        importDefinitionsButton,
                        importHelp
                    );


                    if (
            configurationSection.append(
                        upper !== 'PAGE' &&
                 importControls
                        !ordered.includes(upper)
                    ) {
                        ordered.push(upper);
                    }
                 }
             );
             );


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


             ordered.forEach(
             configurationSection.append(
                 name => {
                 configurationContainer
                    const isSelected =
            );
                        name ===
 
                        this.state.selectedVariable;
            const configSection =
                this.createSection(
                    'Configuration'
                );


                    const isUsed =
            const configHelp =
                         analysis.variables.includes(
                $('<div>')
                            name
                    .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()
                );


                    const isConfigured =
            configSection.append(
                        !!(
                configHelp,
                            this.state.config &&
                reviewConfigButton
                            this.state.config.fields &&
            );
                            this.state.config.fields[name]
                        );


                    const item =
            right.append(
                        $('<button>')
                analysisSection,
                            .attr({
                variablesSection,
                                type: 'button',
                configurationSection,
                                'data-variable':
                configSection
                                    name
            );
                            })
 
                            .addClass(
            layout.append(
                                'preload-editor-variable-item'
                left,
                            )
                right
                            .toggleClass(
            );
                                'is-selected',
 
                                isSelected
            const saveBar =
                            )
                $('<div>')
                            .on(
                    .addClass(
                                'click.preloadEditor',
                        'preload-editor-save-bar'
                                () =>
                    );
                                    this.selectVariable(
                                        name
                                    )
                            );


                    $('<span>')
            saveBar.append(
                        .addClass(
                this.createButton(
                            'preload-editor-variable-name'
                    'Save Preload',
                        )
                    '',
                         .text(name)
                    () =>
                        .appendTo(item);
                         this.savePreloadOnly()
                ),


                    if (name === 'PAGE') {
                this.createButton(
                        item.append(
                    'Save Config',
                            $('<span>')
                    '',
                                .addClass(
                    () =>
                                    'preload-editor-badge'
                        this.saveConfigOnly()
                                )
                ),
                                .text('AUTOMATIC')
 
                        );
                this.createButton(
                    } else if (!isConfigured) {
                    'Save',
                        item.append(
                    'preload-editor-button-primary',
                            $('<span>')
                    () =>
                                .addClass(
                        this.saveAll()
                                    'preload-editor-badge is-warning'
                )
                                )
            );
                                .text(
 
                                    isUsed
            this.root
                                        ? 'NOT CONFIGURED'
                .find('.preload-editor-footer')
                                        : 'DELETED'
                .append(saveBar);
                                )
                        );
                    } else if (!isUsed) {
                        item.append(
                            $('<span>')
                                .addClass(
                                    'preload-editor-badge is-warning'
                                )
                                .text('UNUSED')
                        );
                    }


                    list.append(item);
            this.workspace.append(
                 }
                 layout
             );
             );


             container.append(list);
             this.reanalyze();


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


        renderVariablesBySelector() {
             this.renderAnalysis(
             const container =
                 analysisContainer
                this.root &&
            );
                 this.root.find(
                    '.preload-editor-variables'
                );


             if (
             this.renderVariableConfiguration(
                 container &&
                 configurationContainer
                container.length
             );
             ) {
                this.renderVariables(container);
            }
        },


        selectVariable(name) {
             this.updateEditorTools();
             name =
            this.updateLocalDraftIndicator();
                String(name || '')
                    .trim()
                    .toUpperCase();


             if (!name) {
             this.mountCodeMirror(
                return;
                textarea.get(0)
            }
            ).catch(
                error => {
                    console.error(
                        'Preload Editor CodeMirror:',
                        error
                    );


            const available =
                     this.setStatus(
                ['PAGE'].concat(
                         error.message ||
                     (
                             'Could not initialize CodeMirror.',
                        this.analysis &&
                         'error'
                         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;
        // Variable detection
            }
        // =========================================================


             this.state.selectedVariable =
        detectVariables() {
                 name;
             const source =
                 this.getEditorContent();


             this.renderVariablesBySelector();
             this.state.preloadContent =
             this.renderVariableConfigurationBySelector();
                source;
        },
 
             const content =
                this.extractIncludeonly(
                    source
                );


        renderVariableConfigurationBySelector() {
             const analysis =
             const container =
                 this.analyzePreload(
                 this.root &&
                     content
                this.root.find(
                     '.preload-editor-variable-configuration'
                 );
                 );


            /*
            * If a variable was previously deleted from
            * the configuration, detecting the current
            * preload again should allow it to come back.
            */
             if (
             if (
                 container &&
                 Array.isArray(
                 container.length
                    this.state.deletedVariables
                 )
             ) {
             ) {
                 this.renderVariableConfiguration(
                 const detected =
                     container
                    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 = [];
             }
             }
        },


        renderVariableConfiguration(container) {
             this.markDirty();
             container.empty();


             const analysis =
             this.reanalyze();
                this.analysis ||
 
                this.analyzePreload(
            this.renderVariablesBySelector();
                    this.extractIncludeonly(
            this.renderVariableConfigurationBySelector();
                        this.getEditorContent()
            this.renderAnalysisBySelector();
                    )
            this.updateEditorTools();
                );
 
            this.saveDraft();


             const name =
             this.setStatus(
                 this.state.selectedVariable ||
                 'Variables detected from the current preload.',
                 'PAGE';
                 'success'
            );
        },


             const fields =
        reanalyze() {
                 this.state.config &&
             const source =
                this.state.config.fields
                 this.getEditorContent();
                    ? this.state.config.fields
                    : {};


             const field =
             const content =
                 fields[name];
                 this.extractIncludeonly(source);


             if (name === 'PAGE') {
             const analysis =
                 container.append(
                 this.analyzePreload(
                    this.createAutomaticPageCard(
                     content
                        field ||
                        this.getAutomaticPageField()
                     )
                 );
                 );


                 return;
            this.state.preloadContent =
            }
                 source;


             if (!field) {
             this.state.variables =
                 const missing =
                 analysis.variables;
                    $('<div>')
 
                        .addClass(
            this.state.conditions =
                            'preload-editor-variable preload-editor-variable-missing'
                analysis.conditions;
                        );


                 $('<div>')
            this.state.config =
                     .addClass(
                 this.prepareConfigForVariables(
                         'preload-editor-variable-header'
                     this.state.config ||
                    )
                         this.emptyConfig(),
                     .append(
                     analysis
                        $('<h3>')
                );
                            .text(name),


                        $('<span>')
            this.analysis =
                            .addClass(
                analysis;
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


                 $('<p>')
            const available =
                     .addClass(
                 ['PAGE'].concat(
                         'preload-editor-analysis-note'
                     analysis.variables.filter(
                         name =>
                            name !== 'PAGE'
                     )
                     )
                    .text(
                );
                        'This variable is currently not present in config.json.'
                    )
                    .appendTo(missing);


                 container.append(missing);
            if (
                 return;
                 !available.includes(
                    this.state.selectedVariable
                )
            ) {
                 this.state.selectedVariable =
                    available[0] ||
                    'PAGE';
             }
             }
            container.append(
                this.createVariableCard(
                    name,
                    field,
                    analysis
                )
            );
         },
         },


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


            const header =
        renderAnalysis(container) {
                $('<div>')
            container.empty();
                    .addClass(
                        'preload-editor-variable-header'
                    );


             header.append(
             const analysis =
                $('<h3>').text('PAGE'),
                this.analysis ||
                this.analyzePreload(
                    this.extractIncludeonly(
                        this.getEditorContent()
                    )
                );


                 $('<span>')
            const variableCount =
                    .addClass(
                 analysis.variables.length;
                        'preload-editor-badge'
                    )
                    .text('AUTOMATIC')
            );


             card.append(header);
             const conditionCount =
                analysis.conditions.length;


             $('<p>')
             const configuredCount =
                 .addClass(
                 Object.keys(
                     'preload-editor-analysis-note'
                     this.state.config &&
                )
                    this.state.config.fields
                .text(
                        ? this.state.config.fields
                    'PAGE is a precompiled automatic variable. It is always available and is not edited like normal variables.'
                        : {}
                 )
                 ).length;
                .appendTo(card);


             const label =
             const summary =
                 this.textInput(
                 $('<div>')
                    field.label ||
                    .addClass(
                    'Page Name'
                        'preload-editor-analysis-summary'
                ).prop(
                     );
                    'disabled',
                     true
                );


             const description =
             const createMetric =
                 this.textarea(
                 (
                     field.description ||
                     value,
                     'Name of the page.'
                     label
                 )
                 ) =>
                     .addClass(
                     $('<div>')
                        'preload-editor-small-textarea'
                        .addClass(
                    )
                            'preload-editor-analysis-metric'
                    .prop(
                        )
                        'disabled',
                        .append(
                        true
                            $('<strong>')
                    );
                                .addClass(
                                    'preload-editor-analysis-value'
                                )
                                .text(value),


            const type =
                            $('<span>')
                this.textInput(
                                .addClass(
                    field.type || 'page'
                                    'preload-editor-analysis-label'
                ).prop(
                                )
                    'disabled',
                                .text(label)
                    true
                        );
                );


             const required =
             summary.append(
                this.checkbox(
                 createMetric(
                    field.required !== false
                     variableCount,
                 ).prop(
                     variableCount === 1
                     'disabled',
                        ? 'variable'
                     true
                        : 'variables'
                );
 
            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(
                 createMetric(
                     'Description',
                     conditionCount,
                    description
                    conditionCount === 1
                        ? 'condition marker'
                        : 'condition markers'
                 ),
                 ),


                 this.fieldRow(
                 createMetric(
                     'Type',
                     configuredCount,
                    type
                    configuredCount === 1
                 ),
                        ? 'configured field'
                        : 'configured fields'
                 )
            );


                this.fieldRow(
            container.append(summary);
                    'Required',
                    required
                ),


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


                 this.fieldRow(
            const validation =
                     'Allow new page',
                 this.validateConfig(
                     allowNew
                     this.state.config,
                 )
                     analysis
            );
                 );


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


        createVariableCard(
                validation.errors.forEach(
            name,
                    error => {
            field,
                        $('<li>')
            analysis
                            .text(error)
        ) {
                            .appendTo(errors);
            const card =
                    }
                $('<div>')
                );
                    .addClass(
                        'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );


            const header =
                 container.append(errors);
                 $('<div>')
            }
                    .addClass(
                        'preload-editor-variable-header'
                    );


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


            card.append(header);
                validation.warnings.forEach(
 
                    warning => {
            const label =
                        $('<li>')
                this.textInput(
                            .text(warning)
                     field.label || ''
                            .appendTo(warnings);
                     }
                 );
                 );


            label.on(
                 container.append(warnings);
                 'input.preloadEditor',
            }
                () => {
                    field.label =
                        label.val();


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


             card.append(
        renderAnalysisBySelector() {
                 this.fieldRow(
             const container =
                     'Label',
                this.root &&
                    label
                 this.root.find(
                 )
                     '.preload-editor-analysis'
            );
                 );


             const description =
            if (
                 this.textarea(
                container &&
                     field.description || ''
                container.length
                ).addClass(
            ) {
                     'preload-editor-small-textarea'
                this.renderAnalysis(container);
            }
        },
 
        // =========================================================
        // Variables
        // =========================================================
 
        renderVariables(container) {
            container.empty();
 
             const analysis =
                 this.analysis ||
                this.analyzePreload(
                     this.extractIncludeonly(
                        this.getEditorContent()
                     )
                 );
                 );


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


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


             card.append(
             const configuredFields =
                 this.fieldRow(
                this.state.config &&
                     'Description',
                this.state.config.fields
                     description
                    ? Object.keys(
                 )
                        this.state.config.fields
                    )
                    : [];
 
            configuredFields.forEach(
                 name => {
                    const upper =
                        name.toUpperCase();
 
                     if (
                        upper !== 'PAGE' &&
                        !ordered.includes(upper)
                     ) {
                        ordered.push(upper);
                    }
                 }
             );
             );


             const types = [
             const deleted =
                 ['text', 'Text'],
                 Array.isArray(
                ['textarea', 'Textarea'],
                    this.state.deletedVariables
                 ['number', 'Number'],
                 )
                ['boolean', 'Boolean'],
                    ? this.state.deletedVariables
                ['select', 'Select'],
                    : [];
                ['multiselect', 'Multi-select'],
                ['page', 'Page'],
                ['user', 'User'],
                ['date', 'Date']
            ];


             const typeSelect =
             deleted.forEach(
                this.select(
                name => {
                    types.map(
                    const upper =
                        ([value, label]) => ({
                         String(name).toUpperCase();
                            value,
                            label
                         })
                    ),
                    field.type || 'text'
                );


            typeSelect.on(
                    if (
                'change.preloadEditor',
                        upper !== 'PAGE' &&
                () => {
                         !ordered.includes(upper)
                    field.type =
                     ) {
                         typeSelect.val();
                        ordered.push(upper);
 
                     }
                     this.markConfigDirty();
 
                    this.renderVariableConfigurationBySelector();
                     this.renderConfigReviewState();
                 }
                 }
             );
             );


             card.append(
             const list =
                this.fieldRow(
                $('<div>')
                    'Type',
                    .addClass(
                     typeSelect
                        'preload-editor-variable-list'
                )
                     );
            );


             const required =
             ordered.forEach(
                 this.checkbox(
                 name => {
                     field.required === true
                     const isSelected =
                );
                        name ===
                        this.state.selectedVariable;


            required.on(
                    const isUsed =
                'change.preloadEditor',
                        analysis.variables.includes(
                () => {
                            name
                    field.required =
                         );
                         required.prop('checked');


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


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


            const placeholder =
                    $('<span>')
                this.textInput(
                        .addClass(
                    field.placeholder || ''
                            'preload-editor-variable-name'
                );
                        )
                        .text(name)
                        .appendTo(item);


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


                     this.markConfigDirty();
                     list.append(item);
                    this.renderConfigReviewState();
                 }
                 }
             );
             );


             card.append(
             container.append(list);
                this.fieldRow(
                    'Placeholder',
                    placeholder
                )
            );


             const defaultInput =
             if (!ordered.length) {
                 this.textInput(
                 container.append(
                     field.default === undefined
                     $('<div>')
                         ? ''
                        .addClass(
                         : field.default
                            'preload-editor-empty'
                         )
                        .text(
                            'No variables found in the preload.'
                         )
                 );
                 );
            }
        },


             defaultInput.on(
        renderVariablesBySelector() {
                 'input.preloadEditor',
             const container =
                 () => {
                 this.root &&
                     const value =
                 this.root.find(
                        defaultInput.val();
                     '.preload-editor-variables'
                );


                    if (value) {
            if (
                        field.default =
                container &&
                            value;
                container.length
                    } else {
            ) {
                        delete field.default;
                this.renderVariables(container);
                    }
            }
        },


                     this.markConfigDirty();
        selectVariable(name) {
                     this.renderConfigReviewState();
            name =
                }
                String(name || '')
            );
                     .trim()
                     .toUpperCase();


             card.append(
             if (!name) {
                 this.fieldRow(
                 return;
                    'Default',
             }
                    defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
             );


             if (
             const available =
                 field.type === 'textarea'
                 ['PAGE'].concat(
            ) {
                    (
                const maxRows =
                        this.analysis &&
                    this.textInput(
                        this.analysis.variables
                        field.maxRows || ''
                            ? this.analysis.variables
                     ).attr(
                            : []
                         'type',
                     ).filter(
                        'number'
                         variable =>
                     );
                            variable !== 'PAGE'
                     )
                );


                 maxRows.on(
            const configuredUnused =
                    'input.preloadEditor',
                this.state.config &&
                     () => {
                 this.state.config.fields
                         const value =
                    ? Object.keys(
                             parseInt(
                        this.state.config.fields
                                 maxRows.val(),
                     )
                                10
                         .map(
                            );
                             variable =>
                                 variable.toUpperCase()
                        )
                    : [];


                        if (
            configuredUnused.forEach(
                            Number.isFinite(value) &&
                variable => {
                            value > 0
                    if (
                         ) {
                        !available.includes(variable) &&
                            field.maxRows =
                         variable !== 'PAGE'
                                value;
                    ) {
                        } else {
                         available.push(variable);
                            delete field.maxRows;
                        }
 
                        this.markConfigDirty();
                         this.renderConfigReviewState();
                     }
                     }
                 );
                 }
            );


                card.append(
            if (!available.includes(name)) {
                    this.fieldRow(
                 return;
                        'Maximum rows',
                        maxRows
                    )
                 );
             }
             }


             if (
             this.state.selectedVariable =
                 field.type === 'select' ||
                name;
                 field.type === 'multiselect'
 
            this.renderVariablesBySelector();
            this.renderVariableConfigurationBySelector();
        },
 
        renderVariableConfigurationBySelector() {
            const container =
                 this.root &&
                this.root.find(
                    '.preload-editor-variable-configuration'
                 );
 
            if (
                container &&
                container.length
             ) {
             ) {
                 this.renderSelectConfiguration(
                 this.renderVariableConfiguration(
                     card,
                     container
                    field
                 );
                 );
             }
             }
        },


            /*
        renderVariableConfiguration(container) {
            * Large delete button.
             container.empty();
            *
            * PAGE never reaches this function because PAGE uses
            * createAutomaticPageCard().
            */
             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) {
            const analysis =
                            return;
                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];


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


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


            return card;
                        $('<span>')
        },
                            .addClass(
                                'preload-editor-badge is-warning'
                            )
                            .text(
                                'NOT CONFIGURED'
                            )
                    )
                    .appendTo(missing);


        async deleteVariable(name) {
                $('<p>')
            name =
                    .addClass(
                String(name || '')
                        'preload-editor-analysis-note'
                     .trim()
                    )
                     .toUpperCase();
                     .text(
                        'This variable is currently not present in config.json.'
                    )
                     .appendTo(missing);


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


             if (
             container.append(
                 !this.state.config ||
                 this.createVariableCard(
                 !this.state.config.fields
                    name,
             ) {
                    field,
                return;
                    analysis
            }
                 )
             );
        },


             delete this.state.config.fields[name];
        createAutomaticPageCard(field) {
             const card =
                $('<div>')
                    .addClass(
                        'preload-editor-variable preload-editor-variable-automatic'
                    )
                    .attr(
                        'data-variable',
                        'PAGE'
                    );


             if (
             const header =
                 !Array.isArray(
                 $('<div>')
                     this.state.deletedVariables
                     .addClass(
                )
                        'preload-editor-variable-header'
            ) {
                    );
                this.state.deletedVariables = [];
            }


             if (
             header.append(
                 !this.state.deletedVariables.includes(
                 $('<h3>').text('PAGE'),
                    name
                )
            ) {
                this.state.deletedVariables.push(
                    name
                );
            }


            /*
                $('<span>')
            * Keep the deleted variable selected so the user can
                    .addClass(
            * immediately see that it is now unconfigured/deleted.
                        'preload-editor-badge'
            */
                    )
            this.state.selectedVariable =
                    .text('AUTOMATIC')
                name;
            );


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


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


            this.setStatus(
             const label =
                'Variable "' +
                name +
                '" removed from the configuration.',
                'warning'
            );
        },
 
        renderSelectConfiguration(
            card,
            field
        ) {
             const source =
                 this.textInput(
                 this.textInput(
                     field.source || '',
                     field.label ||
                     'category:Example'
                    'Page Name'
                ).prop(
                     'disabled',
                    true
                 );
                 );


             source.on(
             const description =
                'input.preloadEditor',
                this.textarea(
                 () => {
                    field.description ||
                     const value =
                    'Name of the page.'
                        source.val();
                 )
 
                     .addClass(
                     if (value) {
                        'preload-editor-small-textarea'
                        field.source = value;
                     )
                    } else {
                    .prop(
                         delete field.source;
                        'disabled',
                     }
                         true
                     );


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


             card.append(
             const required =
                 this.fieldRow(
                this.checkbox(
                     'Source',
                    field.required !== false
                     source,
                 ).prop(
                    'Currently supported source format: category:Category Name'
                     'disabled',
                 )
                     true
            );
                 );


             const sourcePrefix =
             const namespace =
                 this.textInput(
                 this.textInput(
                     field['source-prefix'] || ''
                     field.namespace || 'Main'
                ).prop(
                    'disabled',
                    true
                 );
                 );


             sourcePrefix.on(
             const allowNew =
                 'input.preloadEditor',
                this.checkbox(
                 () => {
                    field['allow-new'] === true
                    const value =
                 ).prop(
                        sourcePrefix.val();
                    'disabled',
                    true
                );
 
            card.append(
                this.fieldRow(
                    'Label',
                    label
                 ),
 
                this.fieldRow(
                    'Description',
                    description
                ),
 
                this.fieldRow(
                    'Type',
                    type
                ),


                    if (value) {
                this.fieldRow(
                        field['source-prefix'] =
                    'Required',
                            value;
                     required
                     } else {
                ),
                        delete field['source-prefix'];
                    }


                    this.markConfigDirty();
                this.fieldRow(
                     this.renderConfigReviewState();
                     'Namespace',
                 }
                    namespace
            );
                 ),


            card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Source prefix',
                     'Allow new page',
                     sourcePrefix,
                     allowNew
                    'Only source values beginning with this text are included.'
                 )
                 )
             );
             );


             const excludeCategory =
             return card;
                this.textInput(
        },
                    field.exclude &&
                    field.exclude.category ||
                    ''
                );


             excludeCategory.on(
        createVariableCard(
                'input.preloadEditor',
             name,
                 () => {
            field,
                     const value =
            analysis
                         excludeCategory.val();
        ) {
            const card =
                 $('<div>')
                     .addClass(
                         'preload-editor-variable'
                    )
                    .attr(
                        'data-variable',
                        name
                    );


                    if (value) {
            const header =
                        field.exclude =
                $('<div>')
                            Object.assign(
                     .addClass(
                                {},
                         'preload-editor-variable-header'
                                field.exclude || {},
                     );
                                {
                                    category: value
                                }
                            );
                     } else if (
                         field.exclude
                     ) {
                        delete field.exclude.category;


                        if (
            header.append(
                            !Object.keys(
                $('<h3>').text(name)
                                field.exclude
            );
                             ).length
 
                        ) {
            if (
                            delete field.exclude;
                !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.markConfigDirty();
                     this.markDirty();
                     this.renderConfigReviewState();
                     this.renderConfigReviewAvailability();
                 }
                 }
             );
             );
Line 4,704: Line 4,715:
             card.append(
             card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Exclude category',
                     'Label',
                     excludeCategory
                     label
                 )
                 )
             );
             );


            card.append(
             const description =
                this.createTransformControls(
                 this.textarea(
                    field,
                     field.description || ''
                    '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(
                 ).addClass(
                     'preload-editor-small-textarea'
                     'preload-editor-small-textarea'
                 );
                 );


             options.on(
             description.on(
                 'input.preloadEditor',
                 'input.preloadEditor',
                 () => {
                 () => {
                     const lines =
                     field.description =
                         options
                         description.val();
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


                    if (!lines.length) {
                     this.markDirty();
                        delete field.options;
                     this.renderConfigReviewAvailability();
                    } 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.markConfigDirty();
                     this.renderConfigReviewState();
                 }
                 }
             );
             );
Line 4,811: Line 4,740:
             card.append(
             card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Manual options',
                     'Description',
                     options,
                     description
                    'One per line. Optional label format: value | label. Leave empty when using a source.'
                 )
                 )
             );
             );
        },


        createTransformControls(
            const types = [
            field,
                ['text', 'Text'],
            property,
                ['textarea', 'Textarea'],
            title
                ['number', 'Number'],
        ) {
                ['boolean', 'Boolean'],
            const wrapper =
                ['select', 'Select'],
                 $('<div>')
                ['multiselect', 'Multi-select'],
                    .addClass(
                ['page', 'Page'],
                        'preload-editor-transform'
                 ['user', 'User'],
                    );
                ['date', 'Date'],
                ['file', 'File']
            ];


            $('<h4>')
             const typeSelect =
                .text(title)
                .appendTo(wrapper);
 
             const existing =
                field[property] &&
                typeof field[property] === 'object'
                    ? field[property]
                    : {};
 
            const transform =
                 this.select(
                 this.select(
                     [
                     types.map(
                         {
                         ([value, label]) => ({
                            value: '',
                             value,
                            label:
                             label
                                'No transformation'
                         })
                        },
                     ),
                        {
                     field.type || 'text'
                            value:
                 );
                                'remove-prefix',
                            label:
                                'Remove prefix'
                        },
                        {
                             value:
                                'remove-suffix',
                             label:
                                'Remove suffix'
                        },
                        {
                            value: 'replace',
                            label:
                                'Replace'
                         }
                     ],
                     existing.transform || ''
                 );


             const prefix =
             typeSelect.on(
                 this.textInput(
                 'change.preloadEditor',
                     existing.prefix || ''
                () => {
                );
                     field.type =
                        typeSelect.val();


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


             const from =
                    this.renderVariableConfigurationBySelector();
                 this.textInput(
                    this.renderConfigReviewAvailability();
                     existing.from || ''
                }
            );
 
            card.append(
                this.fieldRow(
                    'Type',
                    typeSelect
                )
            );
 
             const required =
                 this.checkbox(
                     field.required === true
                 );
                 );


             const to =
             required.on(
                 this.textInput(
                 'change.preloadEditor',
                     existing.to || ''
                () => {
                );
                     field.required =
                        required.prop('checked');


            const controls =
                    this.markDirty();
                $('<div>')
                     this.renderConfigReviewAvailability();
                     .addClass(
                }
                        'preload-editor-transform-controls'
            );
                    );


             const prefixRow =
             card.append(
                 this.fieldRow(
                 this.fieldRow(
                     'Prefix',
                     'Required',
                     prefix
                     required
                 );
                 )
            );


             const suffixRow =
             const placeholder =
                 this.fieldRow(
                 this.textInput(
                     'Suffix',
                     field.placeholder || ''
                    suffix
                 );
                 );


             const fromRow =
             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(
                 this.fieldRow(
                     'From',
                     'Placeholder',
                     from
                     placeholder
                 );
                 )
            );


             const toRow =
             const defaultInput =
                 this.fieldRow(
                 this.textInput(
                     'To',
                     field.default === undefined
                    to
                        ? ''
                        : field.default
                 );
                 );


             const renderInputs =
             defaultInput.on(
                'input.preloadEditor',
                 () => {
                 () => {
                     const type =
                     const value =
                         transform.val();
                         defaultInput.val();


                     prefixRow.toggle(
                     if (value) {
                         type === 'remove-prefix'
                         field.default =
                     );
                            value;
                     } else {
                        delete field.default;
                    }


                     suffixRow.toggle(
                     this.markDirty();
                        type === 'remove-suffix'
                    this.renderConfigReviewAvailability();
                    );
                }
            );


                    fromRow.toggle(
            card.append(
                        type === 'replace'
                this.fieldRow(
                     );
                    'Default',
                     defaultInput,
                    'For text-like fields this is used as a placeholder. For select fields it is the empty/default option.'
                )
            );


                     toRow.toggle(
            if (
                         type === 'replace'
                field.type === 'textarea'
            ) {
                const maxRows =
                     this.textInput(
                         field.maxRows || ''
                    ).attr(
                        'type',
                        'number'
                     );
                     );
                };


            const update =
                maxRows.on(
                () => {
                    'input.preloadEditor',
                    const type =
                    () => {
                        transform.val();
                        const value =
                            parseInt(
                                maxRows.val(),
                                10
                            );


                    let object = null;
                        if (
                            Number.isFinite(value) &&
                            value > 0
                        ) {
                            field.maxRows =
                                value;
                        } else {
                            delete field.maxRows;
                        }


                    if (
                         this.markDirty();
                        type === 'remove-prefix' &&
                         this.renderConfigReviewAvailability();
                         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) {
                card.append(
                         field[property] = object;
                     this.fieldRow(
                     } else {
                         'Maximum rows',
                        delete field[property];
                        maxRows
                    }
                     )
                );
            }


                    this.markConfigDirty();
            if (
                    this.renderConfigReviewState();
                field.type === 'select' ||
                };
                field.type === 'multiselect'
            ) {
                this.renderSelectConfiguration(
                    card,
                    field
                );
            }


             transform.on(
             if (
                 'change.preloadEditor',
                 field.type === 'file'
                 () => {
            ) {
                     update();
                 this.renderFileConfiguration(
                     renderInputs();
                     card,
                }
                     field
            );
                );
            }


             [
             const deleteButton =
                 prefix,
                 this.createButton(
                suffix,
                    'Delete variable',
                from,
                    'preload-editor-button-danger preload-editor-delete-variable',
                to
                    async () => {
            ].forEach(
                        const confirmed =
                input => {
                            await this.createConfirmDialog(
                    input.on(
                                'Delete variable',
                        'input.preloadEditor',
                                'Delete "' +
                        update
                                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;
                        }


            controls.append(
                        this.deleteVariable(name);
                this.fieldRow(
                     }
                     'Transformation',
                 );
                    transform
                 ),


                 prefixRow,
            card.append(
                suffixRow,
                 $('<div>')
                fromRow,
                    .addClass(
                toRow
                        'preload-editor-variable-delete'
                    )
                    .append(deleteButton)
             );
             );


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


         // ------------------------------------------------------------
         async deleteVariable(name) {
        // Config output / review
            name =
        // ------------------------------------------------------------
                String(name || '')
                    .trim()
                    .toUpperCase();


        getCleanConfig() {
            if (
            const config =
                !name ||
                 JSON.parse(
                 name === 'PAGE'
                    JSON.stringify(
            ) {
                        this.state.config
                 return;
                    )
            }
                 );


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


             const orderedFields = {};
             delete this.state.config.fields[name];


             orderedFields.PAGE =
             if (
                 this.getAutomaticPageField();
                !Array.isArray(
                    this.state.deletedVariables
                )
            ) {
                 this.state.deletedVariables = [];
            }


             Object.keys(fields)
             if (
                 .filter(
                 !this.state.deletedVariables.includes(
                     name =>
                     name
                        name.toUpperCase() !== 'PAGE'
                 )
                 )
                 .forEach(
            ) {
                     name => {
                 this.state.deletedVariables.push(
                        orderedFields[name] =
                     name
                            fields[name];
                    }
                 );
                 );
            }


             config.fields =
             this.state.selectedVariable =
                 orderedFields;
                 name;
 
            this.markDirty();


             return config;
             this.renderVariablesBySelector();
        },
            this.renderVariableConfigurationBySelector();
            this.renderAnalysisBySelector();
            this.renderConfigReviewAvailability();


        getConfigJSON() {
             this.setStatus(
             return JSON.stringify(
                 'Variable "' +
                 this.getCleanConfig(),
                name +
                 null,
                 '" removed from the configuration.',
                 4
                 'warning'
             );
             );
         },
         },


         /*
         // =========================================================
        * Kept as a tiny compatibility helper because other parts
        // Select configuration
        * of the gadget may still call it.
        // =========================================================
        */
 
         renderConfigPreview(container) {
         renderSelectConfiguration(
             if (container) {
            card,
                 container.text(
            field
                     this.getConfigJSON()
        ) {
             const source =
                 this.textInput(
                     field.source || '',
                    'category:Example'
                 );
                 );
            }
        },


        renderConfigPreviewBySelector() {
            source.on(
            this.renderConfigReviewState();
                'input.preloadEditor',
                () => {
                    const value =
                        source.val();


            this.renderAnalysisBySelector();
                    if (value) {
        },
                        field.source = value;
                    } else {
                        delete field.source;
                    }


        renderConfigReviewState() {
                    this.markDirty();
            /*
                    this.renderConfigReviewAvailability();
            * The actual JSON is no longer rendered permanently.
                }
            * The review dialog always reads getConfigJSON() when
            );
            * opened, so it is automatically up to date.
            */
        },


        // ------------------------------------------------------------
            card.append(
        // Save
                this.fieldRow(
        // ------------------------------------------------------------
                    'Source',
                    source,
                    'Currently supported source format: category:Category Name'
                )
            );


        async getSaveTitle() {
             const sourcePrefix =
             let title =
                 this.textInput(
                 String(
                     field['source-prefix'] || ''
                     this.state.preloadTitle || ''
                 );
                 ).trim();


             if (!title) {
             sourcePrefix.on(
                const result =
                'input.preloadEditor',
                    await this.createPromptDialog(
                () => {
                        'Preload title',
                    const value =
                        'Enter the full title for the preload.'
                        sourcePrefix.val();
                    );


                if (!result) {
                    if (value) {
                    return null;
                        field['source-prefix'] =
                }
                            value;
 
                    } else {
                title = result;
                        delete field['source-prefix'];
 
                     }
                this.state.preloadTitle =
                     title;
            }


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


        validateConfigBeforeSave() {
            card.append(
             const errors = [];
                this.fieldRow(
            const warnings = [];
                    'Source prefix',
                    sourcePrefix,
                    'Only source values beginning with this text are included.'
                )
             );


             const title =
             const excludeCategory =
                 String(
                 this.textInput(
                     this.state.preloadTitle || ''
                     field.exclude &&
                 ).trim();
                    field.exclude.category ||
                    ''
                 );


             if (!title) {
             excludeCategory.on(
                 errors.push(
                 'input.preloadEditor',
                     'A preload title is required.'
                () => {
                );
                     const value =
            }
                        excludeCategory.val();


            if (
                    if (value) {
                title &&
                        field.exclude =
                !/\/Preload$/i.test(title)
                            Object.assign(
            ) {
                                {},
                warnings.push(
                                field.exclude || {},
                    'The title does not end with "/Preload".'
                                {
                );
                                    category: value
            }
                                }
                            );
                    } else if (
                        field.exclude
                    ) {
                        delete field.exclude.category;


            /*
                        if (
            * Reanalyze the current editor so config validation
                            !Object.keys(
            * always corresponds to what is currently being edited.
                                field.exclude
            */
                            ).length
            const content =
                        ) {
                this.getEditorContent();
                            delete field.exclude;
                        }
                    }


            const analysis =
                    this.markDirty();
                this.analyzePreload(
                     this.renderConfigReviewAvailability();
                     this.extractIncludeonly(
                 }
                        content
            );
                    )
                 );


             this.state.config =
             card.append(
                 this.prepareConfigForVariables(
                 this.fieldRow(
                     this.state.config ||
                     'Exclude category',
                        this.emptyConfig(),
                     excludeCategory
                     analysis
                 )
                 );
            );


             const validation =
             card.append(
                 this.validateConfig(
                 this.createTransformControls(
                     this.state.config,
                     field,
                     analysis
                    'value',
                 );
                     'Value transformation'
                 ),


            errors.push(
                this.createTransformControls(
                 ...validation.errors
                    field,
                    'label',
                    'Label transformation'
                 )
             );
             );


             warnings.push(
             const optionsValue =
                 ...validation.warnings
                 Array.isArray(field.options)
            );
                    ? field.options
                        .map(
                            option => {
                                if (
                                    typeof option ===
                                    'string'
                                ) {
                                    return option;
                                }


            return {
                                return (
                errors,
                                    String(
                warnings,
                                        option.value || ''
                valid:
                                    ) +
                    errors.length === 0
                                    ' | ' +
            };
                                    String(
        },
                                        option.label ||
                                        option.value ||
                                        ''
                                    )
                                );
                            }
                        )
                        .join('\n')
                    : '';


        async savePreloadOnly() {
             const options =
             const title =
                 this.textarea(
                 await this.getSaveTitle();
                    optionsValue
                ).addClass(
                    'preload-editor-small-textarea'
                );


             if (!title) {
             options.on(
                return;
                'input.preloadEditor',
            }
                () => {
                    const lines =
                        options
                            .val()
                            .split('\n')
                            .map(
                                line =>
                                    line.trim()
                            )
                            .filter(Boolean);


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


            const validation =
                                    if (
                this.validateBeforeSave();
                                        parts.length ===
                                        1
                                    ) {
                                        return parts[0];
                                    }


            if (validation.errors.length) {
                                    return {
                this.showValidationErrors(
                                        value:
                    validation
                                            parts[0],
                );


                this.saveDraft();
                                        label:
                return;
                                            parts
            }
                                                .slice(1)
                                                .join(
                                                    ' | '
                                                )
                                    };
                                }
                            );
                    }


            this.setStatus(
                    this.markDirty();
                'Saving preload...',
                    this.renderConfigReviewAvailability();
                 'loading'
                 }
             );
             );


             try {
             card.append(
                 const exists =
                 this.fieldRow(
                     await this.pageExists(title);
                    'Manual options',
 
                    options,
                 await this.savePage(
                     'One per line. Optional label format: value | label. Leave empty when using a source.'
                    title,
                )
                    this.state.preloadContent,
            );
                     exists
        },
                        ? 'Updated preload with Preload Editor'
       
                        : 'Created preload with Preload Editor',
                 renderFileConfiguration(
                     !exists
            card,
            field
        ) {
            const acceptValue =
                Array.isArray(field.accept)
                     ? field.accept.join('\n')
                    : '';
 
            const accept =
                this.textarea(
                    acceptValue
                ).addClass(
                     'preload-editor-small-textarea'
                 );
                 );


                 this.state.mode = 'edit';
            accept.on(
                this.state.preloadSource =
                 'input.preloadEditor',
                    this.state.preloadContent;
                () => {
                    const values =
                        accept
                            .val()
                            .split('\n')
                            .map(
                                value =>
                                    value.trim()
                            )
                            .filter(Boolean);


                this.state.preloadDirty =
                    if (values.length) {
                     false;
                        field.accept = values;
                     } else {
                        delete field.accept;
                    }


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


                 if (!this.state.dirty) {
            card.append(
                     this.clearDraft(title);
                 this.fieldRow(
                 } else {
                    'Accepted MIME types',
                    this.saveDraft();
                    accept,
                }
                     'One MIME type per line. Example: image/png'
                 )
            );


                 this.setStatus(
            const filename =
                     'Preload saved successfully.',
                 this.textInput(
                     'success'
                     field.filename ||
                     '%%PAGE%%.%%EXT%%'
                 );
                 );


                mw.notify(
            filename.on(
                    'Preload saved.',
                'input.preloadEditor',
                    {
                () => {
                        type: 'success'
                     const value =
                     }
                        filename.val();
                );
 
            } catch (error) {
                    if (value) {
                console.error(
                        field.filename = value;
                     'Preload Editor save:',
                     } else {
                     error
                        delete field.filename;
                );
                     }


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


                 this.setStatus(
            card.append(
                     error.message ||
                 this.fieldRow(
                        'Could not save preload.',
                     'Filename',
                     'error'
                    filename,
                 );
                     'Filename template. %%PAGE%% is replaced with the page name and %%EXT%% with the uploaded file extension.'
                 )
            );


                 mw.notify(
            const filetext =
                     error.message ||
                 this.textarea(
                        'Could not save preload.',
                     field.filetext || ''
                    {
                        type: 'error'
                    }
                 );
                 );
            }
        },


        async saveConfigOnly() {
            filetext.on(
            const title =
                'input.preloadEditor',
                await this.getSaveTitle();
                () => {
                    const value =
                        filetext.val();


            if (!title) {
                    if (value) {
                return;
                        field.filetext = value;
            }
                    } else {
                        delete field.filetext;
                    }


            const validation =
                    this.markDirty();
                this.validateConfigBeforeSave();
                    this.renderConfigReviewAvailability();
                }
            );


             if (validation.errors.length) {
             card.append(
                 this.showValidationErrors(
                 this.fieldRow(
                     validation
                     'File page text',
                );
                     filetext,
 
                     'Wikitext used for the uploaded File: page.'
                this.saveDraft();
                 )
                return;
            }
 
            const configTitle =
                title.replace(
                     /\/+$/,
                     ''
                 ) +
                '/config.json';
 
            this.setStatus(
                'Saving config...',
                'loading'
             );
             );
        },


             try {
        createTransformControls(
                const configExists =
            field,
                     await this.pageExists(
            property,
                         configTitle
             title
        ) {
            const wrapper =
                $('<div>')
                     .addClass(
                         'preload-editor-transform'
                     );
                     );


                await this.savePage(
            $('<h4>')
                    configTitle,
                .text(title)
                    this.getConfigJSON(),
                 .appendTo(wrapper);
                    configExists
                        ? 'Updated preload config with Preload Editor'
                        : 'Created preload config with Preload Editor',
                    !configExists
                 );


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


                 this.updateDirtyState();
            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 || ''
                );


                if (!this.state.dirty) {
            const prefix =
                    this.clearDraft(title);
                 this.textInput(
                } else {
                     existing.prefix || ''
                    this.saveDraft();
                }
 
                 this.setStatus(
                     'Config saved successfully.',
                    'success'
                 );
                 );


                 mw.notify(
            const suffix =
                     'Preload config saved.',
                 this.textInput(
                    {
                     existing.suffix || ''
                        type: 'success'
                    }
                 );
                 );
             } catch (error) {
 
                 console.error(
             const from =
                     'Preload Editor config save:',
                 this.textInput(
                    error
                     existing.from || ''
                 );
                 );


                 this.saveDraft();
            const to =
                 this.textInput(
                    existing.to || ''
                );


                 this.setStatus(
            const controls =
                     error.message ||
                 $('<div>')
                         'Could not save config.',
                     .addClass(
                     'error'
                         'preload-editor-transform-controls'
                );
                     );


                 mw.notify(
            const prefixRow =
                     error.message ||
                 this.fieldRow(
                        'Could not save config.',
                     'Prefix',
                     {
                     prefix
                        type: 'error'
                    }
                 );
                 );
            }
        },


        async saveAll() {
             const suffixRow =
             const title =
                 this.fieldRow(
                 await this.getSaveTitle();
                    'Suffix',
 
                    suffix
            if (!title) {
                 );
                 return;
            }


             this.state.preloadContent =
             const fromRow =
                 this.getEditorContent();
                 this.fieldRow(
                    'From',
                    from
                );


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


             const validation =
             const renderInputs =
                 this.validateBeforeSave();
                 () => {
                    const type =
                        transform.val();


            if (validation.errors.length) {
                    prefixRow.toggle(
                this.showValidationErrors(
                        type === 'remove-prefix'
                     validation
                     );
                );


                this.saveDraft();
                    suffixRow.toggle(
                return;
                        type === 'remove-suffix'
            }
                    );


            const configTitle =
                    fromRow.toggle(
                title.replace(
                        type === 'replace'
                    /\/+$/,
                    );
                    ''
                ) +
                '/config.json';


            this.setStatus(
                    toRow.toggle(
                'Saving preload and config...',
                        type === 'replace'
                 'loading'
                    );
            );
                 };


             try {
             const update =
                const preloadExists =
                () => {
                    await this.pageExists(title);
                    const type =
                        transform.val();


                await this.savePage(
                     let object = null;
                     title,
                    this.state.preloadContent,
                    preloadExists
                        ? 'Updated preload with Preload Editor'
                        : 'Created preload with Preload Editor',
                    !preloadExists
                );


                const configExists =
                    if (
                     await this.pageExists(
                        type === 'remove-prefix' &&
                         configTitle
                        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()
                        };
                    }


                 await this.savePage(
                    if (object) {
                     configTitle,
                        field[property] = object;
                     this.getConfigJSON(),
                    } 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
                     configExists
                         ? 'Updated preload config with Preload Editor'
                         ? 'Updated preload config with Preload Editor'
                         : 'Created preload config with Preload Editor',
                         : 'Created preload config with Preload Editor'
                    !configExists
                 );
                 );
 
 
                 this.state.mode = 'edit';
                 this.state.mode = 'edit';
                 this.state.dirtyPreload = false;
                 this.state.preloadTitle = title;
                this.state.dirtyConfig = false;
 
                 this.state.dirty = false;
                 this.state.preloadSource =
                this.state.preloadTitle = title;
                    this.state.preloadContent;
 
 
                this.clearDraft(title);
                 this.state.preloadDirty =
 
                     false;
                 this.setStatus(
 
                    'Preload and JSON config saved successfully.',
                 this.state.configDirty =
                    'success'
                     false;
                );
 
 
                 this.updateDirtyState();
                mw.notify(
                    'Preload and config saved. config.json is using the JSON content model.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                     error
                );
 
                this.saveDraft();
 
                 this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                     'error'
                );
 
                 mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
        },


                this.clearDraft(title);
        // =========================================================
 
        // Validation
                this.setStatus(
         // =========================================================
                    'Preload and config saved successfully.',
                    'success'
                );
 
                mw.notify(
                    'Preload and config saved.',
                    {
                        type: 'success'
                    }
                );
            } catch (error) {
                console.error(
                    'Preload Editor save:',
                    error
                );
 
                this.saveDraft();
 
                this.setStatus(
                    error.message ||
                        'Could not save preload/config.',
                    'error'
                );
 
                mw.notify(
                    error.message ||
                        'Could not save preload/config.',
                    {
                        type: 'error'
                    }
                );
            }
         },


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


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