From 5446cc3dcd87bdf989edddacd0abbf48324461fb Mon Sep 17 00:00:00 2001 From: David Woloszyn Date: Thu, 6 Jun 2024 15:05:05 +1000 Subject: [PATCH] MDL-81739 tiny_noautolink: Remove URL checking when preventing auto-link --- .../noautolink/amd/build/commands.min.js | 2 +- .../noautolink/amd/build/commands.min.js.map | 2 +- .../noautolink/amd/build/noautolink.min.js | 2 +- .../amd/build/noautolink.min.js.map | 2 +- .../plugins/noautolink/amd/src/commands.js | 3 -- .../plugins/noautolink/amd/src/noautolink.js | 44 +++++-------------- .../noautolink/lang/en/tiny_noautolink.php | 2 +- .../noautolink/tests/behat/noautolink.feature | 31 +++++++++---- 8 files changed, 39 insertions(+), 49 deletions(-) diff --git a/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js b/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js index 3cbabef3507..e7463822055 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js +++ b/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js @@ -1,3 +1,3 @@ -define("tiny_noautolink/commands",["exports","editor_tiny/utils","core/str","tiny_noautolink/common","tiny_noautolink/noautolink"],(function(_exports,_utils,_str,_common,_noautolink){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0;_exports.getSetup=async()=>{const[buttonText,errorInvalidURL,infoEmptySelection,infoAddSuccess,infoRemoveSuccess,buttonImage]=await Promise.all([(0,_str.get_string)("buttontitle",_common.component),(0,_str.get_string)("errorinvalidurl",_common.component),(0,_str.get_string)("infoemptyselection",_common.component),(0,_str.get_string)("infoaddsuccess",_common.component),(0,_str.get_string)("inforemovesuccess",_common.component),(0,_utils.getButtonImage)("icon",_common.component)]);return editor=>{const messages={errorInvalidURL:errorInvalidURL,infoEmptySelection:infoEmptySelection,infoAddSuccess:infoAddSuccess,infoRemoveSuccess:infoRemoveSuccess};editor.ui.registry.addIcon(_common.buttonIcon,buttonImage.html),editor.ui.registry.addToggleButton(_common.buttonName,{icon:_common.buttonIcon,tooltip:buttonText,onAction:()=>{(0,_noautolink.handleAction)(editor,messages)},onSetup:(0,_noautolink.toggleActiveState)(editor)}),editor.ui.registry.addMenuItem(_common.buttonName,{icon:_common.buttonIcon,text:buttonText,onAction:()=>{(0,_noautolink.handleAction)(editor,messages)}})}}})); +define("tiny_noautolink/commands",["exports","editor_tiny/utils","core/str","tiny_noautolink/common","tiny_noautolink/noautolink"],(function(_exports,_utils,_str,_common,_noautolink){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.getSetup=void 0;_exports.getSetup=async()=>{const[buttonText,infoEmptySelection,infoAddSuccess,infoRemoveSuccess,buttonImage]=await Promise.all([(0,_str.get_string)("buttontitle",_common.component),(0,_str.get_string)("infoemptyselection",_common.component),(0,_str.get_string)("infoaddsuccess",_common.component),(0,_str.get_string)("inforemovesuccess",_common.component),(0,_utils.getButtonImage)("icon",_common.component)]);return editor=>{const messages={infoEmptySelection:infoEmptySelection,infoAddSuccess:infoAddSuccess,infoRemoveSuccess:infoRemoveSuccess};editor.ui.registry.addIcon(_common.buttonIcon,buttonImage.html),editor.ui.registry.addToggleButton(_common.buttonName,{icon:_common.buttonIcon,tooltip:buttonText,onAction:()=>{(0,_noautolink.handleAction)(editor,messages)},onSetup:(0,_noautolink.toggleActiveState)(editor)}),editor.ui.registry.addMenuItem(_common.buttonName,{icon:_common.buttonIcon,text:buttonText,onAction:()=>{(0,_noautolink.handleAction)(editor,messages)}})}}})); //# sourceMappingURL=commands.min.js.map \ No newline at end of file diff --git a/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js.map b/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js.map index 5475dd5fc0d..2a0e632317a 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js.map +++ b/lib/editor/tiny/plugins/noautolink/amd/build/commands.min.js.map @@ -1 +1 @@ -{"version":3,"file":"commands.min.js","sources":["../src/commands.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 .\n\nimport {getButtonImage} from 'editor_tiny/utils';\nimport {get_string as getString} from 'core/str';\nimport {component, buttonName, buttonIcon} from 'tiny_noautolink/common';\nimport {handleAction, toggleActiveState} from 'tiny_noautolink/noautolink';\n\n/**\n * Tiny noautolink commands.\n *\n * @module tiny_noautolink/commands\n * @copyright 2023 Meirza \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nexport const getSetup = async() => {\n const [\n buttonText,\n errorInvalidURL,\n infoEmptySelection,\n infoAddSuccess,\n infoRemoveSuccess,\n buttonImage,\n ] = await Promise.all([\n getString('buttontitle', component),\n getString('errorinvalidurl', component),\n getString('infoemptyselection', component),\n getString('infoaddsuccess', component),\n getString('inforemovesuccess', component),\n getButtonImage('icon', component),\n ]);\n\n return (editor) => {\n\n const messages = {\n errorInvalidURL: errorInvalidURL,\n infoEmptySelection: infoEmptySelection,\n infoAddSuccess: infoAddSuccess,\n infoRemoveSuccess: infoRemoveSuccess\n };\n\n // Register the noautolink Icon.\n editor.ui.registry.addIcon(buttonIcon, buttonImage.html);\n\n // Register the noautolink button.\n editor.ui.registry.addToggleButton(buttonName, {\n icon: buttonIcon,\n tooltip: buttonText,\n onAction: () => {\n handleAction(editor, messages);\n },\n onSetup: toggleActiveState(editor),\n });\n\n // Register the noautolink item.\n editor.ui.registry.addMenuItem(buttonName, {\n icon: buttonIcon,\n text: buttonText,\n onAction: () => {\n handleAction(editor, messages);\n },\n });\n };\n};\n"],"names":["async","buttonText","errorInvalidURL","infoEmptySelection","infoAddSuccess","infoRemoveSuccess","buttonImage","Promise","all","component","editor","messages","ui","registry","addIcon","buttonIcon","html","addToggleButton","buttonName","icon","tooltip","onAction","onSetup","addMenuItem","text"],"mappings":"0RA4BwBA,gBAEhBC,WACAC,gBACAC,mBACAC,eACAC,kBACAC,mBACMC,QAAQC,IAAI,EAClB,mBAAU,cAAeC,oBACzB,mBAAU,kBAAmBA,oBAC7B,mBAAU,qBAAsBA,oBAChC,mBAAU,iBAAkBA,oBAC5B,mBAAU,oBAAqBA,oBAC/B,yBAAe,OAAQA,4BAGnBC,eAEEC,SAAW,CACbT,gBAAiBA,gBACjBC,mBAAoBA,mBACpBC,eAAgBA,eAChBC,kBAAmBA,mBAIvBK,OAAOE,GAAGC,SAASC,QAAQC,mBAAYT,YAAYU,MAGnDN,OAAOE,GAAGC,SAASI,gBAAgBC,mBAAY,CAC3CC,KAAMJ,mBACNK,QAASnB,WACToB,SAAU,kCACOX,OAAQC,WAEzBW,SAAS,iCAAkBZ,UAI/BA,OAAOE,GAAGC,SAASU,YAAYL,mBAAY,CACvCC,KAAMJ,mBACNS,KAAMvB,WACNoB,SAAU,kCACOX,OAAQC"} \ No newline at end of file +{"version":3,"file":"commands.min.js","sources":["../src/commands.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 .\n\nimport {getButtonImage} from 'editor_tiny/utils';\nimport {get_string as getString} from 'core/str';\nimport {component, buttonName, buttonIcon} from 'tiny_noautolink/common';\nimport {handleAction, toggleActiveState} from 'tiny_noautolink/noautolink';\n\n/**\n * Tiny noautolink commands.\n *\n * @module tiny_noautolink/commands\n * @copyright 2023 Meirza \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nexport const getSetup = async() => {\n const [\n buttonText,\n infoEmptySelection,\n infoAddSuccess,\n infoRemoveSuccess,\n buttonImage,\n ] = await Promise.all([\n getString('buttontitle', component),\n getString('infoemptyselection', component),\n getString('infoaddsuccess', component),\n getString('inforemovesuccess', component),\n getButtonImage('icon', component),\n ]);\n\n return (editor) => {\n\n const messages = {\n infoEmptySelection: infoEmptySelection,\n infoAddSuccess: infoAddSuccess,\n infoRemoveSuccess: infoRemoveSuccess\n };\n\n // Register the noautolink Icon.\n editor.ui.registry.addIcon(buttonIcon, buttonImage.html);\n\n // Register the noautolink button.\n editor.ui.registry.addToggleButton(buttonName, {\n icon: buttonIcon,\n tooltip: buttonText,\n onAction: () => {\n handleAction(editor, messages);\n },\n onSetup: toggleActiveState(editor),\n });\n\n // Register the noautolink item.\n editor.ui.registry.addMenuItem(buttonName, {\n icon: buttonIcon,\n text: buttonText,\n onAction: () => {\n handleAction(editor, messages);\n },\n });\n };\n};\n"],"names":["async","buttonText","infoEmptySelection","infoAddSuccess","infoRemoveSuccess","buttonImage","Promise","all","component","editor","messages","ui","registry","addIcon","buttonIcon","html","addToggleButton","buttonName","icon","tooltip","onAction","onSetup","addMenuItem","text"],"mappings":"0RA4BwBA,gBAEhBC,WACAC,mBACAC,eACAC,kBACAC,mBACMC,QAAQC,IAAI,EAClB,mBAAU,cAAeC,oBACzB,mBAAU,qBAAsBA,oBAChC,mBAAU,iBAAkBA,oBAC5B,mBAAU,oBAAqBA,oBAC/B,yBAAe,OAAQA,4BAGnBC,eAEEC,SAAW,CACbR,mBAAoBA,mBACpBC,eAAgBA,eAChBC,kBAAmBA,mBAIvBK,OAAOE,GAAGC,SAASC,QAAQC,mBAAYT,YAAYU,MAGnDN,OAAOE,GAAGC,SAASI,gBAAgBC,mBAAY,CAC3CC,KAAMJ,mBACNK,QAASlB,WACTmB,SAAU,kCACOX,OAAQC,WAEzBW,SAAS,iCAAkBZ,UAI/BA,OAAOE,GAAGC,SAASU,YAAYL,mBAAY,CACvCC,KAAMJ,mBACNS,KAAMtB,WACNmB,SAAU,kCACOX,OAAQC"} \ No newline at end of file diff --git a/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js b/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js index 0dae29b7414..e895e9333cc 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js +++ b/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js @@ -5,6 +5,6 @@ define("tiny_noautolink/noautolink",["exports","core/pending"],(function(_export * @module tiny_noautolink/noautolink * @copyright 2023 Meirza * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.toggleActiveState=_exports.handleAction=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};_exports.handleAction=(editor,messages)=>{const toggleState=isInAnchor(editor,editor.selection.getNode()),urlString=getSelectedContent(editor);toggleState||""===urlString?toggleState?unsetNoAutoLink(editor,messages,urlString):editor.notificationManager.open({text:messages.infoEmptySelection,type:"info",timeout:2e3}):setNoAutoLink(editor,messages,urlString)};const setNoAutoLink=(editor,messages,urlString)=>{if(isValidUrl(urlString)){const pendingPromise=new _pending.default("tiny_noautolink/setNoautolink");setNoautolinkOnSelection(editor,urlString).catch((error=>{editor.notificationManager.open({text:error,type:"error",timeout:2e3})})).finally((()=>{editor.notificationManager.open({text:messages.infoAddSuccess,type:"success",timeout:2e3}),pendingPromise.resolve()}))}else editor.notificationManager.open({text:messages.errorInvalidURL,type:"error",timeout:2e3})},unsetNoAutoLink=(editor,messages)=>{const nodeString=editor.selection.getNode().outerHTML.trim(),wrapper=document.createElement("div");wrapper.innerHTML=nodeString;if(wrapper.firstChild.classList.contains("nolink")){const pendingPromise=new _pending.default("tiny_noautolink/setNoautolink");unsetNoautolinkOnSelection(editor,nodeString).catch((error=>{editor.notificationManager.open({text:error,type:"error",timeout:2e3}),pendingPromise.reject(error)})).finally((()=>{editor.notificationManager.open({text:messages.infoRemoveSuccess,type:"success",timeout:2e3}),pendingPromise.resolve()}))}},getSelectedContent=editor=>{const selection=editor.selection;let content=selection.getContent({format:"text"}).trim();if(""==content){const range=selection.getRng();if(range.startContainer.nodeType===Node.TEXT_NODE){const textContent=range.startContainer.textContent,cursorOffset=range.startOffset;let wordStart=cursorOffset;for(;wordStart>0&&/\S/.test(textContent[wordStart-1]);)wordStart--;let wordEnd=cursorOffset;for(;wordEnd{const newContent="<".concat("span",' class="').concat("nolink",'">').concat(url,"");editor.selection.setContent(newContent);const currentNode=editor.selection.getNode(),currentDOM=editor.dom.select("".concat("span",".").concat("nolink"),currentNode);currentDOM.forEach((function(value,index){value.outerHTML!=newContent||editor.selection.select(currentDOM[index])}))},unsetNoautolinkOnSelection=async(editor,url)=>{const regex=new RegExp("]*>"),"g");url=url.replace(regex,"");editor.dom.getParent(editor.selection.getNode(),"span").outerHTML=url},isValidUrl=urlString=>!!new RegExp("^((http|https):\\/\\/|www\\.)((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$","i").test(urlString),isInAnchor=(editor,selectedElm)=>null!==((editor,selectedElm)=>(selectedElm=selectedElm||editor.selection.getNode(),editor.dom.getParent(selectedElm,"".concat("span",".").concat("nolink"))))(editor,selectedElm);_exports.toggleActiveState=editor=>api=>{const updateState=()=>api.setActive(!editor.mode.isReadOnly()&&isInAnchor(editor,editor.selection.getNode()));return updateState(),((editor,toggler)=>(editor.on("NodeChange",toggler),()=>editor.off("NodeChange",toggler)))(editor,updateState)}})); + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.toggleActiveState=_exports.handleAction=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};_exports.handleAction=(editor,messages)=>{const toggleState=isInAnchor(editor,editor.selection.getNode()),urlString=getSelectedContent(editor);toggleState||""===urlString?toggleState?unsetNoAutoLink(editor,messages,urlString):editor.notificationManager.open({text:messages.infoEmptySelection,type:"info",timeout:2e3}):setNoAutoLink(editor,messages,urlString)};const setNoAutoLink=(editor,messages,urlString)=>{const pendingPromise=new _pending.default("tiny_noautolink/setNoautolink");setNoautolinkOnSelection(editor,urlString).catch((error=>{editor.notificationManager.open({text:error,type:"error",timeout:2e3})})).finally((()=>{editor.notificationManager.open({text:messages.infoAddSuccess,type:"success",timeout:2e3}),pendingPromise.resolve()}))},unsetNoAutoLink=(editor,messages)=>{const nodeString=editor.selection.getNode().outerHTML.trim(),wrapper=document.createElement("div");wrapper.innerHTML=nodeString;if(wrapper.firstChild.classList.contains("nolink")){const pendingPromise=new _pending.default("tiny_noautolink/setNoautolink");unsetNoautolinkOnSelection(editor,nodeString).catch((error=>{editor.notificationManager.open({text:error,type:"error",timeout:2e3}),pendingPromise.reject(error)})).finally((()=>{editor.notificationManager.open({text:messages.infoRemoveSuccess,type:"success",timeout:2e3}),pendingPromise.resolve()}))}},getSelectedContent=editor=>{const selection=editor.selection;let content=selection.getContent({format:"text"}).trim();if(""==content){const range=selection.getRng();if(range.startContainer.nodeType===Node.TEXT_NODE){const textContent=range.startContainer.textContent,cursorOffset=range.startOffset;let wordStart=cursorOffset;for(;wordStart>0&&/\S/.test(textContent[wordStart-1]);)wordStart--;let wordEnd=cursorOffset;for(;wordEnd{const newContent="<".concat("span",' class="').concat("nolink",'">').concat(url,"");editor.selection.setContent(newContent);const currentNode=editor.selection.getNode(),currentDOM=editor.dom.select("".concat("span",".").concat("nolink"),currentNode);currentDOM.forEach((function(value,index){value.outerHTML!=newContent||editor.selection.select(currentDOM[index])}))},unsetNoautolinkOnSelection=async(editor,url)=>{const regex=new RegExp("]*>"),"g");url=url.replace(regex,"");editor.dom.getParent(editor.selection.getNode(),"span").outerHTML=url},isInAnchor=(editor,selectedElm)=>null!==((editor,selectedElm)=>(selectedElm=selectedElm||editor.selection.getNode(),editor.dom.getParent(selectedElm,"".concat("span",".").concat("nolink"))))(editor,selectedElm);_exports.toggleActiveState=editor=>api=>{const updateState=()=>api.setActive(!editor.mode.isReadOnly()&&isInAnchor(editor,editor.selection.getNode()));return updateState(),((editor,toggler)=>(editor.on("NodeChange",toggler),()=>editor.off("NodeChange",toggler)))(editor,updateState)}})); //# sourceMappingURL=noautolink.min.js.map \ No newline at end of file diff --git a/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js.map b/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js.map index 06a59883556..4db87a579fe 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js.map +++ b/lib/editor/tiny/plugins/noautolink/amd/build/noautolink.min.js.map @@ -1 +1 @@ -{"version":3,"file":"noautolink.min.js","sources":["../src/noautolink.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 .\n\n/**\n * Helper for Tiny noautolink plugin.\n *\n * @module tiny_noautolink/noautolink\n * @copyright 2023 Meirza \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Pending from 'core/pending';\n\nconst noautolinkClassName = 'nolink';\nconst noautolinkTagHTML = 'span';\nconst notificationTimeout = 2000;\n\n/**\n * Handle action.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n */\nexport const handleAction = (editor, messages) => {\n const toggleState = isInAnchor(editor, editor.selection.getNode());\n const urlString = getSelectedContent(editor);\n if (!toggleState && urlString !== '') {\n setNoAutoLink(editor, messages, urlString);\n } else if (toggleState) {\n unsetNoAutoLink(editor, messages, urlString);\n } else {\n editor.notificationManager.open({text: messages.infoEmptySelection, type: 'info', timeout: notificationTimeout});\n }\n};\n\n/**\n * Display notification feedback when applying the noautolink to the selected text.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n * @param {String} urlString\n */\nconst setNoAutoLink = (editor, messages, urlString) => {\n // Check whether the string is a URL. Otherwise, show an error notification.\n if (isValidUrl(urlString)) {\n const pendingPromise = new Pending('tiny_noautolink/setNoautolink');\n // Applying the auto-link prevention.\n setNoautolinkOnSelection(editor, urlString)\n .catch(error => {\n editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout});\n })\n .finally(() => {\n editor.notificationManager.open({text: messages.infoAddSuccess, type: 'success', timeout: notificationTimeout});\n pendingPromise.resolve();\n });\n } else {\n editor.notificationManager.open({text: messages.errorInvalidURL, type: 'error', timeout: notificationTimeout});\n }\n};\n\n/**\n * Display notification feedback when removing the noautolink to the selected text.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n */\nconst unsetNoAutoLink = (editor, messages) => {\n const nodeString = editor.selection.getNode().outerHTML.trim();\n // Convert HTML string to DOM element to get nolink class.\n const wrapper = document.createElement('div');\n wrapper.innerHTML = nodeString;\n const tempElement = wrapper.firstChild;\n if (tempElement.classList.contains('nolink')) {\n const pendingPromise = new Pending('tiny_noautolink/setNoautolink');\n // Removing the auto-link prevention.\n unsetNoautolinkOnSelection(editor, nodeString)\n .catch(error => {\n editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout});\n pendingPromise.reject(error); // Handle the error as needed.\n })\n .finally(() => {\n editor.notificationManager.open({text: messages.infoRemoveSuccess, type: 'success', timeout: notificationTimeout});\n pendingPromise.resolve();\n });\n }\n};\n\n/**\n * Return the full string based on the position of the cursor within the string.\n *\n * @param {TinyMCE} editor\n * @returns {String}\n */\nconst getSelectedContent = (editor) => {\n const selection = editor.selection; // Get the selection object.\n let content = selection.getContent({format: 'text'}).trim();\n if (content == '') {\n const range = selection.getRng(); // Get the range object.\n\n // Check if the cursor is within a text node.\n if (range.startContainer.nodeType === Node.TEXT_NODE) {\n const textContent = range.startContainer.textContent;\n const cursorOffset = range.startOffset;\n\n // Find the word boundaries around the cursor.\n let wordStart = cursorOffset;\n while (wordStart > 0 && /\\S/.test(textContent[wordStart - 1])) {\n wordStart--;\n }\n\n let wordEnd = cursorOffset;\n while (wordEnd < textContent.length && /\\S/.test(textContent[wordEnd])) {\n wordEnd++;\n }\n\n // Set the selection range to the word.\n selection.setRng({\n startContainer: range.startContainer,\n startOffset: wordStart,\n endContainer: range.startContainer,\n endOffset: wordEnd,\n });\n content = selection.getContent({format: 'text'}).trim();\n }\n }\n return content;\n};\n\n/**\n * Wrap the selection with the nolink class.\n *\n * @param {TinyMCE} editor\n * @param {String} url URL the link will point to.\n */\nconst setNoautolinkOnSelection = async(editor, url) => {\n const newContent = `<${noautolinkTagHTML} class=\"${noautolinkClassName}\">${url}`;\n editor.selection.setContent(newContent);\n\n // Select the new content.\n const currentNode = editor.selection.getNode();\n const currentDOM = editor.dom.select(`${noautolinkTagHTML}.${noautolinkClassName}`, currentNode);\n currentDOM.forEach(function(value, index) {\n if (value.outerHTML == newContent) {\n editor.selection.select(currentDOM[index]);\n return;\n }\n });\n};\n\n/**\n * Remove the nolink on the selection.\n *\n * @param {TinyMCE} editor\n * @param {String} url URL the link will point to.\n */\nconst unsetNoautolinkOnSelection = async(editor, url) => {\n const regex = new RegExp(`]*>`, \"g\");\n url = url.replace(regex, \"\");\n const currentSpan = editor.dom.getParent(editor.selection.getNode(), noautolinkTagHTML);\n currentSpan.outerHTML = url;\n};\n\n/**\n * Check if given string is a valid URL.\n *\n * @param {String} urlString URL the link will point to.\n * @returns {boolean} True is valid, otherwise false.\n */\nconst isValidUrl = urlString => {\n const urlPattern = new RegExp('^((http|https):\\\\/\\\\/|www\\\\.)' + // A URL must have one of these https/https/www.\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // Validate domain name.\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // Validate ip (v4) address.\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // Validate port and path.\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // Validate query string.\n '(\\\\#[-a-z\\\\d_]*)?$', 'i'); // Validate fragment locator.\n\n return !!urlPattern.test(urlString);\n};\n\n/**\n * Get anchor element.\n *\n * @param {TinyMCE} editor\n * @param {Element} selectedElm\n * @returns {Element}\n */\nconst getAnchorElement = (editor, selectedElm) => {\n selectedElm = selectedElm || editor.selection.getNode();\n return editor.dom.getParent(selectedElm, `${noautolinkTagHTML}.${noautolinkClassName}`);\n};\n\n\n/**\n * Check the current selected element is an anchor or not.\n *\n * @param {TinyMCE} editor\n * @param {Element} selectedElm\n * @returns {boolean}\n */\nconst isInAnchor = (editor, selectedElm) => getAnchorElement(editor, selectedElm) !== null;\n\n/**\n * Change state of button.\n *\n * @param {TinyMCE} editor\n * @param {function()} toggler\n * @returns {function()}\n */\nconst toggleState = (editor, toggler) => {\n editor.on('NodeChange', toggler);\n return () => editor.off('NodeChange', toggler);\n};\n\n/**\n * Change the active state of button.\n *\n * @param {TinyMCE} editor\n * @returns {function(*): function(): *}\n */\nexport const toggleActiveState = (editor) => (api) => {\n const updateState = () => api.setActive(!editor.mode.isReadOnly() && isInAnchor(editor, editor.selection.getNode()));\n updateState();\n return toggleState(editor, updateState);\n};"],"names":["editor","messages","toggleState","isInAnchor","selection","getNode","urlString","getSelectedContent","unsetNoAutoLink","notificationManager","open","text","infoEmptySelection","type","timeout","setNoAutoLink","isValidUrl","pendingPromise","Pending","setNoautolinkOnSelection","catch","error","finally","infoAddSuccess","resolve","errorInvalidURL","nodeString","outerHTML","trim","wrapper","document","createElement","innerHTML","firstChild","classList","contains","unsetNoautolinkOnSelection","reject","infoRemoveSuccess","content","getContent","format","range","getRng","startContainer","nodeType","Node","TEXT_NODE","textContent","cursorOffset","startOffset","wordStart","test","wordEnd","length","setRng","endContainer","endOffset","async","url","newContent","setContent","currentNode","currentDOM","dom","select","forEach","value","index","regex","RegExp","replace","getParent","selectedElm","getAnchorElement","api","updateState","setActive","mode","isReadOnly","toggler","on","off"],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"noautolink.min.js","sources":["../src/noautolink.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 .\n\n/**\n * Helper for Tiny noautolink plugin.\n *\n * @module tiny_noautolink/noautolink\n * @copyright 2023 Meirza \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport Pending from 'core/pending';\n\nconst noautolinkClassName = 'nolink';\nconst noautolinkTagHTML = 'span';\nconst notificationTimeout = 2000;\n\n/**\n * Handle action.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n */\nexport const handleAction = (editor, messages) => {\n const toggleState = isInAnchor(editor, editor.selection.getNode());\n const urlString = getSelectedContent(editor);\n if (!toggleState && urlString !== '') {\n setNoAutoLink(editor, messages, urlString);\n } else if (toggleState) {\n unsetNoAutoLink(editor, messages, urlString);\n } else {\n editor.notificationManager.open({text: messages.infoEmptySelection, type: 'info', timeout: notificationTimeout});\n }\n};\n\n/**\n * Display notification feedback when applying the noautolink to the selected text.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n * @param {String} urlString\n */\nconst setNoAutoLink = (editor, messages, urlString) => {\n const pendingPromise = new Pending('tiny_noautolink/setNoautolink');\n // Applying the auto-link prevention.\n setNoautolinkOnSelection(editor, urlString)\n .catch(error => {\n editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout});\n })\n .finally(() => {\n editor.notificationManager.open({text: messages.infoAddSuccess, type: 'success', timeout: notificationTimeout});\n pendingPromise.resolve();\n });\n};\n\n/**\n * Display notification feedback when removing the noautolink to the selected text.\n *\n * @param {TinyMCE} editor\n * @param {object} messages\n */\nconst unsetNoAutoLink = (editor, messages) => {\n const nodeString = editor.selection.getNode().outerHTML.trim();\n // Convert HTML string to DOM element to get nolink class.\n const wrapper = document.createElement('div');\n wrapper.innerHTML = nodeString;\n const tempElement = wrapper.firstChild;\n if (tempElement.classList.contains('nolink')) {\n const pendingPromise = new Pending('tiny_noautolink/setNoautolink');\n // Removing the auto-link prevention.\n unsetNoautolinkOnSelection(editor, nodeString)\n .catch(error => {\n editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout});\n pendingPromise.reject(error); // Handle the error as needed.\n })\n .finally(() => {\n editor.notificationManager.open({text: messages.infoRemoveSuccess, type: 'success', timeout: notificationTimeout});\n pendingPromise.resolve();\n });\n }\n};\n\n/**\n * Return the full string based on the position of the cursor within the string.\n *\n * @param {TinyMCE} editor\n * @returns {String}\n */\nconst getSelectedContent = (editor) => {\n const selection = editor.selection; // Get the selection object.\n let content = selection.getContent({format: 'text'}).trim();\n if (content == '') {\n const range = selection.getRng(); // Get the range object.\n\n // Check if the cursor is within a text node.\n if (range.startContainer.nodeType === Node.TEXT_NODE) {\n const textContent = range.startContainer.textContent;\n const cursorOffset = range.startOffset;\n\n // Find the word boundaries around the cursor.\n let wordStart = cursorOffset;\n while (wordStart > 0 && /\\S/.test(textContent[wordStart - 1])) {\n wordStart--;\n }\n\n let wordEnd = cursorOffset;\n while (wordEnd < textContent.length && /\\S/.test(textContent[wordEnd])) {\n wordEnd++;\n }\n\n // Set the selection range to the word.\n selection.setRng({\n startContainer: range.startContainer,\n startOffset: wordStart,\n endContainer: range.startContainer,\n endOffset: wordEnd,\n });\n content = selection.getContent({format: 'text'}).trim();\n }\n }\n return content;\n};\n\n/**\n * Wrap the selection with the nolink class.\n *\n * @param {TinyMCE} editor\n * @param {String} url URL the link will point to.\n */\nconst setNoautolinkOnSelection = async(editor, url) => {\n const newContent = `<${noautolinkTagHTML} class=\"${noautolinkClassName}\">${url}`;\n editor.selection.setContent(newContent);\n\n // Select the new content.\n const currentNode = editor.selection.getNode();\n const currentDOM = editor.dom.select(`${noautolinkTagHTML}.${noautolinkClassName}`, currentNode);\n currentDOM.forEach(function(value, index) {\n if (value.outerHTML == newContent) {\n editor.selection.select(currentDOM[index]);\n return;\n }\n });\n};\n\n/**\n * Remove the nolink on the selection.\n *\n * @param {TinyMCE} editor\n * @param {String} url URL the link will point to.\n */\nconst unsetNoautolinkOnSelection = async(editor, url) => {\n const regex = new RegExp(`]*>`, \"g\");\n url = url.replace(regex, \"\");\n const currentSpan = editor.dom.getParent(editor.selection.getNode(), noautolinkTagHTML);\n currentSpan.outerHTML = url;\n};\n\n/**\n * Get anchor element.\n *\n * @param {TinyMCE} editor\n * @param {Element} selectedElm\n * @returns {Element}\n */\nconst getAnchorElement = (editor, selectedElm) => {\n selectedElm = selectedElm || editor.selection.getNode();\n return editor.dom.getParent(selectedElm, `${noautolinkTagHTML}.${noautolinkClassName}`);\n};\n\n\n/**\n * Check the current selected element is an anchor or not.\n *\n * @param {TinyMCE} editor\n * @param {Element} selectedElm\n * @returns {boolean}\n */\nconst isInAnchor = (editor, selectedElm) => getAnchorElement(editor, selectedElm) !== null;\n\n/**\n * Change state of button.\n *\n * @param {TinyMCE} editor\n * @param {function()} toggler\n * @returns {function()}\n */\nconst toggleState = (editor, toggler) => {\n editor.on('NodeChange', toggler);\n return () => editor.off('NodeChange', toggler);\n};\n\n/**\n * Change the active state of button.\n *\n * @param {TinyMCE} editor\n * @returns {function(*): function(): *}\n */\nexport const toggleActiveState = (editor) => (api) => {\n const updateState = () => api.setActive(!editor.mode.isReadOnly() && isInAnchor(editor, editor.selection.getNode()));\n updateState();\n return toggleState(editor, updateState);\n};\n"],"names":["editor","messages","toggleState","isInAnchor","selection","getNode","urlString","getSelectedContent","unsetNoAutoLink","notificationManager","open","text","infoEmptySelection","type","timeout","setNoAutoLink","pendingPromise","Pending","setNoautolinkOnSelection","catch","error","finally","infoAddSuccess","resolve","nodeString","outerHTML","trim","wrapper","document","createElement","innerHTML","firstChild","classList","contains","unsetNoautolinkOnSelection","reject","infoRemoveSuccess","content","getContent","format","range","getRng","startContainer","nodeType","Node","TEXT_NODE","textContent","cursorOffset","startOffset","wordStart","test","wordEnd","length","setRng","endContainer","endOffset","async","url","newContent","setContent","currentNode","currentDOM","dom","select","forEach","value","index","regex","RegExp","replace","getParent","selectedElm","getAnchorElement","api","updateState","setActive","mode","isReadOnly","toggler","on","off"],"mappings":"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"} \ No newline at end of file diff --git a/lib/editor/tiny/plugins/noautolink/amd/src/commands.js b/lib/editor/tiny/plugins/noautolink/amd/src/commands.js index 5912dea3da1..4d0d748a483 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/src/commands.js +++ b/lib/editor/tiny/plugins/noautolink/amd/src/commands.js @@ -29,14 +29,12 @@ import {handleAction, toggleActiveState} from 'tiny_noautolink/noautolink'; export const getSetup = async() => { const [ buttonText, - errorInvalidURL, infoEmptySelection, infoAddSuccess, infoRemoveSuccess, buttonImage, ] = await Promise.all([ getString('buttontitle', component), - getString('errorinvalidurl', component), getString('infoemptyselection', component), getString('infoaddsuccess', component), getString('inforemovesuccess', component), @@ -46,7 +44,6 @@ export const getSetup = async() => { return (editor) => { const messages = { - errorInvalidURL: errorInvalidURL, infoEmptySelection: infoEmptySelection, infoAddSuccess: infoAddSuccess, infoRemoveSuccess: infoRemoveSuccess diff --git a/lib/editor/tiny/plugins/noautolink/amd/src/noautolink.js b/lib/editor/tiny/plugins/noautolink/amd/src/noautolink.js index 37e5814bf69..d77b64e9143 100644 --- a/lib/editor/tiny/plugins/noautolink/amd/src/noautolink.js +++ b/lib/editor/tiny/plugins/noautolink/amd/src/noautolink.js @@ -53,21 +53,16 @@ export const handleAction = (editor, messages) => { * @param {String} urlString */ const setNoAutoLink = (editor, messages, urlString) => { - // Check whether the string is a URL. Otherwise, show an error notification. - if (isValidUrl(urlString)) { - const pendingPromise = new Pending('tiny_noautolink/setNoautolink'); - // Applying the auto-link prevention. - setNoautolinkOnSelection(editor, urlString) - .catch(error => { - editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout}); - }) - .finally(() => { - editor.notificationManager.open({text: messages.infoAddSuccess, type: 'success', timeout: notificationTimeout}); - pendingPromise.resolve(); - }); - } else { - editor.notificationManager.open({text: messages.errorInvalidURL, type: 'error', timeout: notificationTimeout}); - } + const pendingPromise = new Pending('tiny_noautolink/setNoautolink'); + // Applying the auto-link prevention. + setNoautolinkOnSelection(editor, urlString) + .catch(error => { + editor.notificationManager.open({text: error, type: 'error', timeout: notificationTimeout}); + }) + .finally(() => { + editor.notificationManager.open({text: messages.infoAddSuccess, type: 'success', timeout: notificationTimeout}); + pendingPromise.resolve(); + }); }; /** @@ -172,23 +167,6 @@ const unsetNoautolinkOnSelection = async(editor, url) => { currentSpan.outerHTML = url; }; -/** - * Check if given string is a valid URL. - * - * @param {String} urlString URL the link will point to. - * @returns {boolean} True is valid, otherwise false. - */ -const isValidUrl = urlString => { - const urlPattern = new RegExp('^((http|https):\\/\\/|www\\.)' + // A URL must have one of these https/https/www. - '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // Validate domain name. - '((\\d{1,3}\\.){3}\\d{1,3}))' + // Validate ip (v4) address. - '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // Validate port and path. - '(\\?[;&a-z\\d%_.~+=-]*)?' + // Validate query string. - '(\\#[-a-z\\d_]*)?$', 'i'); // Validate fragment locator. - - return !!urlPattern.test(urlString); -}; - /** * Get anchor element. * @@ -233,4 +211,4 @@ export const toggleActiveState = (editor) => (api) => { const updateState = () => api.setActive(!editor.mode.isReadOnly() && isInAnchor(editor, editor.selection.getNode())); updateState(); return toggleState(editor, updateState); -}; \ No newline at end of file +}; diff --git a/lib/editor/tiny/plugins/noautolink/lang/en/tiny_noautolink.php b/lib/editor/tiny/plugins/noautolink/lang/en/tiny_noautolink.php index e142ff65222..03e635b94d1 100644 --- a/lib/editor/tiny/plugins/noautolink/lang/en/tiny_noautolink.php +++ b/lib/editor/tiny/plugins/noautolink/lang/en/tiny_noautolink.php @@ -26,7 +26,7 @@ $string['buttontitle'] = 'No auto-link'; $string['errorinvalidurl'] = 'The selected content is not a URL. Please try again.'; $string['helplinktext'] = 'No auto-link helper'; $string['infoaddsuccess'] = 'Auto-link prevention added.'; -$string['infoemptyselection'] = 'Select a URL and try again.'; +$string['infoemptyselection'] = 'Select text and try again.'; $string['inforemovesuccess'] = 'Auto-link prevention removed.'; $string['pluginname'] = 'Tiny no auto-link'; $string['privacy:metadata'] = 'The tiny_noautolink plugin does not store any personal data.'; diff --git a/lib/editor/tiny/plugins/noautolink/tests/behat/noautolink.feature b/lib/editor/tiny/plugins/noautolink/tests/behat/noautolink.feature index b72297ea217..dc34b9f3122 100644 --- a/lib/editor/tiny/plugins/noautolink/tests/behat/noautolink.feature +++ b/lib/editor/tiny/plugins/noautolink/tests/behat/noautolink.feature @@ -1,21 +1,36 @@ @editor @editor_tiny @tiny_noautolink Feature: Tiny noautolink - To avoid auto-linking, users need to wrap the URL with the 'nolink' class. + In order to prevent auto-linking in TinyMCE + As a User + I need be able to apply the auto-link prevention feature to the selected text - @javascript - Scenario: Insert a link, add and remove the auto-link prevention + Background: Given I log in as "admin" And I navigate to "Plugins > Text editors > TinyMCE editor > General settings" in site administration And I click on "Enable Tiny no auto-link" "link" - When I open my profile in edit mode - And I set the field "Description" to "

