Jump to content

User:L235/formFiller.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by L235 (talk | contribs) at 20:41, 23 May 2025 (update). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/*  Configurable BlankPage Form User‑script
    -------------------------------------------------
    This script reads its behaviour from a JSON page (for now
    [[User:L235/form-config.json]]).  Each entry in the JSON defines:
      • which page the form appears on (formPage) – OR use the object‑key form
      • which questions to render (questions[])
      • the page to append to (targetPage)
      • the template to insert (+ whether to subst)

    JSON can be structured two ways – pick whichever you like:

    1. OBJECT keyed by the form page title (simplest):
    {
      "Special:BlankPage/form": {
        "targetPage": "User:L235/sandbox2",
        "template": { "name": "User:L235/TestTemplate", "subst": true },
        "questions": [ ... ],
        "editSummary": "Append answers via BlankPage/form"
      },
      "Special:BlankPage/animals": {
        "targetPage": "User:L235/animals",
        "template": { "name": "User:L235/AnimalTemplate", "subst": false },
		"questions": [
			{ "label": "Question A:", "name": "q1", "type": "text",      "required": false, "templateParam": "1" },
			{ "label": "Question B:", "name": "q2", "type": "textarea",  "required": true,  "templateParam": "2" },
			{ "label": "Question C:", "name": "q3", "type": "dropdown", "required": false, "options": ["i) apples", "ii) bananas"], "templateParam": "3" },
			{ "label": "Question D:", "name": "q4", "type": "checkbox", "required": false, "options": ["cats", "dogs"], "templateParam": "4" },
			{ "label": "Question E:", "name": "q5", "type": "radio",    "required": true,  "options": ["noun", "verb"], "templateParam": "5" },
			{ "label": "Section title:", "name": "q6", "type": "text",  "required": true,  "templateParam": "6" }
		]
      }
    }

    2. ARRAY of objects:
    [
      {
        "formPage": "Special:BlankPage/form",
        "targetPage": "User:L235/sandbox2",
        "template": { "name": "User:L235/TestTemplate", "subst": true },
        "questions": [ ... ]
      },
      {
        "formPage": "Special:BlankPage/animals",
        "targetPage": "User:L235/animals",
        "template": { "name": "User:L235/AnimalTemplate", "subst": true },
		"questions": [
			{ "label": "Question A:", "name": "q1", "type": "text",      "required": false, "templateParam": "1" },
			{ "label": "Question B:", "name": "q2", "type": "textarea",  "required": true,  "templateParam": "2" },
			{ "label": "Question C:", "name": "q3", "type": "dropdown", "required": false, "options": ["i) apples", "ii) bananas"], "templateParam": "3" },
			{ "label": "Question D:", "name": "q4", "type": "checkbox", "required": false, "options": ["cats", "dogs"], "templateParam": "4" },
			{ "label": "Question E:", "name": "q5", "type": "radio",    "required": true,  "options": ["noun", "verb"], "templateParam": "5" },
			{ "label": "Section title:", "name": "q6", "type": "text",  "required": true,  "templateParam": "6" }
		]
      }
    ]

    The **questions** array is the same as before; see the first script for field
    options.  Required fields must set "required": true.

    -------------------------------------------------
    Save this file as User:<you>/blankpage‑multi‑form.js and import it from your
    common.js.  Make sure your JSON lives at the path in CONFIG_PAGE below.
*/
/* global mw, $ */
(function () {
    var CONFIG_PAGE = 'User:L235/form-config.json';

    mw.loader.using(['mediawiki.api', 'oojs-ui']).then(function () {
        var api = new mw.Api();

        /* ---------- 1. Load JSON config ------------------------------ */
        api.get({
            action: 'query',
            prop: 'revisions',
            titles: CONFIG_PAGE,
            rvprop: 'content',
            formatversion: 2
        }).then(function (data) {
            var pages = data.query.pages;
            if (!pages.length || !pages[0].revisions) {
                console.error('[MultiForm] Config page missing or empty');
                return;
            }
            var raw = pages[0].revisions[0].content;
            var cfg;
            try {
                cfg = JSON.parse(raw);
            } catch (e) {
                console.error('[MultiForm] JSON parse error:', e);
                return;
            }

            var current = mw.config.get('wgPageName').replace(/_/g, ' ');
            var formCfg = findMatchingForm(cfg, current);
            if (!formCfg) {
                return; // not a configured form page – exit silently
            }

            buildForm(formCfg);
        }).fail(function (err) {
            console.error('[MultiForm] API error:', err);
        });

        function findMatchingForm(cfg, pageTitle) {
            // OBJECT form – key is the form page
            if (!Array.isArray(cfg)) {
                if (cfg[pageTitle]) {
                    return cfg[pageTitle];
                }
                // maybe keys are something else; scan values for .formPage
                for (var key in cfg) {
                    if (cfg.hasOwnProperty(key) && cfg[key].formPage === pageTitle) {
                        return cfg[key];
                    }
                }
            } else {
                // ARRAY style
                for (var i = 0; i < cfg.length; i++) {
                    if (cfg[i].formPage === pageTitle) {
                        return cfg[i];
                    }
                }
            }
            return null;
        }

        /* ---------- 2. Render form ----------------------------------- */
        function buildForm(config) {
            var $content = $('#mw-content-text').empty();
            $content.append($('<h2>').text(config.title || 'Submit your answers'));

            var $form = $('<form>').appendTo($content);

            config.questions.forEach(function (q) {
                renderQuestion($form, q);
                $form.append('<br><br>');
            });

            var $submit = $('<input>').attr({ type: 'submit', value: 'Submit' });
            $form.append($submit);

            $form.on('submit', function (e) {
                e.preventDefault();
                handleSubmit($form, config, $submit);
            });
        }

        function renderQuestion($form, q) {
            var $label = $('<label>').text(q.label + (q.required ? ' (required): ' : ': '));
            var $field;
            switch (q.type) {
                case 'text':
                    $field = $('<input>').attr({ type: 'text', name: q.name, size: 40 });
                    break;
                case 'textarea':
                    $field = $('<textarea>').attr({ name: q.name, rows: 4, cols: 60 });
                    break;
                case 'dropdown':
                    $field = $('<select>').attr('name', q.name);
                    q.options.forEach(function (opt) {
                        $field.append($('<option>').val(opt).text(opt));
                    });
                    break;
                case 'checkbox':
                    $field = $('<span>');
                    q.options.forEach(function (opt) {
                        var $l = $('<label>');
                        $l.append($('<input>').attr({ type: 'checkbox', name: q.name, value: opt }), ' ', opt, '\u00A0');
                        $field.append($l);
                    });
                    break;
                case 'radio':
                    $field = $('<span>');
                    q.options.forEach(function (opt, idx) {
                        var $l = $('<label>');
                        $l.append($('<input>').attr({
                            type: 'radio', name: q.name, value: opt,
                            required: q.required && idx === 0
                        }), ' ', opt, '\u00A0');
                        $field.append($l);
                    });
                    break;
                default:
                    console.warn('[MultiForm] Unsupported field type:', q.type);
                    return;
            }
            if (q.required && q.type !== 'radio') {
                $field.attr('required', true);
            }
            $form.append($label.append($field));
        }

        /* ---------- 3. Submission ------------------------------------ */
        function getValue($form, q) {
            switch (q.type) {
                case 'checkbox':
                    return $form.find('[name=' + q.name + ']:checked').map(function () {
                        return this.value;
                    }).get().join(', ');
                case 'radio':
                    return $form.find('[name=' + q.name + ']:checked').val() || '';
                default:
                    return $form.find('[name=' + q.name + ']').val().trim();
            }
        }

        function handleSubmit($form, config, $submit) {
            var missing = config.questions.filter(function (q) {
                return q.required && !getValue($form, q);
            });
            if (missing.length) {
                alert('Please fill required fields: ' + missing.map(function (q) {
                    return q.label.replace(/:\s*$/, '');
                }).join(', '));
                return;
            }

            var params = config.questions.map(function (q) {
                return '|' + q.templateParam + '=' + getValue($form, q);
            }).join('');

            var tplName = config.template.name || config.template;
            if (config.template.subst) tplName = 'subst:' + tplName;

            var wikitext = '\n{{' + tplName + params + '}}\n';

            $submit.prop('disabled', true).val('Submitting…');

            api.postWithToken('csrf', {
                action: 'edit',
                title: config.targetPage,
                appendtext: wikitext,
                summary: config.editSummary || 'Append answers via multi‑form script'
            }).done(function () {
                mw.notify('Saved!', { type: 'success' });
                $form[0].reset();
            }).fail(function (err) {
                console.error('[MultiForm] Edit error:', err);
                mw.notify('Error: ' + err, { type: 'error', autoHide: false });
            }).always(function () {
                $submit.prop('disabled', false).val('Submit');
            });
        }
    });
})();