diff --git a/CHANGELOG.md b/CHANGELOG.md index ca4eadaf..a745e93a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,210 @@ since the previous tag. ## [Unreleased] +### Selection bubble P1: Style ▾, strike, code, clear and a gap-free link field + +The selection bubble gains the rest of its v2 row (spec +`2026-11-17-bubble-and-quick-insert-design.md` §7, v1 contract A21): +Style ▾ │ B I U S ‹› Tx │ A▁▾ 🔗 🖌, and named colour rows. With P2–P4, the +editor chunk group grows 26 B: 394,545 B gz against 394,519 B on `main` at +`2764fb5`. That is a D23 ledger line the owner approved on 2026-11-22 +(`EDITOR_CHUNK_LEDGER_BYTES` 2,205 → 2,231 B), covering the style-lift hook, +List and Quote in the style value and the Insert sheet's nested load. The +per-item lift behind the text styles is injected from the lazy chunks. +Merging `main` `2764fb5` first measured +981 B: the lazy menus imported +lucide's Type, which made Turbopack split the editor group's small modules +into two files. The menus now draw their own copy of the icon +(`components/smart-toolbar/type-icon.ts`). The +"/" chunk is under its 7 KB budget, 7,099 B gz by its own test +(`SLASH_BUDGET=1`; 7,334 B on the P4 tip): the phone Insert sheet now gets +the "/" items at load instead of importing them. The bubble chunk is +14,860 B gz (9,797 B on `main` at `2764fb5`) and the colour chunk +6,580 B gz (3,639 B). + +#### Added + +- **Bubble:** Style ▾ shows the selection's block type as one word (Text, + H1–H6, Title, List, Quote, Code, Mixed), sized once to the longest word, + and opens Turn into away from the text. Strike, inline code and clear + formatting join B, I and U. A comment slot is reserved at the end and + renders nothing until the comments work registers `comment.add`. +- **Turn into:** one menu body for the bubble and the row's Text style ▾: + Text, Heading 1–3, More headings ▸ (4–6), the three lists, Quote and Code + block, with icons, shortcuts and a trailing ✓, and no Markdown chips. + The row keeps Your formats below them. +- **Text styles:** Text and the headings turn the selected list items or + quote lines into that block, lifted to the top level, in one undo step, + wherever they run (Turn into, the palette, the "/" menu, the phone's + Style rows, the shortcuts); unselected items and lines stay in their list + or quote, and a range across a paragraph and a list converts every + block. The lift loads with the bubble (on idle), the menus, the phone + bar or the palette; before any of them, a style shortcut or a "/" pick + in a list restyles in place, as before. +- **Turn into:** after select all it converts everything but the title + ("The title stays a heading."); Code block and Quote lift list items and + quote lines first; Code block over formatting says "Formatting + removed"; a range with table cells converts around them ("Table cells + keep their type."). Each pill has Undo. Opened toward the text, it goes + past the selection's lines, never over them. +- **Colour:** the bubble's and the row's colour menus are named rows: + Recent, then Text | Highlight side by side (Default and No highlight + first, five colours each, the rest under More colours ▸ and More + highlights ▸), with ✓ on the current value, typeahead and the hover + preview. From the bubble the menu opens below or above the selection, + never over it. Enter or Space picks and closes the menu (a change from + O4, spec §7.10), and the pick is announced with Undo. +- **Phone:** the Aa sheet keeps the swatch grid, six per line, names the + current colours under it, and each tap shows a pill naming the colour + ("Teal text") with a 44px Undo. +- **Bubble:** a keyboard selection (Shift+arrows, ⌘A) shows the bubble + 300 ms after Shift is released and the selection is still, never while + Shift is held or a key repeats. +- **Bubble:** Alt+F10 shows a bubble that is still waiting (its delay) at + once, with focus on Style ▾. +- **Bubble:** applying inline code over linked or coloured text says "Link + and colour removed" (or "Link removed", "Colour removed") on the status + pill, with Undo. + +#### Changed + +- **Text style:** the paragraph style is named "Text" everywhere (the + registry label, so the row, the palette, the "/" menu and the phone + agree), and the row's face reads "List" or "Quote" inside a list or + quote, as the bubble's does. +- **Bubble:** inside inline code, B, I, U, S, colour and link say "Inline + code can't take other formatting." instead of the generic refusal; the + Paint format brush says the same on inline code on every surface + (phone cells included), where it said "Code has no formatting." +- **Bubble:** a lighter edge in light mode, its own darker-than-page + surface in dark mode (`oklch(0.24 0 0)`, edge `oklch(1 0 0 / 36%)`), focus + rings drawn inside each button, a dashed bar for a mixed mark, and a + `CanvasText` edge under forced colours. +- **Bubble:** motion follows the O10 token: 120 ms scale-in from the anchor + side, 80 ms fade out, and none at all under reduced motion + (`prefers-reduced-motion` or `data-motion="reduce"`). + +#### Fixed + +- **RTL:** the "/" menu's Markdown hint caps sit at the row's inline end + again (they had drifted next to the labels); the row ⋯ menu's rows line + up; menu shortcut glyphs read left to right; the phone Insert sheet keeps + a note ("3 × 3") next to its label, so it no longer reads as the next + column's. + +- **Bubble:** clicking 🔗 and pasting or typing a URL at once no longer + replaces the selected words: focus moves to the link field in the click + itself, and the bubble hides in the same task. +- **Bubble:** Esc while the bubble is still waiting to show (its delay or + a keyboard selection's settle) cancels it. + +### Phone Insert sheet, Style first in the Aa sheet, words on tablet stand-ins (P4) + +Phase P4 of the selection bubble and quick insert design (spec §8.3, §13.1, +§13.2). Phones get an Insert sheet in place of the desktop dropdown, the Aa +sheet leads with Style, and touch tablets name the row's unclear stand-ins. + +#### Added + +- **Phone:** the bar's Insert cell opens a bottom sheet + (`components/smart-toolbar/phone/insert-sheet.tsx`): the "/" menu's items + as a two-column grid of 44px cells. Suggested (the "/" menu's own rows for the + recent kinds) comes first when there are any, then "Blocks" (the caret's block is empty) + or "Turn into" (it has text), then Insert. Kinds that can't run here show + their reason on a second line. Table and Embed open their step inside the + sheet; Diagram lists the templates. A pick closes the sheet and puts the + caret in the new block, with the keyboard back. "/embed" on a phone opens + the sheet at the embed step. The sheet rides above the keyboard while the + link field has focus, and a pick refused since it opened (a + collaborator's edit) says why inside it. Its cells and steps are their own + lazy chunk, fetched when the browser is idle and on the cell's press. +- **Touch tablets:** on a coarse pointer from 768px, the row's stand-ins + read `T Format ▾`, `¶ Layout ▾` and `⫶ Block ▾` (O8 a), from first paint + (CSS in `app/globals.css`). Below an 848px window the row has no room for + their 120px in a code block or table, so (owner decision, option b) Redo + moves from the row to the top of ⋯ there, and the list button keeps only + List ▾. ⌘⇧Z still redoes. Desktop's ⋯ menu is unchanged. + +#### Changed + +- **Toolbar:** the stand-ins are named "Format" (was "More text + formatting"), "Layout" (was "Paragraph") and "Block: Section tools" and so + on (was "Section tools"), so each name begins with the word shown on it + (WCAG 2.5.3). The phone's slot cell takes the same name. +- **Phone:** the Aa sheet starts with Style: Text and H1–H3, a More + headings disclosure for H4–H6 (open when the current style is one of + them, closable all the same), then the lists and Quote, the current style + pressed. Colours follow. Both sheets end in a 16px fade while they scroll, + above the home indicator. + +Measured against `main` at 84a9458, with the "/" menu's P2 and the grouped ⋯ +menu's P3 work merged in: the editor chunk group gets 23 B smaller (393,995 B +gz against 394,018 B). The phone bar chunk grows 978 B gz (18,175 B), and the +sheet body is a chunk of its own, 3,926 B gz. The app's CSS grows 494 B gz +(16,487 B): 138 B for the tablet words and 71 B for the touch step that +moves Redo; the rest is P2 and P3. + +### Quick insert P2: Suggested, the "/" hint and footer, and the `+` on empty lines + +The "/" menu gains what the second reference set showed it lacked, and a +pointer path to it (spec `2026-11-17-bubble-and-quick-insert-design.md` +§8.2, §8.5; v1 contract A20). The editor chunk group is unchanged +(393,817 B gz, −3 B against `main` at `1548d5e`); the slash chunk grows +from 5,772 B to 7,041 B gz, and its test budget (`SLASH_BUDGET=1`) is +raised from 6 KB to 7 KB (7,168 B) by the owner's decision of 2026-11-22. +The growth by feature (gz): the `+`'s undo handling 336 B, the footer +269 B, the "Type to search" hint 258 B, Suggested 154 B, the RTL anchor +66 B; "New" badges compile out while none is declared. The bubble chunk, which now mounts the +`+`, from 9,798 B to 10,930 B gz. The footer lives in `slash-menu.tsx` +rather than its own `slash-footer.tsx` (the plan's file list): it shares +the menu's state and placement, and a separate module would only add +bytes. + +#### Added + +- **"/" menu:** a Suggested section leads with your last 3 inserted kinds + (table, image, divider…) that can go at the caret; each stays in its own + section too. A new writer sees no Suggested section; "Forget my choices" + clears it. A query hides it and puts a recent kind first among equal + matches. +- **"/" menu:** "Type to search" sits after the "/" while the query is + empty and nothing follows the caret (never during IME composition); a + pinned footer teaches the active row's Markdown shortcut ("Type ## then + space for Heading 2") and has a Close button (Esc still works). On touch + the footer is only a 44 px Close. Hints stay left to right in RTL ("1.", + never ".1"). +- **"/" menu:** rows can carry a "New" badge until a date, hidden once you + have used that kind; none are declared yet. +- **`+` on an empty line:** on a mouse or trackpad, a `+` in the start + margin of an empty paragraph (in line with the heading grips; the right + margin in RTL) types the "/" for you, so the ordinary "/" menu opens. It + shows beside the caret 300 ms after you stop typing, or under the + pointer after a 150 ms rest, never in the title, a list, a quote or a + table cell, and never on touch. The "/" it types is an ordinary one: a + query, a pick, Esc and undo work as after a typed "/". Only with the + query still empty, Esc removes it without an undo step and a pick + undoes to the empty line. It is mounted by + the lazy bubble chunk's desktop wrapper, so it appears once that chunk + has loaded (a deviation from the spec's §15 file split, which put it in + `SlashMenuHost`: that would have grown the editor chunk). +- **Insert menu:** each row shows its "/" alias ("/table", "/code"). + +#### Changed + +- **"/" menu:** 320 px wide (was 288); in an RTL paragraph its right edge + is at the "/". +- **Placeholder:** an empty paragraph reads "Type / for blocks" (was + "Type something..."). + +### Row ⋯ menu in three labelled groups (BQ4) + +The row's ⋯ menu is now Text (Superscript, Subscript, Inline code, Clear +formatting, Paint format), View (Simplified toolbar, Appearance) and Help +(All actions…), with "Forget my choices…" alone at the end. Each group has a +visible heading and `role="group"` with the same label, and every row keeps a +16 px leading slot so the labels line up (Simplified toolbar shows its check +there). Nothing is added or removed. Page width follows with the preferences +work. Editor chunk +1 B against `main` at `84a9458`, from chunk-name hashes only; no eager code. + ### Desktop P2.6f: repair and rebuild the library Repair and rebuild for the format-2 library (offline data-model revision diff --git a/app/globals.css b/app/globals.css index 59fb0fee..2dfe8968 100644 --- a/app/globals.css +++ b/app/globals.css @@ -227,3 +227,72 @@ button[aria-pressed="mixed"]::after { color: GrayText; } } + +/* + * Touch tablets (O8 a, spec §13.2): the row's stand-ins whose icons don't + * explain themselves show one fixed word between the icon and the chevron + * ("Format", "Layout", "Block"; each stand-in's name begins with it, WCAG + * 2.5.3, `collapse-menus.tsx`). Here, with the app's first CSS, so the row + * has its final width at first paint and never shifts, at no cost to the + * editor chunk group. + */ +@media (min-width: 768px) and (pointer: coarse) { + :is( + [data-toolbar-group="marks"], + [data-toolbar-group="paragraph"], + [data-toolbar-group="slot"] + ) + > [data-collapse-standin] + [data-toolbar-item]::after { + order: 1; + font-size: 0.8125rem; + font-weight: 500; + } + + :is( + [data-toolbar-group="marks"], + [data-toolbar-group="paragraph"], + [data-toolbar-group="slot"] + ) + > [data-collapse-standin] + [data-toolbar-item] + > svg:last-child { + order: 2; + } + + [data-toolbar-group="marks"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Format" / ""; + } + + [data-toolbar-group="paragraph"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Layout" / ""; + } + + [data-toolbar-group="slot"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Block" / ""; + } +} + +/* + * The touch ladder's last step (owner decision 2026-11-22, option b): the + * words add 120px, which a row narrower than 832px (the row spans the + * window less 16px, so a window under 848px) has no room for in a code or + * table block. There Redo leaves the row for the top of ⋯ (the same query, + * `TOUCH_ROW_REDO_IN_MORE` in `row/row-menu-bodies.tsx`), and the list + * split keeps only List ▾ (one tap more for the last list type). ⌘⇧Z + * still redoes. + */ +@media (min-width: 768px) and (max-width: 847.98px) and (pointer: coarse) { + [data-variant="fixed"] + [data-toolbar-group="history"] + [data-action-id="history.redo"], + [data-variant="fixed"] .st-split[data-list-face] > [data-action-id^="list."] { + display: none; + } +} diff --git a/components/document-editor/document-editor-config.ts b/components/document-editor/document-editor-config.ts index 16272e7b..7c0478ee 100644 --- a/components/document-editor/document-editor-config.ts +++ b/components/document-editor/document-editor-config.ts @@ -146,7 +146,7 @@ export const LinkPolicyHyperlink = Hyperlink.extend({ const PLACEHOLDER_TEXT: Record = { heading: "Heading", - paragraph: "Type something...", + paragraph: "Type / for blocks", codeBlock: "Write code...", }; diff --git a/components/document-editor/mobile-toolbar-content.tsx b/components/document-editor/mobile-toolbar-content.tsx index 3076c09c..2c477ca9 100644 --- a/components/document-editor/mobile-toolbar-content.tsx +++ b/components/document-editor/mobile-toolbar-content.tsx @@ -17,6 +17,7 @@ import { import { ActionButton } from "@/components/smart-toolbar/action-button"; import { FormatSheetBody } from "@/components/smart-toolbar/phone/format-sheet"; +import { InsertSheet } from "@/components/smart-toolbar/phone/insert-sheet"; import { type MobileBarMode, nextMobileBarMode, @@ -139,8 +140,9 @@ interface MobileToolbarContentProps { /** Esc on a cell: back to the document with its selection. */ onEscape?: () => void; /** - * The last cells (List ▾, Indent, Insert ▾: `PhoneMenuCells`), rendered - * by the editor shell so the row's menus stay in the editor chunk. + * List ▾, Indent and the context slot (`PhoneMenuCells`), rendered by + * the editor shell so the row's menus stay in the editor chunk. Insert + * (its sheet) follows them, from this chunk. */ menuCells: ReactNode; } @@ -151,11 +153,11 @@ interface MobileToolbarContentProps { * undo, redo (from 404px; below, the sheet carries it, so the slot cell * never shifts the others), Aa (the * "Text format" sheet: style, size, colours, align, more), B, I, then - * `menuCells` (list, indent, the context slot, Insert). Toggles show their - * state with `aria-pressed` (#269). Hidden in a read-only document (#308), - * which also closes the sheet. While text is selected it swaps to - * `PhoneSelectionCells` (PR E, spec §4.7), never while focus is in the bar - * or the sheet is open; ✕ keeps the normal cells until the selection + * `menuCells` (list, indent, the context slot), then Insert (its sheet, + * spec §8.3). Toggles show their state with `aria-pressed` (#269). Hidden + * in a read-only document (#308), which also closes the sheets. While text + * is selected it swaps to `PhoneSelectionCells` (PR E, spec §4.7), never + * while focus is in the bar or a sheet is open; ✕ keeps the normal cells until the selection * collapses. Clear of the home indicator while the keyboard is closed * (`data-keyboard`, `phone.scss`). The status pill (design pass §5) sits * 8px above it, a sibling of the cells, never in a masked element. Its own @@ -168,6 +170,7 @@ export function MobileToolbarContent({ menuCells, }: MobileToolbarContentProps) { const [sheetOpen, setSheetOpen] = useState(false); + const [insertOpen, setInsertOpen] = useState(false); /** Opened for `formats.remove`: Your formats starts at its Remove list. */ const [removing, setRemoving] = useState(false); const recent = useRememberedChoice(RECENT_COLORS_CHOICE); @@ -189,7 +192,7 @@ export function MobileToolbarContent({ const [focusInBar, setFocusInBar] = useState(false); const [mode, setMode] = useState("all"); const nextMode = nextMobileBarMode({ - hasTextSelection: selectionKey !== null && !sheetOpen, + hasTextSelection: selectionKey !== null && !sheetOpen && !insertOpen, focusInBar, dismissedForSelection: dismissed, current: mode, @@ -299,6 +302,14 @@ export function MobileToolbarContent({ [editor, readOnly, onSheetOpenChange], ); + const onInsertOpenChange = useCallback( + (open: boolean) => { + setPageInert(editor, open); + setInsertOpen(open); + }, + [editor], + ); + /** Closes the sheet for an action that moves focus elsewhere itself. */ const closeSheet = useCallback(() => { keepFocusOnCloseRef.current = true; @@ -306,8 +317,10 @@ export function MobileToolbarContent({ }, [onSheetOpenChange]); useEffect(() => { - if (readOnly) onSheetOpenChange(false); - }, [readOnly, onSheetOpenChange]); + if (!readOnly) return; + onSheetOpenChange(false); + onInsertOpenChange(false); + }, [readOnly, onSheetOpenChange, onInsertOpenChange]); useEffect(() => () => setPageInert(editor, false), [editor]); @@ -396,6 +409,15 @@ export function MobileToolbarContent({ {menuCells} )} + {/* Mounted in both modes: it answers "/" and palette picks of Table + and Embed (`insert.open`) even while the selection cells show. */} + {sheetOpen ? null : } ); diff --git a/components/smart-toolbar/bubble/bubble-action-button.tsx b/components/smart-toolbar/bubble/bubble-action-button.tsx new file mode 100644 index 00000000..7e89b771 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-action-button.tsx @@ -0,0 +1,116 @@ +"use client"; + +import type { Editor } from "@tiptap/react"; + +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { useActionView } from "@/hooks/use-editor-context"; +import { editorActions } from "@/lib/editor-actions"; +import { INLINE_CODE_REASON } from "@/lib/editor-actions/inline-code-reason"; +import { + ariaKeyShortcuts, + toShortcutKeys, +} from "@/lib/editor-actions/key-combo"; +import { runAction } from "@/lib/editor-actions/registry"; +import { isMac } from "@/lib/shortcuts"; + +/** Keeps the editor selection: act on click, never move focus on press. */ +const keepSelection = (event: React.MouseEvent) => event.preventDefault(); + +/** + * The registry's generic refusals for the bubble's mark, link and colour + * items (`core/inline.ts`, `surface-actions.ts`), copied here because the + * strings stay in the registry. A unit test keeps the two in step. + */ +export const GENERIC_MARK_REASONS: ReadonlySet = new Set([ + "Formatting isn't available here.", + "Links can't go here.", + "Text colour isn't available here.", +]); + +/** + * The reason a refused bubble item gives: inside inline code, which takes + * no other mark, a generic refusal says why (spec §7.2). Every other + * reason (read-only, the title, code blocks) stays the registry's. Kept in + * the bubble chunk so the editor chunk's registry stays as it is. + */ +export function useBubbleReason( + editor: Editor, + reason: string | undefined, +): string | undefined { + const code = useActionView("mark.inlineCode", editor); + return reason !== undefined && + code?.active && + GENERIC_MARK_REASONS.has(reason) + ? INLINE_CODE_REASON + : reason; +} + +/** + * `ActionButton`'s bubble variant, mirroring `components/smart-toolbar/ + * action-button.tsx` (contract §3.5: label, icon, Markdown hint, shortcut, + * `aria-pressed` incl. "mixed", disabled with a reason), plus the inline + * code reason (`useBubbleReason`). A copy, not a prop on `ActionButton`: + * that module is in the editor chunk, and the phase's gate is 0 B. Keep the + * two in step. B I U S, ‹› and Link use it; Tx and 💬 keep `ActionButton`. + */ +export function BubbleActionButton({ + id, + editor, + onRun, +}: { + id: string; + editor: Editor; + /** + * Wraps the run, for what the bubble does around it (the link handoff, + * the pill after ‹›). It must call `run` once. + */ + onRun?: (run: () => boolean) => void; +}) { + const view = useActionView(id, editor); + const action = editorActions.get(id); + const reason = useBubbleReason( + editor, + !view || view.enabled === true ? undefined : view.enabled.reason, + ); + if (!action || !view) return null; + const Icon = action.icon; + const toggle = action.isActive !== undefined; + const tooltip = action.markdownHint ? ( + + {action.label} + + {action.markdownHint.trim()} + + + ) : ( + action.label + ); + return ( + { + const run = () => runAction(editor, action); + if (onRun) onRun(run); + else run(); + }} + > + {Icon ? + ); +} diff --git a/components/smart-toolbar/bubble/bubble-color-split.tsx b/components/smart-toolbar/bubble/bubble-color-split.tsx new file mode 100644 index 00000000..0bf30175 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-color-split.tsx @@ -0,0 +1,81 @@ +"use client"; + +import type { Editor } from "@tiptap/react"; + +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { useActionView } from "@/hooks/use-editor-context"; +import { editorActions } from "@/lib/editor-actions"; +import { runAction } from "@/lib/editor-actions/registry"; +import { colorLabel } from "@/lib/editor-actions/surface-actions"; +import { BaselineIcon, ChevronDownIcon } from "@/lib/icons"; +import { + TEXT_COLOR_CHOICE, + useRememberedChoice, +} from "@/lib/remembered-choice"; + +import { swatchStyle } from "../color/swatch"; +import { ColorPopoverButton } from "../color-controls"; +import { useBubbleReason } from "./bubble-action-button"; +import type { BubblePlacement } from "./bubble-rules"; + +const APPLY_ID = "color.text.apply"; + +/** + * The bubble's text colour split (spec §7.1 slot 7): the face reapplies + * the remembered colour ("Apply text colour: Red"), the 24px chevron opens + * the colour menu away from the text. Mirrors `ColorSplit`'s text half + * (`components/smart-toolbar/color-controls.tsx`) plus the inline code + * reason (`useBubbleReason`): a copy, not a prop on `ColorSplit`, because + * that module is in the editor chunk and the phase's gate is 0 B. Keep the + * two in step. + */ +export function BubbleColorSplit({ + editor, + placement, +}: { + editor: Editor; + placement: BubblePlacement; +}) { + const view = useActionView(APPLY_ID, editor); + const remembered = useRememberedChoice(TEXT_COLOR_CHOICE); + const reason = useBubbleReason( + editor, + !view || view.enabled === true ? undefined : view.enabled.reason, + ); + if (!view) return null; + const faceLabel = `Apply text colour: ${colorLabel(remembered.last)}`; + return ( +
+ event.preventDefault()} + onClick={() => { + const action = editorActions.get(APPLY_ID); + if (action) runAction(editor, action, remembered.last); + }} + > + + + +
+ ); +} diff --git a/components/smart-toolbar/bubble/bubble-controller.ts b/components/smart-toolbar/bubble/bubble-controller.ts index 47cfd174..55c39076 100644 --- a/components/smart-toolbar/bubble/bubble-controller.ts +++ b/components/smart-toolbar/bubble/bubble-controller.ts @@ -9,7 +9,12 @@ import { import type { Editor, EditorEvents } from "@tiptap/core"; import type { Transaction } from "@tiptap/pm/state"; -import { BUBBLE_OFFSET, type BubblePlacement } from "./bubble-rules"; +import { + BUBBLE_OFFSET, + BUBBLE_RESIZE_DELAY_MS, + BUBBLE_SHOW_DELAY_MS, + type BubblePlacement, +} from "./bubble-rules"; /** * Selection bubble controller (spec §12.1): shows, hides and positions one @@ -19,10 +24,8 @@ import { BUBBLE_OFFSET, type BubblePlacement } from "./bubble-rules"; * (`@tiptap/extension-bubble-menu` 3.33); line numbers below cite it. */ -/** Delay before a non-empty selection shows the bubble (`updateDelay`, :378). */ -export const BUBBLE_SHOW_DELAY_MS = 250; -/** Debounce for repositioning on resize and scroll (`resizeDelay`, :379). */ -export const BUBBLE_RESIZE_DELAY_MS = 60; +// The delays live with the pure rules, where the e2e can read them too. +export { BUBBLE_RESIZE_DELAY_MS, BUBBLE_SHOW_DELAY_MS } from "./bubble-rules"; /** What the controller drives: the view's root, rules and callbacks. */ export interface BubbleHost { @@ -36,11 +39,19 @@ export interface BubbleHost { onHide(): void; /** After each applied position (or reference-hidden) result. */ onPosition(): void; + /** + * Quiet time after Shift is released before a keyboard-made selection + * shows (spec §7.2, O7 b). 0 or omitted: off, keyboard selections use + * the normal show delay. + */ + readonly keyboardSettleMs?: number; } /** One editor's bubble: its visibility, position and teardown. */ export interface BubbleController { readonly visible: boolean; + /** A show is waiting: the show delay or a keyboard settle. */ + readonly pending: boolean; /** Re-evaluates now, without the show delay. */ update(): void; updatePosition(): void; @@ -51,6 +62,24 @@ export interface BubbleController { destroy(): void; } +const MODIFIER_KEYS = new Set(["Shift", "Control", "Meta", "Alt"]); +const SELECTION_KEYS = new Set([ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", +]); + +/** Shift+Arrow/Home/End/PageUp/PageDown, or Ctrl/⌘+A. */ +function isKeyboardSelection(event: KeyboardEvent): boolean { + if (event.shiftKey && SELECTION_KEYS.has(event.key)) return true; + return (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "a"; +} + type Timer = ReturnType | undefined; /** One controller per editor (StrictMode effects run twice). */ @@ -70,6 +99,19 @@ function changesSelectionOrDoc( return changes(transaction) || appended.some(changes); } +/** `ySyncPluginKey`'s meta key (y-tiptap): marks remote Yjs transactions. */ +const Y_SYNC_META = "y-sync$"; + +/** A selection change made here, not applied from a collaborator. */ +function isLocalSelectionChange( + transaction: Transaction, + appended: readonly Transaction[], +): boolean { + const local = (tr: Transaction) => + tr.selectionSet && !tr.getMeta(Y_SYNC_META); + return local(transaction) || appended.some(local); +} + /** * Creates the bubble controller for `editor`, replacing any earlier one. * The root is appended to `scrollTarget` (`.document-editor-wrapper`) on @@ -93,6 +135,14 @@ export function createBubbleController( let dragging = false; let preventHide = false; let showTimer: Timer; + let settleTimer: Timer; + /** The selection being changed came from a keydown (O7 b). */ + let keyboardSelecting = false; + /** A keyboard selection is waiting for its settle (set by `evaluate`). */ + let settling = false; + let shiftHeld = false; + /** A key is auto-repeating: it never shows the bubble. */ + let repeating = false; let deferTimer: Timer; let resizeTimer: Timer; let stopAutoUpdate: (() => void) | undefined; @@ -162,7 +212,11 @@ export function createBubbleController( /** :624-639. Cancels a pending show; the root leaves before `onHide`. */ function hide() { clearTimeout(showTimer); + clearTimeout(settleTimer); showTimer = undefined; + settleTimer = undefined; + keyboardSelecting = false; + settling = false; if (!visible) return; visible = false; positionRun += 1; @@ -177,7 +231,11 @@ export function createBubbleController( /** Re-evaluates now (`updateHandler`, :579-603). Never shows mid-drag. */ function update() { clearTimeout(showTimer); + clearTimeout(settleTimer); showTimer = undefined; + settleTimer = undefined; + keyboardSelecting = false; + settling = false; if (destroyed || editor.isDestroyed || view.composing) return; if (editor.state.selection.empty || !host.shouldShow()) { hide(); @@ -199,12 +257,62 @@ export function createBubbleController( } if (dragging) return; clearTimeout(showTimer); + showTimer = undefined; + // Only a hidden bubble settles; a shown one repositions as before. + if (!visible && keyboardSelecting && (host.keyboardSettleMs ?? 0) > 0) { + settling = true; + armSettle(); + return; + } showTimer = setTimeout(() => { showTimer = undefined; update(); }, BUBBLE_SHOW_DELAY_MS); } + /** + * (Re)starts the keyboard settle (O7 b): only once Shift is up and no key + * is repeating; the Shift keyup and each further change call it again. + */ + function armSettle() { + clearTimeout(settleTimer); + settleTimer = undefined; + if (shiftHeld || repeating) return; + settleTimer = setTimeout(() => { + settleTimer = undefined; + update(); + }, host.keyboardSettleMs); + } + + // Capture, on the window: ProseMirror's own keydown handler (Tiptap's + // Mod-a runs `selectAll` synchronously in it) must find the flag set. + const onKeyDown = (event: KeyboardEvent) => { + if (!(event.target instanceof Node && dom.contains(event.target))) return; + shiftHeld = event.shiftKey; + repeating = event.repeat; + if (MODIFIER_KEYS.has(event.key)) return; + keyboardSelecting = isKeyboardSelection(event); + }; + + // On the window: Shift may be released outside the editor. While Shift is + // held the flag stays: Chromium can fire `selectionchange` after a fast + // arrow's keyup. Releasing Shift with nothing pending (a no-op + // Shift+Arrow) leaves nothing to settle. + const onKeyUp = (event: KeyboardEvent) => { + repeating = false; + if (event.key === "Shift" || !event.shiftKey) shiftHeld = false; + if (settling) armSettle(); + else if (!shiftHeld) keyboardSelecting = false; + }; + + // Keys released while the window was away never report their keyup. + const onWindowBlur = () => { + shiftHeld = false; + repeating = false; + if (settling) armSettle(); + else keyboardSelecting = false; + }; + /** Evaluates once the selection has settled (focus :459-462, IME :431-442). */ function evaluateLater() { clearTimeout(deferTimer); @@ -222,6 +330,13 @@ export function createBubbleController( if (!visible && editor.state.selection.empty) return; if (view.composing) return; if (!changesSelectionOrDoc(transaction, appendedTransactions)) return; + // A remote change or a doc-only one must not restart the settle. + if ( + settling && + !isLocalSelectionChange(transaction, appendedTransactions) + ) { + return; + } evaluate(); }; @@ -263,6 +378,10 @@ export function createBubbleController( }; const onPointerDown = () => { + keyboardSelecting = false; + settling = false; + clearTimeout(settleTimer); + settleTimer = undefined; dragging = true; }; @@ -300,6 +419,9 @@ export function createBubbleController( window.removeEventListener("pointercancel", onPointerUp); window.removeEventListener("resize", onReposition); scrollTarget.removeEventListener("scroll", onReposition); + window.removeEventListener("keydown", onKeyDown, { capture: true }); + window.removeEventListener("keyup", onKeyUp, { capture: true }); + window.removeEventListener("blur", onWindowBlur); clearTimeout(deferTimer); clearTimeout(resizeTimer); deferTimer = undefined; @@ -318,6 +440,9 @@ export function createBubbleController( dom.addEventListener("contextmenu", onHideEvent); dom.addEventListener("compositionend", evaluateLater); dom.addEventListener("pointerdown", onPointerDown); + window.addEventListener("keydown", onKeyDown, { capture: true }); + window.addEventListener("keyup", onKeyUp, { capture: true }); + window.addEventListener("blur", onWindowBlur); window.addEventListener("pointerup", onPointerUp); window.addEventListener("pointercancel", onPointerUp); window.addEventListener("resize", onReposition); @@ -327,6 +452,9 @@ export function createBubbleController( get visible() { return visible; }, + get pending() { + return showTimer !== undefined || settleTimer !== undefined; + }, update, updatePosition, hide, diff --git a/components/smart-toolbar/bubble/bubble-rules.ts b/components/smart-toolbar/bubble/bubble-rules.ts index 13d6156c..b71763d4 100644 --- a/components/smart-toolbar/bubble/bubble-rules.ts +++ b/components/smart-toolbar/bubble/bubble-rules.ts @@ -11,11 +11,17 @@ import { * rules are unit tested without a browser. */ -/** B · I · U, text colour, link. Every one is also a row control. */ +/** + * B · I · U · S · ‹› · Tx, text colour, link (spec §7.1). Every one is + * also in the row: a button, or an item of ⋯ More formatting. + */ export const BUBBLE_ACTION_IDS = [ "mark.bold", "mark.italic", "mark.underline", + "mark.strike", + "mark.inlineCode", + "format.clear", "color.text.apply", "mark.link", ] as const; @@ -163,6 +169,16 @@ export interface BubbleRect { export type BubblePlacement = "top" | "bottom"; +/** Delay before a non-empty selection shows the bubble (`updateDelay`, :378). */ +export const BUBBLE_SHOW_DELAY_MS = 250; +/** Debounce for repositioning on resize and scroll (`resizeDelay`, :379). */ +export const BUBBLE_RESIZE_DELAY_MS = 60; +/** + * A keyboard selection shows once Shift is up and the selection has been + * still this long, never on auto-repeat (spec §7.2, O7 b). + */ +export const KEYBOARD_SETTLE_MS = 300; + /** Gap between the selection and the bubble, as the plugin's `offset`. */ export const BUBBLE_OFFSET = 8; diff --git a/components/smart-toolbar/bubble/bubble-style-menu.tsx b/components/smart-toolbar/bubble/bubble-style-menu.tsx new file mode 100644 index 00000000..c94a752b --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-style-menu.tsx @@ -0,0 +1,232 @@ +"use client"; + +import { DirectionProvider } from "@base-ui/react/direction-provider"; +import type { Editor } from "@tiptap/react"; +import { useCallback, useLayoutEffect, useRef, useState } from "react"; + +import { + DropdownMenu, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu-trigger"; +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { editorActions } from "@/lib/editor-actions"; +import { ChevronDownIcon } from "@/lib/icons"; + +import { clearOfSelection } from "../color/clear-of-selection"; +import { + focusLostOnClose, + menuBody, + prefetchMenuBodies, + useMenuGate, +} from "../lazy-menu"; +import { TypeIcon } from "../type-icon"; +import type { BubblePlacement } from "./bubble-rules"; +import { + STYLE_FACE_NAMES, + STYLE_FACES, + type StyleFace, + useStyleFace, +} from "./style-face"; + +const Content = menuBody((bodies) => bodies.ToolbarMenuContent); +/** `ToolbarMenuContent`'s gap to its trigger. */ +const MENU_GAP = 4; +const TurnIntoMenuItems = menuBody((bodies) => bodies.TurnIntoMenuItems); + +/** Spec §7.1 Sizes: the face is at least 64px, and a word past 96px… */ +const FACE_MIN = 64; +const FACE_MAX = 96; +/** …gives way to the type's icon: `padding-inline: 8px 4px`, gap, chevron. */ +const FACE_CHROME = 8 + 4 + 4 + 12; + +/** The registry action whose icon stands for each face. */ +const FACE_ICON_IDS: Partial> = { + List: "list.bullet", + Quote: "insert.quote", + Code: "insert.codeBlock", +}; + +/** + * The icon face, for a locale whose longest word would pass 96px: the + * registry's own icons (no new icon import, so the editor chunk keeps its + * shape), Type for Text, Title and Mixed. + */ +function FaceIcon({ face }: { face: StyleFace }) { + const id = + FACE_ICON_IDS[face] ?? + (face.startsWith("H") ? `style.heading${face.slice(1)}` : ""); + const Icon = editorActions.get(id)?.icon ?? TypeIcon; + return