diff --git a/CHANGELOG.md b/CHANGELOG.md index b439d92..c98e30c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 5.2.1 (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 `]`). + **Behaviour change:** a shortcode without attributes has no trailing space in its placeholder + title and `?sc=` any more (`[year]`, was `[year ]`), so its default placeholder is one character + narrower. + +### Changed + +- `composer.json` declares the licence as MIT, as `license.md` already did. +- UPGRADING: a fresh Silverstripe 5 install gets simpler 1.x; `~0.2` only keeps an existing 0.2/0.3. + ## 5.2.0 (2026-10-11) ### Changed diff --git a/UPGRADING.md b/UPGRADING.md index e6e59d4..2e07894 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -7,8 +7,13 @@ the `shortcodable_classes` config, and the methods a shortcodable class implemen ### From 4.x on Silverstripe 5 -Change the constraint from `^4` (or `~4.0`) to `^5.1`. Nothing else is required: simpler stays on its -`0.x` line (`~0.2`), and the dialog is loaded the same way as on 4.0.16. +Change the constraint from `^4` (or `~4.0`) to `^5.1`. Nothing else is required. The dialog is loaded +the same way as on 4.0.16. + +simpler is required as `~0.2 || ^1`, and simpler 1.x supports Silverstripe 5 as well as 6 (1.0.0 +requires `silverstripe/framework ^5 || ^6`). So a fresh install on Silverstripe 5, or a `composer +update` that includes simpler, gets simpler 1.x. `~0.2` only lets a project that already has simpler +0.2 or 0.3 keep it. Differences you may notice: diff --git a/client/dist/js/shortcodable.js b/client/dist/js/shortcodable.js index c1053cc..bd4bf4b 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,selectionBookmark:null,selectionWasCollapsed:!1,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.selectionWasCollapsed=tinyMCE.activeEditor.selection.isCollapsed(),shortcodable.selectionBookmark=tinyMCE.activeEditor.selection.getBookmark(2,!0),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.selectionBookmark&&(tinyMCE.activeEditor.selection.moveToBookmark(shortcodable.selectionBookmark),shortcodable.selectionWasCollapsed&&tinyMCE.activeEditor.selection.collapse(!1)),tinyMCE.activeEditor.selection.setContent(r),tinyMCE.activeEditor.undoManager.add(),shortcodable.selectionBookmark=null)},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:()=>{},927:()=>{}},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,547: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))),r.O(void 0,[547,344],(()=>r(459)));var a=r.O(void 0,[547,344],(()=>r(927)));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,selectionBookmark:null,selectionWasCollapsed:!1,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.selectionWasCollapsed=tinyMCE.activeEditor.selection.isCollapsed(),shortcodable.selectionBookmark=tinyMCE.activeEditor.selection.getBookmark(2,!0),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.selectionBookmark&&(tinyMCE.activeEditor.selection.moveToBookmark(shortcodable.selectionBookmark),shortcodable.selectionWasCollapsed&&tinyMCE.activeEditor.selection.collapse(!1)),tinyMCE.activeEditor.selection.setContent(r),tinyMCE.activeEditor.undoManager.add(),shortcodable.selectionBookmark=null)},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:()=>{},218:()=>{}},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,126: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))),r.O(void 0,[126,454],(()=>r(355)));var a=r.O(void 0,[126,454],(()=>r(218)));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 2c047e2..8c2b81f 100644 --- a/client/src/js/shortcodable.js +++ b/client/src/js/shortcodable.js @@ -131,15 +131,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); @@ -168,14 +203,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'); @@ -190,7 +234,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')) + ']'); diff --git a/composer.json b/composer.json index 6d11b3b..3724a5a 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ "wysiwyg", "htmleditor" ], - "license": "BSD-3-Clause", + "license": "MIT", "authors": [ { "name": "Restruct", diff --git a/docs/screens/button.png b/docs/screens/button.png deleted file mode 100644 index eb38121..0000000 Binary files a/docs/screens/button.png and /dev/null differ diff --git a/docs/screens/dialog.png b/docs/screens/dialog.png deleted file mode 100644 index e403a72..0000000 Binary files a/docs/screens/dialog.png and /dev/null differ diff --git a/tests/browser/specs/editor.spec.ts b/tests/browser/specs/editor.spec.ts index f01377e..d7e90e9 100644 --- a/tests/browser/specs/editor.spec.ts +++ b/tests/browser/specs/editor.spec.ts @@ -21,14 +21,16 @@ test.describe('Editor integration', () => { const img = placeholders(page); await expect(img).toHaveCount(1); - await expect(img).toHaveAttribute('title', 'scb_year '); + // No trailing space since #11 (was 'scb_year '). + await expect(img).toHaveAttribute('title', 'scb_year'); await expect(img).toHaveAttribute('src', /^admin\/shortcodable\/placeholder\/scb_year\/\?sc=/); // The placeholder action redirects to placehold.img, which answers an SVG. const response = await svg; expect(response.status()).toBe(200); expect(response.headers()['content-type']).toContain('image/svg+xml'); - // Default size: 46 px high, 60 + fontsize/1.8 per character of "[scb_year ]" wide. - expect(await loadedSize(img)).toEqual({ w: 157, h: 46 }); + // Default size: 46 px high, 60 + fontsize/1.8 per character of "[scb_year]" wide (157 px for + // "[scb_year ]" before #11 dropped the trailing space). + expect(await loadedSize(img)).toEqual({ w: 148, h: 46 }); // The text around it is untouched. await expect(editor(page).locator('body p')).toContainText('Before'); await expect(editor(page).locator('body p')).toContainText('after'); diff --git a/tests/browser/specs/names.spec.ts b/tests/browser/specs/names.spec.ts new file mode 100644 index 0000000..bdfad05 --- /dev/null +++ b/tests/browser/specs/names.spec.ts @@ -0,0 +1,53 @@ +import { test, expect, editor, newPage, openPage, placeholders, save, savedContent } from './support'; + +// Which shortcode names get a placeholder (shortcodable.js shortcodesToPlaceholders). A name is +// what Silverstripe's ShortcodeParser accepts, \w+ (letters, digits, underscore), and it ends at +// whitespace or the closing bracket. Issue #11: the old pattern stopped a name at its first digit, +// so [scb_year2] was taken for [scb_year] with an attribute "2" and saved back as [scb_year 2]. + +test.describe('Shortcode names', () => { + test('[scb_year2] is not mistaken for [scb_year] and is saved unchanged', async ({ page }) => { + const { id } = await newPage(page, '

