Proyectos de Subversion Moodle

Rev

Autoría | Ultima modificación | Ver Log |

{"version":3,"file":"utility.min.js","sources":["../src/utility.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Javascript handling for HTML attributes. This module gets autoloaded on page load.\n *\n * With the appropriate HTML attributes, various functionalities defined in this module can be used such as a displaying\n * an alert or a confirmation modal, etc.\n *\n * @module     core/utility\n * @copyright  2021 Andrew Nicols <andrew@nicols.co.uk>\n * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @since      4.0\n *\n * @example <caption>Calling the confirmation modal to delete a block</caption>\n *\n * // The following is an example of how to use this module via an indirect PHP call with a button.\n *\n * $controls[] = new action_menu_link_secondary(\n *     $deleteactionurl,\n *     new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),\n *     $str,\n *     [\n *         'class' => 'editing_delete',\n *         'data-modal' => 'confirmation', // Needed so this module will pick it up in the click handler.\n *         'data-modal-title-str' => json_encode(['deletecheck_modal', 'block']),\n *         'data-modal-content-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),\n *         'data-modal-yes-button-str' => json_encode(['delete', 'core']),\n *         'data-modal-toast' => 'true', // Can be set to inform the user that their action was a success.\n *         'data-modal-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),\n *         'data-modal-destination' => $deleteconfirmationurl->out(false), // Where do you want to direct the user?\n *     ]\n * );\n */\n\nimport * as Str from 'core/str';\nimport Pending from 'core/pending';\nimport {add as addToast} from 'core/toast';\nimport {saveCancelPromise, deleteCancelPromise, exception} from 'core/notification';\n\n// We want to ensure that we only initialize the listeners only once.\nlet registered = false;\n\n/**\n * Either fetch the string or return it from the dom node.\n *\n * @method getConfirmationString\n * @private\n * @param {HTMLElement} dataset The page element to fetch dataset items in\n * @param {String} type The type of string to fetch\n * @param {String} field The dataset field name to fetch the contents of\n * @param {Array|null} [defaultValue=null] The default params to pass to get_string if no value is found in a dataset\n * @return {Promise}\n *\n */\nconst getModalString = (dataset, type, field, defaultValue = null) => {\n    if (dataset[`${type}${field}Str`]) {\n        return Str.get_string.apply(null, JSON.parse(dataset[`${type}${field}Str`]));\n    }\n    if (dataset[`${type}${field}`]) {\n        return Promise.resolve(dataset[`${type}${field}`]);\n    }\n\n    if (defaultValue) {\n        return Str.get_string.apply(null, defaultValue);\n    }\n\n    return null;\n};\n\n/**\n * Display a save/cancel confirmation.\n *\n * @private\n * @param {HTMLElement} source The title of the confirmation\n * @param {String} type The content of the confirmation\n * @returns {Promise}\n */\nconst displayConfirmation = (source, type) => {\n    let confirmationPromise = null;\n    if (`${type}Type` in source.dataset && source.dataset[`${type}Type`] === 'delete') {\n        confirmationPromise = deleteCancelPromise(\n            getModalString(source.dataset, type, 'Title', ['confirm', 'core']),\n            getModalString(source.dataset, type, 'Content'),\n            getModalString(source.dataset, type, 'YesButton', ['yes', 'core'])\n        );\n    } else {\n        confirmationPromise = saveCancelPromise(\n            getModalString(source.dataset, type, 'Title', ['confirm', 'core']),\n            getModalString(source.dataset, type, 'Content'),\n            getModalString(source.dataset, type, 'YesButton', ['yes', 'core'])\n        );\n    }\n    return confirmationPromise.then(() => {\n        if (source.dataset[`${type}Toast`] === 'true') {\n            const stringForToast = getModalString(source.dataset, type, 'ToastConfirmation');\n            if (typeof stringForToast === \"string\") {\n                addToast(stringForToast);\n            } else {\n                stringForToast.then(str => addToast(str)).catch(e => exception(e));\n            }\n        }\n\n        if (source.dataset[`${type}Destination`]) {\n            window.location.href = source.dataset[`${type}Destination`];\n            return;\n        }\n\n        if (source.closest('form')) {\n            // Update the modal and confirmation data fields so that we don't loop.\n            source.dataset.confirmation = 'none';\n            source.dataset.modal = 'none';\n\n            // Click on the button again.\n            // Note: Do not use the form.submit() because it will not work for cancel buttons.\n            source.click();\n            return;\n        }\n\n        const link = source.closest('a');\n        if (link && link.href && link.href !== '#') {\n            window.location.href = link.href;\n            return;\n        }\n\n        const button = source.closest('button, input[type=\"submit\"], input[type=\"button\"], input[type=\"reset\"]');\n        if (button) {\n            source.dataset.modalSubmitting = true;\n            source.click();\n            return;\n        }\n\n        window.console.error(`No destination found for ${type} modal`);\n        return;\n    }).catch(() => {\n        return;\n    });\n};\n\n/**\n * Display an alert and return the promise from it.\n *\n * @private\n * @param {String} title The title of the alert\n * @param {String} body The content of the alert\n * @returns {Promise<ModalAlert>}\n */\nconst displayAlert = async(title, body) => {\n    const pendingPromise = new Pending('core/confirm:alert');\n    const AlertModal = await import('core/local/modal/alert');\n\n    return AlertModal.create({\n        title,\n        body,\n        removeOnClose: true,\n        show: true,\n    })\n    .then((modal) => {\n        pendingPromise.resolve();\n        return modal;\n    });\n};\n\n/**\n * Set up the listeners for the confirmation modal widget within the page.\n *\n * @method registerConfirmationListeners\n * @private\n */\nconst registerConfirmationListeners = () => {\n    document.addEventListener('click', e => {\n        if (e.target.closest('[data-modal-submitting]')) {\n            return;\n        }\n        const confirmRequest = e.target.closest('[data-confirmation=\"modal\"]');\n        if (confirmRequest) {\n            e.preventDefault();\n            displayConfirmation(confirmRequest, 'confirmation');\n        }\n\n        const modalConfirmation = e.target.closest('[data-modal=\"confirmation\"]');\n        if (modalConfirmation) {\n            e.preventDefault();\n            displayConfirmation(modalConfirmation, 'modal');\n        }\n\n        const alertRequest = e.target.closest('[data-modal=\"alert\"]');\n        if (alertRequest) {\n            e.preventDefault();\n            displayAlert(\n                getModalString(alertRequest.dataset, 'modal', 'Title'),\n                getModalString(alertRequest.dataset, 'modal', 'Content'),\n            );\n        }\n    });\n};\n\nif (!registered) {\n    registerConfirmationListeners();\n    registered = true;\n}\n"],"names":["registered","getModalString","dataset","type","field","defaultValue","Str","get_string","apply","JSON","parse","Promise","resolve","displayConfirmation","source","confirmationPromise","then","stringForToast","str","catch","e","window","location","href","closest","confirmation","modal","click","link","modalSubmitting","console","error","document","addEventListener","target","confirmRequest","preventDefault","modalConfirmation","alertRequest","async","title","body","pendingPromise","Pending","create","removeOnClose","show","displayAlert","registerConfirmationListeners"],"mappings":"iwCAqDIA,YAAa,QAcXC,eAAiB,SAACC,QAASC,KAAMC,WAAOC,oEAAe,YACrDH,kBAAWC,aAAOC,cACXE,IAAIC,WAAWC,MAAM,KAAMC,KAAKC,MAAMR,kBAAWC,aAAOC,gBAE/DF,kBAAWC,aAAOC,QACXO,QAAQC,QAAQV,kBAAWC,aAAOC,SAGzCC,aACOC,IAAIC,WAAWC,MAAM,KAAMH,cAG/B,MAWLQ,oBAAsB,CAACC,OAAQX,YAC7BY,oBAAsB,YAEtBA,oBADA,UAAGZ,eAAcW,OAAOZ,SAA6C,WAAlCY,OAAOZ,kBAAWC,eAC/B,qCAClBF,eAAea,OAAOZ,QAASC,KAAM,QAAS,CAAC,UAAW,SAC1DF,eAAea,OAAOZ,QAASC,KAAM,WACrCF,eAAea,OAAOZ,QAASC,KAAM,YAAa,CAAC,MAAO,WAGxC,mCAClBF,eAAea,OAAOZ,QAASC,KAAM,QAAS,CAAC,UAAW,SAC1DF,eAAea,OAAOZ,QAASC,KAAM,WACrCF,eAAea,OAAOZ,QAASC,KAAM,YAAa,CAAC,MAAO,UAG3DY,oBAAoBC,MAAK,QACW,SAAnCF,OAAOZ,kBAAWC,eAAyB,OACrCc,eAAiBhB,eAAea,OAAOZ,QAASC,KAAM,qBAC9B,iBAAnBc,8BACEA,gBAETA,eAAeD,MAAKE,MAAO,cAASA,OAAMC,OAAMC,IAAK,2BAAUA,QAInEN,OAAOZ,kBAAWC,iCAClBkB,OAAOC,SAASC,KAAOT,OAAOZ,kBAAWC,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