https://moodle.org

" + @javascript + Scenario: Add and remove auto-link prevention to URLs + Given I open my profile in edit mode + And I set the field "Description" to "

https://moodle.org

" # Add auto-link prevention. And I select the "p" element in position "0" of the "Description" TinyMCE editor - And I click on the "No auto-link" button for the "Description" TinyMCE editor + When I click on the "No auto-link" button for the "Description" TinyMCE editor Then the field "Description" matches value "

https://moodle.org

" - # Remove auto-link prevention. And I select the "span" element in position "0" of the "Description" TinyMCE editor And I click on the "No auto-link" button for the "Description" TinyMCE editor - Then the field "Description" matches value "

https://moodle.org

" + And the field "Description" matches value "

https://moodle.org

" + + @javascript + Scenario: Add and remove auto-link prevention to simple text + Given I open my profile in edit mode + And I set the field "Description" to "Some text" + # Add auto-link prevention. + And I select the "p" element in position "0" of the "Description" TinyMCE editor + When I click on the "No auto-link" button for the "Description" TinyMCE editor + Then the field "Description" matches value "

Some text

" + # Remove auto-link prevention. + And I select the "span" element in position "0" of the "Description" TinyMCE editor + And I click on the "No auto-link" button for the "Description" TinyMCE editor + And the field "Description" matches value "

Some text

"