From 41118aa516aa4e354b7c9707a0055cf2acf963e5 Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:49:43 +0100 Subject: [PATCH] fix(admin): keyboard path to blocks, typing lag, Word bold, live-session discard Re-audit majors (editor field, v2.7.6/2.7.7): - Ctrl/Cmd+/ is Editor.js' block menu again; the shortcut help moved to Ctrl/Cmd+Alt+/. "+" and the block menu handle are named buttons (role, tabindex, Enter/Space) with a focus ring. - Tab/Shift+Tab and the arrow keys reach controls inside blocks (audio and video Choose, person photo, toggle, column toolbar, button style and new tab, component inputs/combobox/switch); lists, tables and code keep Tab. - Typing at 2,000 blocks: inline sanitiser and canonical block JSON cached by input, save and form update in separate tasks, panels as a transition, draft fingerprints only after re-login, lazy rendered key. s27: p95 149 -> 36-46 ms, longest task 140 ms -> none over 50 ms. - Paste: inline CSS read by exact property name (Word mso-bidi-font-weight:normal kept bold). - Room "Discard changes": Strapi ConfirmDialog naming everyone, Undo with focus, a notice with "Restore my text" for the others in the session. Docs read: Editor.js 2.31.7 dist (BlockEvents keydown, Toolbar plus/settings handlers), React 18 startTransition/useDeferredValue (react.dev), @strapi/admin 5.63 ConfirmDialog types, DS 2.3.1 Button/Dialog, DOMPurify 3 README (pure function of input and config). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 10 + README.md | 4 +- .../src/components/EditorField/RoomNotice.jsx | 100 ++++++++- .../EditorField/ShortcutsDialog.jsx | 7 +- admin/src/components/EditorField/index.jsx | 189 ++++++++++++++++-- .../components/EditorField/useDraftBuffer.js | 17 +- admin/src/editor/apply-remote.js | 8 +- admin/src/editor/block-tab-stops.mjs | 170 ++++++++++++++++ admin/src/editor/room-state.mjs | 16 +- admin/src/editor/sanitize.js | 48 ++++- admin/src/editor/toolbar-a11y.mjs | 46 +++++ admin/src/editor/tools/styles.js | 22 ++ admin/src/translations/editor/de.json | 15 +- admin/src/translations/editor/en.json | 15 +- admin/src/translations/editor/es.json | 15 +- admin/src/translations/editor/fr.json | 15 +- admin/src/translations/editor/pt.json | 15 +- docs/site/llms-full.txt | 6 +- shared/convert/html.mjs | 55 ++++- shared/ydoc.mjs | 45 +++++ tests/admin/block-keyboard.test.jsx | 157 +++++++++++++++ tests/admin/room-notice.test.jsx | 65 ++++++ tests/admin/sanitize-cache.test.jsx | 59 ++++++ tests/convert.test.mjs | 24 +++ tests/room-state.test.mjs | 14 +- tests/shared-ydoc.test.mjs | 20 ++ 27 files changed, 1095 insertions(+), 64 deletions(-) create mode 100644 admin/src/editor/block-tab-stops.mjs create mode 100644 admin/src/editor/toolbar-a11y.mjs create mode 100644 tests/admin/block-keyboard.test.jsx create mode 100644 tests/admin/room-notice.test.jsx create mode 100644 tests/admin/sanitize-cache.test.jsx diff --git a/AGENTS.md b/AGENTS.md index 0e96698..d22d74a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -479,7 +479,7 @@ Private image storage for alt text (`ai.altText.allowPrivateOrigins`, config onl ## Editor field extras -- Markdown shortcuts (`editor/markdown-shortcuts*.{js,mjs}`), find and replace (`shared/find-replace.mjs` + `FindReplacePanel`, CSS Custom Highlight `mex-find`), shortcuts dialog (Ctrl/Cmd+/), focus mode, `BlockSelectionBar` (Editor.js `.ce-block--selected`), quality panel (`QualityPanel`, `useQualityIssues`) with preset violations, `lang`/`dir` from the content locale. The image tool is `MexImageTool` (`tools/alt-text.js`, subclass of `@editorjs/image` adding alt text, the decorative flag and the focal point control). Media tools (`tools/media.js`: `GalleryTool`, `VideoTool`, `AudioTool`; pure logic in `tools/media-logic.mjs`; focal point control `tools/focal-point.js`: disclosure button, click/tap on the preview, arrow keys 1 % / Shift 10 %, reset, polite live value) open the Strapi Media Library dialog through `openMediaLibrary({ multiple, allowedTypes: ['images'|'videos'|'audios'|'files'], accept(asset), onSelect(assets) })`; `EditorField` filters the picked assets with `accept` and returns focus to the trigger. They are offered only with `plugin::upload.read` (`config.permissions.mediaLibrary`, tool config `canBrowse`); without it they are hidden from the toolbox and existing blocks explain why no files can be chosen. Gallery: add (multiple), move earlier/later, remove, per-image alt (default: the file's Media Library alternative text; `requireAlt`/decorative as in the image block), caption, focal point, layout and columns. Video/audio: choose/replace, title, caption, loop (+ muted and poster for video), WebVTT tracks (kind, language defaulting to the content locale, label, one default). +- Markdown shortcuts (`editor/markdown-shortcuts*.{js,mjs}`), find and replace (`shared/find-replace.mjs` + `FindReplacePanel`, CSS Custom Highlight `mex-find`), shortcuts dialog (Ctrl/Cmd+Alt+/; Ctrl/Cmd+/ is the Editor.js block menu), focus mode, `BlockSelectionBar` (Editor.js `.ce-block--selected`), quality panel (`QualityPanel`, `useQualityIssues`) with preset violations, `lang`/`dir` from the content locale. The image tool is `MexImageTool` (`tools/alt-text.js`, subclass of `@editorjs/image` adding alt text, the decorative flag and the focal point control). Media tools (`tools/media.js`: `GalleryTool`, `VideoTool`, `AudioTool`; pure logic in `tools/media-logic.mjs`; focal point control `tools/focal-point.js`: disclosure button, click/tap on the preview, arrow keys 1 % / Shift 10 %, reset, polite live value) open the Strapi Media Library dialog through `openMediaLibrary({ multiple, allowedTypes: ['images'|'videos'|'audios'|'files'], accept(asset), onSelect(assets) })`; `EditorField` filters the picked assets with `accept` and returns focus to the trigger. They are offered only with `plugin::upload.read` (`config.permissions.mediaLibrary`, tool config `canBrowse`); without it they are hidden from the toolbox and existing blocks explain why no files can be chosen. Gallery: add (multiple), move earlier/later, remove, per-image alt (default: the file's Media Library alternative text; `requireAlt`/decorative as in the image block), caption, focal point, layout and columns. Video/audio: choose/replace, title, caption, loop (+ muted and poster for video), WebVTT tracks (kind, language defaulting to the content locale, label, one default). - Field readiness and edits (`editor/input-tracking.mjs`): the field reports content to the form only after the person edited it (Editor.js also reports its normalisation of stored content on the first render). User input (`pointerdown`, `keydown`, `input`, `paste`, `drop`, capture phase on the holder) is tracked from before Editor.js renders, and edits made while Editor.js was starting are saved on `onReady`; after the Content Manager's create -> edit redirect several fields mount at once and text typed before the field's own effects ran used to stay out of the form (Save stayed disabled). The holder (`[data-testid="magic-editor-x"]`) carries `aria-busy="true"` while loading and `data-mex-ready="true"` once Editor.js is ready and every listener is attached; browser tests wait for `data-mex-ready` instead of sleeping. - Editor styles (`editor/tools/styles.js`) are one global style rendered by the first mounted field only (`editor/style-owners.mjs`, `SharedEditorStyles`); one copy per field made styled-components rebuild every copy on each mount and unmount (seconds of blocked main thread on pages with several fields). - `apply-remote.js`: default tune values count as "no tune" in `blockKey` (`shared/default-tunes.mjs`); more than 150 changed blocks (and a quarter of the document) are applied with one `render` instead of per-block updates (Editor.js notifies every block on each mutation). diff --git a/CHANGELOG.md b/CHANGELOG.md index 1765b3d..9095437 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [Unreleased] + +### Fixed (editor field: keyboard, typing speed, paste, live session) + +- **Keyboard path to the block menu.** Ctrl/Cmd+/ opened the plugin's shortcut help, which blocked Editor.js' own shortcut for the block menu, and the **+** and block menu (⋮⋮) handles had no role, name or tab stop. Ctrl/Cmd+/ opens the block menu of the current block again; the shortcut help moved to **Ctrl/Cmd+Alt+/** (also More tools > Keyboard shortcuts). Both handles are buttons with names ("Add a block", "Open the block menu") that open with Enter or Space. The shortcut help and the README list the keyboard path. +- **Controls inside blocks were not reachable by keyboard.** Editor.js moves Tab and the arrow keys only between text inputs, so the audio and video Choose buttons, the person photo, the toggle's show/hide, the column style and layout, the button block's style and "new tab", and the inputs, select and switch of component blocks were skipped. Tab and Shift+Tab now stop on them in document order, the arrow keys stop on a control Editor.js would skip (not on selects), tools that use Tab themselves (lists, tables, code) keep it, and every control in a block shows a focus ring. +- **Typing lag in long documents.** Every keystroke sanitised the whole document with DOMPurify several times (form value, rendered key, draft fingerprint) and compared it in canonical JSON: about 150 ms per key at 2,000 blocks. The inline sanitiser and the canonical JSON of blocks are cached by input (same output, so the same security; the server still sanitises on save), Editor.js' save and the form update run in separate tasks, the field's panels update as a React transition, and the draft fingerprints are only computed after signing in again. At 2,000 blocks a keystroke now takes p95 about 40 ms with no task over 50 ms (see the PR for the measurements). +- **Bold from Word was lost on paste.** Word writes `` and the check for Google Docs' `` wrapper matched the text `font-weight:normal` inside the other property. Inline styles are now read by exact property name, everywhere in the HTML import. +- **"Discard changes" in the live session notice removed other people's text without asking.** It now asks first in a Strapi confirmation that says it affects everyone editing the field, then shows a notice with **Undo** (focused) that puts the previous text back for everyone. People in the same session get a notice that the field went back to the saved content, with **Restore my text**. + ## [2.8.1](https://github.com/Schero94/Magic-Editor-X/compare/v2.8.0...v2.8.1) (2026-11-20) diff --git a/README.md b/README.md index e37b230..6e7a2e7 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ All screenshots use synthetic data (captured on Strapi 5.61.1 and 5.62.0; accept | Version history | More tools > Version history, for a saved document | `access` and Content Manager read on the document; saving, naming and restoring need update. The Activity tab needs `audit.read`. | | Find and replace | More tools > Find and replace, or Ctrl/Cmd+Shift+F in the editor | Everyone who can read the field; replacing needs update. | | Quality checks | More tools > Quality checks (the number counts problems) | Everyone who can read the field; the link check needs `access`. | -| Keyboard shortcuts, focus mode | More tools > Keyboard shortcuts or Focus mode, or Ctrl/Cmd+/ | Everyone who can read the field. | +| Keyboard shortcuts, focus mode | More tools > Keyboard shortcuts or Focus mode, or Ctrl/Cmd+Alt+/ | Everyone who can read the field. | | Field options | Content-Type Builder, Magic Editor X field, Basic and Advanced settings | Content-Type Builder access (development mode). | | AI assistant | Inline toolbar (select text), or a block's menu, the block selection bar or Ctrl/Cmd+Shift+G for whole blocks | `access` and `ai.use`, when an administrator turned the assistant on. | | AI for the whole field | More tools > AI for the whole field | `access` and `ai.use`, when the owner allowed whole-field AI actions and the field does not turn AI off. | @@ -502,7 +502,7 @@ Changing a preset never changes stored content by itself. Turning `sanitizeOnSav | More tools menu | The field toolbar shows undo, redo, **More tools** and full screen. More tools groups the other tools: **Review** (comments, version history, suggestions, quality checks), **Write** (suggest changes, AI for the whole field, check grammar, find and replace, insert template) and **View** (preview, focus mode, keyboard shortcuts). Entries appear only where they can work (permission, settings, field options); counts show in the menu, and a tool that changes the view (preview, focus mode) adds a visible way back to the bar. Keyboard shortcuts are unchanged. | | Markdown shortcuts | At the start of an empty paragraph: `#` to `######` + Space (heading), `-`, `*` or `+` + Space (bulleted list), `1.` + Space (numbered list, other numbers set the start), `[]` or `[x]` + Space (checklist), `>` + Space (quote), ` ``` ` (optionally with a language) + Enter (code block), `---` + Enter (delimiter). While typing: `**bold**`, `__bold__`, `*italic*`, `_italic_`, `~~strike~~`, `` `code` ``. Never inside code, raw HTML or tables; only blocks and marks the field allows. | | Find and replace | Magnifier button or Ctrl/Cmd+Shift+F. Searches every text block, list item, table cell, caption and code block; keeps formatting; match case, whole words, regular expressions (off by default, patterns up to 200 characters). Enter / Shift+Enter move between matches, the current match is highlighted. Replacements are normal edits (undo, collaboration). A match cannot span differently formatted text. | -| Keyboard shortcuts | Ctrl/Cmd+/ or More > Keyboard shortcuts: editor, block and inline tool shortcuts and the Markdown shortcuts of this field. | +| Keyboard shortcuts | Ctrl/Cmd+Alt+/ or More > Keyboard shortcuts: editor, block and inline tool shortcuts and the Markdown shortcuts of this field. Keyboard path to blocks: Ctrl/Cmd+/ opens the block menu of the current block (move, delete, convert), `/` or Tab in an empty block chooses a block type, Tab and the arrow keys reach the buttons and options inside blocks, and the **+** and block menu handles are buttons with names. | | Focus mode | More > Focus mode: full screen, narrower text column, other blocks dimmed. Escape leaves. | | Several selected blocks | Select across blocks (Shift+Arrow at a block edge, Ctrl/Cmd+A twice, or drag across blocks): move up or down, duplicate, copy as Markdown, delete, convert to text, heading, list or quote. | | Counts | Blocks, words, characters and reading time (200 words per minute) in the toolbar, with the field's limits. | diff --git a/admin/src/components/EditorField/RoomNotice.jsx b/admin/src/components/EditorField/RoomNotice.jsx index 6e7e4a5..a3761bb 100644 --- a/admin/src/components/EditorField/RoomNotice.jsx +++ b/admin/src/components/EditorField/RoomNotice.jsx @@ -1,11 +1,17 @@ +import { useEffect, useRef } from 'react'; import { Box, Button, Flex, Typography } from '@strapi/design-system'; import styled from 'styled-components'; +import { ConfirmAction } from '../ui/ConfirmAction'; /** * In-field notice (2.7.4): the live collaboration room still held changes nobody saved (a room * keeps them for `roomTtlMinutes`). The field shows them and marks the form as changed, so the * Save button stores what is shown; this notice says so in one sentence. Discard brings the stored * value back in the editor, the form and the room. Same placement and look as the draft notice. + * + * 2.7.8 (re-audit major 5): Discard affects everyone in the live session, so it asks first (Strapi + * ConfirmDialog that says so). Afterwards `RoomResetNotice` offers Undo to the person who + * discarded and tells the others in the room what happened, with a way to put their text back. */ const Bar = styled(Box)` @@ -16,11 +22,12 @@ const Bar = styled(Box)` /** * @param {object} props - Props. * @param {Function} props.t - Translator. - * @param {() => void} props.onDiscard - Restores the stored value. + * @param {() => Promise} props.onDiscard - Restores the stored value (after confirmation). * @param {boolean} props.disabled - The editor is read-only. + * @param {{ current: HTMLElement|null }} [props.fallbackFocusRef] - Focus after Discard (the notice is gone then). * @returns {JSX.Element} Notice. */ -export const RoomNotice = ({ t, onDiscard, disabled }) => ( +export const RoomNotice = ({ t, onDiscard, disabled, fallbackFocusRef }) => ( ( )} - + } disabled={disabled} - data-testid="mex-room-discard" - > - {t('editor.room.discard', 'Discard changes')} - + title={t('editor.room.discardTitle', 'Discard the unsaved changes for everyone?')} + body={t( + 'editor.room.discardBody', + 'The saved content comes back in this field for everyone editing this entry right now. Their unsaved text in this field is removed too. You can undo this right after.' + )} + confirmLabel={t('editor.room.discardConfirm', 'Discard for everyone')} + onConfirm={onDiscard} + fallbackFocusRef={fallbackFocusRef} + /> ); +/** + * Notice after the unsaved changes of a live session were discarded (2.7.8). + * `kind: 'self'`: this person discarded them; Undo puts the previous text back for everyone. + * `kind: 'remote'`: someone else in the session did; Restore puts the previous text back. + * @param {object} props - Props. + * @param {Function} props.t - Translator. + * @param {'self'|'remote'} props.kind - Who discarded. + * @param {() => void} props.onUndo - Puts the previous text back. + * @param {() => void} props.onDismiss - Closes the notice. + * @param {boolean} [props.autoFocus] - Focus Undo on mount (after the confirmation closed). + * @param {{ current: HTMLElement|null }} [props.undoRef] - Ref of the Undo button. + * @param {boolean} [props.disabled] - The editor is read-only. + * @returns {JSX.Element} Notice. + */ +export const RoomResetNotice = ({ + t, + kind, + onUndo, + onDismiss, + autoFocus = false, + undoRef, + disabled = false, +}) => { + const ownRef = useRef(null); + const ref = undoRef || ownRef; + useEffect(() => { + if (autoFocus && ref.current) ref.current.focus(); + }, [autoFocus, ref]); + return ( + + + + + {kind === 'self' + ? t( + 'editor.room.discarded', + 'The unsaved changes were discarded for everyone. This field shows the saved content.' + ) + : t( + 'editor.room.discardedRemote', + 'Someone in this live session brought this field back to the saved content. Your unsaved text in this field was removed.' + )} + + + + + + + + + ); +}; + export default RoomNotice; diff --git a/admin/src/components/EditorField/ShortcutsDialog.jsx b/admin/src/components/EditorField/ShortcutsDialog.jsx index b9c37c4..c95d3f3 100644 --- a/admin/src/components/EditorField/ShortcutsDialog.jsx +++ b/admin/src/components/EditorField/ShortcutsDialog.jsx @@ -3,7 +3,7 @@ import styled from 'styled-components'; import { shortcutKeyName } from '../../editor/field-tools.mjs'; /** - * Keyboard shortcut help (Ctrl/Cmd + /). Lists the editor's own shortcuts, + * Keyboard shortcut help (Ctrl/Cmd + Alt + /; 2.7.8: Ctrl/Cmd + / opens the Editor.js block menu). Lists the editor's own shortcuts, * the block and inline tool shortcuts and the Markdown shortcuts. */ @@ -72,10 +72,13 @@ export const ShortcutsDialog = ({ ['CMD+Z', t('editor.shortcuts.undo', 'Undo')], ['CMD+SHIFT+Z', t('editor.shortcuts.redo', 'Redo')], ['CMD+SHIFT+F', t('editor.shortcuts.find', 'Find and replace')], - ['CMD+/', t('editor.shortcuts.help', 'Show keyboard shortcuts')], + ['CMD+ALT+/', t('editor.shortcuts.help', 'Show keyboard shortcuts')], + ['CMD+/', t('editor.shortcuts.blockMenu', 'Block menu of the current block (move, delete, convert)')], + ['/', t('editor.shortcuts.addBlock', 'Choose a block type (in an empty block)')], ['CMD+ALT+P', t('editor.shortcuts.preview', 'Show or hide the rendered preview')], ['Tab', t('editor.shortcuts.toolbox', 'Choose a block type (in an empty block)')], ['Escape+Tab', t('editor.shortcuts.leave', 'Leave the editor')], + ['Tab', t('editor.shortcuts.blockControls', 'Buttons and options inside a block (Shift+Tab: back)')], ['Tab', t('editor.shortcuts.tableCell', 'Next table cell (Shift+Tab: previous cell)')], ['ALT+F10', t('editor.shortcuts.tableTools', 'Table tools (in a table cell)')], ['CMD+SHIFT+V', t('editor.shortcuts.plainPaste', 'Paste as plain text')], diff --git a/admin/src/components/EditorField/index.jsx b/admin/src/components/EditorField/index.jsx index 21f5c68..51a577b 100644 --- a/admin/src/components/EditorField/index.jsx +++ b/admin/src/components/EditorField/index.jsx @@ -1,4 +1,13 @@ -import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { + startTransition, + useCallback, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, +} from 'react'; import { createPortal } from 'react-dom'; import { useIntl } from 'react-intl'; import { useHref, useLocation, useNavigate } from 'react-router-dom'; @@ -37,7 +46,7 @@ import { normalizePalette } from '../../../../shared/inline-format.mjs'; import { abbreviationAnnotation, annotationsFromSummaries } from '../../../../shared/blocks/annotations.mjs'; import { createCspGuard } from '../../editor/tools/csp-guard'; import { prepareEditorValue, prepareRemoteData, sanitizeInline } from '../../editor/sanitize'; -import { roomDiffersFromStored } from '../../editor/room-state.mjs'; +import { roomDiffersFromStored, roomWasReset } from '../../editor/room-state.mjs'; import { createSubmitGuard } from '../../editor/submit-guard.mjs'; import { applyToEditor, blockKey, rememberBlocks } from '../../editor/apply-remote'; import { holdSelection } from '../../editor/selection-keeper.mjs'; @@ -47,7 +56,7 @@ import { reportUnpushedComponents, } from '../../editor/tools/component'; import { computeStats } from '../../../../shared/editor-data.mjs'; -import { stableStringify } from '../../../../shared/ydoc.mjs'; +import { stableStringify, stableStringifyBlocks } from '../../../../shared/ydoc.mjs'; import { useEditorConfig } from '../../hooks/useEditorConfig'; import { getTranslation } from '../../utils/getTranslation'; import { API, readApiError } from '../../utils/api'; @@ -144,7 +153,9 @@ import { escapeHtml } from '../../../../shared/render/inline.mjs'; // 2.5: local draft buffer (protect unsaved work) and lazy start of fields (performance). import { useDraftBuffer } from './useDraftBuffer'; import { DraftNotice } from './DraftNotice'; -import { RoomNotice } from './RoomNotice'; +import { RoomNotice, RoomResetNotice } from './RoomNotice'; +import { focusTabStop, isTextStop, nextTabStop, skippedControl } from '../../editor/block-tab-stops.mjs'; +import { decorateToolbar } from '../../editor/toolbar-a11y.mjs'; import { SessionBanner } from './SessionBanner'; import { useLazyActivation } from './useLazyActivation'; import { LazyPlaceholder } from './LazyPlaceholder'; @@ -397,7 +408,13 @@ const restoreCaret = (ref, fallback) => { * @param {object|null} data - Editor data. * @returns {string} Fingerprint. */ -const contentKey = (data) => stableStringify(data && Array.isArray(data.blocks) ? data.blocks : []); +const contentKey = (data) => stableStringifyBlocks(data && Array.isArray(data.blocks) ? data.blocks : []); + +/** + * Resolves in a new task, so long work before and after does not add up to one long task. + * @returns {Promise} Resolves after the browser had a chance to handle input and paint. + */ +const yieldToBrowser = () => new Promise((resolve) => setTimeout(resolve, 0)); /** * Fingerprint of content as the field would render it (normalised and @@ -462,6 +479,9 @@ const EditorFieldBody = ({ const undoRef = useRef(null); const knownRef = useRef(new Map()); const lastEmittedRef = useRef(null); + // 2.7.8: what was emitted last (source for the lazy rendered key) and the object handed to the form. + const lastEmittedSourceRef = useRef(null); + const lastEmittedValueRef = useRef(undefined); const lastEmittedRawRef = useRef(null); const applyingRef = useRef(false); const saveTimerRef = useRef(null); @@ -472,6 +492,9 @@ const EditorFieldBody = ({ const syncedOnceRef = useRef(false); // 2.7.4 (M3): the first room state held unsaved changes; `saved` is the stored value at that time. const [roomNotice, setRoomNotice] = useState(null); + // 2.7.8: after unsaved room changes were discarded ({ kind: 'self'|'remote', previous, focus }). + const [roomReset, setRoomReset] = useState(null); + const roomUndoRef = useRef(null); const savedValueRef = useRef(undefined); // 2.6: the editor shows the room (after its first render), so a found buffer is compared with the room. const [roomRendered, setRoomRendered] = useState(false); @@ -720,7 +743,9 @@ const EditorFieldBody = ({ const key = contentKey(next); if (key === lastEmittedRawRef.current) return; lastEmittedRawRef.current = key; - lastEmittedRef.current = renderedKey(next); + // 2.7.8: the rendered key (a full sanitise) is computed only when a different value arrives. + lastEmittedRef.current = null; + lastEmittedSourceRef.current = next; if (baselineOnly) return; // Editor.js reuses the tune objects of a block between saves, and the // Content Manager form freezes what it stores. Hand over a copy so the @@ -737,6 +762,7 @@ const EditorFieldBody = ({ } copy.fieldKey = key; } + lastEmittedValueRef.current = copy; onChangeRef.current(name, copy); }, [name] @@ -749,10 +775,18 @@ const EditorFieldBody = ({ pendingLocalRef.current = false; try { const data = await editor.save(); + // 2.7.8: Editor.js' save of a long document is one task; the form update + // and the field's own state follow in the next task, and the field's + // panels (stats, comments, quality) re-render as a transition that React + // can interrupt. Each task stays short while typing in 2,000 blocks. + await yieldToBrowser(); + if (editorRef.current !== editor) return; rememberBlocks(knownRef.current, data); - setStats(computeStats(data)); - setCurrentData(data); - setContentVersion((version) => version + 1); + startTransition(() => { + setStats(computeStats(data)); + setCurrentData(data); + setContentVersion((version) => version + 1); + }); if (!userTouchedRef.current) { emit(data, { baselineOnly: true }); return; @@ -836,6 +870,38 @@ const EditorFieldBody = ({ return; } if (!['Shift', 'Control', 'Alt', 'Meta'].includes(event.key)) leaveArmed = false; + // 2.7.8 (re-audit major 2): the arrow keys stop on controls Editor.js would skip between two texts. + if ( + ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight'].includes(event.key) && + !event.shiftKey && + !event.altKey && + !event.ctrlKey && + !event.metaKey + ) { + const from = document.activeElement; + window.setTimeout(() => { + const control = skippedControl(holder, from, document.activeElement); + if (control) control.focus(); + }, 0); + return; + } + // 2.7.8 (re-audit major 2): Tab reaches the controls inside blocks (audio and video Choose, + // person photo, toggle, column style and layout, button style and new tab). Editor.js only + // moves between text inputs; text-to-text moves and tools with their own Tab stay as they were. + if (event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey) { + const active = document.activeElement; + const selection = window.getSelection(); + // An empty block opens the block types on Tab, a selection belongs to the inline toolbar. + if (active && active.isContentEditable && !event.shiftKey && !String(active.textContent || '').trim()) + return; + if (selection && !selection.isCollapsed && isTextStop(active)) return; + const { target, handled } = nextTabStop(holder, active, event.shiftKey); + if (!handled) return; + event.stopPropagation(); + if (!target) return; + event.preventDefault(); + focusTabStop(target, event.shiftKey); + } }; window.addEventListener('keydown', onKeyDown, true); // 2.7.4 (m12): Save or Ctrl/Cmd+Enter right after typing waits until the input is in the form. @@ -961,6 +1027,8 @@ const EditorFieldBody = ({ const first = !syncedOnceRef.current; syncedOnceRef.current = true; const storedView = viewRef.current; + // 2.7.8: what this editor showed before the update (its own unsaved text included). + const shownBefore = first ? null : prepareEditorValue(currentDataRef.current).data; await applyExternal(shared, { emitToForm: !first, live: true }); // The editor's own serialisation of what it now shows is the base of the next local diff; // 2.6: component blocks count with the room's values, so edits not pushed yet stay a difference. @@ -970,6 +1038,23 @@ const EditorFieldBody = ({ viewRef.current = shown || shared; reportUnpushedComponents(); if (first) setRoomRendered(true); + // 2.7.8: someone else discarded the unsaved room changes (the room went back to the stored value). + if (!first && saved) { + const storedNow = prepareEditorValue(savedValueRef.current).data; + if (roomWasReset(shownBefore, shown || shared, storedNow)) { + setRoomNotice(null); + // This person's own discard (an echo of it) keeps its Undo notice. + setRoomReset((current) => + current && current.kind === 'self' + ? current + : { kind: 'remote', previous: shownBefore, focus: false } + ); + // The form goes back to the stored value itself, so it is no longer marked as changed. + lastEmittedRawRef.current = contentKey(shown || shared); + onChangeRef.current(name, savedValueRef.current === undefined ? null : savedValueRef.current); + userTouchedRef.current = false; + } + } // 2.7.4 (M3): a room keeps unsaved text for a while after the last editor left. When the first // room state differs from the stored value, the form is marked as changed (Save stores what // is shown) and a notice says so, with Discard to go back to the stored value. @@ -1454,8 +1539,11 @@ const EditorFieldBody = ({ // Value changes from outside the editor (form reset after save/discard, locale switch). useEffect(() => { if (!ready || collaboration.active) return; + // 2.7.8: the form gives back the object this field emitted: nothing to compare (typing in long documents). + if (value !== null && value !== undefined && value === lastEmittedValueRef.current) return; const prepared = prepareEditorValue(value); const key = contentKey(prepared.data); + if (lastEmittedRef.current === null) lastEmittedRef.current = renderedKey(lastEmittedSourceRef.current); if (key === lastEmittedRef.current) return; lastEmittedRef.current = key; applyExternal(prepared.data, { emitToForm: false }); @@ -1744,6 +1832,8 @@ const EditorFieldBody = ({ const notice = roomNotice; const editor = editorRef.current; if (!notice || !editor) return; + // 2.7.8: what the room showed before, for Undo. + const before = prepareEditorValue(await editor.save().catch(() => null)).data; setRoomNotice(null); const stored = notice.saved === undefined ? null : notice.saved; await applyExternal(prepareEditorValue(stored).data, { emitToForm: false, live: true }); @@ -1759,7 +1849,39 @@ const EditorFieldBody = ({ viewRef.current = componentRoomView(local) || local; } } + if (before) setRoomReset({ kind: 'self', previous: before, focus: true }); }, [applyExternal, name, roomNotice]); + + /** Focuses the editor text (after the room notices close). */ + const focusEditorText = useCallback(() => { + window.requestAnimationFrame(() => { + const holder = holderRef.current; + const first = holder && holder.querySelector('[contenteditable="true"]'); + if (first) first.focus(); + }); + }, []); + + /** 2.7.8: Undo (own discard) or Restore (someone else's): the previous room text comes back for everyone. */ + const undoRoomReset = useCallback(async () => { + const reset = roomReset; + if (!reset || !reset.previous) return; + setRoomReset(null); + await replaceContent(reset.previous); + if (reset.kind === 'self') { + setRoomNotice({ saved: savedValueRef.current }); + window.requestAnimationFrame(() => { + const discard = + frameRef.current && frameRef.current.querySelector('[data-testid="mex-room-discard"]'); + if (discard) discard.focus(); + else focusEditorText(); + }); + } else focusEditorText(); + }, [roomReset, replaceContent, focusEditorText]); + + const dismissRoomReset = useCallback(() => { + setRoomReset(null); + focusEditorText(); + }, [focusEditorText]); const draft = useDraftBuffer({ enabled: Boolean(target.uid && config && config.drafts && config.drafts.enabled !== false), ttlHours: config && config.drafts ? config.drafts.ttlHours : undefined, @@ -2055,7 +2177,17 @@ const EditorFieldBody = ({ // selected blocks or the block with the caret (with selected text the inline AI tool runs). const blockAiByKey = Boolean(aiAllowed && target.uid && !readOnly); - // Editor shortcuts: Ctrl/Cmd+Shift+F find and replace, Ctrl/Cmd+/ help. + // 2.7.8: "+" and the block menu handle are buttons with names (Editor.js renders a div and a span). + useEffect(() => { + if (!ready) return undefined; + return decorateToolbar(holderRef.current, { + add: t('editor.toolbar.add', 'Add a block'), + menu: t('editor.toolbar.blockMenu', 'Open the block menu'), + }); + }, [ready, t]); + + // Editor shortcuts: Ctrl/Cmd+Shift+F find and replace, Ctrl/Cmd+Alt+/ help. + // 2.7.8: Ctrl/Cmd+/ (without Alt) belongs to Editor.js again: it opens the block menu. useEffect(() => { if (!ready) return undefined; const onKey = (event) => { @@ -2064,7 +2196,17 @@ const EditorFieldBody = ({ // Suggest mode has its own editor; the field's tools stay closed (2.4). if (suggestModeRef.current) return; const mod = event.metaKey || event.ctrlKey; - if (!mod || event.altKey) return; + if (!mod) return; + if (event.altKey) { + // Ctrl/Cmd+Alt+/ opens the shortcut help (macOS writes "÷" for Alt+/, so the key code counts too). + if (!event.shiftKey && (event.code === 'Slash' || event.key === '/')) { + event.preventDefault(); + event.stopPropagation(); + rememberCaret(shortcutsReturnRef); + setShortcutsOpen(true); + } + return; + } if (event.shiftKey && (event.key === 'g' || event.key === 'G') && blockAiByKey) { const selection = window.getSelection(); const holder = holderRef.current; @@ -2089,11 +2231,6 @@ const EditorFieldBody = ({ event.preventDefault(); event.stopPropagation(); setFindOpen(true); - } else if (!event.shiftKey && event.key === '/') { - event.preventDefault(); - event.stopPropagation(); - rememberCaret(shortcutsReturnRef); - setShortcutsOpen(true); } }; window.addEventListener('keydown', onKey, true); @@ -3132,7 +3269,7 @@ const EditorFieldBody = ({ group: 'view', label: t('editor.toolbar.shortcuts', 'Keyboard shortcuts'), icon: , - shortcut: 'CMD+/', + shortcut: 'CMD+ALT+/', movesFocus: true, onSelect: () => { shortcutsReturnRef.current = null; @@ -3238,7 +3375,23 @@ const EditorFieldBody = ({ /> {target.uid ? : null} {roomUnsaved && ready && !suggestMode ? ( - + + ) : null} + {roomReset && ready && !suggestMode ? ( + ) : null} {draft.notice && ready && !suggestMode ? ( { // 2.6: default tune values count as no tune (shared/default-tunes.mjs): the room and the form // write the same content in both shapes, which made an equal buffer look different. // A non-breaking space is written as ` ` by the editor and as U+00A0 or a space after a round trip. - const key = stableStringify( + const key = stableStringifyBlocks( comparableBlocks(data && Array.isArray(data.blocks) ? data.blocks : []) ).replace(/ |\u00a0/g, ' '); return { data, key }; @@ -274,8 +274,15 @@ export const useDraftBuffer = ({ ]); // 2.6: signed in again. Strapi reloads the entry and resets the form: put the buffered text back once. - const valueKey = useMemo(() => fingerprint(value).key, [value]); - const savedKey = useMemo(() => fingerprint(savedValue).key, [savedValue]); + // 2.7.8: the keys matter only after signing in again; they are not computed while typing + // (a full-document fingerprint on every keystroke was part of the typing lag at 2,000 blocks), + // and the form value is read deferred so this never blocks an urgent render. + const deferredValue = useDeferredValue(value); + const valueKey = useMemo( + () => (resumedAt ? fingerprint(deferredValue).key : null), + [deferredValue, resumedAt] + ); + const savedKey = useMemo(() => (resumedAt ? fingerprint(savedValue).key : null), [savedValue, resumedAt]); useEffect(() => { if (!id || !ready || readOnly || !resumedAt || typeof onRecover !== 'function') return undefined; if (recoveredRef.current === resumedAt) return undefined; diff --git a/admin/src/editor/apply-remote.js b/admin/src/editor/apply-remote.js index 747c8a1..dc3cdb0 100644 --- a/admin/src/editor/apply-remote.js +++ b/admin/src/editor/apply-remote.js @@ -1,4 +1,4 @@ -import { stableStringify } from '../../../shared/ydoc.mjs'; +import { stableStringify, stableStringifyCached } from '../../../shared/ydoc.mjs'; import { meaningfulTunes } from '../../../shared/default-tunes.mjs'; import { applyComponentValues } from './tools/component'; import { deleteBlockKeepingFocus } from './focus-guard.mjs'; @@ -25,7 +25,11 @@ export const blockKey = (block) => { // Blocks are treated as immutable; unchanged blocks keep their identity, so the key is cached. let key = keys.get(block); if (key === undefined) { - key = stableStringify({ type: block.type, data: block.data || {}, tunes: meaningfulTunes(block.tunes) }); + key = stableStringifyCached({ + type: block.type, + data: block.data || {}, + tunes: meaningfulTunes(block.tunes), + }); keys.set(block, key); } return key; diff --git a/admin/src/editor/block-tab-stops.mjs b/admin/src/editor/block-tab-stops.mjs new file mode 100644 index 0000000..125c1db --- /dev/null +++ b/admin/src/editor/block-tab-stops.mjs @@ -0,0 +1,170 @@ +/** + * Keyboard path to the controls inside blocks (2.7.8, re-audit major 2). + * + * Editor.js handles Tab inside a block: it moves the caret to the next + * *text input* (`[contenteditable]`, text inputs, textareas) and prevents the + * default, so buttons, selects, checkboxes and switches that a block renders + * (audio and video "Choose", person photo, toggle show/hide, column style and + * layout, the button block's style and "new tab") were never reached. + * + * This module computes the tab stops of an editor in document order (text + * inputs plus those controls) and the next stop for Tab or Shift+Tab. The + * field steps in only when the next or previous stop is a control, or when + * focus is on a control; text-to-text moves are left to Editor.js, and tools + * that use Tab themselves (lists, tables, code) keep it. + * + * Pure DOM queries, no Editor.js internals beyond its public class names. + */ + +/** Text inputs as Editor.js finds them. */ +const TEXT_SELECTOR = + '[contenteditable="true"], textarea, input:not([type]), input[type="text"], input[type="url"], input[type="email"], input[type="number"], input[type="search"]'; + +/** Controls a block may render. */ +const CONTROL_SELECTOR = + 'button, select, input[type="checkbox"], input[type="radio"], input[type="file"]:not([hidden]), [role="switch"], [role="combobox"], [role="button"][tabindex], [tabindex="0"]:not([contenteditable]), a[href]'; + +/** Editor chrome that is not part of a block (own keyboard handling or reached otherwise). */ +const OUTSIDE_BLOCKS = '.ce-toolbar, .ce-popover, .ce-inline-toolbar, .ce-conversion-toolbar, .ce-settings'; + +/** Blocks whose tools use Tab themselves (nested lists, table cells, code indentation). */ +const OWN_TAB = + '.cdx-list, .cdx-nested-list, .cdx-checklist, .mex-table, table, .ce-code, .mex-code, textarea'; + +/** + * True for an element that can take focus from Tab. + * @param {Element} element - Candidate. + * @param {(element: Element) => boolean} isVisible - Visibility check (rendered and not hidden). + * @returns {boolean} Result. + */ +const focusable = (element, isVisible) => { + if (!element || element.closest(OUTSIDE_BLOCKS)) return false; + if (!element.closest('.ce-block')) return false; + if (element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true') return false; + if (element.getAttribute('tabindex') === '-1') return false; + if (element.closest('[inert], [hidden], [aria-hidden="true"]')) return false; + return isVisible(element); +}; + +/** + * True when the element is a text input (Editor.js moves between these itself). + * @param {Element|null} element - Element. + * @returns {boolean} Result. + */ +export const isTextStop = (element) => Boolean(element && element.matches && element.matches(TEXT_SELECTOR)); + +/** + * Tab stops of an editor in document order. + * @param {Element} holder - Editor holder. + * @param {(element: Element) => boolean} [isVisible] - Visibility check. + * @returns {Element[]} Stops. + */ +export const tabStops = (holder, isVisible = (element) => element.getClientRects().length > 0) => { + if (!holder) return []; + return Array.from(holder.querySelectorAll(`${TEXT_SELECTOR}, ${CONTROL_SELECTOR}`)).filter( + (element, index, all) => + focusable(element, isVisible) && + // A control inside a contenteditable (an inline chip) is part of the text. + !( + element.matches(CONTROL_SELECTOR) && + element.parentElement && + element.parentElement.closest('[contenteditable="true"]') + ) && + all.indexOf(element) === index + ); +}; + +/** + * The stop to focus for Tab or Shift+Tab, or null to leave the key to Editor.js and the tools. + * @param {Element} holder - Editor holder. + * @param {Element|null} active - Focused element. + * @param {boolean} backwards - Shift+Tab. + * @param {(element: Element) => boolean} [isVisible] - Visibility check. + * @returns {{ target: Element|null, handled: boolean }} `handled` false: do nothing; `target` null with + * `handled` true: no stop left in this direction (focus leaves the editor the browser's way). + */ +export const nextTabStop = (holder, active, backwards, isVisible) => { + if (!holder || !active || !holder.contains(active)) return { target: null, handled: false }; + const stops = tabStops(holder, isVisible); + // The focused stop itself first: a stop can contain another (the clear button inside a combobox). + const current = + stops.find((stop) => stop === active) || stops.filter((stop) => stop.contains(active)).pop() || null; + if (!current) return { target: null, handled: false }; + const onControl = !isTextStop(current); + // Tools that use Tab themselves keep it while the caret is in their text. + if (!onControl && current.closest(OWN_TAB)) return { target: null, handled: false }; + const index = stops.indexOf(current); + const target = stops[backwards ? index - 1 : index + 1] || null; + if (onControl) return { target, handled: true }; + if (target && !isTextStop(target)) return { target, handled: true }; + // A form input in another block (component blocks render Design System inputs): Editor.js + // focuses it without preventing the default, so the browser moved one stop further. + if ( + target && + !target.matches('[contenteditable="true"]') && + target.closest('.ce-block') !== current.closest('.ce-block') + ) + return { target, handled: true }; + return { target: null, handled: false }; +}; + +/** + * Puts focus on a stop; a text stop gets the caret at its start (Tab) or end (Shift+Tab). + * @param {Element} target - Stop. + * @param {boolean} backwards - Shift+Tab. + * @returns {void} + */ +export const focusTabStop = (target, backwards) => { + target.focus({ preventScroll: false }); + if (!isTextStop(target) || target.getAttribute('contenteditable') !== 'true') return; + const selection = target.ownerDocument.defaultView.getSelection(); + if (!selection) return; + const range = target.ownerDocument.createRange(); + range.selectNodeContents(target); + range.collapse(!backwards); + selection.removeAllRanges(); + selection.addRange(range); +}; + +/** Blocks whose controls have their own keyboard entry (the table tools: Alt+F10). */ +const OWN_CONTROLS = '.mex-table, table'; + +/** + * Controls that Editor.js skipped when an arrow key moved the caret from one text input to another + * (2.7.8): blocks without text (audio, video) and buttons before or after a block's text (toggle, + * columns) are otherwise never reached with the arrow keys. Returns the control to focus instead, + * the nearest one in the direction of the move, or null. + * @param {Element} holder - Editor holder. + * @param {Element|null} from - Focused element before the key. + * @param {Element|null} to - Focused element after Editor.js handled the key. + * @param {(element: Element) => boolean} [isVisible] - Visibility check. + * @returns {Element|null} Control. + */ +export const skippedControl = (holder, from, to, isVisible) => { + if (!holder || !from || !to || from === to || !holder.contains(from) || !holder.contains(to)) return null; + const fromBlock = from.closest('.ce-block'); + const toBlock = to.closest('.ce-block'); + if (!fromBlock || !toBlock || fromBlock === toBlock) return null; + const stops = tabStops(holder, isVisible); + const position = (element) => { + const exact = stops.indexOf(element); + if (exact >= 0) return exact; + let found = -1; + stops.forEach((stop, index) => { + if (stop.contains(element)) found = index; + }); + return found; + }; + const a = position(from); + const b = position(to); + if (a < 0 || b < 0) return null; + const forward = b > a; + const between = stops + .slice(Math.min(a, b) + 1, Math.max(a, b)) + // A select or combobox changes its value with the arrow keys; Tab reaches those. + .filter( + (stop) => !isTextStop(stop) && !stop.closest(OWN_CONTROLS) && !stop.matches('select, [role="combobox"]') + ); + if (!between.length) return null; + return forward ? between[0] : between[between.length - 1]; +}; diff --git a/admin/src/editor/room-state.mjs b/admin/src/editor/room-state.mjs index adae9f4..52eb16c 100644 --- a/admin/src/editor/room-state.mjs +++ b/admin/src/editor/room-state.mjs @@ -1,5 +1,5 @@ import { comparableBlocks } from '../../../shared/default-tunes.mjs'; -import { stableStringify } from '../../../shared/ydoc.mjs'; +import { stableStringifyBlocks } from '../../../shared/ydoc.mjs'; /** * Live collaboration room vs. stored value (2.7.4, M3). @@ -17,7 +17,7 @@ import { stableStringify } from '../../../shared/ydoc.mjs'; * @returns {string} Fingerprint. */ const fingerprint = (blocks) => - stableStringify( + stableStringifyBlocks( comparableBlocks(Array.isArray(blocks) ? blocks : []).filter( (block) => // An empty paragraph is what an empty field shows; it is not content. @@ -37,3 +37,15 @@ const fingerprint = (blocks) => */ export const roomDiffersFromStored = (room, stored) => fingerprint(room && room.blocks) !== fingerprint(stored && stored.blocks); + +/** + * True when a live update brought a room with unsaved changes back to the stored value (2.7.8): + * another person discarded the unsaved changes (or undid them all). The field then says so and + * offers to put the previous text back. + * @param {{ blocks?: Array }|null|undefined} before - Room content shown before the update. + * @param {{ blocks?: Array }|null|undefined} after - Room content shown after the update. + * @param {{ blocks?: Array }|null|undefined} stored - Stored value, prepared. + * @returns {boolean} Result. + */ +export const roomWasReset = (before, after, stored) => + Boolean(before && after) && roomDiffersFromStored(before, stored) && !roomDiffersFromStored(after, stored); diff --git a/admin/src/editor/sanitize.js b/admin/src/editor/sanitize.js index dd8d218..b758472 100644 --- a/admin/src/editor/sanitize.js +++ b/admin/src/editor/sanitize.js @@ -82,13 +82,27 @@ const ALLOWED_ATTR = Array.from(new Set(Object.values(INLINE_ATTRIBUTES).flat()) const ANNOTATION_VALUE_ATTRIBUTE = /^data-mex-a-[a-z][a-z0-9]{0,23}$/; /** - * Sanitises inline HTML (paragraph text, captions, table cells). - * @param {string} html - Untrusted HTML. + * 2.7.8: results of `sanitizeInline` by input string. Every change of a + * field sanitised the whole document again (form value, rendered key, draft + * fingerprint), which cost about 155 ms per keystroke at 2,000 blocks. The + * sanitiser is a pure function of its input (fixed config, hooks that only + * read the node), so an unchanged string gets the same output from the + * cache; only changed text is parsed again. Least recently used entries are + * dropped beyond the limit, and very long strings are not kept. The server + * still sanitises on save and stays the authority. + */ +const INLINE_CACHE_LIMIT = 20000; +const INLINE_CACHE_MAX_LENGTH = 65536; +const inlineCache = new Map(); + +/** + * Sanitises inline HTML without the cache. + * @param {string} input - Untrusted HTML. * @returns {string} Safe HTML. */ -export const sanitizeInline = (html) => +const sanitizeInlineUncached = (input) => canonicalInlineExtras( - instance().sanitize(String(html || ''), { + instance().sanitize(input, { ALLOWED_TAGS: [...INLINE_TAGS], ALLOWED_ATTR, ALLOW_DATA_ATTR: false, @@ -110,6 +124,32 @@ export const sanitizeInline = (html) => }) ); +/** + * Sanitises inline HTML (paragraph text, captions, table cells). + * Memoised by input (see `inlineCache`). + * @param {string} html - Untrusted HTML. + * @returns {string} Safe HTML. + */ +export const sanitizeInline = (html) => { + const input = String(html || ''); + if (input === '') return ''; + if (input.length > INLINE_CACHE_MAX_LENGTH) return sanitizeInlineUncached(input); + const hit = inlineCache.get(input); + if (hit !== undefined) { + // Refresh the entry so it is dropped last. + inlineCache.delete(input); + inlineCache.set(input, hit); + return hit; + } + const clean = sanitizeInlineUncached(input); + inlineCache.set(input, clean); + if (inlineCache.size > INLINE_CACHE_LIMIT) inlineCache.delete(inlineCache.keys().next().value); + return clean; +}; + +/** Size of the inline sanitiser cache (tests). @returns {number} Entries. */ +export const inlineCacheSize = () => inlineCache.size; + /** * Sanitises markup of a custom block template (admin-defined, rendered for every editor). * @param {string} html - Template HTML. diff --git a/admin/src/editor/toolbar-a11y.mjs b/admin/src/editor/toolbar-a11y.mjs new file mode 100644 index 0000000..cd9ed5c --- /dev/null +++ b/admin/src/editor/toolbar-a11y.mjs @@ -0,0 +1,46 @@ +/** + * Accessible block toolbar (2.7.8, re-audit major 1). + * + * Editor.js 2.31 renders the "+" (add a block) control as a `div` and the + * "⋮⋮" (block menu) control as a `span`, without a role, a name or a tab stop. + * Both get `role="button"`, `tabindex="0"`, a translated name and + * Enter/Space activation here. Editor.js opens the toolbox on `click` of "+" + * and the block menu on `mousedown` of "⋮⋮" (editorjs.mjs, Toolbar module), so + * the keys dispatch the same events. Ctrl/Cmd+/ (Editor.js' own block menu + * shortcut) and "/" or Tab in an empty block (block types) stay the keyboard + * shortcuts; these buttons serve Tab and screen reader users. + */ + +/** + * Decorates the toolbar controls of one editor. + * @param {Element|null} holder - Editor holder. + * @param {{ add: string, menu: string }} labels - Translated names. + * @returns {() => void} Cleanup (removes the key handlers; the attributes stay with the nodes). + */ +export const decorateToolbar = (holder, labels) => { + if (!holder) return () => {}; + const plus = holder.querySelector('.ce-toolbar__plus'); + const menu = holder.querySelector('.ce-toolbar__settings-btn'); + const cleanups = []; + const decorate = (node, label, activate) => { + if (!node) return; + node.setAttribute('role', 'button'); + node.setAttribute('tabindex', '0'); + node.setAttribute('aria-label', label); + node.setAttribute('aria-haspopup', 'menu'); + const onKeyDown = (event) => { + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + event.stopPropagation(); + activate(node); + }; + node.addEventListener('keydown', onKeyDown); + cleanups.push(() => node.removeEventListener('keydown', onKeyDown)); + }; + decorate(plus, labels.add, (node) => node.click()); + decorate(menu, labels.menu, (node) => { + const view = node.ownerDocument.defaultView; + node.dispatchEvent(new view.MouseEvent('mousedown', { bubbles: true, cancelable: true })); + }); + return () => cleanups.forEach((cleanup) => cleanup()); +}; diff --git a/admin/src/editor/tools/styles.js b/admin/src/editor/tools/styles.js index 9ab3163..f0e1f6e 100644 --- a/admin/src/editor/tools/styles.js +++ b/admin/src/editor/tools/styles.js @@ -119,6 +119,13 @@ export const editorStyles = css` background: ${c('neutral150')}; color: ${c('neutral800')}; } + + /* 2.7.8: the handles are keyboard buttons (editor/toolbar-a11y.mjs). */ + &:focus-visible { + outline: 2px solid ${c('primary600')}; + outline-offset: 1px; + color: ${c('neutral800')}; + } } .ce-toolbar__settings-btn[draggable='true'] { @@ -150,6 +157,21 @@ export const editorStyles = css` outline: none; } + /* 2.7.8: every control inside a block shows a focus ring (tools may refine it below). */ + .ce-block + :is( + button, + select, + input[type='checkbox'], + input[type='radio'], + [role='switch'], + [role='button'], + a[href] + ):focus-visible { + outline: 2px solid ${c('primary600')}; + outline-offset: 2px; + } + [data-placeholder]:empty::before, .ce-paragraph[data-placeholder]:empty::before, .mex-tool__editable[data-placeholder]:empty::before { diff --git a/admin/src/translations/editor/de.json b/admin/src/translations/editor/de.json index a475eb8..c74c48f 100644 --- a/admin/src/translations/editor/de.json +++ b/admin/src/translations/editor/de.json @@ -771,5 +771,18 @@ "editor.session.opened": "Melden Sie sich im neuen Tab an. Diese Seite bleibt mit Ihren Änderungen geöffnet.", "editor.session.blocked": "Ihr Browser hat den neuen Tab blockiert.", "editor.session.blockedLink": "Anmeldeseite öffnen", - "editor.session.resumed": "Sie sind wieder angemeldet. Speichern Sie den Eintrag, um Ihre Änderungen zu behalten." + "editor.session.resumed": "Sie sind wieder angemeldet. Speichern Sie den Eintrag, um Ihre Änderungen zu behalten.", + "editor.toolbar.add": "Block hinzufügen", + "editor.toolbar.blockMenu": "Blockmenü öffnen", + "editor.shortcuts.blockMenu": "Blockmenü des aktuellen Blocks (verschieben, löschen, umwandeln)", + "editor.shortcuts.addBlock": "Blocktyp wählen (in einem leeren Block)", + "editor.shortcuts.blockControls": "Schaltflächen und Optionen in einem Block (Umschalt+Tab: zurück)", + "editor.room.discardTitle": "Nicht gespeicherte Änderungen für alle verwerfen?", + "editor.room.discardBody": "Der gespeicherte Inhalt kehrt in diesem Feld für alle zurück, die diesen Eintrag gerade bearbeiten. Auch deren nicht gespeicherter Text in diesem Feld wird entfernt. Sie können das direkt danach rückgängig machen.", + "editor.room.discardConfirm": "Für alle verwerfen", + "editor.room.discarded": "Die nicht gespeicherten Änderungen wurden für alle verworfen. Dieses Feld zeigt den gespeicherten Inhalt.", + "editor.room.discardedRemote": "Jemand in dieser Live-Sitzung hat dieses Feld auf den gespeicherten Inhalt zurückgesetzt. Ihr nicht gespeicherter Text in diesem Feld wurde entfernt.", + "editor.room.undoDiscard": "Rückgängig", + "editor.room.restoreText": "Meinen Text wiederherstellen", + "editor.room.dismiss": "Ausblenden" } diff --git a/admin/src/translations/editor/en.json b/admin/src/translations/editor/en.json index 2582a14..73f943d 100644 --- a/admin/src/translations/editor/en.json +++ b/admin/src/translations/editor/en.json @@ -771,5 +771,18 @@ "editor.session.opened": "Sign in in the new tab. This page stays open with your changes.", "editor.session.blocked": "Your browser blocked the new tab.", "editor.session.blockedLink": "Open the sign-in page", - "editor.session.resumed": "You are signed in again. Save the entry to keep your changes." + "editor.session.resumed": "You are signed in again. Save the entry to keep your changes.", + "editor.toolbar.add": "Add a block", + "editor.toolbar.blockMenu": "Open the block menu", + "editor.shortcuts.blockMenu": "Block menu of the current block (move, delete, convert)", + "editor.shortcuts.addBlock": "Choose a block type (in an empty block)", + "editor.shortcuts.blockControls": "Buttons and options inside a block (Shift+Tab: back)", + "editor.room.discardTitle": "Discard the unsaved changes for everyone?", + "editor.room.discardBody": "The saved content comes back in this field for everyone editing this entry right now. Their unsaved text in this field is removed too. You can undo this right after.", + "editor.room.discardConfirm": "Discard for everyone", + "editor.room.discarded": "The unsaved changes were discarded for everyone. This field shows the saved content.", + "editor.room.discardedRemote": "Someone in this live session brought this field back to the saved content. Your unsaved text in this field was removed.", + "editor.room.undoDiscard": "Undo", + "editor.room.restoreText": "Restore my text", + "editor.room.dismiss": "Dismiss" } diff --git a/admin/src/translations/editor/es.json b/admin/src/translations/editor/es.json index 9a810c4..067e0b2 100644 --- a/admin/src/translations/editor/es.json +++ b/admin/src/translations/editor/es.json @@ -771,5 +771,18 @@ "editor.session.opened": "Inicie sesión en la pestaña nueva. Esta página sigue abierta con sus cambios.", "editor.session.blocked": "Su navegador bloqueó la pestaña nueva.", "editor.session.blockedLink": "Abrir la página de inicio de sesión", - "editor.session.resumed": "Ha vuelto a iniciar sesión. Guarde la entrada para conservar sus cambios." + "editor.session.resumed": "Ha vuelto a iniciar sesión. Guarde la entrada para conservar sus cambios.", + "editor.toolbar.add": "Añadir un bloque", + "editor.toolbar.blockMenu": "Abrir el menú del bloque", + "editor.shortcuts.blockMenu": "Menú del bloque actual (mover, eliminar, convertir)", + "editor.shortcuts.addBlock": "Elegir un tipo de bloque (en un bloque vacío)", + "editor.shortcuts.blockControls": "Botones y opciones dentro de un bloque (Mayús+Tab: atrás)", + "editor.room.discardTitle": "¿Descartar los cambios sin guardar para todos?", + "editor.room.discardBody": "El contenido guardado vuelve a este campo para todas las personas que editan esta entrada ahora mismo. Su texto sin guardar en este campo también se elimina. Puede deshacerlo justo después.", + "editor.room.discardConfirm": "Descartar para todos", + "editor.room.discarded": "Los cambios sin guardar se descartaron para todos. Este campo muestra el contenido guardado.", + "editor.room.discardedRemote": "Alguien en esta sesión en vivo devolvió este campo al contenido guardado. Su texto sin guardar en este campo se eliminó.", + "editor.room.undoDiscard": "Deshacer", + "editor.room.restoreText": "Restaurar mi texto", + "editor.room.dismiss": "Descartar aviso" } diff --git a/admin/src/translations/editor/fr.json b/admin/src/translations/editor/fr.json index 608f5f5..24ec4ad 100644 --- a/admin/src/translations/editor/fr.json +++ b/admin/src/translations/editor/fr.json @@ -771,5 +771,18 @@ "editor.session.opened": "Connectez-vous dans le nouvel onglet. Cette page reste ouverte avec vos modifications.", "editor.session.blocked": "Votre navigateur a bloqué le nouvel onglet.", "editor.session.blockedLink": "Ouvrir la page de connexion", - "editor.session.resumed": "Vous êtes de nouveau connecté. Enregistrez l’entrée pour conserver vos modifications." + "editor.session.resumed": "Vous êtes de nouveau connecté. Enregistrez l’entrée pour conserver vos modifications.", + "editor.toolbar.add": "Ajouter un bloc", + "editor.toolbar.blockMenu": "Ouvrir le menu du bloc", + "editor.shortcuts.blockMenu": "Menu du bloc actuel (déplacer, supprimer, convertir)", + "editor.shortcuts.addBlock": "Choisir un type de bloc (dans un bloc vide)", + "editor.shortcuts.blockControls": "Boutons et options dans un bloc (Maj+Tab : retour)", + "editor.room.discardTitle": "Abandonner les modifications non enregistrées pour tout le monde ?", + "editor.room.discardBody": "Le contenu enregistré revient dans ce champ pour toutes les personnes qui modifient cette entrée en ce moment. Leur texte non enregistré dans ce champ est aussi supprimé. Vous pourrez l'annuler juste après.", + "editor.room.discardConfirm": "Abandonner pour tout le monde", + "editor.room.discarded": "Les modifications non enregistrées ont été abandonnées pour tout le monde. Ce champ affiche le contenu enregistré.", + "editor.room.discardedRemote": "Une personne de cette session en direct a rétabli le contenu enregistré de ce champ. Votre texte non enregistré dans ce champ a été supprimé.", + "editor.room.undoDiscard": "Annuler", + "editor.room.restoreText": "Restaurer mon texte", + "editor.room.dismiss": "Masquer" } diff --git a/admin/src/translations/editor/pt.json b/admin/src/translations/editor/pt.json index ff55b79..2b85a89 100644 --- a/admin/src/translations/editor/pt.json +++ b/admin/src/translations/editor/pt.json @@ -771,5 +771,18 @@ "editor.session.opened": "Inicie sessão no novo separador. Esta página continua aberta com as suas alterações.", "editor.session.blocked": "O seu navegador bloqueou o novo separador.", "editor.session.blockedLink": "Abrir a página de início de sessão", - "editor.session.resumed": "Tem sessão iniciada novamente. Guarde a entrada para manter as suas alterações." + "editor.session.resumed": "Tem sessão iniciada novamente. Guarde a entrada para manter as suas alterações.", + "editor.toolbar.add": "Adicionar um bloco", + "editor.toolbar.blockMenu": "Abrir o menu do bloco", + "editor.shortcuts.blockMenu": "Menu do bloco atual (mover, excluir, converter)", + "editor.shortcuts.addBlock": "Escolher um tipo de bloco (em um bloco vazio)", + "editor.shortcuts.blockControls": "Botões e opções dentro de um bloco (Shift+Tab: voltar)", + "editor.room.discardTitle": "Descartar as alterações não salvas para todos?", + "editor.room.discardBody": "O conteúdo salvo volta a este campo para todas as pessoas que editam esta entrada agora. O texto não salvo delas neste campo também é removido. Você pode desfazer isso logo em seguida.", + "editor.room.discardConfirm": "Descartar para todos", + "editor.room.discarded": "As alterações não salvas foram descartadas para todos. Este campo mostra o conteúdo salvo.", + "editor.room.discardedRemote": "Alguém nesta sessão ao vivo voltou este campo ao conteúdo salvo. O seu texto não salvo neste campo foi removido.", + "editor.room.undoDiscard": "Desfazer", + "editor.room.restoreText": "Restaurar meu texto", + "editor.room.dismiss": "Dispensar" } diff --git a/docs/site/llms-full.txt b/docs/site/llms-full.txt index dcc3ec2..e300898 100644 --- a/docs/site/llms-full.txt +++ b/docs/site/llms-full.txt @@ -155,7 +155,7 @@ All screenshots use synthetic data (captured on Strapi 5.61.1 and 5.62.0; accept | Version history | More tools > Version history, for a saved document | `access` and Content Manager read on the document; saving, naming and restoring need update. The Activity tab needs `audit.read`. | | Find and replace | More tools > Find and replace, or Ctrl/Cmd+Shift+F in the editor | Everyone who can read the field; replacing needs update. | | Quality checks | More tools > Quality checks (the number counts problems) | Everyone who can read the field; the link check needs `access`. | -| Keyboard shortcuts, focus mode | More tools > Keyboard shortcuts or Focus mode, or Ctrl/Cmd+/ | Everyone who can read the field. | +| Keyboard shortcuts, focus mode | More tools > Keyboard shortcuts or Focus mode, or Ctrl/Cmd+Alt+/ | Everyone who can read the field. | | Field options | Content-Type Builder, Magic Editor X field, Basic and Advanced settings | Content-Type Builder access (development mode). | | AI assistant | Inline toolbar (select text), or a block's menu, the block selection bar or Ctrl/Cmd+Shift+G for whole blocks | `access` and `ai.use`, when an administrator turned the assistant on. | | AI for the whole field | More tools > AI for the whole field | `access` and `ai.use`, when the owner allowed whole-field AI actions and the field does not turn AI off. | @@ -507,7 +507,7 @@ Changing a preset never changes stored content by itself. Turning `sanitizeOnSav | More tools menu | The field toolbar shows undo, redo, **More tools** and full screen. More tools groups the other tools: **Review** (comments, version history, suggestions, quality checks), **Write** (suggest changes, AI for the whole field, check grammar, find and replace, insert template) and **View** (preview, focus mode, keyboard shortcuts). Entries appear only where they can work (permission, settings, field options); counts show in the menu, and a tool that changes the view (preview, focus mode) adds a visible way back to the bar. Keyboard shortcuts are unchanged. | | Markdown shortcuts | At the start of an empty paragraph: `#` to `######` + Space (heading), `-`, `*` or `+` + Space (bulleted list), `1.` + Space (numbered list, other numbers set the start), `[]` or `[x]` + Space (checklist), `>` + Space (quote), ` ``` ` (optionally with a language) + Enter (code block), `---` + Enter (delimiter). While typing: `**bold**`, `__bold__`, `*italic*`, `_italic_`, `~~strike~~`, `` `code` ``. Never inside code, raw HTML or tables; only blocks and marks the field allows. | | Find and replace | Magnifier button or Ctrl/Cmd+Shift+F. Searches every text block, list item, table cell, caption and code block; keeps formatting; match case, whole words, regular expressions (off by default, patterns up to 200 characters). Enter / Shift+Enter move between matches, the current match is highlighted. Replacements are normal edits (undo, collaboration). A match cannot span differently formatted text. | -| Keyboard shortcuts | Ctrl/Cmd+/ or More > Keyboard shortcuts: editor, block and inline tool shortcuts and the Markdown shortcuts of this field. | +| Keyboard shortcuts | Ctrl/Cmd+Alt+/ or More > Keyboard shortcuts: editor, block and inline tool shortcuts and the Markdown shortcuts of this field. Keyboard path to blocks: Ctrl/Cmd+/ opens the block menu of the current block (move, delete, convert), `/` or Tab in an empty block chooses a block type, Tab and the arrow keys reach the buttons and options inside blocks, and the **+** and block menu handles are buttons with names. | | Focus mode | More > Focus mode: full screen, narrower text column, other blocks dimmed. Escape leaves. | | Several selected blocks | Select across blocks (Shift+Arrow at a block edge, Ctrl/Cmd+A twice, or drag across blocks): move up or down, duplicate, copy as Markdown, delete, convert to text, heading, list or quote. | | Counts | Blocks, words, characters and reading time (200 words per minute) in the toolbar, with the field's limits. | @@ -1925,7 +1925,7 @@ Private image storage for alt text (`ai.altText.allowPrivateOrigins`, config onl ## Editor field extras -- Markdown shortcuts (`editor/markdown-shortcuts*.{js,mjs}`), find and replace (`shared/find-replace.mjs` + `FindReplacePanel`, CSS Custom Highlight `mex-find`), shortcuts dialog (Ctrl/Cmd+/), focus mode, `BlockSelectionBar` (Editor.js `.ce-block--selected`), quality panel (`QualityPanel`, `useQualityIssues`) with preset violations, `lang`/`dir` from the content locale. The image tool is `MexImageTool` (`tools/alt-text.js`, subclass of `@editorjs/image` adding alt text, the decorative flag and the focal point control). Media tools (`tools/media.js`: `GalleryTool`, `VideoTool`, `AudioTool`; pure logic in `tools/media-logic.mjs`; focal point control `tools/focal-point.js`: disclosure button, click/tap on the preview, arrow keys 1 % / Shift 10 %, reset, polite live value) open the Strapi Media Library dialog through `openMediaLibrary({ multiple, allowedTypes: ['images'|'videos'|'audios'|'files'], accept(asset), onSelect(assets) })`; `EditorField` filters the picked assets with `accept` and returns focus to the trigger. They are offered only with `plugin::upload.read` (`config.permissions.mediaLibrary`, tool config `canBrowse`); without it they are hidden from the toolbox and existing blocks explain why no files can be chosen. Gallery: add (multiple), move earlier/later, remove, per-image alt (default: the file's Media Library alternative text; `requireAlt`/decorative as in the image block), caption, focal point, layout and columns. Video/audio: choose/replace, title, caption, loop (+ muted and poster for video), WebVTT tracks (kind, language defaulting to the content locale, label, one default). +- Markdown shortcuts (`editor/markdown-shortcuts*.{js,mjs}`), find and replace (`shared/find-replace.mjs` + `FindReplacePanel`, CSS Custom Highlight `mex-find`), shortcuts dialog (Ctrl/Cmd+Alt+/; Ctrl/Cmd+/ is the Editor.js block menu), focus mode, `BlockSelectionBar` (Editor.js `.ce-block--selected`), quality panel (`QualityPanel`, `useQualityIssues`) with preset violations, `lang`/`dir` from the content locale. The image tool is `MexImageTool` (`tools/alt-text.js`, subclass of `@editorjs/image` adding alt text, the decorative flag and the focal point control). Media tools (`tools/media.js`: `GalleryTool`, `VideoTool`, `AudioTool`; pure logic in `tools/media-logic.mjs`; focal point control `tools/focal-point.js`: disclosure button, click/tap on the preview, arrow keys 1 % / Shift 10 %, reset, polite live value) open the Strapi Media Library dialog through `openMediaLibrary({ multiple, allowedTypes: ['images'|'videos'|'audios'|'files'], accept(asset), onSelect(assets) })`; `EditorField` filters the picked assets with `accept` and returns focus to the trigger. They are offered only with `plugin::upload.read` (`config.permissions.mediaLibrary`, tool config `canBrowse`); without it they are hidden from the toolbox and existing blocks explain why no files can be chosen. Gallery: add (multiple), move earlier/later, remove, per-image alt (default: the file's Media Library alternative text; `requireAlt`/decorative as in the image block), caption, focal point, layout and columns. Video/audio: choose/replace, title, caption, loop (+ muted and poster for video), WebVTT tracks (kind, language defaulting to the content locale, label, one default). - Field readiness and edits (`editor/input-tracking.mjs`): the field reports content to the form only after the person edited it (Editor.js also reports its normalisation of stored content on the first render). User input (`pointerdown`, `keydown`, `input`, `paste`, `drop`, capture phase on the holder) is tracked from before Editor.js renders, and edits made while Editor.js was starting are saved on `onReady`; after the Content Manager's create -> edit redirect several fields mount at once and text typed before the field's own effects ran used to stay out of the form (Save stayed disabled). The holder (`[data-testid="magic-editor-x"]`) carries `aria-busy="true"` while loading and `data-mex-ready="true"` once Editor.js is ready and every listener is attached; browser tests wait for `data-mex-ready` instead of sleeping. - Editor styles (`editor/tools/styles.js`) are one global style rendered by the first mounted field only (`editor/style-owners.mjs`, `SharedEditorStyles`); one copy per field made styled-components rebuild every copy on each mount and unmount (seconds of blocked main thread on pages with several fields). - `apply-remote.js`: default tune values count as "no tune" in `blockKey` (`shared/default-tunes.mjs`); more than 150 changed blocks (and a quarter of the document) are applied with one `render` instead of per-block updates (Editor.js notifies every block on each mutation). diff --git a/shared/convert/html.mjs b/shared/convert/html.mjs index 2a8ad17..0642849 100644 --- a/shared/convert/html.mjs +++ b/shared/convert/html.mjs @@ -191,22 +191,59 @@ const textOf = (node, depth = 0) => { const hasBlockChild = (node) => (node.children || []).some((child) => isElement(child) && BLOCK_ELEMENTS.has(child.name)); +/** + * Value of one CSS property in an inline style attribute, matched by its exact + * name (2.7.8: a substring match read `mso-bidi-font-weight:normal` as + * `font-weight:normal` and dropped Word's bold). + * @param {string} style - Style attribute. + * @param {string} name - Lower-case property name. + * @returns {string|null} Lower-case value without `!important`, or null. + */ +export const cssProperty = (style, name) => { + let found = null; + for (const declaration of String(style || '').split(';')) { + const colon = declaration.indexOf(':'); + if (colon < 0) continue; + if (declaration.slice(0, colon).trim().toLowerCase() !== name) continue; + // The last declaration wins, as in CSS. + found = declaration + .slice(colon + 1) + .replace(/!important/i, '') + .trim() + .toLowerCase(); + } + return found; +}; + +/** + * True when a style sets a normal font weight (`font-weight: normal` or `400`). + * Only the exact property counts: Word writes `mso-bidi-font-weight:normal` on + * real bold text (2.7.8). + * @param {string} style - Lower-case style attribute. + * @returns {boolean} Result. + */ +const isNormalWeight = (style) => /^(normal|400)$/.test(cssProperty(style, 'font-weight') || ''); + /** * Inline marks from a style attribute (Google Docs and Word use styled spans). + * Properties are matched by exact name, so vendor properties such as + * `mso-bidi-font-weight` never count as `font-weight`. * @param {string} style - Lower-case style attribute. * @returns {string[]} Mark names. */ const marksFromStyle = (style) => { const marks = []; if (!style) return marks; - const weight = /font-weight\s*:\s*([a-z0-9]+)/.exec(style); - if (weight && (/^(bold|bolder)$/.test(weight[1]) || Number(weight[1]) >= 600)) marks.push('bold'); - if (/font-style\s*:\s*(italic|oblique)/.test(style)) marks.push('italic'); - const decoration = /text-decoration(?:-line)?\s*:\s*([^;]+)/.exec(style); - if (decoration && /underline/.test(decoration[1])) marks.push('underline'); - if (decoration && /line-through/.test(decoration[1])) marks.push('strike'); - const align = /vertical-align\s*:\s*(super|sub)/.exec(style); - if (align) marks.push(align[1] === 'super' ? 'sup' : 'sub'); + const weight = cssProperty(style, 'font-weight'); + if (weight && (/^(bold|bolder)$/.test(weight) || Number(weight) >= 600)) marks.push('bold'); + if (/^(italic|oblique)/.test(cssProperty(style, 'font-style') || '')) marks.push('italic'); + const decoration = [cssProperty(style, 'text-decoration'), cssProperty(style, 'text-decoration-line')] + .filter(Boolean) + .join(' '); + if (/underline/.test(decoration)) marks.push('underline'); + if (/line-through/.test(decoration)) marks.push('strike'); + const align = cssProperty(style, 'vertical-align'); + if (align === 'super' || align === 'sub') marks.push(align === 'super' ? 'sup' : 'sub'); return marks; }; @@ -296,7 +333,7 @@ const inlineOf = (nodes, state, depth = 0) => { const marks = []; const tagMark = TAG_MARKS[name]; // Google Docs wraps the whole clipboard in . - if (tagMark && !(tagMark === 'bold' && /font-weight\s*:\s*(normal|400)/.test(style))) marks.push(tagMark); + if (tagMark && !(tagMark === 'bold' && isNormalWeight(style))) marks.push(tagMark); for (const mark of marksFromStyle(style)) if (!marks.includes(mark)) marks.push(mark); for (const mark of marks) inner = wrapMark(inner, mark); html += inner; diff --git a/shared/ydoc.mjs b/shared/ydoc.mjs index c0b1d0a..f49e26d 100644 --- a/shared/ydoc.mjs +++ b/shared/ydoc.mjs @@ -81,6 +81,51 @@ export const stableStringify = (value) => { return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; }; +/** `undefined` becomes `null`, as in `stableStringify`, so the native key below is unambiguous. */ +const nullReplacer = (_key, value) => (value === undefined ? null : value); +const STABLE_CACHE_LIMIT = 20000; +const stableCache = new Map(); + +/** + * `stableStringify` of a list of blocks with a cache per block (2.7.8). The + * key of each block is the native `JSON.stringify` of it, which is much faster + * than the canonical form; a block that did not change since the last call + * gets its canonical string from the cache. The output is exactly + * `stableStringify(blocks)`. Typing in a 2,000-block field compared whole + * documents several times per keystroke. + * @param {Array} blocks - Blocks. + * @returns {string} Canonical JSON of the list. + */ +export const stableStringifyBlocks = (blocks) => { + if (!Array.isArray(blocks)) return stableStringify(blocks); + const parts = new Array(blocks.length); + for (let index = 0; index < blocks.length; index += 1) parts[index] = stableStringifyCached(blocks[index]); + return `[${parts.join(',')}]`; +}; + +/** + * `stableStringify` of one value with the cache described above (2.7.8). + * @param {unknown} value - Value (a block). + * @returns {string} Canonical JSON, exactly `stableStringify(value)`. + */ +export const stableStringifyCached = (value) => { + if (value === null || typeof value !== 'object') return stableStringify(value); + let raw; + try { + raw = JSON.stringify(value, nullReplacer); + } catch { + raw = undefined; + } + if (typeof raw !== 'string') return stableStringify(value); + let canonical = stableCache.get(raw); + if (canonical === undefined) { + canonical = stableStringify(value); + stableCache.set(raw, canonical); + if (stableCache.size > STABLE_CACHE_LIMIT) stableCache.delete(stableCache.keys().next().value); + } + return canonical; +}; + const equal = (a, b) => a === b || stableStringify(a) === stableStringify(b); /** diff --git a/tests/admin/block-keyboard.test.jsx b/tests/admin/block-keyboard.test.jsx new file mode 100644 index 0000000..e5bda7c --- /dev/null +++ b/tests/admin/block-keyboard.test.jsx @@ -0,0 +1,157 @@ +/** + * 2.7.8 re-audit majors 1 and 2: the block toolbar controls are named buttons, and Tab reaches the + * controls inside blocks (Editor.js itself only moves between text inputs). + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + nextTabStop, + tabStops, + focusTabStop, + skippedControl, +} from '../../admin/src/editor/block-tab-stops.mjs'; +import { decorateToolbar } from '../../admin/src/editor/toolbar-a11y.mjs'; + +const visible = () => true; + +const editor = () => { + const holder = document.createElement('div'); + holder.innerHTML = ` +
+
+
Paragraph A
+
+
Toggle
+
  • Item
+
+
Paragraph B
+
+
+
`; + document.body.append(holder); + return holder; +}; + +test('tab stops: text inputs and block controls in document order, no toolbar, no disabled', () => { + const holder = editor(); + const ids = tabStops(holder, visible).map((element) => element.id || element.textContent.trim()); + assert.deepEqual(ids, ['Paragraph A', 'choose', 'toggle', 'title', 'item', 'style', 'newtab', 'B']); + holder.remove(); +}); + +test('Tab from text to a control is handled; text to text is left to Editor.js', () => { + const holder = editor(); + const a = holder.querySelector('[data-id=A] [contenteditable]'); + let step = nextTabStop(holder, a, false, visible); + assert.equal(step.handled, true); + assert.equal(step.target.id, 'choose'); + // From a control, every step is handled (Editor.js would skip the next control). + step = nextTabStop(holder, holder.querySelector('#choose'), false, visible); + assert.equal(step.target.id, 'toggle'); + step = nextTabStop(holder, holder.querySelector('#toggle'), false, visible); + assert.equal(step.target.id, 'title'); + // Toggle title -> list item: text to text, Editor.js moves. + assert.equal(nextTabStop(holder, holder.querySelector('#title'), false, visible).handled, false); + // A list keeps Tab (nesting). + assert.equal(nextTabStop(holder, holder.querySelector('#item'), false, visible).handled, false); + // Shift+Tab from paragraph B reaches the checkbox, then the select. + step = nextTabStop(holder, holder.querySelector('#B'), true, visible); + assert.equal(step.target.id, 'newtab'); + step = nextTabStop(holder, step.target, true, visible); + assert.equal(step.target.id, 'style'); + holder.remove(); +}); + +test('focusTabStop puts the caret at the start (Tab) of a text stop', () => { + const holder = editor(); + const title = holder.querySelector('#title'); + focusTabStop(title, false); + assert.equal(document.activeElement, title); + const range = window.getSelection().getRangeAt(0); + assert.equal(range.collapsed, true); + assert.equal(range.startOffset, 0); + holder.remove(); +}); + +test('toolbar: "+" and the block menu handle are named buttons that open with Enter and Space', () => { + const holder = editor(); + const plus = holder.querySelector('.ce-toolbar__plus'); + const menu = holder.querySelector('.ce-toolbar__settings-btn'); + let clicks = 0; + let downs = 0; + plus.addEventListener('click', () => (clicks += 1)); + menu.addEventListener('mousedown', () => (downs += 1)); + const cleanup = decorateToolbar(holder, { add: 'Add a block', menu: 'Open the block menu' }); + for (const [node, name] of [ + [plus, 'Add a block'], + [menu, 'Open the block menu'], + ]) { + assert.equal(node.getAttribute('role'), 'button'); + assert.equal(node.getAttribute('tabindex'), '0'); + assert.equal(node.getAttribute('aria-label'), name); + } + plus.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + menu.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true })); + menu.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true })); + assert.equal(clicks, 1); + assert.equal(downs, 1); + cleanup(); + plus.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + assert.equal(clicks, 1, 'handlers removed on cleanup'); + holder.remove(); +}); + +test('arrow keys: a control Editor.js skipped between two texts is focused instead', () => { + const holder = editor(); + const a = holder.querySelector('[data-id=A] [contenteditable]'); + const title = holder.querySelector('#title'); + const b = holder.querySelector('#B'); + // A -> toggle title skipped the audio block and the toggle button: the nearest one going down. + assert.equal(skippedControl(holder, a, title, visible).id, 'choose'); + // B -> list item going up skipped the checkbox and the select: the nearest one going up. + assert.equal(skippedControl(holder, b, holder.querySelector('#item'), visible).id, 'newtab'); + // Same block or nothing in between: Editor.js' move stands. + assert.equal(skippedControl(holder, title, holder.querySelector('#item'), visible), null); + assert.equal(skippedControl(holder, a, a, visible), null); + holder.remove(); +}); + +test('component block: Design System inputs, combobox and switch are tab stops; stepper buttons are not', () => { + const holder = document.createElement('div'); + holder.innerHTML = ` +
A
+
+
Info
+ + +
+
B
`; + document.body.append(holder); + const ids = tabStops(holder, visible).map((element) => element.id); + assert.deepEqual(ids, ['A', 'headline', 'tone', 'count', 'featured', 'B']); + // Text -> form input in another block: handled here (Editor.js would let the browser move one further). + const step = nextTabStop(holder, holder.querySelector('#A'), false, visible); + assert.equal(step.handled, true); + assert.equal(step.target.id, 'headline'); + assert.equal(nextTabStop(holder, holder.querySelector('#headline'), false, visible).target.id, 'tone'); + // The arrow keys never stop on a combobox (they change its value). + assert.equal( + skippedControl(holder, holder.querySelector('#A'), holder.querySelector('#B'), visible).id, + 'featured' + ); + holder.remove(); +}); + +test('a stop inside another stop (clear button in a combobox) moves on instead of staying', () => { + const holder = document.createElement('div'); + holder.innerHTML = ` +
+
Info
+ +
`; + document.body.append(holder); + const clear = holder.querySelector('#clear'); + assert.equal(nextTabStop(holder, clear, false, visible).target.id, 'count'); + assert.equal(nextTabStop(holder, holder.querySelector('#count'), true, visible).target.id, 'clear'); + holder.remove(); +}); diff --git a/tests/admin/room-notice.test.jsx b/tests/admin/room-notice.test.jsx new file mode 100644 index 0000000..aaa56d3 --- /dev/null +++ b/tests/admin/room-notice.test.jsx @@ -0,0 +1,65 @@ +/** + * 2.7.8 re-audit major 5: "Discard changes" in the live-session notice asks first (it affects + * everyone in the room), and the notice after a discard offers Undo with focus on it. + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { act } from 'react'; +import { renderStrict, settle } from './harness/index.jsx'; +import { RoomNotice, RoomResetNotice } from '../../admin/src/components/EditorField/RoomNotice.jsx'; + +const t = (_id, text) => text; + +const click = async (element) => { + await act(async () => { + element.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 0 })); + element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })); + element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, button: 0 })); + element.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0 })); + element.click(); + }); + await settle(); +}; + +const button = (root, name) => + Array.from(root.querySelectorAll('button')).find((node) => node.textContent.trim() === name); + +test('Discard opens a confirmation that names everyone; Cancel discards nothing', async () => { + let discarded = 0; + const handle = await renderStrict( + (discarded += 1)} /> + ); + await click(button(document.body, 'Discard changes')); + const dialog = document.querySelector('[role="alertdialog"]'); + assert.ok(dialog, 'confirmation shown'); + assert.match(dialog.textContent, /Discard the unsaved changes for everyone\?/); + assert.match(dialog.textContent, /for everyone editing this entry/); + await click(button(dialog, 'Cancel')); + assert.equal(discarded, 0); + assert.equal(document.querySelector('[role="alertdialog"]'), null); + await click(button(document.body, 'Discard changes')); + await click(button(document.querySelector('[role="alertdialog"]'), 'Discard for everyone')); + assert.equal(discarded, 1); + await handle.unmount(); +}); + +test('after a discard, Undo has focus and calls back; the remote notice offers Restore', async () => { + let undone = 0; + const handle = await renderStrict( + (undone += 1)} onDismiss={() => {}} /> + ); + assert.equal(document.activeElement && document.activeElement.textContent.trim(), 'Undo'); + assert.equal( + document.querySelector('[data-testid="mex-room-reset-notice"] [role="status"]') !== null, + true + ); + await click(button(document.body, 'Undo')); + assert.equal(undone, 1); + await handle.unmount(); + const remote = await renderStrict( + {}} onDismiss={() => {}} /> + ); + assert.ok(button(document.body, 'Restore my text')); + assert.match(document.body.textContent, /Someone in this live session/); + await remote.unmount(); +}); diff --git a/tests/admin/sanitize-cache.test.jsx b/tests/admin/sanitize-cache.test.jsx new file mode 100644 index 0000000..1aec854 --- /dev/null +++ b/tests/admin/sanitize-cache.test.jsx @@ -0,0 +1,59 @@ +/** + * 2.7.8 re-audit (major 3): typing at 2,000 blocks cost ~155 ms per keystroke because every change + * sanitised the whole document with DOMPurify. `sanitizeInline` is memoised by input; the output + * must stay identical to an uncached run (same security guarantees) and a 2,000-block document + * must be prepared again cheaply when only one block changed. + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { inlineCacheSize, prepareEditorValue, sanitizeInline } from '../../admin/src/editor/sanitize.js'; + +const doc = (n, changed = -1) => ({ + time: 1, + version: '2.31.7', + blocks: Array.from({ length: n }, (_, i) => ({ + id: 'p' + i, + type: 'paragraph', + data: { + text: + 'Paragraph ' + + i + + (i === changed ? ' edited' : '') + + ' with bold, italic and a link .', + }, + })), +}); + +test('cached output equals the first (uncached) output and stays safe', () => { + const dirty = + 'abd'; + const first = sanitizeInline(dirty); + const second = sanitizeInline(dirty); + assert.equal(second, first); + assert.doesNotMatch(first, /onclick|javascript:|a<\/b>/); + assert.equal(sanitizeInline(''), ''); + assert.equal(sanitizeInline(null), ''); +}); + +test('target=_blank gets rel on a cache hit too', () => { + const html = 'x'; + assert.match(sanitizeInline(html), /rel="noopener noreferrer"/); + assert.match(sanitizeInline(html), /rel="noopener noreferrer"/); +}); + +test('2,000 blocks: preparing again after a one-block change is fast and equal', () => { + const full = prepareEditorValue(doc(2000)).data; + assert.equal(full.blocks.length, 2000); + assert.doesNotMatch(JSON.stringify(full), /onerror/); + const t0 = performance.now(); + const again = prepareEditorValue(doc(2000, 1000)).data; + const ms = performance.now() - t0; + assert.match(again.blocks[1000].data.text, /edited/); + assert.deepEqual(again.blocks[999], full.blocks[999]); + assert.ok(inlineCacheSize() >= 2000); + // jsdom is far slower than a browser; the uncached run takes several hundred ms here. + assert.ok(ms < 150, `re-prepare took ${Math.round(ms)} ms`); +}); diff --git a/tests/convert.test.mjs b/tests/convert.test.mjs index 0f16976..cb54a24 100644 --- a/tests/convert.test.mjs +++ b/tests/convert.test.mjs @@ -305,3 +305,27 @@ test('DOM adapter maps nodes like the htmlparser2 adapter', () => { const nodes = parseHtmlWithDom('

ignored

', FakeParser); assert.equal(htmlToBlocks('x', { parse: () => nodes }).blocks[0].data.text, 'Hi there'); }); + +test('2.7.8: Word bold with mso-bidi-font-weight:normal keeps bold; Google Docs wrapper does not', () => { + const word = htmlToBlocks( + "

Plain word bold and italic

", + { parse } + ).blocks; + assert.equal(word.length, 1); + assert.match(word[0].data.text, /word bold<\/b>/); + assert.match(word[0].data.text, /italic<\/i>/); + const gdocs = htmlToBlocks( + '

real bold plain

', + { parse } + ).blocks; + assert.equal(gdocs.length, 1); + assert.equal(gdocs[0].data.text, 'real bold plain'); + // A span whose only weight is a vendor property is not bold. + const vendor = htmlToBlocks('

not bold

', { + parse, + }).blocks; + assert.equal(vendor[0].data.text, 'not bold'); + // Inline wrapper without blocks: font-weight:400 on is not bold, a later bold declaration wins. + assert.equal(htmlToInline('x', parse), 'x'); + assert.equal(htmlToInline('y', parse), 'y'); +}); diff --git a/tests/room-state.test.mjs b/tests/room-state.test.mjs index 6bebab0..95c09b5 100644 --- a/tests/room-state.test.mjs +++ b/tests/room-state.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { roomDiffersFromStored } from '../admin/src/editor/room-state.mjs'; +import { roomDiffersFromStored, roomWasReset } from '../admin/src/editor/room-state.mjs'; const p = (id, text, tunes) => ({ id, type: 'paragraph', data: { text }, ...(tunes ? { tunes } : {}) }); @@ -40,3 +40,15 @@ test('M3: an empty field and a room with one empty paragraph are equal', () => { assert.equal(roomDiffersFromStored({ blocks: [p('x', '')] }, null), false); assert.equal(roomDiffersFromStored({ blocks: [] }, { blocks: [] }), false); }); + +test('2.7.8: roomWasReset detects a room that went back to the stored value', () => { + const stored = { blocks: [{ id: 'a', type: 'paragraph', data: { text: 'Stored text.' } }] }; + const unsaved = { + blocks: [{ id: 'a', type: 'paragraph', data: { text: 'Stored text. Unsaved live text.' } }], + }; + assert.equal(roomWasReset(unsaved, stored, stored), true); + assert.equal(roomWasReset(stored, unsaved, stored), false, 'new typing is not a reset'); + assert.equal(roomWasReset(unsaved, unsaved, stored), false); + assert.equal(roomWasReset(stored, stored, stored), false); + assert.equal(roomWasReset(null, stored, stored), false); +}); diff --git a/tests/shared-ydoc.test.mjs b/tests/shared-ydoc.test.mjs index b1d237b..2851db3 100644 --- a/tests/shared-ydoc.test.mjs +++ b/tests/shared-ydoc.test.mjs @@ -280,3 +280,23 @@ test('three-way text merge keeps every whole insert and delete of both sides (pr } } }); + +test('2.7.8: stableStringifyBlocks and stableStringifyCached equal stableStringify', async () => { + const { stableStringify, stableStringifyBlocks, stableStringifyCached } = + await import('../shared/ydoc.mjs'); + const blocks = [ + { id: 'a', type: 'paragraph', data: { text: 'x', b: undefined }, tunes: { z: 1, a: 2 } }, + { type: 'paragraph', id: 'a', data: { b: undefined, text: 'x' }, tunes: { a: 2, z: 1 } }, + { id: 'c', type: 'list', data: { items: [{ content: 'i', items: [] }, undefined] } }, + null, + 'raw', + ]; + for (let round = 0; round < 2; round += 1) { + assert.equal(stableStringifyBlocks(blocks), stableStringify(blocks)); + for (const block of blocks) assert.equal(stableStringifyCached(block), stableStringify(block)); + } + // `undefined` and an absent key are different canonical values; the cache must not merge them. + assert.equal(stableStringifyCached({ a: undefined }), '{"a":null}'); + assert.equal(stableStringifyCached({}), '{}'); + assert.equal(stableStringifyBlocks('x'), stableStringify('x')); +});