From 0d5bf47f53970457e7ad77c185626bbb806c62ae Mon Sep 17 00:00:00 2001 From: rtibblesbot Date: Sun, 29 Nov 2026 18:34:43 +0000 Subject: [PATCH 1/2] Carry MathML through TipTap and report unedited content as loaded - Math nodes keep stored MathML in a `mathml` attribute and restore it on save - An editor whose content matches what it loaded reports the loaded value - An image's size is saved only by the author's insert, replacement or resize - Add `schemaKeepsContent` to check whether TipTap's schema keeps a field's markup - Code blocks keep their newlines when content loads Co-Authored-By: Claude Opus 5.5 --- .../TipTapEditor/TipTapEditor.vue | 58 +- .../components/image/ImageNodeView.vue | 262 ++-- .../components/image/ImageUploadModal.vue | 16 +- .../components/math/FormulasMenu.vue | 8 +- .../components/math/LazyMathNodeView.vue | 75 +- .../components/math/MathNodeView.vue | 16 +- .../TipTapEditor/composables/useEditor.js | 9 +- .../composables/useImageHandling.js | 96 +- .../composables/useMathHandling.js | 23 +- .../composables/useToolbarActions.js | 5 +- .../TipTapEditor/extensions/Math.js | 18 +- .../TipTapEditor/utils/comparisonKey.js | 34 +- .../TipTapEditor/utils/editorHTML.js | 24 + .../TipTapEditor/TipTapEditor/utils/mathml.js | 136 +++ .../TipTapEditor/utils/pasteTransform.js | 19 + .../TipTapEditor/utils/schemaPass.js | 285 +++++ .../__tests__/TipTapEditor.spec.js | 1071 ++++++++++++++++- .../__tests__/comparisonKey.spec.js | 117 ++ .../__tests__/hasRichTextContent.spec.js | 8 + .../__tests__/mathFallback.spec.js | 88 ++ .../__tests__/mathFallbackFocus.spec.js | 39 + .../__tests__/mathLiveCopy.spec.js | 33 + .../__tests__/mathLiveUnavailable.spec.js | 33 + .../__tests__/pasteTransform.spec.js | 7 + .../TipTapEditor/__tests__/schemaPass.spec.js | 133 ++ .../TipTapEditor/__tests__/useEditor.spec.js | 131 ++ 26 files changed, 2509 insertions(+), 235 deletions(-) create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/utils/editorHTML.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/utils/mathml.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/utils/schemaPass.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/mathFallback.spec.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/mathFallbackFocus.spec.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/mathLiveCopy.spec.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/mathLiveUnavailable.spec.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/schemaPass.spec.js diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue index babb27ae2f..3a745164ae 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue @@ -107,6 +107,7 @@ import { preprocessMarkdown } from './utils/markdown'; import { resolveImageSrcs, storedHTML } from './utils/imageSrc'; import { toInlineHTML } from './utils/inlineContent'; + import { contentWithCodeBlockWhitespace } from './utils/editorHTML'; import MobileTopBar from './components/toolbar/MobileTopBar.vue'; import MobileFormattingBar from './components/toolbar/MobileFormattingBar.vue'; import { getTipTapEditorStrings } from './TipTapEditorStrings'; @@ -139,12 +140,10 @@ // editors mounted at once each work with their own modal. const imageUploadModal = ref(null); const formulasMenu = ref(null); + const editorMode = computed(() => props.mode); + provide('editorMode', editorMode); - const mathHandler = useMathHandling( - editor, - computed(() => props.mode), - () => formulasMenu.value?.$el, - ); + const mathHandler = useMathHandling(editor, editorMode, () => formulasMenu.value?.$el); provide('mathHandler', mathHandler); const imageHandler = useImageHandling(editor, () => imageUploadModal.value?.$el); @@ -186,6 +185,36 @@ // detect when an incoming prop.value is just our own emitted value echoed // back, so we can skip unnecessary re-rendering of the editor content. let lastEmittedMarkdown = null; + let loadedValue = props.value; + let loadedContent = null; + let loadedDoc = null; + const autoTrailingParagraphs = new WeakSet(); + + const addsOnlyTrailingParagraph = (before, after) => { + const paragraph = after.type.schema.nodes.paragraph; + return Boolean( + paragraph && + before.lastChild?.type !== paragraph && + after.childCount === before.childCount + 1 && + after.lastChild.eq(paragraph.create()) && + after.content.cutByIndex(0, before.childCount).eq(before.content), + ); + }; + + const recordAutoTrailingParagraphs = ({ appendedTransactions }) => { + for (const { before, doc } of appendedTransactions) { + if (addsOnlyTrailingParagraph(before, doc)) autoTrailingParagraphs.add(doc.lastChild); + } + }; + + const rememberLoadedContent = value => { + const { doc } = editor.value.state; + loadedValue = value; + loadedContent = getContent(); + loadedDoc = autoTrailingParagraphs.has(doc.lastChild) + ? doc.copy(doc.content.cutByIndex(0, doc.childCount - 1)) + : doc; + }; /** * Focus the content once it is in the page. TipTap puts it there only when the editor is @@ -247,12 +276,18 @@ extensions: props.extensions, inlineOnly, }); + editor.value.on('transaction', recordAutoTrailingParagraphs); return; } if (getContent() !== newValue) { - editor.value.commands.setContent(processedContent, false); + imageHandler.invalidateEditingImage(); + editor.value.commands.setContent( + contentWithCodeBlockWhitespace(processedContent, () => editor.value.schema), + false, + ); } + rememberLoadedContent(newValue); }, { immediate: true }, ); @@ -263,7 +298,13 @@ return; } - const content = getContent(); + const current = getContent(); + const { doc } = editor.value.state; + const unchanged = + loadedDoc && addsOnlyTrailingParagraph(loadedDoc, doc) + ? autoTrailingParagraphs.has(doc.lastChild) + : current === loadedContent; + const content = unchanged ? loadedValue : current; if (content !== props.value) { lastEmittedMarkdown = content; emit('update', content); @@ -275,6 +316,7 @@ */ watch(isReady, ready => { if (ready) { + rememberLoadedContent(props.value); emit('ready', editor.value); } }); @@ -316,7 +358,7 @@ isTouchDevice, imageHandler, sharedEventHandlers, - editorMode: computed(() => props.mode), + editorMode, emitMinimize: minimize, handleContainerKeydown, TipTapEditorLabel$, diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageNodeView.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageNodeView.vue index d89124f2c8..bb7c0f464e 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageNodeView.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageNodeView.vue @@ -53,8 +53,8 @@ tabindex="0" role="slider" aria-label="Resize image" - aria-valuemin="50" - :aria-valuenow="width" + :aria-valuemin="resizeMinWidth" + :aria-valuenow="resizeWidth" data-copy-ignore @mousedown.prevent="onResizeStart" @keydown.prevent="onResizeKeyDown" @@ -83,10 +83,16 @@ const imageRef = ref(null); const containerRef = ref(null); const resizeHandleRef = ref(null); + const naturalWidth = ref(0); const naturalAspectRatio = ref(null); const minWidth = 50; const compactThreshold = 200; let resizeListeners = null; + let committedSize = null; + let awaitingResizeHeight = false; + let pendingKeyboardResize = false; + const resizeWidthFloor = ref(minWidth); + const renderedWidth = ref(0); // Compute wrapper style based on textAlign attribute const wrapperStyle = computed(() => { @@ -103,69 +109,79 @@ }; }); - // Create debounced version of saveSize function - const debouncedSaveSize = debounce(() => { - props.updateAttributes({ - width: width.value, - height: height.value, - }); - }, 500); + const debouncedSaveSize = debounce(saveSize, 500); - // (to work with undo/redo) Watch for external changes to the node's width and height - watch( - () => props.node.attrs.width, - newWidth => { - width.value = newWidth; - }, - ); + const stopDragging = () => { + if (!resizeListeners) return; + document.removeEventListener('mousemove', resizeListeners.move); + document.removeEventListener('mouseup', resizeListeners.up); + resizeListeners = null; + }; - watch( - () => props.node.attrs.height, - newHeight => { - height.value = newHeight; - }, - ); + const cancelResize = () => { + debouncedSaveSize.cancel(); + pendingKeyboardResize = false; + stopDragging(); + awaitingResizeHeight = false; + }; - // Watch for src changes to recalculate aspect ratio watch( - () => props.node.attrs.src, - () => { - // Reset aspect ratio when src changes - naturalAspectRatio.value = null; - // Force image to reload and recalculate dimensions - if (imageRef.value) { - imageRef.value.onload = onImageLoad; + [() => props.node.attrs.width, () => props.node.attrs.height, () => props.node.attrs.src], + ([storedWidth, storedHeight, src], [, , previousSrc]) => { + if (src !== previousSrc) { + naturalWidth.value = 0; + naturalAspectRatio.value = null; + renderedWidth.value = 0; + } + const ownResize = + committedSize?.width === storedWidth && committedSize?.height === storedHeight; + committedSize = null; + if (ownResize) return; + cancelResize(); + resizeWidthFloor.value = minWidth; + width.value = storedWidth; + height.value = storedHeight; + if (src === previousSrc) { + onImageLoad(); } }, ); + const completeResizeHeight = () => { + if (!awaitingResizeHeight || !props.editor.isEditable) return; + height.value ||= calculateProportionalHeight(width.value); + if (!height.value) return; + const { state, view } = props.editor; + const pos = props.getPos(); + const image = typeof pos === 'number' ? state.doc.nodeAt(pos) : null; + if ( + image?.type.name !== 'image' || + image.attrs.src !== props.node.attrs.src || + image.attrs.width !== width.value || + image.attrs.height !== null + ) + return; + awaitingResizeHeight = false; + view.dispatch( + state.tr.setNodeAttribute(pos, 'height', height.value).setMeta('addToHistory', false), + ); + }; + const onImageLoad = () => { - if (imageRef.value && imageRef.value.naturalWidth && imageRef.value.naturalHeight) { - naturalAspectRatio.value = imageRef.value.naturalWidth / imageRef.value.naturalHeight; - - // If no dimensions are set, use natural dimensions but constrain to editor width - if (!width.value && !height.value) { - // Get the editor's actual container width - const editorContainer = props.editor.view.dom.closest('.editor-container'); - const editorWidth = editorContainer - ? editorContainer.offsetWidth - : window.innerWidth * 0.4; // fallback: 40% of viewport width - - const maxWidth = Math.min(imageRef.value.naturalWidth, editorWidth); - - width.value = maxWidth; - height.value = Math.round(maxWidth / naturalAspectRatio.value); - - saveSize(); - } else if (width.value && !height.value) { - // If we have width but no height, calculate height - height.value = calculateProportionalHeight(width.value); - saveSize(); - } else if (!width.value && height.value) { - // If we have height but no width, calculate width - width.value = Math.round(height.value * naturalAspectRatio.value); - saveSize(); - } + const image = imageRef.value; + if (!image?.naturalWidth || !image.naturalHeight) return; + naturalWidth.value = image.naturalWidth; + naturalAspectRatio.value = image.naturalWidth / image.naturalHeight; + + if (!width.value && !height.value) { + renderedWidth.value = fittedWidth(); + } else if (Number(width.value) > 0 && !height.value) { + height.value = calculateProportionalHeight(width.value); + if (resizeListeners) return; + if (pendingKeyboardResize) debouncedSaveSize.flush(); + else completeResizeHeight(); + } else if (!width.value && Number(height.value) > 0) { + width.value = Math.max(1, Math.round(height.value * naturalAspectRatio.value)); } }; @@ -174,31 +190,56 @@ return props.editor.view.dom.closest('[dir="rtl"]') !== null; }); - const styleWidth = computed(() => (width.value ? `${width.value}px` : 'auto')); - const isCompact = computed(() => width.value < compactThreshold); - - const saveSize = () => { - props.updateAttributes({ - width: width.value, - height: height.value, - }); + const styleWidth = computed(() => { + const displayWidth = width.value || naturalWidth.value; + return displayWidth ? (Number(displayWidth) ? `${displayWidth}px` : displayWidth) : 'auto'; + }); + const resizeWidth = computed(() => Number(width.value) || renderedWidth.value || minWidth); + const isCompact = computed(() => resizeWidth.value < compactThreshold); + const resizeMinWidth = computed(() => Math.min(resizeWidthFloor.value, resizeWidth.value)); + const fittedWidth = () => + Math.min(naturalWidth.value, props.editor.view.dom.clientWidth || naturalWidth.value); + const measureWidth = () => { + renderedWidth.value = containerRef.value?.offsetWidth || fittedWidth(); }; + const prepareResize = () => { + if (!Number(width.value)) measureWidth(); + resizeWidthFloor.value = resizeMinWidth.value; + return resizeWidth.value; + }; + const clampWidth = candidate => + Math.max(1, Math.round(Math.max(resizeMinWidth.value, candidate))); - const calculateProportionalHeight = newWidth => { - if (naturalAspectRatio.value) { - return Math.round(newWidth / naturalAspectRatio.value); + function saveSize() { + pendingKeyboardResize = false; + if (width.value && height.value === null) { + height.value = calculateProportionalHeight(width.value); } - // Fallback: try to get aspect ratio directly from the image element - if (imageRef.value && imageRef.value.naturalWidth && imageRef.value.naturalHeight) { - const ratio = imageRef.value.naturalWidth / imageRef.value.naturalHeight; - return Math.round(newWidth / ratio); - } - return null; + const size = { width: width.value, height: height.value }; + if (size.width === props.node.attrs.width && size.height === props.node.attrs.height) + return; + awaitingResizeHeight = size.height === null; + committedSize = size; + props.updateAttributes(size); + } + + const calculateProportionalHeight = newWidth => { + const image = imageRef.value; + const ratio = + naturalAspectRatio.value || + (image?.naturalWidth && image.naturalHeight + ? image.naturalWidth / image.naturalHeight + : null); + return ratio ? Math.max(1, Math.round(newWidth / ratio)) : null; }; const onResizeStart = startEvent => { const startX = startEvent.clientX; - const startWidth = width.value || containerRef.value.offsetWidth; + const startWidth = prepareResize(); + const startingSize = { width: width.value, height: height.value }; + let moved = false; + let dragWidth = startWidth; + stopDragging(); const onMouseMove = moveEvent => { const deltaX = moveEvent.clientX - startX; @@ -207,23 +248,21 @@ ? startWidth - deltaX // In RTL, moving right should decrease width : startWidth + deltaX; // In LTR, moving right should increase width - const clampedWidth = Math.max(minWidth, newWidth); + const clampedWidth = clampWidth(newWidth); - // Batch DOM updates - requestAnimationFrame(() => { - width.value = clampedWidth; - height.value = calculateProportionalHeight(clampedWidth); - }); + if (clampedWidth === dragWidth) return; + moved = true; + dragWidth = clampedWidth; + debouncedSaveSize.cancel(); + width.value = dragWidth === startWidth ? startingSize.width : dragWidth; + height.value = + dragWidth === startWidth ? startingSize.height : calculateProportionalHeight(dragWidth); }; const onMouseUp = () => { - // Clean up listeners - if (resizeListeners) { - document.removeEventListener('mousemove', resizeListeners.move); - document.removeEventListener('mouseup', resizeListeners.up); - resizeListeners = null; - } - saveSize(); + stopDragging(); + if (dragWidth !== startWidth || (moved && pendingKeyboardResize)) saveSize(); + else completeResizeHeight(); }; // Store listeners for proper cleanup @@ -238,37 +277,23 @@ }; const onResizeKeyDown = event => { - const step = 10; - // Use ref instead of DOM query - const currentWidth = width.value || containerRef.value.offsetWidth; - let newWidth = currentWidth; - - // Invert keyboard controls for RTL - const rightKey = isRtl.value ? 'ArrowLeft' : 'ArrowRight'; - const leftKey = isRtl.value ? 'ArrowRight' : 'ArrowLeft'; - - if (event.key === rightKey) { - newWidth = currentWidth + step; - } else if (event.key === leftKey) { - newWidth = currentWidth - step; - } else if (event.key === 'Escape' || event.key === 'Enter') { - // Use ref instead of DOM query + if (event.key === 'Escape' || event.key === 'Enter') { resizeHandleRef.value?.blur(); const endPosition = props.getPos() + props.node.nodeSize; props.editor.chain().focus().insertContentAt(endPosition, { type: 'paragraph' }).run(); return; - } else { - return; } + if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; - const clampedWidth = Math.max(minWidth, newWidth); + const startWidth = prepareResize(); + const grows = (event.key === 'ArrowRight') !== isRtl.value; + const clampedWidth = clampWidth(startWidth + (grows ? 10 : -10)); + if (clampedWidth === startWidth) return; - // Batch DOM updates - requestAnimationFrame(() => { - width.value = clampedWidth; - height.value = calculateProportionalHeight(clampedWidth); - }); + width.value = clampedWidth; + height.value = calculateProportionalHeight(clampedWidth); + pendingKeyboardResize = true; debouncedSaveSize(); }; @@ -284,29 +309,22 @@ props.editor.emit('open-image-editor', { pos: props.getPos(), attrs: { ...props.node.attrs }, + flushPendingResize: () => debouncedSaveSize.flush(), }); }; onMounted(() => { + measureWidth(); if (imageRef.value && imageRef.value.complete) { onImageLoad(); } }); - onUnmounted(() => { - // Cancel any pending debounced calls - debouncedSaveSize.cancel(); - - // Clean up any remaining resize listeners - if (resizeListeners) { - document.removeEventListener('mousemove', resizeListeners.move); - document.removeEventListener('mouseup', resizeListeners.up); - resizeListeners = null; - } - }); + onUnmounted(cancelResize); return { - width, + resizeWidth, + resizeMinWidth, imageRef, containerRef, resizeHandleRef, diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageUploadModal.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageUploadModal.vue index ead1c97ef3..81fb520b76 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageUploadModal.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/image/ImageUploadModal.vue @@ -66,6 +66,7 @@
fileInput.value.click(); const onFileSelect = event => handleFileChange(event.target.files[0]); - const onInsert = () => emit('insert', { src: previewSrc.value, alt: altText.value }); + const onInsert = () => + emit('insert', { src: previewSrc.value, alt: altText.value }, previewImage.value); const onSave = () => - emit('update', { - src: previewSrc.value, - alt: altText.value, - permanentSrc: previewSrc.value, - }); + emit( + 'update', + { src: previewSrc.value, alt: altText.value, permanentSrc: previewSrc.value }, + previewImage.value, + ); useFocusTrap(modalRoot); @@ -286,6 +289,7 @@ modalRoot, modalState, fileInput, + previewImage, previewSrc, altText, fileName, diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue index 5fb8e13f45..5ff983ad0f 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue @@ -125,6 +125,7 @@ useFocusTrap(rootEl); const currentLatex = ref(''); + let initialExpandedLatex; // Load MathLive dynamically const loadMathLive = async () => { @@ -158,6 +159,7 @@ if (mathfieldEl.value) { mathfieldEl.value.mathVirtualKeyboardPolicy = 'manual'; mathfieldEl.value.value = props.initialLatex; + initialExpandedLatex = mathfieldEl.value.getValue?.('latex-expanded'); mathfieldEl.value.focus(); mathfieldEl.value.addEventListener('input', updateLatex); currentLatex.value = props.initialLatex; @@ -223,7 +225,11 @@ const onSave = () => { if (mathfieldEl.value && mathLiveLoaded.value) { const newLatex = mathfieldEl.value.getValue('latex'); - emit('save', newLatex); + emit( + 'save', + newLatex, + initialExpandedLatex === mathfieldEl.value.getValue('latex-expanded'), + ); } }; diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue index d05933c9c1..a5a59e32bb 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue @@ -4,13 +4,22 @@ as="span" class="math-node-wrapper" > -
{{ mathText }} + - {{ node.attrs.latex }} -
+ {{ mathText || node.attrs.latex }} + @@ -27,8 +38,9 @@