Text [scb_year2] end

'); + await openPage(page, id); + // Not a registered shortcode: no placeholder. + await expect(placeholders(page)).toHaveCount(0); + + // Edit, so the editor content is serialised again on save. + await editor(page).locator('body p').click(); + await page.keyboard.press('End'); + await page.keyboard.type(' x'); + await save(page, id); + + const content = await savedContent(page, id); + expect(content).toContain('[scb_year2] end x'); + expect(content).not.toContain('[scb_year 2]'); + }); + + test('names with digits get a placeholder; a longer name or a hyphen does not match a shorter one', async ({ page }) => { + const { id } = await newPage(page, '

Plain text

'); + await openPage(page, id); + + // The conversion itself, with a placeholder list that holds a name with a digit (the editor + // gets its list from config; a TinyMCE target carries it in data-config). + const result = await page.evaluate(() => { + const target = document.createElement('div'); + target.setAttribute('data-config', JSON.stringify({ shortcodable_placeholder_codes: ['h2_title', 'button', 'scb_year'] })); + const html = (window as any).shortcodable.shortcodesToPlaceholders( + '

[h2_title] [button-large] [scb_year2] [scb_year] [button id="3" label="Go"]

', + { targetElm: target }, + ); + // Read back in a parsed (inert) document: placeholder images in the live page would be + // fetched from a URL relative to this one and log a 404. + const doc = new DOMParser().parseFromString(html, 'text/html'); + return { + titles: Array.from(doc.querySelectorAll('img.sc-placeholder')).map((img) => img.getAttribute('title')), + text: doc.body.textContent, + }; + }); + + // No trailing space for a shortcode without attributes; one space before the attributes. + expect(result.titles).toEqual(['h2_title', 'scb_year', 'button id="3" label="Go"']); + expect(result.text).toContain('[button-large]'); + expect(result.text).toContain('[scb_year2]'); + }); +}); diff --git a/tests/browser/specs/selection.spec.ts b/tests/browser/specs/selection.spec.ts new file mode 100644 index 0000000..b341d78 --- /dev/null +++ b/tests/browser/specs/selection.spec.ts @@ -0,0 +1,79 @@ +import type { Page } from '@playwright/test'; +import { test, expect, editor, newPage, openDialog, openPage } from './support'; + +// Reading the attributes of a shortcode that is selected as plain text when the dialog is opened +// (shortcodable.js getCurrentEditorSelectionAsParsedShortcodeData). The selection is text typed by +// any CMS editor, so parsing it must never create live elements in the CMS document: attributes +// are data, not markup. + +/** + * Select the text of the Content editor's one paragraph (not the paragraph itself), through + * TinyMCE's own selection API. A keyboard select-all is platform-dependent: Meta+A on macOS selects + * the text, Control+A on Linux (CI) selects the whole

