From ccdae3e08b5b231e8d8d355f070ee6c0602b8bbd Mon Sep 17 00:00:00 2001 From: Serena Caraco <15524864+SybelBlue@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:48:16 -0800 Subject: [PATCH 1/2] Render toolbar labels with host MathJax --- .changeset/mathjax-toolbar-labels.md | 5 ++ sketch_tool/README.md | 5 ++ sketch_tool/index.html | 11 +++ sketch_tool/lib/toolbar.js | 122 +++++++++++++++++++++++---- sketch_tool/lib/util/zdom.js | 11 +-- sketch_tool/pl-demo.js | 14 +-- 6 files changed, 141 insertions(+), 27 deletions(-) create mode 100644 .changeset/mathjax-toolbar-labels.md diff --git a/.changeset/mathjax-toolbar-labels.md b/.changeset/mathjax-toolbar-labels.md new file mode 100644 index 0000000..102a36b --- /dev/null +++ b/.changeset/mathjax-toolbar-labels.md @@ -0,0 +1,5 @@ +--- +'@prairielearn/sketchresponse': minor +--- + +Render toolbar labels with a host-provided MathJax instance, including dropdown and responsive overflow labels. diff --git a/sketch_tool/README.md b/sketch_tool/README.md index 530cc2b..c84e6bc 100644 --- a/sketch_tool/README.md +++ b/sketch_tool/README.md @@ -47,6 +47,11 @@ You'll need to have [Node.js](http://nodejs.org) and npm (which is now packaged - _coordinates:_ cartesian or polar. - _plugins:_ modules that extend drawing functionality either automatically (for example axes and image) or are placed in the top toolbar (freeform, horizontal and vertical lines) and let the user draw the corresponding shape on the canvas. + Toolbar labels are typeset with a host-provided `window.MathJax` when it exposes + `typesetPromise()`. Labels use the host's configured delimiters and remain plain text when + MathJax is unavailable. For example, a JavaScript label containing inline math can be written as + `label: 'Cubic branch for \\(x < 1\\)'`. + You can also load these additional configurations which show various features of the tool: - allPluginsLatex - initialState diff --git a/sketch_tool/index.html b/sketch_tool/index.html index 2c399a1..b35d5ef 100644 --- a/sketch_tool/index.html +++ b/sketch_tool/index.html @@ -19,6 +19,17 @@ height: 2rem; } + + diff --git a/sketch_tool/lib/toolbar.js b/sketch_tool/lib/toolbar.js index 7f8c530..96e14c7 100644 --- a/sketch_tool/lib/toolbar.js +++ b/sketch_tool/lib/toolbar.js @@ -16,17 +16,6 @@ function renderIcon(id, src, alt) { }); } -function renderLabel(id, text, hasDropdown) { - return z( - 'div.label', - z('span', { id }, text), - z.if( - hasDropdown, - z('span', { 'aria-label': 'Open dropdown menu' }, ' \u25be'), - ), - ); -} - export default class Toolbar { constructor(id, params, app) { this.id = id; @@ -38,6 +27,9 @@ export default class Toolbar { this.focusedItemID = null; this.openDropdownID = null; // TODO: better name this.overflowOpen = false; + this.labelText = new WeakMap(); + this.labelsToTypeset = new Set(); + this.labelTypesetFrame = null; if (!params.readonly) { let resizeFrame; @@ -74,6 +66,92 @@ export default class Toolbar { app.__messageBus.on('closeDropdown', this.closeDropdown.bind(this)); } + clearLabelTypesetting(element) { + this.labelsToTypeset.delete(element); + if (typeof window.MathJax?.typesetClear !== 'function') return; + + try { + window.MathJax.typesetClear([element]); + } catch (error) { + console.error( + 'Unable to clear a SketchResponse toolbar label from MathJax.', + error, + ); + } + } + + queueLabelTypesetting(element) { + this.labelsToTypeset.add(element); + if (this.labelTypesetFrame !== null) return; + + this.labelTypesetFrame = requestAnimationFrame(() => { + this.labelTypesetFrame = null; + const elements = [...this.labelsToTypeset].filter( + (label) => label.isConnected, + ); + this.labelsToTypeset.clear(); + + if ( + elements.length === 0 || + typeof window.MathJax?.typesetPromise !== 'function' + ) { + this.updateOverflow(); + return; + } + + Promise.resolve() + .then(() => window.MathJax.typesetPromise(elements)) + .catch((error) => { + console.error( + 'Unable to typeset SketchResponse toolbar labels with MathJax.', + error, + ); + elements + .filter((label) => label.isConnected) + .forEach((label) => { + this.clearLabelTypesetting(label); + label.textContent = String(this.labelText.get(label)); + }); + }) + .then(() => { + elements + .filter((label) => !label.isConnected) + .forEach((label) => this.clearLabelTypesetting(label)); + this.updateOverflow(); + }); + }); + } + + updateLabel(element, text) { + if (this.labelText.has(element) && this.labelText.get(element) === text) + return; + if (this.labelText.has(element)) this.clearLabelTypesetting(element); + + element.textContent = String(text); + this.labelText.set(element, text); + this.queueLabelTypesetting(element); + } + + renderLabelText(id, text) { + return z('span.mathjax_process', { + id, + onmount: (element) => this.updateLabel(element, text), + onupdate: (element) => this.updateLabel(element, text), + onunmount: (element) => this.clearLabelTypesetting(element), + }); + } + + renderLabel(id, text, hasDropdown) { + return z( + 'div.label', + this.renderLabelText(id, text), + z.if( + hasDropdown, + z('span', { 'aria-label': 'Open dropdown menu' }, ' \u25be'), + ), + ); + } + // Called when the toolbar plugin itself is activated activate() { this.isActive = true; @@ -254,10 +332,18 @@ export default class Toolbar { z.each(items, (item) => { if (item.type === 'splitbutton') { // Flatten tool groups into sections rather than nesting dropdowns. + const headingId = `${this.id}-overflow-${item.id}-heading`; return z( 'div', - { role: 'group', 'aria-label': item.label }, - z('div.si-overflow-heading', item.label), + { + key: item.id, + role: 'group', + 'aria-labelledby': headingId, + }, + z( + 'div.si-overflow-heading', + this.renderLabelText(headingId, item.label), + ), z.each(item.items, (child) => this.renderDropdownButton(child, item.id, true), ), @@ -272,11 +358,13 @@ export default class Toolbar { const id = `${this.id}-${overflow ? 'overflow' : groupId}-${item.id}`; return z( 'div.si-dropdown-item', + { key: item.id }, z( 'button.si-dropdown-button', { id, type: 'button', + 'aria-labelledby': `${id}-label`, ...(overflow ? { 'data-is-active': String(item.id === this.activeItemID), @@ -300,7 +388,7 @@ export default class Toolbar { }, }, renderIcon(`${id}-icon`, item.icon.src, ''), - renderLabel(`${id}-label`, item.label, false), + this.renderLabel(`${id}-label`, item.label, false), ), ); } @@ -322,7 +410,7 @@ export default class Toolbar { onclick: () => this.setOverflowOpen(!this.overflowOpen), }, z('span.icon.si-more-icon', { 'aria-hidden': 'true' }, '⋯'), - renderLabel(`${this.id}-more-label`, 'More', false), + this.renderLabel(`${this.id}-more-label`, 'More', false), ), z('menu.si-dropdown.si-overflow-menu', { id: `${this.id}-overflow-menu`, @@ -390,7 +478,7 @@ export default class Toolbar { type: 'button', }, renderIcon(`${id}-icon`, icon.src, icon.alt), - renderLabel(`${id}-label`, label, hasDropdown), + this.renderLabel(`${id}-label`, label, hasDropdown), ), ), z.if( @@ -426,7 +514,7 @@ export default class Toolbar { 'aria-haspopup': 'true', type: 'button', }, - renderLabel(`${id}-label`, label, hasDropdown), + this.renderLabel(`${id}-label`, label, hasDropdown), ), ), z.if( diff --git a/sketch_tool/lib/util/zdom.js b/sketch_tool/lib/util/zdom.js index f1ea5a9..ca30451 100644 --- a/sketch_tool/lib/util/zdom.js +++ b/sketch_tool/lib/util/zdom.js @@ -159,8 +159,9 @@ class ZElement extends ZNode { } unmount(cleanupDOM) { + if (this.props.onunmount) this.props.onunmount(this.el); + this.childCollection.unmount(false); super.unmount(cleanupDOM); - this.childCollection.unmount(false); // Note: we've already cleaned up DOM elements for them delete this.el; } @@ -180,8 +181,8 @@ class ZElement extends ZNode { Object.keys(newProps) .filter((propName) => oldProps[propName] !== newProps[propName]) .forEach((propName) => { - if (['key', 'onmount'].indexOf(propName) >= 0) return; - if (['key', 'onupdate'].indexOf(propName) >= 0) return; + if (['key', 'onmount', 'onupdate', 'onunmount'].includes(propName)) + return; const { namespaceURI, localName } = qualify(propName); if (localName.slice(0, 2) === 'on' && namespaceURI === null) { @@ -202,8 +203,8 @@ class ZElement extends ZNode { // eslint-disable-next-line no-prototype-builtins .filter((propName) => !newProps.hasOwnProperty(propName)) .forEach((propName) => { - if (['key', 'onmount'].indexOf(propName) >= 0) return; // TODO: eliminate code duplication - if (['key', 'onupdate'].indexOf(propName) >= 0) return; + if (['key', 'onmount', 'onupdate', 'onunmount'].includes(propName)) + return; const { namespaceURI, localName } = qualify(propName); if (localName.slice(0, 2) === 'on' && namespaceURI === null) { diff --git a/sketch_tool/pl-demo.js b/sketch_tool/pl-demo.js index 7163639..e7f8303 100644 --- a/sketch_tool/pl-demo.js +++ b/sketch_tool/pl-demo.js @@ -6,18 +6,22 @@ const config = { enforceBounds: true, plugins: [ { name: 'axes', id: 'axes' }, - { name: 'point', id: 'p' }, + { name: 'point', id: 'p', label: 'Point \\((x, y)\\)' }, { name: 'line-segment', id: 'line' }, { name: 'group', id: 'curves', - label: 'Curves', + label: 'Curves \\(f(x)\\)', plugins: [ - { name: 'polyline', id: 'poly' }, - { name: 'spline', id: 'spline' }, + { name: 'polyline', id: 'poly', label: 'Polyline \\(C_1\\)' }, + { name: 'spline', id: 'spline', label: 'Spline \\(C_2\\)' }, ], }, - { name: 'freeform', id: 'free' }, + { + name: 'freeform', + id: 'free', + label: 'Cubic branch for \\(x < 1\\)', + }, ], }; From 7ef05207d3b7e81add4f4a48676a470eb1c60d0e Mon Sep 17 00:00:00 2001 From: Serena Caraco <15524864+SybelBlue@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:58:29 -0800 Subject: [PATCH 2/2] Simplify to use existing scheme --- .changeset/mathjax-toolbar-labels.md | 2 +- sketch_tool/lib/toolbar.js | 147 ++++++++++----------------- sketch_tool/lib/util/zdom.js | 11 +- 3 files changed, 58 insertions(+), 102 deletions(-) diff --git a/.changeset/mathjax-toolbar-labels.md b/.changeset/mathjax-toolbar-labels.md index 102a36b..42f55d1 100644 --- a/.changeset/mathjax-toolbar-labels.md +++ b/.changeset/mathjax-toolbar-labels.md @@ -1,5 +1,5 @@ --- -'@prairielearn/sketchresponse': minor +"@prairielearn/sketchresponse": minor --- Render toolbar labels with a host-provided MathJax instance, including dropdown and responsive overflow labels. diff --git a/sketch_tool/lib/toolbar.js b/sketch_tool/lib/toolbar.js index 96e14c7..746ce75 100644 --- a/sketch_tool/lib/toolbar.js +++ b/sketch_tool/lib/toolbar.js @@ -16,6 +16,27 @@ function renderIcon(id, src, alt) { }); } +// Labels are immutable after registration, so MathJax can own their contents. +function renderLabelText(id, text) { + return z('span.mathjax_process', { + id, + onmount: (element) => { + element.textContent = String(text); + }, + }); +} + +function renderLabel(id, text, hasDropdown) { + return z( + 'div.label', + renderLabelText(id, text), + z.if( + hasDropdown, + z('span', { 'aria-label': 'Open dropdown menu' }, ' \u25be'), + ), + ); +} + export default class Toolbar { constructor(id, params, app) { this.id = id; @@ -27,8 +48,6 @@ export default class Toolbar { this.focusedItemID = null; this.openDropdownID = null; // TODO: better name this.overflowOpen = false; - this.labelText = new WeakMap(); - this.labelsToTypeset = new Set(); this.labelTypesetFrame = null; if (!params.readonly) { @@ -66,92 +85,27 @@ export default class Toolbar { app.__messageBus.on('closeDropdown', this.closeDropdown.bind(this)); } - clearLabelTypesetting(element) { - this.labelsToTypeset.delete(element); - if (typeof window.MathJax?.typesetClear !== 'function') return; - - try { - window.MathJax.typesetClear([element]); - } catch (error) { - console.error( - 'Unable to clear a SketchResponse toolbar label from MathJax.', - error, - ); - } - } - - queueLabelTypesetting(element) { - this.labelsToTypeset.add(element); - if (this.labelTypesetFrame !== null) return; - + queueLabelTypesetting() { + cancelAnimationFrame(this.labelTypesetFrame); + // The toolbar and its responsive menu render in consecutive frames. this.labelTypesetFrame = requestAnimationFrame(() => { - this.labelTypesetFrame = null; - const elements = [...this.labelsToTypeset].filter( - (label) => label.isConnected, - ); - this.labelsToTypeset.clear(); - - if ( - elements.length === 0 || - typeof window.MathJax?.typesetPromise !== 'function' - ) { - this.updateOverflow(); - return; - } - - Promise.resolve() - .then(() => window.MathJax.typesetPromise(elements)) - .catch((error) => { + this.updateOverflow(); + this.labelTypesetFrame = requestAnimationFrame(async () => { + this.labelTypesetFrame = null; + if (typeof window.MathJax?.typesetPromise !== 'function') return; + try { + await window.MathJax.typesetPromise([this.el]); + this.updateOverflow(); + } catch (error) { console.error( 'Unable to typeset SketchResponse toolbar labels with MathJax.', error, ); - elements - .filter((label) => label.isConnected) - .forEach((label) => { - this.clearLabelTypesetting(label); - label.textContent = String(this.labelText.get(label)); - }); - }) - .then(() => { - elements - .filter((label) => !label.isConnected) - .forEach((label) => this.clearLabelTypesetting(label)); - this.updateOverflow(); - }); - }); - } - - updateLabel(element, text) { - if (this.labelText.has(element) && this.labelText.get(element) === text) - return; - if (this.labelText.has(element)) this.clearLabelTypesetting(element); - - element.textContent = String(text); - this.labelText.set(element, text); - this.queueLabelTypesetting(element); - } - - renderLabelText(id, text) { - return z('span.mathjax_process', { - id, - onmount: (element) => this.updateLabel(element, text), - onupdate: (element) => this.updateLabel(element, text), - onunmount: (element) => this.clearLabelTypesetting(element), + } + }); }); } - renderLabel(id, text, hasDropdown) { - return z( - 'div.label', - this.renderLabelText(id, text), - z.if( - hasDropdown, - z('span', { 'aria-label': 'Open dropdown menu' }, ' \u25be'), - ), - ); - } - // Called when the toolbar plugin itself is activated activate() { this.isActive = true; @@ -217,6 +171,7 @@ export default class Toolbar { } this.items.push(item); this.render(); + this.queueLabelTypesetting(); } openDropdown(id) { @@ -320,51 +275,53 @@ export default class Toolbar { elements.forEach((el, index) => { el.hidden = !visible.has(items[index].id); }); - const overflowItems = items.filter((item) => !visible.has(item.id)); - this.renderOverflowMenu(overflowItems); + // Keep every overflow copy mounted so it only needs to be typeset once. + this.renderOverflowMenu(items, visible); if (fits) this.setOverflowOpen(false); } - renderOverflowMenu(items) { + renderOverflowMenu(items, visible) { const menu = this.el.querySelector('.si-overflow-menu'); z.render( menu, z.each(items, (item) => { + const hidden = visible.has(item.id); if (item.type === 'splitbutton') { // Flatten tool groups into sections rather than nesting dropdowns. - const headingId = `${this.id}-overflow-${item.id}-heading`; return z( 'div', { - key: item.id, role: 'group', - 'aria-labelledby': headingId, + 'aria-label': item.label, + ...(hidden ? { hidden: true } : {}), }, z( 'div.si-overflow-heading', - this.renderLabelText(headingId, item.label), + renderLabelText( + `${this.id}-overflow-${item.id}-heading`, + item.label, + ), ), z.each(item.items, (child) => this.renderDropdownButton(child, item.id, true), ), ); } - return this.renderDropdownButton(item, null, true); + return this.renderDropdownButton(item, null, true, hidden); }), ); } - renderDropdownButton(item, groupId, overflow = false) { + renderDropdownButton(item, groupId, overflow = false, hidden = false) { const id = `${this.id}-${overflow ? 'overflow' : groupId}-${item.id}`; return z( 'div.si-dropdown-item', - { key: item.id }, + hidden ? { hidden: true } : {}, z( 'button.si-dropdown-button', { id, type: 'button', - 'aria-labelledby': `${id}-label`, ...(overflow ? { 'data-is-active': String(item.id === this.activeItemID), @@ -388,7 +345,7 @@ export default class Toolbar { }, }, renderIcon(`${id}-icon`, item.icon.src, ''), - this.renderLabel(`${id}-label`, item.label, false), + renderLabel(`${id}-label`, item.label, false), ), ); } @@ -410,7 +367,7 @@ export default class Toolbar { onclick: () => this.setOverflowOpen(!this.overflowOpen), }, z('span.icon.si-more-icon', { 'aria-hidden': 'true' }, '⋯'), - this.renderLabel(`${this.id}-more-label`, 'More', false), + renderLabel(`${this.id}-more-label`, 'More', false), ), z('menu.si-dropdown.si-overflow-menu', { id: `${this.id}-overflow-menu`, @@ -478,7 +435,7 @@ export default class Toolbar { type: 'button', }, renderIcon(`${id}-icon`, icon.src, icon.alt), - this.renderLabel(`${id}-label`, label, hasDropdown), + renderLabel(`${id}-label`, label, hasDropdown), ), ), z.if( @@ -514,7 +471,7 @@ export default class Toolbar { 'aria-haspopup': 'true', type: 'button', }, - this.renderLabel(`${id}-label`, label, hasDropdown), + renderLabel(`${id}-label`, label, hasDropdown), ), ), z.if( diff --git a/sketch_tool/lib/util/zdom.js b/sketch_tool/lib/util/zdom.js index ca30451..f1ea5a9 100644 --- a/sketch_tool/lib/util/zdom.js +++ b/sketch_tool/lib/util/zdom.js @@ -159,9 +159,8 @@ class ZElement extends ZNode { } unmount(cleanupDOM) { - if (this.props.onunmount) this.props.onunmount(this.el); - this.childCollection.unmount(false); super.unmount(cleanupDOM); + this.childCollection.unmount(false); // Note: we've already cleaned up DOM elements for them delete this.el; } @@ -181,8 +180,8 @@ class ZElement extends ZNode { Object.keys(newProps) .filter((propName) => oldProps[propName] !== newProps[propName]) .forEach((propName) => { - if (['key', 'onmount', 'onupdate', 'onunmount'].includes(propName)) - return; + if (['key', 'onmount'].indexOf(propName) >= 0) return; + if (['key', 'onupdate'].indexOf(propName) >= 0) return; const { namespaceURI, localName } = qualify(propName); if (localName.slice(0, 2) === 'on' && namespaceURI === null) { @@ -203,8 +202,8 @@ class ZElement extends ZNode { // eslint-disable-next-line no-prototype-builtins .filter((propName) => !newProps.hasOwnProperty(propName)) .forEach((propName) => { - if (['key', 'onmount', 'onupdate', 'onunmount'].includes(propName)) - return; + if (['key', 'onmount'].indexOf(propName) >= 0) return; // TODO: eliminate code duplication + if (['key', 'onupdate'].indexOf(propName) >= 0) return; const { namespaceURI, localName } = qualify(propName); if (localName.slice(0, 2) === 'on' && namespaceURI === null) {