diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c347ca..03891e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [Unreleased] + +### Fixed (editor field: names, focus, panels, translations) + +- **Names.** The editor of a field is a group named by the field label (as Strapi's Blocks field). Inline toolbar buttons are named after their tool, the component block switch after its attribute, and the repeated Accept, Reject, Edit, Reply, Resolve and Reopen buttons say whose comment or suggestion and which text they act on. +- **Inline toolbar by keyboard.** With text selected, Alt+F10 moves focus into the inline toolbar (as in the table and column tools), the arrow keys move between its buttons, and Escape goes back to the selected text. Escape in the link input returns to the text too. The shortcut timing (Ctrl/Cmd+I, U, Shift+M, K pressed within about 150 ms of selecting) is Editor.js behaviour: its inline tool shortcuts work only once the inline toolbar was built after the debounced selection change (Editor.js 2.31 `InlineToolbar.enableShortcuts`); it is left as is. +- **Focus.** After inserting a video, audio or attachment block, focus is on its Choose button. After the Media Library dialog (Confirm, Escape or Close), the caret is in the inserted image or back where the block was inserted. After posting a reply or cancelling an edit, after sending suggestions, after Replace and Replace all, after Check links and after a grammar check or fix, focus stays on a defined control. Cancel or Escape in the template replace and version restore confirmations returns to the button that opened them. The grammar panel takes focus, and Escape closes the quality, grammar, comments and suggestions panels also when the focused button shows its tooltip. +- **States.** A comments load error shows the error with Try again instead of read-only with zero counts. "No links were checked." replaces "Link check finished: no problems" when nothing was checked. The AI dialogs show their own messages for `UNREACHABLE`, `BAD_RESPONSE`, `RESPONSE_TOO_LARGE`, `EMPTY` and `PROVIDER_ERROR`. +- **Suggest mode.** More tools offers only the entries that work while suggesting (keyboard shortcuts); the others acted on the hidden field. +- **Presence.** Joining and leaving the entry is announced once per entry, not once per field. +- **Layout and dark mode.** A blocked person photo shows its Content Security Policy notice in its own row instead of the 72 px circle. Below 650 px the **+** and block menu handles use the DS surface and border (they were white in dark mode) and 32 px targets on phones; the bottom sheet's backdrop uses the DS overlay colour. The side panel's Check is a DS button. Native checkboxes, selects and inputs in blocks follow the admin theme (`color-scheme`), and the attachment download hover, the image tool, the loader and "Nothing found" no longer show Editor.js' light colours in dark mode. +- **Translations.** The indent block tune, the embed caption and attachment title placeholders and the code languages "Plain text" and "HTML and XML" are translated in all five admin languages. + ## [2.8.2](https://github.com/Schero94/Magic-Editor-X/compare/v2.8.1...v2.8.2) (2026-11-20) diff --git a/admin/src/components/EditorField/AiDialog.jsx b/admin/src/components/EditorField/AiDialog.jsx index 4a1c794..c9258dd 100644 --- a/admin/src/components/EditorField/AiDialog.jsx +++ b/admin/src/components/EditorField/AiDialog.jsx @@ -14,6 +14,7 @@ import { useFetchClient } from '../../utils/fetch-client'; import { API, readApiError } from '../../utils/api'; import { changeViews } from '../../../../shared/ai-blocks.mjs'; import { TextOps } from './VersionDiff'; +import { aiErrorEntry } from '../../editor/ai-errors.mjs'; /** * AI assistant dialog: the admin picks an action for the selected text, the @@ -45,16 +46,6 @@ const TONE_LABELS = { persuasive: ['editor.ai.tone.persuasive', 'Persuasive'], }; -const ERROR_MESSAGES = { - DISABLED: ['editor.ai.error.disabled', 'The AI assistant is turned off.'], - NOT_CONFIGURED: ['editor.ai.error.notConfigured', 'The AI assistant is not configured yet.'], - NO_API_KEY: ['editor.ai.error.noKey', 'The AI provider key is missing.'], - AUTH_FAILED: ['editor.ai.error.auth', 'The AI provider rejected the key.'], - PROVIDER_RATE_LIMIT: ['editor.ai.error.busy', 'The AI provider is busy. Try again later.'], - TIMEOUT: ['editor.ai.error.timeout', 'The AI provider did not answer in time.'], - REFUSED: ['editor.ai.error.refused', 'The AI provider declined this request.'], -}; - /** * Plain text of an HTML snippet (inert parsing). * @param {string} html - HTML. @@ -103,7 +94,7 @@ export const AiDialog = ({ t, request, config, target, onApply, onClose, returnF if (abort.current && abort.current.signal.aborted) return; const info = readApiError(error); const [key, text] = - ERROR_MESSAGES[info.code] || + aiErrorEntry(info.code) || (info.status === 429 ? ['editor.ai.error.rateLimit', 'You sent many requests. Try again in a minute.'] : info.status === 413 diff --git a/admin/src/components/EditorField/BlockAiDialog.jsx b/admin/src/components/EditorField/BlockAiDialog.jsx index cd9d77e..b1a31fa 100644 --- a/admin/src/components/EditorField/BlockAiDialog.jsx +++ b/admin/src/components/EditorField/BlockAiDialog.jsx @@ -18,6 +18,7 @@ import { sanitizeInline } from '../../editor/sanitize'; import { segmentPlainText } from '../../../../shared/ai-fields.mjs'; import { applyBlockResult, blockSegments, changeViews } from '../../../../shared/ai-blocks.mjs'; import { TextOps } from './VersionDiff'; +import { aiErrorEntry } from '../../editor/ai-errors.mjs'; /** * Block-aware AI actions (2.4): rewrite, shorten, translate or change the @@ -44,14 +45,8 @@ const TONE_LABELS = { persuasive: ['editor.ai.tone.persuasive', 'Persuasive'], }; +/** Codes this dialog words differently from the shared AI messages (`editor/ai-errors.mjs`). */ const ERROR_MESSAGES = { - DISABLED: ['editor.ai.error.disabled', 'The AI assistant is turned off.'], - NOT_CONFIGURED: ['editor.ai.error.notConfigured', 'The AI assistant is not configured yet.'], - NO_API_KEY: ['editor.ai.error.noKey', 'The AI provider key is missing.'], - AUTH_FAILED: ['editor.ai.error.auth', 'The AI provider rejected the key.'], - PROVIDER_RATE_LIMIT: ['editor.ai.error.busy', 'The AI provider is busy. Try again later.'], - TIMEOUT: ['editor.ai.error.timeout', 'The AI provider did not answer in time.'], - REFUSED: ['editor.ai.error.refused', 'The AI provider declined this request.'], BAD_RESPONSE: ['editor.aiField.error.format', 'The answer had an unexpected format. Nothing changed.'], }; @@ -164,7 +159,7 @@ export const BlockAiDialog = ({ if (abort.current && abort.current.signal.aborted) return; const info = error && error.mismatch ? { code: 'BAD_RESPONSE' } : readApiError(error); const [key, text] = - ERROR_MESSAGES[info.code] || + aiErrorEntry(info.code, ERROR_MESSAGES) || (info.status === 429 ? ['editor.ai.error.rateLimit', 'You sent many requests. Try again in a minute.'] : info.status === 413 diff --git a/admin/src/components/EditorField/CommentThread.jsx b/admin/src/components/EditorField/CommentThread.jsx index b006a36..c6deea6 100644 --- a/admin/src/components/EditorField/CommentThread.jsx +++ b/admin/src/components/EditorField/CommentThread.jsx @@ -1,9 +1,10 @@ -import { forwardRef, useState } from 'react'; +import { forwardRef, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; import { Badge, Box, Button, Flex, Typography } from '@strapi/design-system'; import styled from 'styled-components'; import { ConfirmAction } from '../ui/ConfirmAction'; import { MentionTextarea } from './MentionTextarea'; +import { refocusLater } from './usePanelFocus'; import { normalizeExcerpt, relativeTimeParts } from '../../../../shared/comments.mjs'; import { mentionSegments } from '../../../../shared/comment-mentions.mjs'; @@ -87,6 +88,30 @@ const List = styled.ol` gap: ${({ theme }) => theme.spaces[3]}; `; +/** Characters of a comment or quote in an action's accessible name (2.7.8). */ +const NAME_EXCERPT = 40; + +/** + * Short excerpt for accessible names of repeated actions ("Edit comment by Ben M.: First words…"). + * @param {string|null|undefined} text - Comment body or quote. + * @returns {string} Excerpt. + */ +export const nameExcerpt = (text) => { + const plain = normalizeExcerpt(String(text || '').replace(/<[^>]*>/g, ' ')); + return plain.length > NAME_EXCERPT ? `${plain.slice(0, NAME_EXCERPT - 1)}…` : plain; +}; + +/** + * Display name of a comment author. + * @param {object} comment - Comment. + * @param {Function} t - Translator. + * @returns {string} Name. + */ +const authorOf = (comment, t) => + comment.author.deleted + ? t('editor.comments.deletedUser', 'Deleted user') + : comment.author.name || t('editor.comments.deletedUser', 'Deleted user'); + /** * Author name, relative time (absolute time as tooltip) and "edited". * @param {object} props - Props. @@ -96,9 +121,7 @@ const List = styled.ol` */ const CommentMeta = ({ comment, t }) => { const { formatRelativeTime, formatDate } = useIntl(); - const name = comment.author.deleted - ? t('editor.comments.deletedUser', 'Deleted user') - : comment.author.name || t('editor.comments.deletedUser', 'Deleted user'); + const name = authorOf(comment, t); const { value, unit } = relativeTimeParts(comment.createdAt); const absolute = formatDate(comment.createdAt, { dateStyle: 'medium', timeStyle: 'short' }); return ( @@ -162,6 +185,9 @@ export const CommentThread = forwardRef(function CommentThread( const [replyMentions, setReplyMentions] = useState([]); const [editing, setEditing] = useState(null); const [busy, setBusy] = useState(null); + // 2.7.8: focus targets after a reply is sent or cancelled and after an edit is saved or cancelled. + const replyButtonRef = useRef(null); + const editButtonsRef = useRef(new Map()); const resolved = thread.status === 'resolved'; // 2.4: a thread written under a positional path before 2.4 that belongs to no single entry (read-only). const positional = Boolean(thread.positional); @@ -198,6 +224,7 @@ export const CommentThread = forwardRef(function CommentThread( setReply(''); setReplyMentions([]); setReplying(false); + refocusLater(replyButtonRef); announce(t('editor.comments.announce.replied', 'Reply added')); } catch (error) { fail(errorMessage(error)); @@ -211,7 +238,7 @@ export const CommentThread = forwardRef(function CommentThread( setBusy(`edit:${editing.id}`); try { reportDropped(await actions.edit(editing.id, editing.value, editing.mentions)); - setEditing(null); + stopEditing(editing.id); announce(t('editor.comments.announce.saved', 'Comment saved')); } catch (error) { fail(errorMessage(error)); @@ -220,6 +247,24 @@ export const CommentThread = forwardRef(function CommentThread( } }; + /** Leaves the edit box and puts focus back on the comment's Edit button. */ + const stopEditing = (id) => { + setEditing(null); + refocusLater(() => editButtonsRef.current.get(id) || null); + }; + + /** Closes the reply box and puts focus back on Reply. */ + const stopReplying = () => { + setReplying(false); + refocusLater(replyButtonRef); + }; + + const first = thread.comments[0] || null; + const threadName = { + name: first ? authorOf(first, t) : '', + excerpt: nameExcerpt(quote || (first ? first.body : '') || excerpt), + }; + const toggleResolved = async () => { if (busy) return; setBusy('resolve'); @@ -377,7 +422,7 @@ export const CommentThread = forwardRef(function CommentThread( onMentionsChange={(next) => setEditing((current) => ({ ...current, mentions: next }))} search={searchMentions} onSubmit={saveEdit} - onCancel={() => setEditing(null)} + onCancel={() => stopEditing(comment.id)} t={t} autoFocus /> @@ -390,7 +435,7 @@ export const CommentThread = forwardRef(function CommentThread( > {t('editor.comments.save', 'Save')} - @@ -406,6 +451,14 @@ export const CommentThread = forwardRef(function CommentThread( } @@ -474,7 +538,7 @@ export const CommentThread = forwardRef(function CommentThread( onMentionsChange={setReplyMentions} search={searchMentions} onSubmit={sendReply} - onCancel={() => setReplying(false)} + onCancel={stopReplying} t={t} autoFocus /> @@ -482,17 +546,33 @@ export const CommentThread = forwardRef(function CommentThread( - ) : ( - - diff --git a/admin/src/components/EditorField/CommentsPanel.jsx b/admin/src/components/EditorField/CommentsPanel.jsx index 0ad46e9..a779f7d 100644 --- a/admin/src/components/EditorField/CommentsPanel.jsx +++ b/admin/src/components/EditorField/CommentsPanel.jsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useRef, useState } from 'react'; -import { usePanelAutoFocus } from './usePanelFocus'; +import { escapeBelongsInside, usePanelAutoFocus } from './usePanelFocus'; import { Box, Button, @@ -263,7 +263,7 @@ export const CommentsPanel = ({ }; const onKeyDown = (event) => { - if (event.key !== 'Escape' || event.defaultPrevented) return; + if (event.key !== 'Escape' || escapeBelongsInside(event)) return; const tag = event.target && event.target.tagName; if (tag === 'TEXTAREA' || tag === 'INPUT') return; if ( @@ -361,13 +361,15 @@ export const CommentsPanel = ({ {t('editor.comments.title', 'Comments')} - - {t( - 'editor.comments.summary', - '{open, plural, one {# open thread} other {# open threads}} · {resolved} resolved', - { open: counts.open, resolved: counts.resolved } - )} - + {loaded ? ( + + {t( + 'editor.comments.summary', + '{open, plural, one {# open thread} other {# open threads}} · {resolved} resolved', + { open: counts.open, resolved: counts.resolved } + )} + + ) : null} @@ -411,27 +413,30 @@ export const CommentsPanel = ({ ) : null} - - {canWrite ? ( - - ) : ( - - {t('editor.comments.readOnly', 'You can read comments but not add any.')} - - )} - setShowResolved(value === true)}> - {t('editor.comments.showResolved', 'Show resolved threads')} - - + {/* 2.7.8: before the first load (or when it failed) nothing is known about counts or rights. */} + {loaded ? ( + + {canWrite ? ( + + ) : ( + + {t('editor.comments.readOnly', 'You can read comments but not add any.')} + + )} + setShowResolved(value === true)}> + {t('editor.comments.showResolved', 'Show resolved threads')} + + + ) : null} {canWrite && blocks.length === 0 ? ( diff --git a/admin/src/components/EditorField/ComponentBlockView.jsx b/admin/src/components/EditorField/ComponentBlockView.jsx index 3865498..5f9cbc6 100644 --- a/admin/src/components/EditorField/ComponentBlockView.jsx +++ b/admin/src/components/EditorField/ComponentBlockView.jsx @@ -85,6 +85,8 @@ const AttributeInput = ({ field, value, onChange, readOnly, t, inputName }) => { return ( onChange(checked === true)} onLabel={t('editor.component.on', 'On')} diff --git a/admin/src/components/EditorField/EditorToolbar.jsx b/admin/src/components/EditorField/EditorToolbar.jsx index f84a6d0..e4236a1 100644 --- a/admin/src/components/EditorField/EditorToolbar.jsx +++ b/admin/src/components/EditorField/EditorToolbar.jsx @@ -86,6 +86,7 @@ const initials = (name) => /** * @param {object} props - Props. + * @param {string[]|null} [props.onlyTools] - 2.7.8: ids of the More tools entries to keep (suggest mode). * @returns {JSX.Element} Toolbar. */ export const EditorToolbar = ({ @@ -103,8 +104,11 @@ export const EditorToolbar = ({ stats, limits = {}, tools = [], + onlyTools = null, moreButtonRef, }) => { + // 2.7.8: suggest mode keeps only the tools that work there (the others act on the hidden field). + const menuTools = onlyTools ? tools.filter((tool) => onlyTools.includes(tool.id)) : tools; const status = STATUS[collaboration.status]; const peers = collaboration.peers || []; const upgrade = collaboration.status === 'error' && collaboration.error === 'UPGRADE_REQUIRED'; @@ -144,7 +148,7 @@ export const EditorToolbar = ({ )} - + { if (findRef.current) findRef.current.focus(); @@ -98,9 +101,29 @@ export const FindReplacePanel = ({ t, getData, onApply, onSelect, onClose, readO await search(); } finally { busyRef.current = false; + // 2.7.8: after Replace all the replace buttons are disabled (no matches left) and the editor + // may have taken focus: focus stays in the panel, on the button used or the Find input. + keepFocusInPanel(all ? replaceAllRef : replaceRef); } }; + /** + * Keeps focus in the panel after a replace. + * @param {{ current: HTMLElement|null }} preferred - Button that was used. + * @returns {void} + */ + const keepFocusInPanel = (preferred) => { + window.requestAnimationFrame(() => + window.requestAnimationFrame(() => { + const panel = panelRef.current; + if (!panel || panel.contains(document.activeElement)) return; + const button = preferred.current; + const target = button && !button.disabled && button.isConnected ? button : findRef.current; + if (target) target.focus(); + }) + ); + }; + const onFindKey = (event) => { if (event.key === 'Enter') { event.preventDefault(); @@ -123,6 +146,7 @@ export const FindReplacePanel = ({ t, getData, onApply, onSelect, onClose, readO return ( {readOnly ? null : ( <> - - diff --git a/admin/src/components/EditorField/GrammarPanel.jsx b/admin/src/components/EditorField/GrammarPanel.jsx index bd53d52..2611546 100644 --- a/admin/src/components/EditorField/GrammarPanel.jsx +++ b/admin/src/components/EditorField/GrammarPanel.jsx @@ -11,6 +11,7 @@ import { } from '@strapi/design-system'; import { Cross } from '@strapi/icons'; import styled from 'styled-components'; +import { closeOnEscape, refocusIfLost, usePanelAutoFocus } from './usePanelFocus'; import { API, readApiError } from '../../utils/api'; import { collectSegments, @@ -143,6 +144,7 @@ export const afterReplacement = (matches, applied, replacement) => { * @param {(match: object|null, occurrence?: number) => void} props.onSelect - Highlights a match (null clears). * @param {() => void} props.onClose - Closes the panel. * @param {boolean} [props.readOnly] - No "Apply" buttons. + * @param {boolean} [props.autoFocus=true] - 2.7.8: the panel opens from More tools; its heading takes focus. * @returns {JSX.Element} Panel. */ export const GrammarPanel = ({ @@ -154,12 +156,17 @@ export const GrammarPanel = ({ onSelect, onClose, readOnly = false, + autoFocus = true, }) => { const [state, setState] = useState({ status: 'idle', matches: [], parts: [], truncated: false, error: '' }); const [current, setCurrent] = useState(null); const [announcement, setAnnouncement] = useState(''); const [notice, setNotice] = useState(''); const abortRef = useRef(null); + const headingRef = useRef(null); + const checkRef = useRef(null); + const listRef = useRef(null); + usePanelAutoFocus(autoFocus, headingRef); useEffect( () => () => { @@ -225,6 +232,9 @@ export const GrammarPanel = ({ ? ['editor.grammar.error.tooLong', 'This field is too long to check at once.'] : ['editor.grammar.error.generic', 'The grammar check is not available right now.']); setState((previous) => ({ ...previous, status: 'error', error: t(key, text) })); + } finally { + // 2.7.8: the button is disabled while the check runs; focus comes back to it, not the page. + if (!controller.signal.aborted) refocusIfLost(checkRef); } }, [fetchClient, getData, onSelect, t, target.field, target.locale, target.uid]); @@ -275,6 +285,8 @@ export const GrammarPanel = ({ ), })); setAnnouncement(t('editor.grammar.applied', 'Replaced with "{text}"', { text: replacement })); + // 2.7.8: the fixed issue's buttons are gone: focus moves to the next issue, else the heading. + refocusIfLost(() => (listRef.current && listRef.current.querySelector('button')) || headingRef.current); }; const contextOf = (match) => { @@ -298,11 +310,12 @@ export const GrammarPanel = ({ hasRadius minWidth={0} data-testid="mex-grammar-panel" + onKeyDown={(event) => closeOnEscape(event, onClose)} > - + {t('editor.grammar.title', 'Grammar check')} @@ -321,7 +334,13 @@ export const GrammarPanel = ({ - ) : null} @@ -609,7 +617,15 @@ export const HistoryModal = ({ ) : null} - !open && !restoring && setConfirm(null)}> + { + if (open || restoring) return; + setConfirm(null); + // 2.7.8: Cancel or Escape returns focus to the Restore button that asked. + refocusLater(restoreOpenerRef.current); + }} + > {confirm ? ( extractLinks(data), [data]); const linkCount = links.internal.length + links.external.length + links.media.length; @@ -263,18 +264,21 @@ export const QualityPanel = ({ external: [], }; if (!externalEnabled) result.external = links.external.map(({ url }) => ({ url, status: 'skipped' })); - const problems = [...result.internal, ...result.media, ...result.external].filter((item) => - PROBLEMS.has(item.status) - ).length; + const all = [...result.internal, ...result.media, ...result.external]; + const problems = all.filter((item) => PROBLEMS.has(item.status)).length; + // 2.7.8: "no problems" only when something was checked (external links may all be skipped). + const checked = all.filter((item) => item.status !== 'skipped').length; setCheck({ state: 'done', result, message: '' }); setAnnouncement( - t( - 'editor.quality.links.done', - 'Link check finished: {count, plural, =0 {no problems} one {# problem} other {# problems}}', - { - count: problems, - } - ) + checked === 0 + ? t('editor.quality.links.noneChecked', 'No links were checked.') + : t( + 'editor.quality.links.done', + 'Link check finished: {count, plural, =0 {no problems} one {# problem} other {# problems}}', + { + count: problems, + } + ) ); } catch (error) { if (requestRef.current !== id) return; @@ -285,6 +289,9 @@ export const QualityPanel = ({ : t('editor.quality.links.failed', 'The links could not be checked.'); setCheck({ state: 'error', result: null, message }); setAnnouncement(message); + } finally { + // 2.7.8: the button is disabled while it loads, which dropped focus to the page body. + if (requestRef.current === id) refocusIfLost(checkButtonRef); } }, [externalEnabled, fetchClient, links, t]); @@ -489,6 +496,7 @@ export const QualityPanel = ({ borderColor="neutral200" hasRadius minWidth={0} + onKeyDown={onClose ? (event) => closeOnEscape(event, onClose) : undefined} > @@ -593,6 +601,7 @@ export const QualityPanel = ({ {t('editor.quality.links.title', 'Links and media')} } @@ -499,6 +527,11 @@ export const SuggestionsPanel = ({ loading={busy === suggestion.id} disabled={working} data-testid="mex-suggestion-accept" + aria-label={t( + 'editor.suggestions.acceptNamed', + 'Accept suggestion by {name}: {op}, {excerpt}', + named + )} > {t('editor.suggestions.accept', 'Accept')} @@ -510,6 +543,11 @@ export const SuggestionsPanel = ({ onClick={() => reject(item)} disabled={working} data-testid="mex-suggestion-reject" + aria-label={t( + 'editor.suggestions.rejectNamed', + 'Reject suggestion by {name}: {op}, {excerpt}', + named + )} > {t('editor.suggestions.reject', 'Reject')} @@ -517,7 +555,16 @@ export const SuggestionsPanel = ({ {suggestion.author.own ? ( + } @@ -535,6 +582,11 @@ export const SuggestionsPanel = ({ ); @@ -298,7 +301,7 @@ const SummaryStatus = ({ t, summary }) => { if (summary.status === 'error' && !summary.data) return ( - + {t('entryPanel.error', 'Comments and quality could not be loaded.')} +
+ `; + await settle(); + const buttons = holder.querySelectorAll('button'); + assert.equal(buttons[0].getAttribute('aria-label'), 'Bold'); + assert.equal(buttons[1].getAttribute('aria-label'), 'Marker'); + assert.equal(buttons[2].getAttribute('aria-label'), 'Mention an entry', 'own names stay'); + stop(); + holder.remove(); +}); + +test('inlineToolbarItems lists enabled, rendered items (jsdom: rects stubbed)', () => { + const holder = document.createElement('div'); + holder.innerHTML = `
`; + document.body.append(holder); + for (const button of holder.querySelectorAll('button')) button.getClientRects = () => [{}]; + assert.deepEqual( + inlineToolbarItems(holder).map((element) => element.id), + ['a'] + ); + holder.remove(); +}); + +test('insertedBlockControl: a video block gets its Choose button, a paragraph nothing', () => { + const visible = () => true; + const wrap = document.createElement('div'); + wrap.innerHTML = `
+
Text
`; + assert.equal(insertedBlockControl(wrap.querySelector('#v'), visible).id, 'choose'); + assert.equal(insertedBlockControl(wrap.querySelector('#p'), visible), null); + assert.equal(insertedBlockControl(document.createTextNode('x'), visible), null); +}); + +test('attachment "Select a file" (a div in @editorjs/attaches) becomes a keyboard button', async () => { + const { decorateDivButtons } = await import('../../admin/src/editor/toolbar-a11y.mjs'); + const holder = document.createElement('div'); + document.body.append(holder); + const stop = decorateDivButtons(holder); + holder.innerHTML = '
Select a file
'; + await settle(); + const button = holder.querySelector('.cdx-attaches__button'); + assert.equal(button.getAttribute('role'), 'button'); + assert.equal(button.getAttribute('tabindex'), '0'); + let clicks = 0; + button.addEventListener('click', () => (clicks += 1)); + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + assert.equal(clicks, 1); + assert.equal( + insertedBlockControl(holder.querySelector('.ce-block'), () => true), + button + ); + stop(); + holder.remove(); +}); diff --git a/tests/admin/panels-a11y.test.jsx b/tests/admin/panels-a11y.test.jsx new file mode 100644 index 0000000..ca69c8d --- /dev/null +++ b/tests/admin/panels-a11y.test.jsx @@ -0,0 +1,356 @@ +/** + * 2.7.8 re-audit minors (field panels): the grammar panel takes focus when it opens, and Escape + * closes the grammar and quality panels (their onClose returns focus to More tools). + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { act } from 'react'; +import { renderStrict, settle } from './harness/index.jsx'; +import { GrammarPanel } from '../../admin/src/components/EditorField/GrammarPanel.jsx'; +import { QualityPanel } from '../../admin/src/components/EditorField/QualityPanel.jsx'; + +const t = (_id, text, values) => + values ? String(text).replace(/\{(\w+)[^}]*\}/g, (_m, key) => (key in values ? values[key] : '')) : text; +const frame = () => new Promise((resolve) => window.requestAnimationFrame(() => resolve())); +const escape = async (element) => { + await act(async () => { + element.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); + }); +}; + +test('grammar panel: heading takes focus on open; Escape closes', async () => { + let closed = 0; + const handle = await renderStrict( + ({ data: { matches: [] } }) }} + target={{ uid: 'api::article.article', field: 'body', locale: 'en' }} + getData={async () => ({ blocks: [] })} + onApply={async () => true} + onSelect={() => {}} + onClose={() => (closed += 1)} + /> + ); + await frame(); + await settle(); + const panel = document.querySelector('[data-testid="mex-grammar-panel"]'); + assert.equal(document.activeElement && document.activeElement.tagName, 'H3'); + assert.ok(panel.contains(document.activeElement)); + await escape(panel.querySelector('button')); + assert.equal(closed, 1); + await handle.unmount(); +}); + +test('quality panel: Escape closes; Escape inside a listbox does not', async () => { + let closed = 0; + const handle = await renderStrict( +
+ ({ data: {} }), get: async () => ({ data: {} }) }} + externalEnabled={false} + onSelectBlock={() => {}} + onClose={() => (closed += 1)} + /> +
+ ); + await settle(); + const section = document.querySelector('section[aria-label="Quality checks"]'); + const listbox = document.createElement('div'); + listbox.setAttribute('role', 'listbox'); + section.appendChild(listbox); + await escape(listbox); + assert.equal(closed, 0); + listbox.remove(); + await escape(section.querySelector('h3')); + assert.equal(closed, 1); + await handle.unmount(); +}); + +const click = async (element) => { + await act(async () => { + element.click(); + }); + await settle(); +}; +const byText = (root, text) => + Array.from(root.querySelectorAll('button')).find((node) => node.textContent.trim() === text); +const frames = async (count = 3) => { + for (let index = 0; index < count; index += 1) await frame(); +}; + +test('comments: contextual names; focus back on Reply after sending and on Edit after cancelling', async () => { + const { CommentThread } = await import('../../admin/src/components/EditorField/CommentThread.jsx'); + let replies = 0; + const thread = { + id: 't1', + status: 'open', + blockId: 'b1', + excerpt: 'Block text', + comments: [ + { + id: 'c1', + body: 'Please check the first sentence of this paragraph again', + author: { name: 'Ben M.', own: true }, + createdAt: '2026-11-20T10:00:00.000Z', + mentions: [], + }, + ], + }; + const handle = await renderStrict( + (replies += 1), edit: async () => ({}) }} + onSelectBlock={() => {}} + announce={() => {}} + fail={() => {}} + fallbackFocusRef={{ current: null }} + /> + ); + const names = Array.from(document.querySelectorAll('button[aria-label]')).map((node) => + node.getAttribute('aria-label') + ); + assert.ok( + names.includes('Edit comment by Ben M.: Please check the first sentence of this…'), + names.join(' | ') + ); + assert.ok(names.some((name) => name.startsWith('Reply to Ben M.: Please check'))); + assert.ok(names.some((name) => name.startsWith('Resolve comment by Ben M.'))); + // Reply, type, send: focus on the Reply button again. + await click(byText(document.body, 'Reply')); + const box = document.querySelector('textarea'); + await act(async () => { + const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set; + setter.call(box, 'Done'); + box.dispatchEvent(new Event('input', { bubbles: true })); + }); + await settle(); + const send = Array.from(document.querySelectorAll('button')) + .filter((node) => node.textContent.trim() === 'Reply') + .pop(); + await click(send); + await frames(); + assert.equal(replies, 1); + assert.match(document.activeElement.getAttribute('aria-label') || '', /^Reply to Ben M\./); + // Edit, Cancel: focus on Edit. + await click(byText(document.body, 'Edit')); + await click(byText(document.body, 'Cancel')); + await frames(); + assert.match(document.activeElement.getAttribute('aria-label') || '', /^Edit comment by Ben M\./); + await handle.unmount(); +}); + +test('comments panel: a failed first load shows the error and Try again, no counts or rights', async () => { + const { CommentsPanel } = await import('../../admin/src/components/EditorField/CommentsPanel.jsx'); + let retried = 0; + const comments = { + loaded: false, + error: true, + threads: [], + counts: { open: 0, resolved: 0 }, + canWrite: false, + canModerate: false, + positionalThreads: [], + notifications: [], + actions: {}, + newFromOthers: 0, + clearNew: () => {}, + refresh: () => (retried += 1), + }; + const handle = await renderStrict( + {}} + onClose={() => {}} + fail={() => {}} + /> + ); + const panel = document.querySelector('[data-testid="mex-comments-panel"]'); + assert.match(panel.textContent, /The comments could not be loaded\./); + assert.equal(panel.querySelector('[data-testid="mex-comments-summary"]'), null); + assert.doesNotMatch(panel.textContent, /You can read comments but not add any|0 open threads/); + await click(byText(panel, 'Try again')); + assert.equal(retried, 1); + await handle.unmount(); +}); + +test('find and replace: after Replace all focus stays in the panel', async () => { + const { FindReplacePanel } = await import('../../admin/src/components/EditorField/FindReplacePanel.jsx'); + let data = { blocks: [{ id: 'a', type: 'paragraph', data: { text: 'alpha beta alpha' } }] }; + const outside = document.createElement('button'); + document.body.append(outside); + const handle = await renderStrict( + data} + onApply={async (next) => { + data = next; + outside.focus(); + }} + onSelect={() => {}} + onClose={() => {}} + readOnly={false} + contentVersion={0} + /> + ); + const [find, replacement] = document.querySelectorAll('input'); + const type = async (input, value) => { + await act(async () => { + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set; + setter.call(input, value); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + await settle(10, 20); + }; + await type(find, 'alpha'); + await type(replacement, 'gamma'); + const all = byText(document.body, 'Replace all'); + await click(all); + await settle(10, 20); + await frames(); + assert.match(data.blocks[0].data.text, /gamma beta gamma/); + const panel = document.querySelector('section[aria-label="Find and replace"]'); + assert.ok(panel.contains(document.activeElement), `focus on ${document.activeElement.tagName}`); + outside.remove(); + await handle.unmount(); +}); + +test('quality: only skipped links announce "No links were checked", focus back on Check links', async () => { + const handle = await renderStrict( + x' } }, + ], + }} + options={{}} + fetchClient={{ + post: async () => ({ data: { data: { internal: [], media: [], external: [] } } }), + get: async () => ({ data: {} }), + }} + externalEnabled={false} + onSelectBlock={() => {}} + onClose={() => {}} + /> + ); + const button = byText(document.body, 'Check links'); + button.focus(); + await click(button); + await settle(10, 20); + await frames(); + const announced = document.querySelector('section[aria-label="Quality checks"]').textContent; + assert.match(announced, /No links were checked\./); + assert.doesNotMatch(announced, /no problems/); + assert.equal(document.activeElement, byText(document.body, 'Check links')); + await handle.unmount(); +}); + +test('suggestions: Accept, Reject and Show block name the suggestion they act on', async () => { + const { SuggestionsPanel } = await import('../../admin/src/components/EditorField/SuggestionsPanel.jsx'); + const current = { + time: 1, + version: '2.31.7', + blocks: [{ id: 'b1', type: 'paragraph', data: { text: 'Old text' } }], + }; + const suggestions = { + loaded: true, + error: false, + counts: { open: 1 }, + suggestions: [ + { + id: 's1', + status: 'open', + op: 'update', + blockId: 'b1', + baseHash: null, + proposed: { id: 'b1', type: 'paragraph', data: { text: 'New wording for the first block' } }, + author: { name: 'Ben M.', own: false }, + createdAt: '2026-11-20T10:00:00.000Z', + }, + ], + actions: {}, + newFromOthers: 0, + clearNew: () => {}, + refresh: () => {}, + }; + const handle = await renderStrict( + 1} + onSelectBlock={() => {}} + onClose={() => {}} + fail={() => {}} + /> + ); + const names = Array.from( + document.querySelectorAll('[data-testid="mex-suggestion"] button[aria-label]') + ).map((node) => node.getAttribute('aria-label')); + assert.ok( + names.some((name) => /^Accept suggestion by Ben M\.: Change, New wording/.test(name)), + names.join(' | ') + ); + assert.ok(names.some((name) => /^Reject suggestion by Ben M\.: Change, New wording/.test(name))); + assert.ok(names.some((name) => /^Show block of the suggestion by Ben M\./.test(name))); + await handle.unmount(); +}); + +test('side panel: the Check action is a Design System button with a contextual name', async () => { + const { ENTRY_PANEL_SECTIONS } = await import('../../admin/src/components/EntryPanel/sections.jsx'); + const Quality = ENTRY_PANEL_SECTIONS.find((section) => section.id === 'quality').Component; + const summary = { + data: { + fields: [ + { + field: 'body', + path: 'body', + label: 'Body', + issues: { errors: 1, warnings: 0 }, + brokenLinks: { draft: 0 }, + }, + ], + quality: { errors: 1, warnings: 0 }, + links: { enabled: false, draft: 0, published: 0 }, + comments: { enabled: false }, + }, + }; + const handle = await renderStrict(); + const button = document.querySelector('[data-testid="mex-panel-quality"] button[aria-label="Check Body"]'); + assert.ok(button, 'Check button'); + assert.equal(button.textContent.trim(), 'Check'); + // The 24 x 24 px target itself is measured in the browser (DS Button size S). + await handle.unmount(); +}); + +test('nested confirms: refocusLater puts focus back on the opener (ref or element); refocusIfLost only when lost', async () => { + const { refocusLater, refocusIfLost } = + await import('../../admin/src/components/EditorField/usePanelFocus.js'); + const opener = document.createElement('button'); + const other = document.createElement('button'); + document.body.append(opener, other); + document.body.focus(); + refocusLater({ current: opener }); + await frames(); + assert.equal(document.activeElement, opener); + other.focus(); + refocusIfLost(() => opener); + await frames(); + assert.equal(document.activeElement, other, 'focus that moved on purpose stays'); + other.blur(); + refocusIfLost(opener); + await frames(); + assert.equal(document.activeElement, opener); + opener.remove(); + other.remove(); +}); diff --git a/tests/ai-errors.test.mjs b/tests/ai-errors.test.mjs new file mode 100644 index 0000000..7b6cb5f --- /dev/null +++ b/tests/ai-errors.test.mjs @@ -0,0 +1,25 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { AI_ERROR_MESSAGES, aiErrorEntry } from '../admin/src/editor/ai-errors.mjs'; + +test('2.7.8: every AI error code the server answers with has a message in the dialogs', () => { + const controller = readFileSync(new URL('../server/src/controllers/ai.js', import.meta.url), 'utf8'); + const start = controller.indexOf('const MESSAGES = {'); + const block = controller.slice(start, controller.indexOf('};', start)); + const codes = [...block.matchAll(/^\s+([A-Z_]+): \[\d{3},/gm)].map((match) => match[1]); + for (const code of ['UNREACHABLE', 'BAD_RESPONSE', 'RESPONSE_TOO_LARGE', 'EMPTY', 'PROVIDER_ERROR']) + assert.ok(codes.includes(code), `server lists ${code}`); + // Image alt text (tools) and whole-field actions (FieldAiDialog's own entry) are worded elsewhere. + for (const code of codes.filter((name) => !['IMAGES_DISABLED', 'FIELD_ACTIONS_DISABLED'].includes(name))) + assert.ok(aiErrorEntry(code), `message for ${code}`); +}); + +test('2.7.8: dialog-specific wording wins, unknown codes fall through', () => { + assert.deepEqual(aiErrorEntry('UNREACHABLE'), AI_ERROR_MESSAGES.UNREACHABLE); + const own = { BAD_RESPONSE: ['editor.aiField.error.format', 'x'] }; + assert.deepEqual(aiErrorEntry('BAD_RESPONSE', own), own.BAD_RESPONSE); + assert.equal(aiErrorEntry('SOMETHING_NEW'), null); + assert.equal(aiErrorEntry(undefined), null); + assert.equal(aiErrorEntry('toString'), null); +}); diff --git a/tests/presence-announce.test.mjs b/tests/presence-announce.test.mjs new file mode 100644 index 0000000..68fb5ec --- /dev/null +++ b/tests/presence-announce.test.mjs @@ -0,0 +1,26 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { claimPresence, diffPeers } from '../admin/src/editor/presence-announce.mjs'; + +test('2.7.8: diffPeers by display name (a second socket of the same person is no join)', () => { + const a = [{ id: '1', name: 'Ben M.' }]; + assert.deepEqual(diffPeers([], a), { joined: ['Ben M.'], left: [] }); + assert.deepEqual(diffPeers(a, [...a, { id: '2', name: 'Ben M.' }]), { joined: [], left: [] }); + assert.deepEqual(diffPeers(a, []), { joined: [], left: ['Ben M.'] }); +}); + +test('2.7.8: three fields of one entry announce a join once; another entry announces again', () => { + const registry = new Map(); + const base = { entry: '/admin/x/1', event: 'joined', names: ['Ben M.'] }; + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f1' }), ['Ben M.']); + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f2' }), []); + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f3' }), []); + // StrictMode: the same field renders twice + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f1' }), ['Ben M.']); + assert.deepEqual(claimPresence(registry, { ...base, entry: '/admin/x/2', owner: 'f4' }), ['Ben M.']); + // Leaving is announced once, by whichever field sees it first; a later join again once. + assert.deepEqual(claimPresence(registry, { ...base, event: 'left', owner: 'f2' }), ['Ben M.']); + assert.deepEqual(claimPresence(registry, { ...base, event: 'left', owner: 'f1' }), []); + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f3' }), ['Ben M.']); + assert.deepEqual(claimPresence(registry, { ...base, owner: 'f1' }), []); +});