diff --git a/CHANGELOG.md b/CHANGELOG.md index 844cbef..fb47cb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ This file covers the 4.x line (Silverstripe 4 and 5). Later releases are documented on `main`. +## 4.0.18 (2026-11-02) + +### Fixed + +- **The attributes of a shortcode selected in the editor are parsed without creating DOM nodes.** + Opening the dialog on a selected shortcode built it as an element in the CMS document to read its + attributes. They are now parsed in an inert document; values, entities and lower-cased attribute + names come out as before. Upgrading is recommended. +- **Shortcode names with digits are matched whole** (#11). The placeholder pattern stopped a name at + its first digit, so `[year2]` was taken for `[year]` with an attribute `2` and saved back as + `[year 2]`, and a registered name such as `h2_title` got no placeholder. Names are now matched as + Silverstripe's `ShortcodeParser` matches them (`\w+`, ending at whitespace or `]`). A shortcode + without attributes has no trailing space in its placeholder title any more. + ## 4.0.17 ### Fixed diff --git a/client/dist/js/shortcodable.js b/client/dist/js/shortcodable.js index 45713f8..34942b2 100644 --- a/client/dist/js/shortcodable.js +++ b/client/dist/js/shortcodable.js @@ -1 +1 @@ -(()=>{var e,o={448:()=>{var e;e=jQuery,shortcodable={controller_url:"admin/shortcodable",initialized:!1,savedBookmark:null,init:function(){this.initialized=!0,e("body").on("change","select.shortcode-type",(function(o){e.post(shortcodable.controller_url,e(this).parents("form").serializeArray(),(function(o){simpler.modal.bodyHtml=e("#xhr_buffer").html(o).html()})).fail((function(e){shortcodable.handleErrorResponse(e)}))})),e("body").on("submit","#Form_ShortcodeForm",(function(e){return e.preventDefault(),shortcodable.insertShortcode(),simpler.modal.show=!1,!1}))},openDialog:function(){shortcodable.savedBookmark=tinyMCE.activeEditor.selection.isCollapsed()?null:tinyMCE.activeEditor.selection.getBookmark(2),simpler.modal.show=!0,simpler.modal.title="Insert/edit shortcode",simpler.modal.closeBtn=!1,simpler.modal.closeTxt="Close",simpler.modal.saveBtn=!1,simpler.modal.saveTxt="Insert shortcode",simpler.modal.bodyHtml=simpler.spinner,e.post(shortcodable.controller_url,shortcodable.getCurrentEditorSelectionAsParsedShortcodeData(),(function(o){simpler.modal.bodyHtml=e("#xhr_buffer").html(o).html()})).fail((function(e){shortcodable.handleErrorResponse(e)}))},handleErrorResponse:function(e){var o=e.responseText.split('
').pop().split('
').shift()||e.responseText;simpler.modal.bodyHtml='
ERROR loading shortcode (‘'+e.statusText+"’):
"+o},insertShortcode:function(){var o=e("#Form_ShortcodeForm").serializeArray(),t=["..."];e.each(o,(function(e,o){"SecurityID"!==o.name&&("ShortcodeType"===o.name?t[0]=o.value:t.push("".concat(o.name,'="').concat(o.value,'"')))}));var r="[".concat(t.join(" "),"]");r.length&&(shortcodable.savedBookmark&&(tinyMCE.activeEditor.selection.moveToBookmark(shortcodable.savedBookmark),shortcodable.savedBookmark=null),tinyMCE.activeEditor.selection.setContent(r),tinyMCE.activeEditor.undoManager.add())},getCurrentEditorSelectionAsParsedShortcodeData:function(){if(!tinyMCE.activeEditor.selection.isCollapsed()){var o=tinymce.activeEditor.selection.getContent().trim();if(!((o=shortcodable.placeholdersToShortcodes(o,tinyMCE.activeEditor)).length<=2||"["!==o.charAt(0)||"]"!==o.slice(-1))){var t={ShortcodeType:o.slice(1,-1).split(" ").shift()};return e.each(e("<".concat(o.slice(1,-1)," />")).get(0).attributes,(function(e,o){t[o.name]=o.value})),t}}},parseAttributeValue:function(e,o){var t=new RegExp(o+'="([^"]+)"',"g").exec(e);return t?tinymce.DOM.decode(t[1]):""},shortcodesToPlaceholders:function(o,t){var r=e(t.targetElm).data("shortcodableplaceholdercodes");if(!r){var a=e(t.targetElm).attr("data-config");if(a)try{var l=JSON.parse(a);r=l.shortcodable_placeholder_codes}catch(e){console.warn("Could not parse data-config:",e)}}return r?o.replace(/\[([a-z_]+)\s*([^\]]*)\]/gi,(function(o,t,a){if(-1!==r.indexOf(t)){var l=shortcodable.parseAttributeValue(a,"id"),i=encodeURI(shortcodable.controller_url+"/placeholder/"+t+"/"+l+"?sc=["+t+" "+a+"]");return e("").attr("type","image/svg+xml").attr("class","sc-placeholder mceItem mceNonEditable").attr("title",t+" "+a).attr("src",i).prop("outerHTML")}return o})):o},placeholdersToShortcodes:function(o,t){var r=e("
"+o+"
");return r.find(".sc-placeholder").each((function(){var o=e(this);o.replaceWith("["+tinymce.trim(o.attr("title"))+"]")})),r.html()}}},459:()=>{}},t={};function r(e){var a=t[e];if(void 0!==a)return a.exports;var l=t[e]={exports:{}};return o[e](l,l.exports,r),l.exports}r.m=o,e=[],r.O=(o,t,a,l)=>{if(!t){var i=1/0;for(d=0;d=l)&&Object.keys(r.O).every((e=>r.O[e](t[s])))?t.splice(s--,1):(n=!1,l0&&e[d-1][2]>l;d--)e[d]=e[d-1];e[d]=[t,a,l]},r.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),(()=>{var e={906:0,344:0};r.O.j=o=>0===e[o];var o=(o,t)=>{var a,l,[i,n,s]=t,c=0;if(i.some((o=>0!==e[o]))){for(a in n)r.o(n,a)&&(r.m[a]=n[a]);if(s)var d=s(r)}for(o&&o(t);cr(448)));var a=r.O(void 0,[344],(()=>r(459)));a=r.O(a)})(); \ No newline at end of file +(()=>{var e,t={305:()=>{var e;e=jQuery,shortcodable={controller_url:"admin/shortcodable",initialized:!1,savedBookmark:null,init:function(){this.initialized=!0,e("body").on("change","select.shortcode-type",(function(t){e.post(shortcodable.controller_url,e(this).parents("form").serializeArray(),(function(t){simpler.modal.bodyHtml=e("#xhr_buffer").html(t).html()})).fail((function(e){shortcodable.handleErrorResponse(e)}))})),e("body").on("submit","#Form_ShortcodeForm",(function(e){return e.preventDefault(),shortcodable.insertShortcode(),simpler.modal.show=!1,!1}))},openDialog:function(){shortcodable.savedBookmark=tinyMCE.activeEditor.selection.isCollapsed()?null:tinyMCE.activeEditor.selection.getBookmark(2),simpler.modal.show=!0,simpler.modal.title="Insert/edit shortcode",simpler.modal.closeBtn=!1,simpler.modal.closeTxt="Close",simpler.modal.saveBtn=!1,simpler.modal.saveTxt="Insert shortcode",simpler.modal.bodyHtml=simpler.spinner,e.post(shortcodable.controller_url,shortcodable.getCurrentEditorSelectionAsParsedShortcodeData(),(function(t){simpler.modal.bodyHtml=e("#xhr_buffer").html(t).html()})).fail((function(e){shortcodable.handleErrorResponse(e)}))},handleErrorResponse:function(e){var t=e.responseText.split('
').pop().split('
').shift()||e.responseText;simpler.modal.bodyHtml='
ERROR loading shortcode (‘'+e.statusText+"’):
"+t},insertShortcode:function(){var t=e("#Form_ShortcodeForm").serializeArray(),o=["..."];e.each(t,(function(e,t){"SecurityID"!==t.name&&("ShortcodeType"===t.name?o[0]=t.value:o.push("".concat(t.name,'="').concat(t.value,'"')))}));var r="[".concat(o.join(" "),"]");r.length&&(shortcodable.savedBookmark&&(tinyMCE.activeEditor.selection.moveToBookmark(shortcodable.savedBookmark),shortcodable.savedBookmark=null),tinyMCE.activeEditor.selection.setContent(r),tinyMCE.activeEditor.undoManager.add())},getCurrentEditorSelectionAsParsedShortcodeData:function(){if(!tinyMCE.activeEditor.selection.isCollapsed()){var t=tinymce.activeEditor.selection.getContent().trim();if(!((t=shortcodable.placeholdersToShortcodes(t,tinyMCE.activeEditor)).length<=2||"["!==t.charAt(0)||"]"!==t.slice(-1))){var o=t.slice(1,-1).split(" ").shift(),r={ShortcodeType:o};return e.each(shortcodable.parseAttributes(t.slice(1,-1).slice(o.length)),(function(e,t){r[e]=t})),r}}},inertDocument:null,getInertDocument:function(){return shortcodable.inertDocument||(shortcodable.inertDocument=document.implementation.createHTMLDocument("")),shortcodable.inertDocument},parseAttributes:function(t){var o=shortcodable.getInertDocument().createElement("div");o.innerHTML="";var r={},a=o.firstChild;return a&&a.attributes&&e.each(a.attributes,(function(e,t){r[t.name]=t.value})),r},parseAttributeValue:function(e,t){var o=new RegExp(t+'="([^"]+)"',"g").exec(e);return o?tinymce.DOM.decode(o[1]):""},shortcodesToPlaceholders:function(t,o){var r=e(o.targetElm).data("shortcodableplaceholdercodes");if(!r){var a=e(o.targetElm).attr("data-config");if(a)try{var n=JSON.parse(a);r=n.shortcodable_placeholder_codes}catch(e){console.warn("Could not parse data-config:",e)}}return r?t.replace(/\[(\w+)(?:\s+([^\]]*))?\]/g,(function(t,o,a){var n=(a=a||"")?o+" "+a:o;if(-1!==r.indexOf(o)){var l=shortcodable.parseAttributeValue(a,"id"),i=encodeURI(shortcodable.controller_url+"/placeholder/"+o+"/"+l+"?sc=["+n+"]");return e("").attr("type","image/svg+xml").attr("class","sc-placeholder mceItem mceNonEditable").attr("title",n).attr("src",i).prop("outerHTML")}return t})):t},placeholdersToShortcodes:function(t,o){var r=shortcodable.getInertDocument().createElement("div");r.innerHTML=t;var a=e(r);return a.find(".sc-placeholder").each((function(){var t=e(this);t.replaceWith("["+tinymce.trim(t.attr("title"))+"]")})),a.html()}}},355:()=>{}},o={};function r(e){var a=o[e];if(void 0!==a)return a.exports;var n=o[e]={exports:{}};return t[e](n,n.exports,r),n.exports}r.m=t,e=[],r.O=(t,o,a,n)=>{if(!o){var l=1/0;for(d=0;d=n)&&Object.keys(r.O).every((e=>r.O[e](o[s])))?o.splice(s--,1):(i=!1,n0&&e[d-1][2]>n;d--)e[d]=e[d-1];e[d]=[o,a,n]},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={995:0,454:0};r.O.j=t=>0===e[t];var t=(t,o)=>{var a,n,[l,i,s]=o,c=0;if(l.some((t=>0!==e[t]))){for(a in i)r.o(i,a)&&(r.m[a]=i[a]);if(s)var d=s(r)}for(t&&t(o);cr(305)));var a=r.O(void 0,[454],(()=>r(355)));a=r.O(a)})(); \ No newline at end of file diff --git a/client/src/js/shortcodable.js b/client/src/js/shortcodable.js index 26603c0..691f52c 100644 --- a/client/src/js/shortcodable.js +++ b/client/src/js/shortcodable.js @@ -128,15 +128,50 @@ } // Now 'parse' the shortcode attributes by creating it in jQuery as if it's an HTML node; - var shortcodeData = { 'ShortcodeType': selectedTxt.slice(1,-1).split(' ').shift() }; - $.each($(`<${selectedTxt.slice(1,-1)} />`).get(0).attributes, function(index, attr){ - shortcodeData[attr.name] = attr.value + // (no longer in jQuery: $('<...>') builds the element in the live CMS document, where + // an attribute such as onerror runs and a src is fetched. The selection is text any + // CMS editor can type, so it is parsed in an inert document instead, see parseAttributes) + var shortcodeName = selectedTxt.slice(1,-1).split(' ').shift(); + var shortcodeData = { 'ShortcodeType': shortcodeName }; +// $.each($(`<${selectedTxt.slice(1,-1)} />`).get(0).attributes, function(index, attr){ +// shortcodeData[attr.name] = attr.value +// }); + $.each(shortcodable.parseAttributes(selectedTxt.slice(1,-1).slice(shortcodeName.length)), function(name, value){ + shortcodeData[name] = value; }); // console.log('106: ', shortcodeData); return shortcodeData; }, + // An HTML document without a browsing context: elements created in it never run event + // handlers or scripts and never fetch resources. Created once, on first use. + inertDocument: null, + getInertDocument: function() { + if (!shortcodable.inertDocument) { + shortcodable.inertDocument = document.implementation.createHTMLDocument(''); + } + return shortcodable.inertDocument; + }, + + // Parse a shortcode's attribute string (everything after the name, eg ' id="1" title=x') into + // {name: value}. The HTML attribute parser of an inert document does the work, so quoting, + // entities and (lower-cased) names come out exactly as they did when this went through + // jQuery, but nothing in the string can act on the CMS document. A fixed tag name keeps the + // shortcode's own name (which may be 'table', 'tr', ...) out of the parsing. + parseAttributes: function(attrString) { + var wrapper = shortcodable.getInertDocument().createElement('div'); + wrapper.innerHTML = ''; + var attrs = {}; + var el = wrapper.firstChild; + if (el && el.attributes) { + $.each(el.attributes, function(index, attr){ + attrs[attr.name] = attr.value; + }); + } + return attrs; + }, + // get a specific attribute value from a shortcode string by its key, eg 'id' from '[myshortcode id="1" other="etc"] parseAttributeValue: function (string, key) { var attr = new RegExp(key + '=\"([^\"]+)\"', 'g').exec(string); @@ -165,14 +200,23 @@ } if (placeholder_shortcodes) { - return source.replace(/\[([a-z_]+)\s*([^\]]*)\]/gi, function (found, name, params) { + // A name is what ShortcodeParser accepts (\w+) and ends at whitespace or ']' (#11: + // [a-z_]+ followed by \s* stopped a name at its first digit, so [year2] was taken + // for [year] with an attribute '2' and saved back as [year 2]) +// return source.replace(/\[([a-z_]+)\s*([^\]]*)\]/gi, function (found, name, params) { + return source.replace(/\[(\w+)(?:\s+([^\]]*))?\]/g, function (found, name, params) { + // no attributes: params is undefined, and the shortcode text gets no trailing space + params = params || ''; + var shortcodeText = params ? name + ' ' + params : name; if (placeholder_shortcodes.indexOf(name) !== -1) { var id = shortcodable.parseAttributeValue(params, 'id'); - var src = encodeURI(shortcodable.controller_url + '/placeholder/' + name + '/' + id + '?sc=[' + name + ' ' + params + ']'); +// var src = encodeURI(shortcodable.controller_url + '/placeholder/' + name + '/' + id + '?sc=[' + name + ' ' + params + ']'); + var src = encodeURI(shortcodable.controller_url + '/placeholder/' + name + '/' + id + '?sc=[' + shortcodeText + ']'); var el = $('') .attr('type', 'image/svg+xml') .attr('class', 'sc-placeholder mceItem mceNonEditable') - .attr('title', name + ' ' + params) +// .attr('title', name + ' ' + params) + .attr('title', shortcodeText) .attr('src', src); // console.log(el.prop('outerHTML')); return el.prop('outerHTML'); @@ -187,7 +231,12 @@ // Substitutes placeholder images with their shortcode equivalents placeholdersToShortcodes: function(source, editor) { // find & replace .sc-placeholder images in the html - var wrappedContent = $('
' + source + '
'); + // (in an inert document rather than the live CMS one, so nothing in the content can run + // or load while it is rewritten; innerHTML directly, as jQuery's .html() may evaluate scripts) +// var wrappedContent = $('
' + source + '
'); + var wrapper = shortcodable.getInertDocument().createElement('div'); + wrapper.innerHTML = source; + var wrappedContent = $(wrapper); wrappedContent.find('.sc-placeholder').each(function () { var el = $(this); el.replaceWith('[' + tinymce.trim(el.attr('title')) + ']');