, whose content then does not start with + * '[' and is never parsed, so a spec relying on it passed without testing anything. + */ +async function selectAll(page: Page): Promise { + await editor(page).locator('body p').click(); + await page.evaluate(() => { + const ed = (window as any).tinyMCE.activeEditor; + const text = ed.getBody().querySelector('p').firstChild; + const rng = ed.dom.createRng(); + rng.setStart(text, 0); + rng.setEnd(text, text.length); + ed.selection.setRng(rng); + }); +} + +test.describe('Selected shortcode attributes', () => { + // Unregistered names typed as text. A data: URL that is not an image makes an fail without + // any network request, so on a live element the handler would fire within a tick; the second + // case's src would be fetched from this host. One shortcode per case: the selection is parsed + // as a single shortcode, so a second one in the same text would only add junk attributes. + for (const [label, content] of [ + ['a handler attribute never runs', '

[img src="data:," onerror="window.__scbProbe = 1"]

'], + ['a src is never fetched', '

[img src="/scb-probe-fetch.png"]

'], + ]) { + test(`are read as data: ${label}`, async ({ page }) => { + const { id } = await newPage(page, content); + await openPage(page, id); + + const fetched: string[] = []; + page.on('request', (r) => { + if (r.url().includes('scb-probe-fetch')) { + fetched.push(r.url()); + } + }); + + await selectAll(page); + const posted = new URLSearchParams(await openDialog(page)); + // The selection was parsed at all (else the checks below pass without testing anything). + expect(posted.get('ShortcodeType'), 'the selected shortcode was parsed').toBe('img'); + // Give an error event (and a fetch) time to happen if an element was created. + await page.waitForTimeout(750); + + expect(await page.evaluate(() => (window as any).__scbProbe), 'the onerror attribute did not run').toBeUndefined(); + expect(fetched, 'the src attribute was not fetched').toEqual([]); + }); + } + + test('quoted, unquoted, entity and non-ASCII values are parsed as before', async ({ page }) => { + const { id } = await newPage( + page, + `

[scb_plain title="Two words" single='it is' bare=plain amp="a & b <c>" Mixed="Case" accent="café ü"]

`, + ); + await openPage(page, id); + + await selectAll(page); + const posted = new URLSearchParams(await openDialog(page)); + // Attribute names come out lower-cased, as the HTML attribute parser has always returned them. + expect(Object.fromEntries(posted)).toEqual({ + ShortcodeType: 'scb_plain', + title: 'Two words', + single: 'it is', + bare: 'plain', + amp: 'a & b ', + mixed: 'Case', + accent: 'café ü', + }); + }); +});