From 0723258c898f7d28191b479acc00cf524f238f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 06:55:15 -0300 Subject: [PATCH 01/15] Polish editor controls, article rows, and notifications --- CHANGELOG.md | 3 ++ docs/help/file-and-folder-workflows.md | 2 +- docs/help/markdown-reference.md | 4 ++- docs/specification.md | 14 ++++---- e2e/desktop/specs/code-collapse.spec.ts | 6 ++-- e2e/desktop/specs/document-tabs.spec.ts | 14 ++++++++ e2e/desktop/specs/heading-outline.spec.ts | 15 ++++++++ e2e/desktop/specs/legacy-encoding.spec.ts | 24 ++++++++++++- e2e/desktop/specs/table-controls.spec.ts | 12 ++++++- src/app.css | 3 +- src/components/layout/shell.tsx | 5 +++ src/components/ui/toast.tsx | 34 ++++++++++++------- .../editor/components/heading-outline.css | 4 +-- .../editor/components/milkdown-editor.css | 14 +++----- .../editor/plugins/codeBlockCollapse.test.ts | 15 ++++---- .../editor/plugins/codeBlockCollapse.ts | 2 +- src/features/editor/plugins/codeBlockView.ts | 29 ++++------------ .../editor/plugins/controlTooltip.test.ts | 3 +- .../editor/plugins/tableControls.test.ts | 30 +++++++++++++++- src/features/editor/plugins/tableControls.ts | 22 +++++------- .../components/article-navigator.test.tsx | 7 +++- .../components/article-navigator.tsx | 16 +++++++-- .../utils/articleNavigatorRows.test.ts | 3 ++ .../utils/articleNavigatorRows.ts | 11 +++++- src/locales/en.json | 2 +- 25 files changed, 200 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a853977..f18f8bb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ Leafdown uses lightweight [Keep a Changelog](https://keepachangelog.com/en/1.1.0 ### Fixed - Keep a table column without an alignment that way when it is copied and pasted, instead of left-aligning it. +- Keep article names steady when selected and mark articles with unsaved changes in the navigator. +- Use the shared code-block toggle to collapse long blocks and add a selection grip to table headers. +- Center the heading outline dots on the same axis and place notification actions below the message. ## [0.1.0-alpha.5] - 2026-10-19 diff --git a/docs/help/file-and-folder-workflows.md b/docs/help/file-and-folder-workflows.md index 65c57af5..ed338cf0 100644 --- a/docs/help/file-and-folder-workflows.md +++ b/docs/help/file-and-folder-workflows.md @@ -56,7 +56,7 @@ Renaming a file or folder moves its open tabs in every window and preserves edit ## Work in the article navigator -Choose a Markdown row to preview it. Expand folders to reach nested notes. Keyboard focus moves with the arrow keys; `Enter` or `Space` opens the focused article. **View > Collapse all folders** and **Expand all folders** change the tree at once. +Choose a Markdown row to preview it. A dot at the right edge marks any article with unsaved changes in this window. Expand folders to reach nested notes. Keyboard focus moves with the arrow keys; `Enter` or `Space` opens the focused article. **View > Collapse all folders** and **Expand all folders** change the tree at once. Right-click a row, or press `Shift+F10` on it, to open its context menu: diff --git a/docs/help/markdown-reference.md b/docs/help/markdown-reference.md index 80aaa191..534f52f9 100644 --- a/docs/help/markdown-reference.md +++ b/docs/help/markdown-reference.md @@ -131,7 +131,7 @@ Use pipes between cells and a separator row after the header. Colons in that sep **Try it:** **Insert > Table** creates a table. **Format > Table** adds, moves, or deletes rows and columns, and **Format > Table > Column alignment** aligns the current or selected columns. In the document, table controls provide those actions beside the table too. -Right-click in a table, or press `Shift+F10`, to open its commands. Choose the row or column selector above the action icons to select that scope and show its actions. The selectors name the current row or column, or the selected range; the header is named **Header row**, and body rows start at one. Hover an action to read its name. In column scope, **Align left**, **Align center**, and **Align right** set the columns' alignment; choose the highlighted one again to remove it. **Delete table** stays beside the selectors, after a divider. The slim grips on the table's edges select or drag rows and columns, and the `+` buttons insert at a boundary. +Right-click in a table, or press `Shift+F10`, to open its commands. Choose the row or column selector above the action icons to select that scope and show its actions. The selectors name the current row or column, or the selected range; the header is named **Header row**, and body rows start at one. Hover an action to read its name. In column scope, **Align left**, **Align center**, and **Align right** set the columns' alignment; choose the highlighted one again to remove it. **Delete table** stays beside the selectors, after a divider. Click the slim grips on the table's edges to select any row or column. Drag a grip to move a column or body row. The header row stays at the top, and the `+` buttons insert at a boundary. ## Code blocks @@ -147,6 +147,8 @@ const pots = 3; **Try it:** **Insert > Code block** or **Format > Code block** (`Mod+Alt+C`). Click a fenced block's language badge or use **Format > Code block language...** to change its language. Line numbers and soft wrap change presentation, never the saved code. +For a collapsed code block, choose **Show more lines** below the preview. Use **Expand all code blocks** in a code block's toolbar to expand or collapse long blocks throughout the document, or press `Mod+.` with the caret in a long block to toggle that block. + ## Footnotes and definitions Footnotes are supported in addition to CommonMark and GFM. A reference names a definition elsewhere in the document. diff --git a/docs/specification.md b/docs/specification.md index 0601b436..f6e99373 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -53,7 +53,7 @@ Primary user interface surfaces: - **Document surface:** contains the active document's hybrid Markdown editor below the document tabs. In a folder-only session, it displays a centered placeholder illustration and text prompting the user to select an article or create a new file, or, when the folder has no articles, saying that no Markdown files were found. - **Document tabs:** a strip above the document surface, beside the article navigator, while at least one document is open. Each open document has a tab in the order it was opened, a new tab going after the active one; tabs cannot be reordered. A tab names its file, followed by its folder's name while another tab has the same name, or `Untitled`, `Untitled 2`, and so on for untitled documents, and hovering it shows the file's full path. A tab with unsaved changes shows a dot that becomes a close mark on hover; other tabs show the close mark while active or hovered. Choosing a tab makes it active and puts focus in its editor; the close mark or a middle click closes it as `Close document` does, without making it active first. When the tabs do not fit, they narrow to a minimum width and then the strip scrolls sideways, with the mouse wheel too, keeping the active tab in view. A `+` button after the tabs creates a new document. A window has at most one preview tab, whose name is set in italics: a file opened only to look at, from the article navigator, a folder search result, a link, or as the index of a folder being opened, takes the preview tab's place and replaces its document, or opens in a new preview tab after the active one when the window has none. Editing its document, saving it, double-clicking the tab or the file's navigator row, `Keep tab`, or opening the file again in that window from Open, recent files, a drop, or the operating system makes it an ordinary tab, so a document with unsaved changes is never replaced. Replacing a preview closes its document as closing a clean tab does. Assistive technology reads the strip as a tab list named `Open documents`: arrow keys move between tabs, `Enter` or `Space` chooses one, and each tab's name says when its document has unsaved changes and when its tab is a preview. The close marks are for the pointer; from the keyboard, `Close document` closes the active tab. - **Article navigator:** appears only while a folder context is open. Without one, the document surface spans the workspace and `Toggle sidebar` is unavailable, leaving the sidebar visibility setting untouched for the next folder. It shows the current folder context's articles (supported Markdown files) in a nested tree, leaving out ignored directories and everything in them. Articles open in the editor. A directory is listed when it holds an article at any depth, or when it holds no file at any depth, so a folder just created with `New folder` stays visible; files Leafdown cannot open, and directories holding only such files, are left out. With the [Show all files](./reference.md#general) setting on, every non-ignored file and directory is listed instead. Every file that is not an article is then listed among them in a muted style; hovering it, or reading it with assistive technology, says that Leafdown can only open Markdown files, and choosing it opens nothing, in Leafdown or in another application. A directory holding only such files then expands to show them. An empty directory has nothing to expand under either setting. Directories are listed before files within each folder, then the selected article sort order is applied within each group, with articles and other files sorted together. Each row starts with an icon for what it lists: a filled folder, drawn open while expanded; an article's page of lines; or, for any other file, a page marked with its type as its extension names it, whether image, video, audio, code, data, spreadsheet, archive, PDF, or document, and a blank page otherwise. The [File icons](./reference.md#appearance) setting draws them Neutral, in the interface's gray with articles darker than other files, or Colored, where folders are amber and articles and each file type take a color of their own that stays the same under every accent color. The icons are decorative and hidden from assistive technology. The navigator's article filter and its empty-folder message concern articles only under either setting: filtering never matches another file, and a folder without articles says that no supported Markdown files were found while still listing whatever entries the setting shows. Folder scans skip symlinked entries rather than following them, and skip the staging files Leafdown writes while saving. When the active saved document is outside the current folder context, the article navigator keeps showing the current folder context and displays a compact detached-document message instead of selecting an article. Context menus on its rows and on its empty space create, rename, delete, locate, and copy the paths of files and folders inside the current folder context, as described in [Article Navigator Actions](#article-navigator-actions). Moving, copying, and duplicating entries is left to the system file manager. -- **Document outline:** floats at the right edge of the document surface while the active document has at least one heading, including untitled documents and files opened without a folder; a document without headings shows no outline. At rest it is a column of dots, one per listed heading in document order and sized by heading level, with the current heading's dot in the accent color. Hovering the column opens it in place after a short delay: the dots spread apart and each heading's title appears beside its dot, indented by level from the shallowest listed level. The heading under the pointer stays level with it as the outline opens, so pointing low on the column opens the lower part of the outline. When the open list is taller than the surface, its top and bottom edges fade while headings lie beyond them, and moving the pointer up and down over the dots scrolls it, while over the titles it holds still for choosing. The outline closes shortly after the pointer leaves it, when focus leaves it, or with Escape, which returns focus to where it came from. Tab reaches the current heading's row and opens the outline there; Up, Down, Home, and End move between rows, and Enter or Space chooses one. A press on the closed column, such as a tap, opens it without choosing a heading. The H1 to H6 control in the panel header lists headings down to the chosen level, H1–H3 by default, while the open outline keeps its place under the pointer, moving only as far as it must to stay on the surface, with the current heading in view, and keeps the choice as the [Outline levels](./reference.md#general) setting. A document whose shallowest heading is deeper than that level still lists its shallowest level. A heading that is not listed marks the nearest listed heading before it as current. Headings inside a folded section stay listed, and choosing one unfolds the sections around it; a heading hidden by a fold is never current. A folded heading's dot is hollow, at the size its level gives it. The outline offers no fold control of its own, and its levels and the editor's folds do not change each other. Choosing a heading places the caret at its start without changing the document and scrolls the heading to where the document's first line rests before any scrolling, so it keeps the editor's top padding at every width and stays clear of an open search panel; a heading in the last screen stops wherever scrolling ends. A heading that opens the document, with no content before it in the document or in its container, returns the view to the start. Duplicate labels navigate by position rather than text. Headings inside lists, blockquotes, and callouts name their container in their accessible name and tooltip. The current heading is the last one to reach a line just below the top of the view. Over the final screen of scrolling that line moves down to the bottom of the view, so the last headings become current in turn, and a heading chosen from the outline stays current while the view stays where navigation left it. Before the first heading none is current. Editing, paste, heading-level changes, Undo and Redo, scrolling, resizing, and document switches refresh the rows and the current heading. +- **Document outline:** floats at the right edge of the document surface while the active document has at least one heading, including untitled documents and files opened without a folder; a document without headings shows no outline. At rest it is a column of dots, one per listed heading in document order and centered on the same axis. H1 and H2 use larger dots, H4–H6 use a more muted color, and the current heading uses the accent color. Hovering the column opens it in place after a short delay: the dots spread apart and each heading's title appears beside its dot, indented by level from the shallowest listed level. The heading under the pointer stays level with it as the outline opens, so pointing low on the column opens the lower part of the outline. When the open list is taller than the surface, its top and bottom edges fade while headings lie beyond them, and moving the pointer up and down over the dots scrolls it, while over the titles it holds still for choosing. The outline closes shortly after the pointer leaves it, when focus leaves it, or with Escape, which returns focus to where it came from. Tab reaches the current heading's row and opens the outline there; Up, Down, Home, and End move between rows, and Enter or Space chooses one. A press on the closed column, such as a tap, opens it without choosing a heading. The H1 to H6 control in the panel header lists headings down to the chosen level, H1–H3 by default, while the open outline keeps its place under the pointer, moving only as far as it must to stay on the surface, with the current heading in view, and keeps the choice as the [Outline levels](./reference.md#general) setting. A document whose shallowest heading is deeper than that level still lists its shallowest level. A heading that is not listed marks the nearest listed heading before it as current. Headings inside a folded section stay listed, and choosing one unfolds the sections around it; a heading hidden by a fold is never current. A folded heading's dot is hollow, at the size its level gives it. The outline offers no fold control of its own, and its levels and the editor's folds do not change each other. Choosing a heading places the caret at its start without changing the document and scrolls the heading to where the document's first line rests before any scrolling, so it keeps the editor's top padding at every width and stays clear of an open search panel; a heading in the last screen stops wherever scrolling ends. A heading that opens the document, with no content before it in the document or in its container, returns the view to the start. Duplicate labels navigate by position rather than text. Headings inside lists, blockquotes, and callouts name their container in their accessible name and tooltip. The current heading is the last one to reach a line just below the top of the view. Over the final screen of scrolling that line moves down to the bottom of the view, so the last headings become current in turn, and a heading chosen from the outline stays current while the view stays where navigation left it. Before the first heading none is current. Editing, paste, heading-level changes, Undo and Redo, scrolling, resizing, and document switches refresh the rows and the current heading. - **Status bar:** appears along the bottom of the workspace, beneath the article navigator and the document surface, while a document is open and `Status bar visibility` is on. Like the menu bar, it has no surface of its own. Assistive technology reads it as one labeled region that does not announce its changes, and only its controls take focus. It shows, as the document and selection change: - **Block path:** with a collapsed caret, the names of the blocks holding it from the outermost in, such as `Blockquote › Task list › Paragraph`. Headings name their level, code blocks their language when set, and a table cell its row and column counted from the header row; a paragraph inside a table cell is not named. The path is hidden while a selection is expanded. In a narrow window it is cut short from its outer end, and hovering it shows it in full. - **Document state:** `Unsaved` while the document has unsaved changes, `Changed on disk` while a newer version of its file is recorded, and `File missing` while its file is missing, as [Filesystem Watching](#filesystem-watching) describes. Unsaved changes are named together with either file state, as in `Unsaved, file missing`. Nothing is shown for a clean document whose file holds the version it was read or saved as. @@ -69,7 +69,7 @@ Primary user interface surfaces: Menus and the editor context popup share an opaque theme surface, subtle border and shadow, and rounded corners. The menu bar retains text labels, leading checkmarks, trailing shortcut keycaps, and submenu arrows. Navigator actions carry icons, with Delete in a separate final group using the destructive color. In the light appearance, a faint neutral workspace background separates the white document and navigator panes. -The active article row, document tab, and Preferences section share a neutral background, medium-weight label, and a short, rounded vertical marker in the accent color near the left edge. Hovering an inactive item shows a softer neutral background without a marker; hovering the active item retains its appearance. Keyboard focus has a separate outer ring and can rest on an inactive row or tab without changing which document or section is active. A tab's unsaved-changes dot remains separate at its right edge. +The active article row, document tab, and Preferences section share a neutral background and a short, rounded vertical marker in the accent color near the left edge. Article names keep the same weight when selected. The active tab and Preferences section use medium-weight labels. Hovering an inactive item shows a softer neutral background without a marker; hovering the active item retains its appearance. Keyboard focus has a separate outer ring and can rest on an inactive row or tab without changing which document or section is active. Tabs and article rows show a separate dot at their right edge when the document has unsaved changes in the current window. Assistive technology reads the article name and its unsaved state. Hover text in the app shell and the editor's own controls is a tooltip in the app's theme, never the webview's native title. A control has one only where it adds to what the control shows: the name of an icon control whose glyph does not make its action clear, such as Match case or Soft wrap; text the control has cut short, such as a navigator row's name or the block path, shown only while it is cut short; or details the control does not show, such as a tab's path or the character count. Close marks, add buttons, previous and next arrows, chevrons, block handles, table grips, and a callout's type icon have none, since the glyph or its place says what they do. The first tooltip opens once the pointer has rested on its control for a short delay, and moving straight on to another control with a tooltip opens that one at once; keyboard focus opens one at once where the control takes it. A tooltip closes when the pointer leaves, on a press, and on Escape. It stays closed while a press or drag is under way and beneath a menu or popup covering its control, and the pointer passes through it to whatever lies beneath. A tooltip never replaces a control's accessible name. Titles authored in Markdown links and images are part of the document and keep the webview's own presentation. @@ -236,9 +236,9 @@ The editor is a unified hybrid Markdown surface. Behavior is governed by renderi - A fenced code block whose info string starts with the exact language `math` renders its content as display math while the caret is outside it. Either backtick or tilde fences qualify, and words after `math` remain metadata; `Math`, `latex`, and `tex` do not qualify. Clicking rendered math puts the caret in the code. While the caret is inside, the code stays directly editable with a rendered preview below it. TeX that does not render stays visible as code, with the error available as its description and below the code while editing. Rendering does not change the fence, info string, or content that the block writes to Markdown. - A fenced code block whose first info-string word is `mermaid`, ignoring case, renders as a diagram while neither end of the selection is in its code. Other info words are preserved but do not configure the diagram; aliases and indented code do not qualify. Clicking the diagram puts the caret at the start of its code, and an arrow key leaving the neighboring block toward the diagram enters its code at the near edge. While the caret is inside, the code stays directly editable with Mermaid syntax highlighting and the last rendered diagram below it, rendered again once typing pauses. Selecting the whole block shows its diagram. A failed diagram stays editable as source with its error; while the caret is inside, the last rendered diagram stays below the error. Editing the source tries again. Source over 10,000 characters and Mermaid configuration directives or frontmatter stay as source with an explanation. The renderer limits a diagram to 200 edges. A diagram is drawn at its own size in the app's light or dark colors; a diagram wider than the page scrolls horizontally at that size, and pressing its scrollbar does not enter source editing. It is drawn again when the theme changes. The diagram image has a name and a source-text alternative. The authored Markdown, not the image, supplies Undo, Redo, clipboard, block selection and movement, and save. A clean open/save preserves its fence, info string, whitespace, line endings, comments, and directives. - A fenced code block names its language on a badge at its top right. Clicking the badge opens the language picker for that block; `Code block language...` opens the same picker from the menu, the context popup, or the keyboard. A block without a language shows a faint `Language` badge only while the pointer is over it or the caret or selection is in it. Indented code has no fence line to hold a language, so it shows no badge and does not offer the command. The badge is chrome outside the code: it never reaches the saved Markdown, copied content, or counts, and pressing it leaves the selection where it was. -- A code block of 10 or more lines opens collapsed whenever its document opens: it shows its first 8 lines, which fade out toward its bottom edge, and a bar below them reading `Show N more lines` expands it. An expanded long block shows a chevron beside its language badge, or in that corner when it has none, that collapses it again. Shorter blocks show in full and offer neither control. Lines are counted as the code is written, so under soft wrap a collapsed block shows its first 8 lines with all their wrapped rows. A block that grows past the threshold while it is edited, or arrives by paste, starts expanded; one edited below it shows in full. The controls are chrome outside the code with no tab stop: pressing either leaves the selection where it was, and `Fold or unfold section` (`Mod+.`) collapses or expands the long block holding the caret before it considers the heading's section. Only code shown as code collapses; rendered math and Mermaid diagrams show in full and offer no control. +- A code block of 10 or more lines opens collapsed whenever its document opens: it shows its first 8 lines, which fade out toward its bottom edge, and a bar below them reading `Show N more lines` expands it. The shared code block toggle collapses long blocks again. Shorter blocks always show in full. Lines are counted as the code is written, so under soft wrap a collapsed block shows its first 8 lines with all their wrapped rows. A block that grows past the threshold while it is edited, or arrives by paste, starts expanded; one edited below it shows in full. The expansion bar is chrome outside the code with no tab stop. Pressing it leaves the selection where it was, and `Fold or unfold section` (`Mod+.`) collapses or expands the long block holding the caret before it considers the heading's section. Only code shown as code collapses; rendered math and Mermaid diagrams show in full and offer no control. - Collapsing changes only the view, as heading folds do: the Markdown, save, dirty state, Undo and Redo, copying, counts, and find keep every hidden line, and collapse state is not recorded in the file or in history. It resets when the document is closed, reopened, or reloaded after an outside change. A caret on a shown line keeps the block collapsed. Anything that places the caret or either end of the selection on a hidden line expands the block, including `Down` from the last row of the last shown line, `Right` at its end, Undo and Redo, navigation, and the current find match; a selection that only passes over hidden lines, such as `Select all`, leaves the block collapsed and still copies them. Collapsing a block whose hidden lines hold the caret or selection moves the caret to the end of the last shown line. Highlighting, line numbers, soft wrap, and the language badge work in both states. -- Every code block carries three toggles in a header row it always reserves, so they never cover code: `Expand all code blocks`, `Soft wrap for code blocks`, and `Display line numbers for code blocks`, in that order before the collapse chevron and language badge. They show while the pointer is over the block or the caret or selection is in it, and each shows whether it is on. Each acts on every code block in the document, not only its own. `Expand all code blocks` appears only while the document holds a block long enough to collapse, and is on while none is collapsed: pressing it expands every collapsed block, or, when none is, collapses every long one. Like a single block's collapse, it changes only the view and resets when the document is closed, reopened, or reloaded, and collapsing every block moves a caret it would hide to the end of that block's last shown line. The other two change the Editor setting they name, so Preferences and every open document in every window follow at once, and no document is modified. The toggles follow the language badge's rules: they have no tab stop, never reach the saved Markdown, copied content, or counts, and pressing one leaves the selection where it was. Rendered math and Mermaid diagrams show no toggles. +- Every code block carries three toggles in a header row it always reserves, so they never cover code: `Expand all code blocks`, `Soft wrap for code blocks`, and `Display line numbers for code blocks`, in that order before the language badge. They show while the pointer is over the block or the caret or selection is in it, and each shows whether it is on. Each acts on every code block in the document, not only its own. `Expand all code blocks` appears only while the document holds a block long enough to collapse, and is on while none is collapsed: pressing it expands every collapsed block, or, when none is, collapses every long one. Like a single block's collapse, it changes only the view and resets when the document is closed, reopened, or reloaded, and collapsing every block moves a caret it would hide to the end of that block's last shown line. The other two change the Editor setting they name, so Preferences and every open document in every window follow at once, and no document is modified. The toggles follow the language badge's rules: they have no tab stop, never reach the saved Markdown, copied content, or counts, and pressing one leaves the selection where it was. Rendered math and Mermaid diagrams show no toggles. - The picker opens under the badge with an empty search field focused above the languages Leafdown highlights, each with its aliases, and marks the one the block has. When the block has a language, `No language` comes first, noting the metadata it also removes. Typing narrows the list by name or alias. Clicking a language, or arrowing onto one and pressing `Enter`, sets it. Otherwise `Enter` sets the search text exactly as typed, which may be an alias, a partial name, or any identifier Leafdown does not highlight; such an identifier is kept as written and receives no highlighting. A language is one word: surrounding spaces are trimmed, and text holding a space is refused because the text after the space would be read back as metadata. `Enter` with nothing typed or chosen closes the picker without a change. A change is one transaction and one `Undo` step that keeps the fence's metadata after the language, the spacing before it, and the fence's own form; the badge, highlighting, and status bar follow from the block. Clearing removes the language and, because metadata cannot be written without one, the metadata too. Choosing the language the block already has changes nothing. `Escape`, `Tab`, or a click outside closes the picker without a change, returning focus to the editor except where the click put it. Any document edit while the picker is open retires it, so a staged language never applies to a block other than the one it opened on. - Footnote definitions render as editable definition blocks that always show their source: `[^` and `]:` as muted monospace marker runs, the label between them in bold, and the definition body in muted text, with a small gap separating the label from each marker run. The label stays in the body's opening row even when that block has multiple lines. The presentation does not depend on the caret: it neither appears when a caret arrives nor resolves when one leaves. The label is document text a caret and a selection reach and edit; the marker runs are chrome that hold no document position, so a caret aimed at one resolves inside the definition. A backspace at the start of the definition's body moves the caret to the end of the label rather than merging the body into it. - Editing a footnote definition's label renames the definition and every reference that named it, so the resolution key moves on both sides together and no reference is left naming a label the file no longer defines. The label commits when the caret leaves it, and a file written while the caret is still in it is written with the label the author typed. The label is edited as the file spells it, so a backslash in it is the escape the file holds. An empty label, a label holding a bracket or a line ending, a label ending in a backslash that would escape its closing bracket, and a label another definition already answers to do not commit; the label the definition was read with stands. `Undo` restores the label the typing began from and returns the caret to it, which reopens the edit, so the rename it reverses settles when the caret next leaves or when the file is written. @@ -440,9 +440,9 @@ For editor input and clipboard ownership, see [Architecture](./architecture.md#e - The context popup groups table commands in a two-row bar. Its first row selects the row or column scope and offers a separate `Delete table` button, with a spaced divider before it. The second row shows that scope's icon-only actions: insert before or after, move in either direction, and delete. Column scope adds `Align left`, `Align center`, and `Align right` toggles before delete, with a divider on each side of them. A toggle is pressed while every target column has its alignment, and choosing a pressed toggle returns the target columns to `Default`. Action names remain available to assistive technology and in tooltips, and unavailable actions stay visible but disabled. The selectors keep the popup's normal arrow-key traversal; `Enter` or `Space` changes scope. - Scope selectors name the current row or column, or selected range. Body rows and columns are numbered from one; the protected first row is named `Header row`. Choosing a scope selects its whole rows or columns without changing content or taking focus out of the popup. Switching between scopes retains the original targets; changing the selection or editing the table establishes new ones. A grip opens its matching scope; a caret or ordinary cell selection opens row actions. -- Hovering a table cell shows a slim rail grip on the table's left border beside the cell's row and one on its top border above the cell's column. A grip uses the accent color while hovered or while its row or column is selected. The header row has no row grip. While the table is scrolled sideways, the row grip stays at the table's visible left edge and the column grip scrolls with its column, showing only while its column is in view. +- Hovering a table cell shows a slim rail grip on the table's left border beside the cell's row and one on its top border above the cell's column. A grip uses the accent color while hovered or while its row or column is selected. The header row grip selects its row and opens the row actions. While the table is scrolled sideways, the row grip stays at the table's visible left edge and the column grip scrolls with its column, showing only while its column is in view. - Clicking a grip selects its whole row or column as a cell selection, keeps focus in the editor, and opens the context popup with the table's commands on release, as a block handle does for its block. `Shift`-click extends or reverses the selected row or column range. Clicking a grip within a selected row or column range collapses it to that row or column on release. -- Dragging a grip moves its row or column, or the selected range it belongs to, to the row or column boundary nearest the pointer, shown by a line at that boundary. Nothing lands above the header row, and a drag that would leave the range where it started shows no line and changes nothing. The move is one undoable change, leaves the moved rows or columns selected, and does not open the popup. A selected row range that includes the header row is not dragged as a range. +- Dragging a grip moves its body row or column, or the selected range it belongs to, to the row or column boundary nearest the pointer, shown by a line at that boundary. Nothing lands above the header row, and a drag that would leave the range where it started shows no line and changes nothing. The move is one undoable change, leaves the moved rows or columns selected, and does not open the popup. A selected row range that includes the header row is not dragged as a range. - One insertion button on the table's left border follows the pointer to the nearest row boundary below the header row, and one on its top border to the nearest column boundary in view; both include the table's ends. Hovering a button shows a faint line at its boundary, and clicking it inserts an empty row or column there, as one undoable change, with the caret in the new row's first cell or the new column's header cell. - The controls are overlays: appearing, moving, or hiding moves no text or table geometry, and none of them changes the document until a command runs. Over the table, the table's controls respond; in the gutter, the block handle and block insertion button keep theirs, and a table control straddling the left border keeps the pointer only while the pointer rests on it. A menu or popup covering the table keeps the pointer for itself. - The controls carry accessible names but add no tab stops; the context popup's table commands remain the keyboard route. @@ -730,7 +730,7 @@ For local-path resolution and asset-protocol handling, see [Architecture](./arch - Routine creation, opening, closing, saving, reopening with an encoding, and confirmed external reloads produce no success notification; the document and navigator show the result. Copy feedback, export destinations, bulk-replacement counts, and explicit update-check results retain feedback. - External changes to clean or edited documents and missing files share one persistent notification per window, alongside the blocking decisions described in [Filesystem Watching](#filesystem-watching). Its Actions menu names each affected document and offers Show, Save as, and, for a changed file, Reload from disk. Actions still target that document after switching tabs, and reload from the menu uses the existing unsaved-changes confirmation. Cancelled or failed actions leave the notice available. - A notice updates in place for new external versions. It disappears when the affected files resolve or close. Dismissal acknowledges the currently reported versions without clearing file state or save protections; the same version does not notify again, but a new version, or a missing file that returns and disappears again, can. -- Persistent notifications use the regular notification stack and its presentation, with no timeout. Session preservation/restoration failures, lost recovery text, incomplete exports, and partial folder-replacement results stay until dismissed. A search result that has become unavailable uses its result-row state without another toast. +- Notification actions appear below the message. Persistent notifications use the regular notification stack without a timeout. Session preservation/restoration failures, lost recovery text, incomplete exports, and partial folder-replacement results stay until dismissed. A search result that has become unavailable uses its result-row state without another toast. - Reset all settings asks before restoring General, Files, Editor, and Appearance across windows. Cancelling or dismissing the confirmation leaves all settings unchanged. Confirming preserves documents and produces no routine success notification. File operations govern how Leafdown writes to disk and resolves conflicts or errors. diff --git a/e2e/desktop/specs/code-collapse.spec.ts b/e2e/desktop/specs/code-collapse.spec.ts index c3ef3d6c..8a504005 100644 --- a/e2e/desktop/specs/code-collapse.spec.ts +++ b/e2e/desktop/specs/code-collapse.spec.ts @@ -36,7 +36,7 @@ const caretLine = () => }); describe("desktop code block collapse", () => { - it("shows eight lines, expands under the arrow keys, and collapses from its chevron", async () => { + it("shows eight lines, expands under the arrow keys, and collapses from the shared toggle", async () => { const { codeCollapse: fixture } = await getDesktopE2ERunContext(); await openRecentPath(fixture.path); await expect(block()).toHaveAttribute("data-leafdown-code-collapse", "collapsed"); @@ -49,7 +49,7 @@ describe("desktop code block collapse", () => { })) as number; expect(Math.round(shownLines)).toBe(8); await expect($("pre .leafdown-code-expand")).toBeDisplayed(); - await expect($("pre .leafdown-code-collapse")).not.toBeDisplayed(); + await expect($("pre .leafdown-code-collapse")).not.toExist(); await browser.execute(() => { const code = document.querySelector( @@ -73,7 +73,7 @@ describe("desktop code block collapse", () => { timeoutMsg: "ArrowDown did not land on the first revealed line.", }); - await click(await centerOf("pre .leafdown-code-collapse")); + await click(await centerOf(control("Expand all code blocks"))); await expect(block()).toHaveAttribute("data-leafdown-code-collapse", "collapsed"); await browser.waitUntil(async () => (await caretLine()) === 8, { diff --git a/e2e/desktop/specs/document-tabs.spec.ts b/e2e/desktop/specs/document-tabs.spec.ts index 10aed878..886635ed 100644 --- a/e2e/desktop/specs/document-tabs.spec.ts +++ b/e2e/desktop/specs/document-tabs.spec.ts @@ -9,6 +9,7 @@ import { countDocumentTabs, dismissToasts, findDocumentTab, + findTreeItem, openRecentPath, } from "../support/ui.js"; @@ -72,11 +73,24 @@ describe("desktop document tabs", () => { await expect(await findDocumentTab(separatorName)).toHaveAttribute("aria-selected", "true"); const tabGeometry = await getTabGeometry(); + const separatorRow = await findTreeItem(separatorName); + const getFilenameGeometry = () => + separatorRow.execute((row) => { + const range = document.createRange(); + range.selectNodeContents(row.querySelector(".truncate")!); + const { x, width } = range.getBoundingClientRect(); + return { x, width }; + }); + const filenameGeometry = await getFilenameGeometry(); await appendToActiveEditor("Separator tab edit"); + await expect(separatorRow).toHaveAttribute("aria-description", "Unsaved changes"); await (await findDocumentTab(calloutsName)).click(); await expect(await findDocumentTab(calloutsName)).toHaveAttribute("aria-selected", "true"); expect(await getTabGeometry()).toEqual(tabGeometry); + await expect(separatorRow).toHaveAttribute("aria-selected", "false"); + await expect(separatorRow).toHaveAttribute("aria-description", "Unsaved changes"); + expect(await getFilenameGeometry()).toEqual(filenameGeometry); await expect($(ACTIVE_EDITOR)).not.toHaveText(expect.stringContaining("Separator tab edit")); await appendToActiveEditor("Callouts tab edit"); diff --git a/e2e/desktop/specs/heading-outline.spec.ts b/e2e/desktop/specs/heading-outline.spec.ts index c8d8188b..46093c8e 100644 --- a/e2e/desktop/specs/heading-outline.spec.ts +++ b/e2e/desktop/specs/heading-outline.spec.ts @@ -296,6 +296,21 @@ describe("desktop heading outline", () => { await rows[3].getAttribute("data-outline-position"), ); expect(await rows[0].getAttribute("aria-current")).toBe("location"); + const marks = await browser.execute( + (selector) => + [...document.querySelectorAll(`${selector} .leafdown-outline-mark`)].map((mark) => { + const { x, width } = mark.getBoundingClientRect(); + return { + center: x + width / 2, + size: Number.parseFloat(getComputedStyle(mark, "::before").width), + }; + }), + OUTLINE, + ); + expect(marks[0].size).toBeGreaterThan(marks[1].size); + expect(marks.every(({ center, size }) => center === marks[0].center && size % 2 === 0)).toBe( + true, + ); await hoverRow(await rows[3].getAttribute("data-outline-position")); await browser.waitUntil(isOutlineOpen, { timeoutMsg: "Hovering did not open the outline." }); diff --git a/e2e/desktop/specs/legacy-encoding.spec.ts b/e2e/desktop/specs/legacy-encoding.spec.ts index 7bb5d393..4091afbb 100644 --- a/e2e/desktop/specs/legacy-encoding.spec.ts +++ b/e2e/desktop/specs/legacy-encoding.spec.ts @@ -25,8 +25,30 @@ describe("desktop legacy encoding", () => { await openRecentPath(legacyEncoding.path); - const errorToast = $('[data-slot="toast"][data-type="error"]'); + const errorToastSelector = '[data-slot="toast"][data-type="error"]'; + const errorToast = $(errorToastSelector); await expect(errorToast).toHaveText(expect.stringContaining("Invalid Markdown file encoding.")); + const layout = await browser.execute((selector) => { + const toast = document.querySelector(selector)!; + const bounds = toast.getBoundingClientRect(); + const description = toast + .querySelector('[data-slot="toast-description"]')! + .getBoundingClientRect(); + const action = toast.querySelector("button[aria-haspopup]")!.getBoundingClientRect(); + const close = toast.querySelector('[data-slot="toast-close"]')!.getBoundingClientRect(); + return { + messageWidthRatio: description.width / bounds.width, + actionBelowMessage: action.top >= description.bottom, + closeAboveAction: close.bottom <= action.top, + actionWithinToast: action.bottom <= bounds.bottom && action.right <= bounds.right, + }; + }, errorToastSelector); + expect(layout.messageWidthRatio).toBeGreaterThan(0.65); + expect(layout).toMatchObject({ + actionBelowMessage: true, + closeAboveAction: true, + actionWithinToast: true, + }); await errorToast.$("button=Reopen with encoding").click(); await (await findMenuItem((text) => text === "Western (Windows-1252, ISO-8859-1)")).click(); diff --git a/e2e/desktop/specs/table-controls.spec.ts b/e2e/desktop/specs/table-controls.spec.ts index 8f8f9140..4136b806 100644 --- a/e2e/desktop/specs/table-controls.spec.ts +++ b/e2e/desktop/specs/table-controls.spec.ts @@ -169,6 +169,17 @@ describe("desktop table controls", () => { ]); const before = await tableRect(); + const popup = $("[data-testid='editor-context-popup']"); + await hover(await cellPoint(0, 0)); + const headerGrip = await waitForControl(ROW_GRIP_SELECTOR); + await dispatchPointerSequence([ + { type: "mousedown", point: headerGrip, buttons: 1 }, + { type: "mouseup", point: headerGrip, buttons: 0 }, + ]); + await expect(popup.$("button=Header row")).toHaveAttribute("aria-pressed", "true"); + await browser.keys(Key.Escape); + await expect(popup).not.toExist(); + await hover(await cellPoint(1, 0)); const rowGrip = await waitForControl(ROW_GRIP_SELECTOR); await waitForControl(COLUMN_GRIP_SELECTOR); @@ -189,7 +200,6 @@ describe("desktop table controls", () => { await expect( $("[data-testid='editor-context-popup'] [aria-label='Delete row']"), ).toBeDisplayed(); - const popup = $("[data-testid='editor-context-popup']"); await expect(popup.$("button=Row 1")).toHaveAttribute("aria-pressed", "true"); await expect(popup.$("[aria-label='Add row below']")).toHaveText(""); const dividerGap = await browser.execute(() => { diff --git a/src/app.css b/src/app.css index d1053d88..2222ce26 100644 --- a/src/app.css +++ b/src/app.css @@ -316,7 +316,8 @@ &[aria-selected="true"]:hover, &[data-active="true"], &[data-active="true"]:hover { - @apply bg-accent font-medium text-foreground; + @apply bg-accent text-foreground; + font-weight: var(--active-item-font-weight, var(--font-weight-medium)); } &[aria-selected="true"]::before, diff --git a/src/components/layout/shell.tsx b/src/components/layout/shell.tsx index 381c081d..8892dc55 100644 --- a/src/components/layout/shell.tsx +++ b/src/components/layout/shell.tsx @@ -104,6 +104,7 @@ export function Shell() { const commands = useAppCommands(); const sessionMode = useSessionStore(getSessionMode); const activeDocument = useSessionStore((state) => state.activeDocument); + const tabs = useSessionStore((state) => state.tabs); const folderContext = useSessionStore((state) => state.folderContext); const folderContextLoadPath = useSessionStore((state) => state.folderContextLoad?.path ?? null); const sidebarVisible = useSettingsStore((state) => state.sidebarVisible); @@ -112,6 +113,9 @@ export function Shell() { const folderSearchOpen = useFolderSearchStore((state) => state.open); const statusBarVisible = useSettingsStore((state) => state.statusBarVisible); const activeArticlePath = activeDocument?.status === "saved" ? activeDocument.path : null; + const unsavedArticlePaths = tabs.flatMap(({ document }) => + document.status === "saved" && document.isDirty ? [document.path] : [], + ); const sidebarAvailable = commands.commandState("view.toggleSidebar").enabled; const sidebarShown = sidebarAvailable && sidebarVisible; const articleNavigatorShown = Boolean(folderContext || folderContextLoadPath) && sidebarVisible; @@ -250,6 +254,7 @@ export function Shell() { onKeepArticle={handleKeepArticle} onOpenArticle={handleOpenArticle} showAllFiles={showAllFiles} + unsavedArticlePaths={unsavedArticlePaths} /> )} diff --git a/src/components/ui/toast.tsx b/src/components/ui/toast.tsx index 3e9f9706..94f33b04 100644 --- a/src/components/ui/toast.tsx +++ b/src/components/ui/toast.tsx @@ -29,6 +29,8 @@ import { } from "@/lib/toast"; import { cn } from "@/lib/utils"; +const TOAST_ACTION_CLASS_NAME = "mt-2 h-auto min-h-8 max-w-full self-start py-1 whitespace-normal"; + function ToastProvider({ ...props }: ToastPrimitive.Provider.Props) { return ; } @@ -87,7 +89,7 @@ function ToastContent({ className, ...props }: ToastPrimitive.Content.Props) { ); @@ -144,7 +146,7 @@ function ToastClose({ aria-label={t("ui.toast.close")} render={render} className={cn( - "relative shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground", + "relative -mt-1.5 -mr-1.5 shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground", className, )} {...props} @@ -184,7 +186,7 @@ function ToastIcon({ type }: { type: string | undefined }) { return ( {icon} @@ -200,7 +202,9 @@ function ToastActionMenu({ menu }: ToastActionMenuProps) { return ( - }> + } + > {menu.label} @@ -211,7 +215,7 @@ function ToastActionMenu({ menu }: ToastActionMenuProps) { {item.label} @@ -223,7 +227,11 @@ function ToastActionMenu({ menu }: ToastActionMenuProps) { onValueChange={(index: string) => menu.items[Number(index)]?.run()} > {menu.items.map((item, index) => ( - + {item.label} ))} @@ -242,15 +250,15 @@ function ToastList() { -
+
+ {toastItem.data?.actionMenu ? ( + + ) : ( + + )}
- {toastItem.data?.actionMenu ? ( - - ) : ( - - )} diff --git a/src/features/editor/components/heading-outline.css b/src/features/editor/components/heading-outline.css index 5705398e..d9f9e903 100644 --- a/src/features/editor/components/heading-outline.css +++ b/src/features/editor/components/heading-outline.css @@ -177,7 +177,7 @@ } [data-level="1"] > &::before { - @apply size-[7px]; + @apply size-2; } [data-level="2"] > &::before { @@ -187,7 +187,7 @@ [data-level="4"] > &::before, [data-level="5"] > &::before, [data-level="6"] > &::before { - @apply size-[3px]; + @apply bg-muted-foreground/30; } [data-preview] > &::before { diff --git a/src/features/editor/components/milkdown-editor.css b/src/features/editor/components/milkdown-editor.css index 353c4c44..f20975f3 100644 --- a/src/features/editor/components/milkdown-editor.css +++ b/src/features/editor/components/milkdown-editor.css @@ -703,14 +703,6 @@ @apply inline-block size-1.5 rotate-45 border-r-[1.5px] border-b-[1.5px] border-current; } - .leafdown-code-collapse { - @apply flex size-6 cursor-pointer items-center justify-center rounded-sm text-muted-foreground select-none hover:bg-foreground/8 hover:text-foreground; - - .leafdown-code-chevron { - @apply mt-0.5 -rotate-135; - } - } - /* Collapsed lines stay in the document and its text, hidden only from view. */ .leafdown-code-collapsed-lines { @apply hidden; @@ -738,7 +730,7 @@ [data-math-code-rendered="true"]:not(.leafdown-code-block--active), [data-mermaid-mode="diagram"] ) - :is(.leafdown-code-collapse, .leafdown-code-expand, .leafdown-code-controls) { + :is(.leafdown-code-expand, .leafdown-code-controls) { @apply hidden; } @@ -1456,6 +1448,10 @@ &[data-axis="row"] { @apply h-8 w-3.5; + &[data-fixed] { + @apply cursor-pointer active:cursor-pointer; + } + &::before { @apply h-full w-1.5; } diff --git a/src/features/editor/plugins/codeBlockCollapse.test.ts b/src/features/editor/plugins/codeBlockCollapse.test.ts index cfeff2ba..5eb159af 100644 --- a/src/features/editor/plugins/codeBlockCollapse.test.ts +++ b/src/features/editor/plugins/codeBlockCollapse.test.ts @@ -31,8 +31,8 @@ const preOf = (mounted: MountedMilkdownEditor) => mounted.view.dom.querySelector const expandButtonOf = (mounted: MountedMilkdownEditor) => preOf(mounted).querySelector(".leafdown-code-expand")!; -const collapseButtonOf = (mounted: MountedMilkdownEditor) => - preOf(mounted).querySelector(".leafdown-code-collapse")!; +const expandAllButtonOf = (mounted: MountedMilkdownEditor) => + preOf(mounted).querySelector('[aria-label="Expand all code blocks"]')!; const hiddenText = (mounted: MountedMilkdownEditor) => [...preOf(mounted).querySelectorAll(".leafdown-code-collapsed-lines")] @@ -62,7 +62,6 @@ describe("code block collapse", () => { expect(expandButtonOf(mounted)).toHaveTextContent("Show 4 more lines"); expect(expandButtonOf(mounted)).toHaveAttribute("aria-expanded", "false"); expect(expandButtonOf(mounted).tabIndex).toBe(-1); - expect(collapseButtonOf(mounted).hidden).toBe(true); expect(preOf(mounted).querySelector("code")).toHaveTextContent("row 12"); }); @@ -72,7 +71,7 @@ describe("code block collapse", () => { expect(collapseOf(short)).toBeNull(); expect(hiddenText(short)).toBe(""); expect(expandButtonOf(short).hidden).toBe(true); - expect(collapseButtonOf(short).hidden).toBe(true); + expect(expandAllButtonOf(short).hidden).toBe(true); const long = await mountEditor(withCode(10)); @@ -92,11 +91,9 @@ describe("code block collapse", () => { expect(collapseOf(mounted)).toBe("expanded"); expect(hiddenText(mounted)).toBe(""); expect(expandButtonOf(mounted).hidden).toBe(true); - expect(collapseButtonOf(mounted).hidden).toBe(false); - expect(collapseButtonOf(mounted)).toHaveAccessibleName("Collapse code block"); - expect(collapseButtonOf(mounted)).toHaveAttribute("aria-expanded", "true"); + expect(preOf(mounted).querySelector(".leafdown-code-collapse")).toBeNull(); - expect(press(collapseButtonOf(mounted)).defaultPrevented).toBe(true); + expect(press(expandAllButtonOf(mounted)).defaultPrevented).toBe(true); expect(collapseOf(mounted)).toBe("collapsed"); expect(mounted.view.state.selection.from).toBe(caret); @@ -187,7 +184,7 @@ describe("code block collapse", () => { const mounted = await mountEditor(withCode(12)); setTextSelection(mounted.view, rowPosition(mounted, 11, 2)); - press(collapseButtonOf(mounted)); + press(expandAllButtonOf(mounted)); expect(collapseOf(mounted)).toBe("collapsed"); expect(mounted.view.state.selection.empty).toBe(true); diff --git a/src/features/editor/plugins/codeBlockCollapse.ts b/src/features/editor/plugins/codeBlockCollapse.ts index cc328f73..11c5b8b3 100644 --- a/src/features/editor/plugins/codeBlockCollapse.ts +++ b/src/features/editor/plugins/codeBlockCollapse.ts @@ -259,7 +259,7 @@ const collapseCodeBlocks = (view: EditorView, blocks: readonly number[], scroll: view.dispatch(transaction); }; -export const collapseCodeBlock = (view: EditorView, position: number) => { +const collapseCodeBlock = (view: EditorView, position: number) => { const { state } = view; const node = state.doc.nodeAt(position); if (!node || !isCollapsibleCodeBlock(node) || getCollapsedCodeBlocks(state).includes(position)) { diff --git a/src/features/editor/plugins/codeBlockView.ts b/src/features/editor/plugins/codeBlockView.ts index b12b7d5c..6eefdc3f 100644 --- a/src/features/editor/plugins/codeBlockView.ts +++ b/src/features/editor/plugins/codeBlockView.ts @@ -13,7 +13,6 @@ import { readCodeFenced } from "../utils/codeMarkdown"; import { describeMathError, renderMathTex } from "../utils/mathRender"; import { collapseAllCodeBlocks, - collapseCodeBlock, countCollapsedCodeLines, expandAllCodeBlocks, expandCodeBlock, @@ -95,7 +94,6 @@ class LeafdownCodeBlockNodeView implements NodeView { readonly dom = document.createElement("pre"); readonly contentDOM = document.createElement("code"); private readonly badge = document.createElement("button"); - private readonly collapseButton = document.createElement("button"); private readonly expandButton = document.createElement("button"); private readonly expandLabel = document.createElement("span"); private readonly header = document.createElement("span"); @@ -144,13 +142,11 @@ class LeafdownCodeBlockNodeView implements NodeView { this.badge.dataset.leafdownCodeLanguage = ""; this.badge.addEventListener("mousedown", this.handleChromeMouseDown); this.badge.addEventListener("click", this.handleBadgeClick); - // Like the badge, the collapse controls cost no tab stop; `Fold or unfold section` reaches them. - for (const button of [this.collapseButton, this.expandButton]) { - button.type = "button"; - button.contentEditable = "false"; - button.tabIndex = -1; - button.addEventListener("mousedown", this.handleChromeMouseDown); - } + // Like the badge, the expand bar costs no tab stop; `Fold or unfold section` reaches it. + this.expandButton.type = "button"; + this.expandButton.contentEditable = "false"; + this.expandButton.tabIndex = -1; + this.expandButton.addEventListener("mousedown", this.handleChromeMouseDown); // The controls that act on every code block cost no tab stop either; Preferences holds both // settings, and `Fold or unfold section` expands a block from its caret. this.controls.className = "leafdown-code-controls"; @@ -168,10 +164,6 @@ class LeafdownCodeBlockNodeView implements NodeView { this.controls.append(button); } this.controlsChange = onCodeBlockControlsChange(view, () => this.renderControls()); - this.collapseButton.className = "leafdown-code-collapse"; - this.collapseButton.setAttribute("aria-expanded", "true"); - this.collapseButton.append(createChevron()); - this.collapseButton.addEventListener("click", this.handleCollapseClick); this.expandButton.className = "leafdown-code-expand"; this.expandButton.setAttribute("aria-expanded", "false"); this.expandButton.append(createChevron(), this.expandLabel); @@ -198,7 +190,7 @@ class LeafdownCodeBlockNodeView implements NodeView { ); this.header.className = "leafdown-code-header"; this.header.contentEditable = "false"; - this.header.append(this.controls, this.collapseButton, this.badge); + this.header.append(this.controls, this.badge); this.dom.append( this.header, this.contentDOM, @@ -264,8 +256,6 @@ class LeafdownCodeBlockNodeView implements NodeView { this.localizationChange.dispose(); this.badge.removeEventListener("mousedown", this.handleChromeMouseDown); this.badge.removeEventListener("click", this.handleBadgeClick); - this.collapseButton.removeEventListener("mousedown", this.handleChromeMouseDown); - this.collapseButton.removeEventListener("click", this.handleCollapseClick); this.expandButton.removeEventListener("mousedown", this.handleChromeMouseDown); this.expandButton.removeEventListener("click", this.handleExpandClick); this.controlsChange(); @@ -311,9 +301,7 @@ class LeafdownCodeBlockNodeView implements NodeView { this.mathPreview.textContent = describeMathError(this.mathError); } - this.collapseButton.hidden = this.collapse !== "expanded"; this.expandButton.hidden = this.collapse !== "collapsed"; - this.collapseButton.setAttribute("aria-label", t("editor.codeBlock.collapse")); if (this.collapse === "collapsed") { this.expandLabel.textContent = t("editor.codeBlock.expand", { count: countCollapsedCodeLines(this.node), @@ -508,11 +496,6 @@ ${source}`; event.preventDefault(); }; - private readonly handleCollapseClick = () => { - const position = this.getPos(); - if (position !== undefined) collapseCodeBlock(this.view, position); - }; - private readonly handleExpandClick = () => { const position = this.getPos(); if (position !== undefined) expandCodeBlock(this.view, position); diff --git a/src/features/editor/plugins/controlTooltip.test.ts b/src/features/editor/plugins/controlTooltip.test.ts index 1466bf2f..de40bab7 100644 --- a/src/features/editor/plugins/controlTooltip.test.ts +++ b/src/features/editor/plugins/controlTooltip.test.ts @@ -164,7 +164,6 @@ describe("editor control tooltips", () => { "[data-leafdown-table-insert]", "[data-leafdown-callout-type]", ".leafdown-callout-toggle", - ".leafdown-code-collapse", "[data-leafdown-block-insert]", ".leafdown-fold-indicator", ].join(", "), @@ -172,7 +171,7 @@ describe("editor control tooltips", () => { ]; useTooltipTime(); - expect(controls.length).toBeGreaterThanOrEqual(9); + expect(controls.length).toBeGreaterThanOrEqual(8); for (const control of controls) { expect(control.getAttribute("aria-label")).toBeTruthy(); diff --git a/src/features/editor/plugins/tableControls.test.ts b/src/features/editor/plugins/tableControls.test.ts index 9cc76f4e..318010ba 100644 --- a/src/features/editor/plugins/tableControls.test.ts +++ b/src/features/editor/plugins/tableControls.test.ts @@ -141,7 +141,8 @@ describe("table controls", () => { expect(indicator).toHaveAttribute("hidden"); hover(cellCenter(0, 0)); - expect(rowGrip).toHaveAttribute("hidden"); + expect(rowGrip).not.toHaveAttribute("hidden"); + expect(rowGrip.style.top).toBe(`${String(cellCenter(0, 0).clientY)}px`); expect(columnGrip.style.left).toBe(`${String(cellCenter(0, 0).clientX)}px`); expect(rowInsert.style.top).toBe(`${String(rowBoundaryY(1))}px`); @@ -252,6 +253,33 @@ describe("table controls", () => { expect(mounted.getMarkdown()).toBe(original); }); + it("selects the header with its grip and keeps a range containing it anchored", async () => { + const mounted = await mountEditor(THREE_BODY_ROWS); + layOutTable(mounted); + const { rowGrip, indicator } = getControls(); + const before = mounted.getMarkdown(); + + hover(cellCenter(0, 0)); + dispatchMouseEvent(rowGrip, "mousedown", { button: 0, buttons: 1 }); + dispatchMouseEvent(rowGrip, "mouseup", { button: 0 }); + expect(selectedRect(mounted.view.state)).toMatchObject({ top: 0, bottom: 1 }); + + hover(cellCenter(1, 0)); + dispatchMouseEvent(rowGrip, "mousedown", { button: 0, buttons: 1, shiftKey: true }); + dispatchMouseEvent(rowGrip, "mouseup", { button: 0 }); + expect(selectedRect(mounted.view.state)).toMatchObject({ top: 0, bottom: 2 }); + + dragGrip( + rowGrip, + { clientX: TABLE_LEFT, clientY: cellCenter(1, 0).clientY }, + { clientX: TABLE_LEFT, clientY: rowBoundaryY(4) }, + ); + expect(indicator).toHaveAttribute("hidden"); + dispatchMouseEvent(document.body, "mouseup", { button: 0 }); + expect(selectedRect(mounted.view.state)).toMatchObject({ top: 0, bottom: 2 }); + expect(mounted.getMarkdown()).toBe(before); + }); + it("lands nothing above the header row and changes nothing for a drop where the drag started", async () => { const mounted = await mountEditor(THREE_BODY_ROWS); layOutTable(mounted); diff --git a/src/features/editor/plugins/tableControls.ts b/src/features/editor/plugins/tableControls.ts index ff15347c..34264797 100644 --- a/src/features/editor/plugins/tableControls.ts +++ b/src/features/editor/plugins/tableControls.ts @@ -439,17 +439,18 @@ class TableControlsView { ] as const) { const range = tablePos === null ? null : getSelectedTableAxis(this.view.state, tablePos, axis); - grip.toggleAttribute( - "data-selected", - range !== null && index >= range.from && index < range.to, - ); + const isSelected = range !== null && index >= range.from && index < range.to; + grip.toggleAttribute("data-selected", isSelected); + if (axis === "row") { + grip.toggleAttribute("data-fixed", index === 0 || (isSelected && range.from === 0)); + } } this.place( this.rowGrip, geometry.rowControlsX, row ? row.top + row.height / 2 : NaN, - hovered.row >= 1 && row !== undefined, + row !== undefined, ); this.place( this.columnGrip, @@ -595,22 +596,15 @@ class TableControlsView { const axis: TableAxis = event.currentTarget === this.rowGrip ? "row" : "column"; const index = axis === "row" ? hovered.row : hovered.col; - // The header row never moves, so a row range reaching it is not one a grip carries. - const first = axis === "row" ? 1 : 0; const selected = getSelectedTableAxis(this.view.state, tablePos, axis); let anchor = index; let range: TableAxisRange = { from: index, to: index + 1 }; let collapseTo: number | null = null; - if (event.shiftKey && selected && selected.anchor >= first) { + if (event.shiftKey && selected) { anchor = selected.anchor; range = { from: Math.min(anchor, index), to: Math.max(anchor, index) + 1 }; - } else if ( - selected && - selected.from >= first && - selected.from <= index && - index < selected.to - ) { + } else if (selected && selected.from <= index && index < selected.to) { range = selected; collapseTo = index; } diff --git a/src/features/folder-context/components/article-navigator.test.tsx b/src/features/folder-context/components/article-navigator.test.tsx index 2ba845d6..ae02ba72 100644 --- a/src/features/folder-context/components/article-navigator.test.tsx +++ b/src/features/folder-context/components/article-navigator.test.tsx @@ -241,12 +241,13 @@ describe("article-navigator", () => { expect(emptyDirectory).not.toHaveAttribute("aria-disabled"); }); - it("marks the open document as the selected row", () => { + it("marks the active article and describes unsaved changes independently of selection", () => { render( , ); @@ -260,6 +261,10 @@ describe("article-navigator", () => { ["docs", "false"], ["empty", "false"], ]); + expect(screen.getByRole("treeitem", { name: "draft.markdown" })).toHaveAccessibleDescription( + "Unsaved changes", + ); + expect(screen.getByRole("treeitem", { name: "readme.md" })).not.toHaveAccessibleDescription(); expect(screen.queryByRole("treeitem", { current: "page" })).not.toBeInTheDocument(); }); diff --git a/src/features/folder-context/components/article-navigator.tsx b/src/features/folder-context/components/article-navigator.tsx index c306ccfc..dc242330 100644 --- a/src/features/folder-context/components/article-navigator.tsx +++ b/src/features/folder-context/components/article-navigator.tsx @@ -125,6 +125,7 @@ interface ArticleNavigatorProps { onOpenArticle: (path: string) => void; /** Lists the files Leafdown cannot open, and the directories holding only them, as well. */ showAllFiles?: boolean; + unsavedArticlePaths?: readonly string[]; } type ArticleNavigatorMenuTarget = @@ -145,6 +146,7 @@ export function ArticleNavigator({ onKeepArticle, onOpenArticle, showAllFiles = false, + unsavedArticlePaths, }: ArticleNavigatorProps) { const { t } = useLocalization(); const expandedDirectoryPaths = useArticleNavigatorStore((state) => state.expandedDirectoryPaths); @@ -184,6 +186,7 @@ export function ArticleNavigator({ draft: edit?.kind === "create" ? edit : null, expandedDirectoryPaths: expandedPaths, tree: filteredTree, + unsavedArticlePaths, }); const hasRows = rows.length > 0; const menuTargetLabelKind = menuTarget.kind === "unsupportedFile" ? "file" : menuTarget.kind; @@ -898,7 +901,11 @@ function ArticleNavigatorTreeItem({ whenCutShort={!isUnsupportedFile} render={ {nameEditor ?? {row.name}} + {row.kind === "file" && nameEditor === null && ( + + {row.isDirty && } + + )} ); } diff --git a/src/features/folder-context/utils/articleNavigatorRows.test.ts b/src/features/folder-context/utils/articleNavigatorRows.test.ts index 844eddcc..f2dec8a3 100644 --- a/src/features/folder-context/utils/articleNavigatorRows.test.ts +++ b/src/features/folder-context/utils/articleNavigatorRows.test.ts @@ -45,6 +45,7 @@ describe("article navigator rows", () => { activeArticlePath: "c:\\notes\\docs\\guide.md", expandedDirectoryPaths: ["c:\\notes\\docs\\"], tree: articleTree, + unsavedArticlePaths: ["c:\\notes\\readme.md"], }), ).toEqual([ { @@ -62,6 +63,7 @@ describe("article navigator rows", () => { kind: "file", depth: 1, isActive: true, + isDirty: false, name: "guide.md", parentIndex: 0, path: "C:/Notes/docs/guide.md", @@ -83,6 +85,7 @@ describe("article navigator rows", () => { kind: "file", depth: 0, isActive: false, + isDirty: true, name: "readme.md", parentIndex: null, path: "C:/Notes/readme.md", diff --git a/src/features/folder-context/utils/articleNavigatorRows.ts b/src/features/folder-context/utils/articleNavigatorRows.ts index 3c1226a7..faf7f176 100644 --- a/src/features/folder-context/utils/articleNavigatorRows.ts +++ b/src/features/folder-context/utils/articleNavigatorRows.ts @@ -21,6 +21,7 @@ export interface ArticleNavigatorDirectoryRow extends ArticleNavigatorRowBase { export interface ArticleNavigatorFileRow extends ArticleNavigatorRowBase { kind: "file"; isActive: boolean; + isDirty: boolean; } export interface ArticleNavigatorUnsupportedFileRow extends ArticleNavigatorRowBase { @@ -51,6 +52,7 @@ interface BuildArticleNavigatorRowsOptions { draft?: ArticleNavigatorDraft | null; expandedDirectoryPaths: string[]; tree: ArticleTree; + unsavedArticlePaths?: readonly string[]; } interface ArticleNavigatorDraftNode { @@ -70,9 +72,11 @@ export const buildArticleNavigatorRows = ({ draft = null, expandedDirectoryPaths, tree, + unsavedArticlePaths, }: BuildArticleNavigatorRowsOptions): ArticleNavigatorRow[] => { const expandedDirectoryPathSet = new PathSet(expandedDirectoryPaths); const activeArticlePaths = new PathSet(activeArticlePath ? [activeArticlePath] : []); + const unsavedPaths = new PathSet(unsavedArticlePaths); const roots: ArticleNavigatorNode[] = tree.children; const entries = flattenTree({ getChildren: (node) => getNavigatorNodeChildren(node, draft), @@ -92,7 +96,12 @@ export const buildArticleNavigatorRows = ({ case "draft": return { ...base, kind: "draft", entryKind: node.entryKind }; case "file": - return { ...base, kind: "file", isActive: activeArticlePaths.has(node.path) }; + return { + ...base, + kind: "file", + isActive: activeArticlePaths.has(node.path), + isDirty: unsavedPaths.has(node.path), + }; case "unsupportedFile": return { ...base, kind: "unsupportedFile" }; case "directory": diff --git a/src/locales/en.json b/src/locales/en.json index c9d0a8a8..f09efbdb 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -612,6 +612,7 @@ "articleNavigator.detachedDocument": "Current document is outside this folder context.", "articleNavigator.scanWarnings": "Some folder entries could not be scanned. {count, plural, one {# issue found.} other {# issues found.}}", "articleNavigator.tree.label": "Articles", + "articleNavigator.unsavedChanges": "Unsaved changes", "articleNavigator.draftRow.label": "{entryKind, select, file {New file} other {New folder}}", "articleNavigator.unsupportedFile.description": "Leafdown can only open Markdown files.", "articleNavigator.nameEditor.label": "{entryKind, select, file {File name} other {Folder name}}", @@ -738,7 +739,6 @@ "editor.codeBlock.badge.label": "Code block language: {language}", "editor.codeBlock.badge.emptyLabel": "Set code block language", "editor.codeBlock.expand": "{count, plural, one {Show # more line} other {Show # more lines}}", - "editor.codeBlock.collapse": "Collapse code block", "editor.codeBlock.expandAll": "Expand all code blocks", "editor.codeBlock.softWrap": "Soft wrap for code blocks", "editor.codeBlock.lineNumbers": "Display line numbers for code blocks", From 2848300d2e2e0e5832e4cd1f277543edbee3e5fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 08:24:25 -0300 Subject: [PATCH 02/15] Move the desktop gutter test pointer to the status bar --- e2e/desktop/specs/block-selection.spec.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index be6989f1..e5b19029 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -667,7 +667,17 @@ describe("desktop block selection", () => { await expect($('[data-slot="toast"][data-type="success"]')).not.toExist(); await dismissToasts(); - await browser.action("pointer").move({ origin: "viewport", x: 1, y: 1 }).perform(); + const nestedItem = await getGeometryForText("Nested second"); + await moveToBlock(nestedItem.pos); + await browser.waitUntil( + async () => (await findGeometryForText("Nested second"))?.handleOpacity === "1", + { timeoutMsg: "Hovering the nested item did not reveal its block handle." }, + ); + await $('[data-testid="status-bar"]').moveTo(); + await browser.waitUntil( + async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), + { timeoutMsg: "A block handle stayed visible after moving the pointer to the status bar." }, + ); const wideGeometry = await handleGeometry(); expect(wideGeometry.length).toBeGreaterThanOrEqual(9); @@ -698,10 +708,6 @@ describe("desktop block selection", () => { expect(wideGeometry.every(({ label, tabIndex }) => Boolean(label) && tabIndex === -1)).toBe( true, ); - await browser.waitUntil(async () => - (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), - ); - const listItemLefts = new Set( wideGeometry.filter(({ blockTag }) => blockTag === "LI").map(({ blockLeft }) => blockLeft), ); From 1fbf3853c4c51f26fd518fe5517a3cebe384e86c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 08:35:42 -0300 Subject: [PATCH 03/15] Clear block gutter hover on pointer movement outside the editor --- e2e/desktop/specs/block-selection.spec.ts | 9 ++- .../plugins/blockSelectionInteraction.test.ts | 4 +- .../plugins/blockSelectionInteraction.ts | 55 +++++++++---------- 3 files changed, 35 insertions(+), 33 deletions(-) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index e5b19029..5b8706f0 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -673,7 +673,14 @@ describe("desktop block selection", () => { async () => (await findGeometryForText("Nested second"))?.handleOpacity === "1", { timeoutMsg: "Hovering the nested item did not reveal its block handle." }, ); - await $('[data-testid="status-bar"]').moveTo(); + const statusBar = $('[data-testid="status-bar"]'); + await statusBar.moveTo(); + await browser.waitUntil( + async () => (await statusBar.execute((bar) => bar.matches(":hover"))) === true, + { + timeoutMsg: "The pointer did not enter the status bar.", + }, + ); await browser.waitUntil( async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), { timeoutMsg: "A block handle stayed visible after moving the pointer to the status bar." }, diff --git a/src/features/editor/plugins/blockSelectionInteraction.test.ts b/src/features/editor/plugins/blockSelectionInteraction.test.ts index 0a87ff1e..64486725 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.test.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.test.ts @@ -563,14 +563,14 @@ describe("block selection interaction", () => { expect(getHandle(paragraphs[0].pos).parentElement).not.toHaveAttribute("data-hovered"); expect(getHandle(paragraphs[1].pos).parentElement).toHaveAttribute("data-hovered"); - dispatchMouseEvent(mounted.view.dom, "mouseleave"); + dispatchMouseEvent(document.body, "mousemove"); expect(document.querySelector(".leafdown-block-gutter[data-hovered]")).toBeNull(); const firstHandle = getHandle(paragraphs[0].pos); dispatchMouseEvent(firstHandle, "mouseover"); expect(firstHandle.parentElement).toHaveAttribute("data-handle-hovered"); - dispatchMouseEvent(firstHandle, "mouseout", { relatedTarget: document.body }); + dispatchMouseEvent(document.body, "mouseover"); expect(firstHandle.parentElement).not.toHaveAttribute("data-handle-hovered"); }); diff --git a/src/features/editor/plugins/blockSelectionInteraction.ts b/src/features/editor/plugins/blockSelectionInteraction.ts index 5fb7ab86..90e5a326 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.ts @@ -191,6 +191,7 @@ class BlockSelectionView { >(); private animationFrame: number | null = null; private hoveredPos: number | null = null; + private hoveredHandleGutter: HTMLDivElement | null = null; private pendingCollapsePos: number | null = null; private pressedHandle: { x: number; y: number } | null = null; private resizeObserver: ResizeObserver | null = null; @@ -241,22 +242,22 @@ class BlockSelectionView { getOverlayOwner(view).append(this.overlay, this.status); this.overlay.addEventListener("mousedown", this.handleMouseDown); this.overlay.addEventListener("mouseup", this.handleMouseUp); - this.overlay.addEventListener("mouseover", this.handleHandleMouseOver); - this.overlay.addEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.addEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.addEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.addEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.addEventListener("click", this.openInsertionMenu); doc.addEventListener("mousemove", this.handleDragMove); + doc.addEventListener("mousemove", this.handleHoverPointer, true); + doc.addEventListener("mouseover", this.handleHoverPointer, true); doc.addEventListener("mousemove", this.handleInsertionPointer); doc.addEventListener("mouseover", this.handleInsertionPointer); doc.addEventListener("mouseup", this.handleDocumentMouseUp); doc.addEventListener("mouseleave", this.cancelPendingDrag); + doc.addEventListener("mouseleave", this.clearHover); doc.addEventListener("mouseleave", this.handleInsertionLeave); doc.defaultView?.addEventListener("blur", this.cancelPendingDrag); + doc.defaultView?.addEventListener("blur", this.clearHover); doc.defaultView?.addEventListener("blur", this.handleInsertionLeave); - view.dom.addEventListener("mousemove", this.handleEditorMouseMove); - view.dom.addEventListener("mouseleave", this.handleEditorMouseLeave); view.root.addEventListener("scroll", this.schedulePosition, true); view.dom.ownerDocument.defaultView?.addEventListener("resize", this.schedulePosition); @@ -289,22 +290,22 @@ class BlockSelectionView { this.localizationChange.dispose(); this.overlay.removeEventListener("mousedown", this.handleMouseDown); this.overlay.removeEventListener("mouseup", this.handleMouseUp); - this.overlay.removeEventListener("mouseover", this.handleHandleMouseOver); - this.overlay.removeEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.removeEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.removeEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.removeEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.removeEventListener("click", this.openInsertionMenu); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleDragMove); + this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleHoverPointer, true); + this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleHoverPointer, true); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseup", this.handleDocumentMouseUp); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.cancelPendingDrag); + this.view.dom.ownerDocument.removeEventListener("mouseleave", this.clearHover); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.handleInsertionLeave); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.cancelPendingDrag); + this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.clearHover); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.handleInsertionLeave); - this.view.dom.removeEventListener("mousemove", this.handleEditorMouseMove); - this.view.dom.removeEventListener("mouseleave", this.handleEditorMouseLeave); this.view.root.removeEventListener("scroll", this.schedulePosition, true); this.view.dom.ownerDocument.defaultView?.removeEventListener("resize", this.schedulePosition); this.resizeObserver?.disconnect(); @@ -818,33 +819,27 @@ class BlockSelectionView { return null; } - private readonly handleEditorMouseMove = (event: MouseEvent) => { - this.setHoveredPosition(this.getBlockAt(event.target)?.pos ?? null); - }; + private setHoveredHandleGutter(gutter: HTMLDivElement | null) { + if (gutter === this.hoveredHandleGutter) return; + this.hoveredHandleGutter?.removeAttribute("data-handle-hovered"); + this.hoveredHandleGutter = gutter; + gutter?.setAttribute("data-handle-hovered", ""); + } - private readonly handleEditorMouseLeave = () => { - this.setHoveredPosition(null); - }; + private readonly handleHoverPointer = (event: MouseEvent) => { + const target = event.target; + if (!(target instanceof Element)) return this.clearHover(); - private readonly handleHandleMouseOver = (event: MouseEvent) => { - const handle = getHandle(event); + const block = this.view.dom.contains(target) ? this.getBlockAt(target) : null; + this.setHoveredPosition(block?.pos ?? null); + const handle = this.overlay.contains(target) ? getHandle(event) : null; const pos = handle ? readHandlePosition(handle) : null; - - if (pos !== null) { - this.gutters.get(pos)?.setAttribute("data-handle-hovered", ""); - } + this.setHoveredHandleGutter(pos === null ? null : (this.gutters.get(pos) ?? null)); }; - private readonly handleHandleMouseOut = (event: MouseEvent) => { - const handle = getHandle(event); - const pos = handle ? readHandlePosition(handle) : null; - - if ( - pos !== null && - !(event.relatedTarget instanceof Node && handle?.contains(event.relatedTarget)) - ) { - this.gutters.get(pos)?.removeAttribute("data-handle-hovered"); - } + private readonly clearHover = () => { + this.setHoveredPosition(null); + this.setHoveredHandleGutter(null); }; private updateSelectionPresentation() { From f763354711befdb97021165189d54f74bd419656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 08:45:56 -0300 Subject: [PATCH 04/15] Target the active document tab in the desktop gutter test --- e2e/desktop/specs/block-selection.spec.ts | 28 +++++++--- .../plugins/blockSelectionInteraction.test.ts | 4 +- .../plugins/blockSelectionInteraction.ts | 55 ++++++++++--------- 3 files changed, 52 insertions(+), 35 deletions(-) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index 5b8706f0..a6304565 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -661,9 +661,8 @@ describe("desktop block selection", () => { await closeAllDocuments(); await openRecentPath(blocks.path); await expect($("[data-testid=active-document-host] .ProseMirror")).toBeDisplayed(); - await expect($('[data-testid="document-tab"][data-active]')).toHaveText( - path.basename(blocks.path), - ); + const activeTabSelector = '[data-testid="document-tab"][data-active]'; + await expect($(activeTabSelector)).toHaveText(path.basename(blocks.path)); await expect($('[data-slot="toast"][data-type="success"]')).not.toExist(); await dismissToasts(); @@ -673,17 +672,30 @@ describe("desktop block selection", () => { async () => (await findGeometryForText("Nested second"))?.handleOpacity === "1", { timeoutMsg: "Hovering the nested item did not reveal its block handle." }, ); - const statusBar = $('[data-testid="status-bar"]'); - await statusBar.moveTo(); + const tabCenter = await browser.execute((selector) => { + const bounds = document.querySelector(selector)!.getBoundingClientRect(); + return { + x: Math.round(bounds.left + bounds.width / 2), + y: Math.round(bounds.top + bounds.height / 2), + }; + }, activeTabSelector); + await browser + .action("pointer") + .move({ duration: 0, origin: "viewport", ...tabCenter }) + .perform(); await browser.waitUntil( - async () => (await statusBar.execute((bar) => bar.matches(":hover"))) === true, + () => + browser.execute( + (selector) => document.querySelector(selector)?.matches(":hover") ?? false, + activeTabSelector, + ), { - timeoutMsg: "The pointer did not enter the status bar.", + timeoutMsg: "The pointer did not enter the active document tab.", }, ); await browser.waitUntil( async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), - { timeoutMsg: "A block handle stayed visible after moving the pointer to the status bar." }, + { timeoutMsg: "A block handle stayed visible after moving the pointer to the document tab." }, ); const wideGeometry = await handleGeometry(); diff --git a/src/features/editor/plugins/blockSelectionInteraction.test.ts b/src/features/editor/plugins/blockSelectionInteraction.test.ts index 64486725..0a87ff1e 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.test.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.test.ts @@ -563,14 +563,14 @@ describe("block selection interaction", () => { expect(getHandle(paragraphs[0].pos).parentElement).not.toHaveAttribute("data-hovered"); expect(getHandle(paragraphs[1].pos).parentElement).toHaveAttribute("data-hovered"); - dispatchMouseEvent(document.body, "mousemove"); + dispatchMouseEvent(mounted.view.dom, "mouseleave"); expect(document.querySelector(".leafdown-block-gutter[data-hovered]")).toBeNull(); const firstHandle = getHandle(paragraphs[0].pos); dispatchMouseEvent(firstHandle, "mouseover"); expect(firstHandle.parentElement).toHaveAttribute("data-handle-hovered"); - dispatchMouseEvent(document.body, "mouseover"); + dispatchMouseEvent(firstHandle, "mouseout", { relatedTarget: document.body }); expect(firstHandle.parentElement).not.toHaveAttribute("data-handle-hovered"); }); diff --git a/src/features/editor/plugins/blockSelectionInteraction.ts b/src/features/editor/plugins/blockSelectionInteraction.ts index 90e5a326..5fb7ab86 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.ts @@ -191,7 +191,6 @@ class BlockSelectionView { >(); private animationFrame: number | null = null; private hoveredPos: number | null = null; - private hoveredHandleGutter: HTMLDivElement | null = null; private pendingCollapsePos: number | null = null; private pressedHandle: { x: number; y: number } | null = null; private resizeObserver: ResizeObserver | null = null; @@ -242,22 +241,22 @@ class BlockSelectionView { getOverlayOwner(view).append(this.overlay, this.status); this.overlay.addEventListener("mousedown", this.handleMouseDown); this.overlay.addEventListener("mouseup", this.handleMouseUp); + this.overlay.addEventListener("mouseover", this.handleHandleMouseOver); + this.overlay.addEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.addEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.addEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.addEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.addEventListener("click", this.openInsertionMenu); doc.addEventListener("mousemove", this.handleDragMove); - doc.addEventListener("mousemove", this.handleHoverPointer, true); - doc.addEventListener("mouseover", this.handleHoverPointer, true); doc.addEventListener("mousemove", this.handleInsertionPointer); doc.addEventListener("mouseover", this.handleInsertionPointer); doc.addEventListener("mouseup", this.handleDocumentMouseUp); doc.addEventListener("mouseleave", this.cancelPendingDrag); - doc.addEventListener("mouseleave", this.clearHover); doc.addEventListener("mouseleave", this.handleInsertionLeave); doc.defaultView?.addEventListener("blur", this.cancelPendingDrag); - doc.defaultView?.addEventListener("blur", this.clearHover); doc.defaultView?.addEventListener("blur", this.handleInsertionLeave); + view.dom.addEventListener("mousemove", this.handleEditorMouseMove); + view.dom.addEventListener("mouseleave", this.handleEditorMouseLeave); view.root.addEventListener("scroll", this.schedulePosition, true); view.dom.ownerDocument.defaultView?.addEventListener("resize", this.schedulePosition); @@ -290,22 +289,22 @@ class BlockSelectionView { this.localizationChange.dispose(); this.overlay.removeEventListener("mousedown", this.handleMouseDown); this.overlay.removeEventListener("mouseup", this.handleMouseUp); + this.overlay.removeEventListener("mouseover", this.handleHandleMouseOver); + this.overlay.removeEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.removeEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.removeEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.removeEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.removeEventListener("click", this.openInsertionMenu); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleDragMove); - this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleHoverPointer, true); - this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleHoverPointer, true); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseup", this.handleDocumentMouseUp); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.cancelPendingDrag); - this.view.dom.ownerDocument.removeEventListener("mouseleave", this.clearHover); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.handleInsertionLeave); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.cancelPendingDrag); - this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.clearHover); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.handleInsertionLeave); + this.view.dom.removeEventListener("mousemove", this.handleEditorMouseMove); + this.view.dom.removeEventListener("mouseleave", this.handleEditorMouseLeave); this.view.root.removeEventListener("scroll", this.schedulePosition, true); this.view.dom.ownerDocument.defaultView?.removeEventListener("resize", this.schedulePosition); this.resizeObserver?.disconnect(); @@ -819,27 +818,33 @@ class BlockSelectionView { return null; } - private setHoveredHandleGutter(gutter: HTMLDivElement | null) { - if (gutter === this.hoveredHandleGutter) return; - this.hoveredHandleGutter?.removeAttribute("data-handle-hovered"); - this.hoveredHandleGutter = gutter; - gutter?.setAttribute("data-handle-hovered", ""); - } + private readonly handleEditorMouseMove = (event: MouseEvent) => { + this.setHoveredPosition(this.getBlockAt(event.target)?.pos ?? null); + }; - private readonly handleHoverPointer = (event: MouseEvent) => { - const target = event.target; - if (!(target instanceof Element)) return this.clearHover(); + private readonly handleEditorMouseLeave = () => { + this.setHoveredPosition(null); + }; - const block = this.view.dom.contains(target) ? this.getBlockAt(target) : null; - this.setHoveredPosition(block?.pos ?? null); - const handle = this.overlay.contains(target) ? getHandle(event) : null; + private readonly handleHandleMouseOver = (event: MouseEvent) => { + const handle = getHandle(event); const pos = handle ? readHandlePosition(handle) : null; - this.setHoveredHandleGutter(pos === null ? null : (this.gutters.get(pos) ?? null)); + + if (pos !== null) { + this.gutters.get(pos)?.setAttribute("data-handle-hovered", ""); + } }; - private readonly clearHover = () => { - this.setHoveredPosition(null); - this.setHoveredHandleGutter(null); + private readonly handleHandleMouseOut = (event: MouseEvent) => { + const handle = getHandle(event); + const pos = handle ? readHandlePosition(handle) : null; + + if ( + pos !== null && + !(event.relatedTarget instanceof Node && handle?.contains(event.relatedTarget)) + ) { + this.gutters.get(pos)?.removeAttribute("data-handle-hovered"); + } }; private updateSelectionPresentation() { From 5b05347a37513f5a8d2d76294fa8402e950fb83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 08:54:17 -0300 Subject: [PATCH 05/15] Check resting block gutters over empty editor padding --- e2e/desktop/specs/block-selection.spec.ts | 37 ++++++++++------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index a6304565..27401300 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -661,8 +661,9 @@ describe("desktop block selection", () => { await closeAllDocuments(); await openRecentPath(blocks.path); await expect($("[data-testid=active-document-host] .ProseMirror")).toBeDisplayed(); - const activeTabSelector = '[data-testid="document-tab"][data-active]'; - await expect($(activeTabSelector)).toHaveText(path.basename(blocks.path)); + await expect($('[data-testid="document-tab"][data-active]')).toHaveText( + path.basename(blocks.path), + ); await expect($('[data-slot="toast"][data-type="success"]')).not.toExist(); await dismissToasts(); @@ -672,30 +673,24 @@ describe("desktop block selection", () => { async () => (await findGeometryForText("Nested second"))?.handleOpacity === "1", { timeoutMsg: "Hovering the nested item did not reveal its block handle." }, ); - const tabCenter = await browser.execute((selector) => { - const bounds = document.querySelector(selector)!.getBoundingClientRect(); - return { - x: Math.round(bounds.left + bounds.width / 2), - y: Math.round(bounds.top + bounds.height / 2), - }; - }, activeTabSelector); + const paddingPoint = await browser.execute( + (y) => { + const editor = document.querySelector("[data-testid=active-document-host] .ProseMirror")!; + const x = Math.round(editor.getBoundingClientRect().left + 8); + if (document.elementFromPoint(x, y) !== editor) { + throw new Error("The pointer target is outside the editor's empty padding."); + } + return { x, y }; + }, + Math.round(nestedItem.blockTop + nestedItem.blockHeight / 2), + ); await browser .action("pointer") - .move({ duration: 0, origin: "viewport", ...tabCenter }) + .move({ duration: 0, origin: "viewport", ...paddingPoint }) .perform(); - await browser.waitUntil( - () => - browser.execute( - (selector) => document.querySelector(selector)?.matches(":hover") ?? false, - activeTabSelector, - ), - { - timeoutMsg: "The pointer did not enter the active document tab.", - }, - ); await browser.waitUntil( async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), - { timeoutMsg: "A block handle stayed visible after moving the pointer to the document tab." }, + { timeoutMsg: "A block handle stayed visible after moving the pointer to empty padding." }, ); const wideGeometry = await handleGeometry(); From 638ce78f59276d0dd3036637a5a6221eadb07b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 09:02:36 -0300 Subject: [PATCH 06/15] Deliver gutter hover exit events in the desktop geometry test --- e2e/desktop/specs/block-selection.spec.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index 27401300..fa4f316c 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -688,6 +688,25 @@ describe("desktop block selection", () => { .action("pointer") .move({ duration: 0, origin: "viewport", ...paddingPoint }) .perform(); + await browser.execute(({ x, y }) => { + const editor = document.querySelector("[data-testid=active-document-host] .ProseMirror")!; + for (const handle of document.querySelectorAll("[data-leafdown-block-handle]")) { + if (handle.matches(":hover")) { + throw new Error( + "The pointer stayed over a block handle after the move to empty padding.", + ); + } + handle.dispatchEvent( + new MouseEvent("mouseout", { + bubbles: true, + clientX: x, + clientY: y, + relatedTarget: editor, + }), + ); + } + editor.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y })); + }, paddingPoint); await browser.waitUntil( async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), { timeoutMsg: "A block handle stayed visible after moving the pointer to empty padding." }, From 239b72bf6e0be665db96bec82e36940924a7defb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 13:49:45 -0300 Subject: [PATCH 07/15] Drive block gutter hover from document mouse events The embedded WebDriver delivers mouse moves through DOM events while CSS hover follows the Windows cursor. Keeping both as sources lets handles retain hover independently of the event target. --- e2e/desktop/specs/block-selection.spec.ts | 45 ++------------- .../editor/components/milkdown-editor.css | 10 +--- .../plugins/blockSelectionInteraction.test.ts | 6 +- .../plugins/blockSelectionInteraction.ts | 55 +++++++++---------- 4 files changed, 34 insertions(+), 82 deletions(-) diff --git a/e2e/desktop/specs/block-selection.spec.ts b/e2e/desktop/specs/block-selection.spec.ts index fa4f316c..76b86705 100644 --- a/e2e/desktop/specs/block-selection.spec.ts +++ b/e2e/desktop/specs/block-selection.spec.ts @@ -667,49 +667,15 @@ describe("desktop block selection", () => { await expect($('[data-slot="toast"][data-type="success"]')).not.toExist(); await dismissToasts(); - const nestedItem = await getGeometryForText("Nested second"); - await moveToBlock(nestedItem.pos); + await moveToHandle($(await getHandleSelectorForText("Nested second"))); await browser.waitUntil( async () => (await findGeometryForText("Nested second"))?.handleOpacity === "1", - { timeoutMsg: "Hovering the nested item did not reveal its block handle." }, + { timeoutMsg: "Moving over the nested handle did not reveal it." }, ); - const paddingPoint = await browser.execute( - (y) => { - const editor = document.querySelector("[data-testid=active-document-host] .ProseMirror")!; - const x = Math.round(editor.getBoundingClientRect().left + 8); - if (document.elementFromPoint(x, y) !== editor) { - throw new Error("The pointer target is outside the editor's empty padding."); - } - return { x, y }; - }, - Math.round(nestedItem.blockTop + nestedItem.blockHeight / 2), - ); - await browser - .action("pointer") - .move({ duration: 0, origin: "viewport", ...paddingPoint }) - .perform(); - await browser.execute(({ x, y }) => { - const editor = document.querySelector("[data-testid=active-document-host] .ProseMirror")!; - for (const handle of document.querySelectorAll("[data-leafdown-block-handle]")) { - if (handle.matches(":hover")) { - throw new Error( - "The pointer stayed over a block handle after the move to empty padding.", - ); - } - handle.dispatchEvent( - new MouseEvent("mouseout", { - bubbles: true, - clientX: x, - clientY: y, - relatedTarget: editor, - }), - ); - } - editor.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y })); - }, paddingPoint); + await $('[data-testid="status-bar"]').moveTo(); await browser.waitUntil( async () => (await handleGeometry()).every(({ handleOpacity }) => handleOpacity === "0"), - { timeoutMsg: "A block handle stayed visible after moving the pointer to empty padding." }, + { timeoutMsg: "A block handle stayed visible after moving to the status bar." }, ); const wideGeometry = await handleGeometry(); @@ -788,9 +754,6 @@ describe("desktop block selection", () => { const first = $(await getHandleSelectorForText("Nested first")); await moveToHandle(first); - await first.execute((handle) => - handle.dispatchEvent(new MouseEvent("mouseover", { bubbles: true })), - ); await browser.waitUntil(async () => { const geometry = await handleGeometry(); const hovered = geometry.find(({ pos }) => pos === firstGeometry.pos); diff --git a/src/features/editor/components/milkdown-editor.css b/src/features/editor/components/milkdown-editor.css index f20975f3..5bb6de6c 100644 --- a/src/features/editor/components/milkdown-editor.css +++ b/src/features/editor/components/milkdown-editor.css @@ -1402,17 +1402,11 @@ inset-block-start: calc(var(--leafdown-block-first-line) / 2 - 0.5rem); } -.leafdown-block-gutter[data-hovered] .leafdown-block-handle { +.leafdown-block-gutter:is([data-hovered], [data-handle-hovered]) .leafdown-block-handle { @apply opacity-100; } -.leafdown-block-gutter[data-handle-hovered] .leafdown-block-handle, -.leafdown-block-handle:hover { - @apply opacity-100; -} - -.leafdown-block-gutter[data-handle-hovered] .leafdown-block-handle::before, -.leafdown-block-handle:hover::before { +.leafdown-block-gutter[data-handle-hovered] .leafdown-block-handle::before { @apply h-full bg-foreground/70; inset-block-start: 0; } diff --git a/src/features/editor/plugins/blockSelectionInteraction.test.ts b/src/features/editor/plugins/blockSelectionInteraction.test.ts index 0a87ff1e..226c70ab 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.test.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.test.ts @@ -563,14 +563,14 @@ describe("block selection interaction", () => { expect(getHandle(paragraphs[0].pos).parentElement).not.toHaveAttribute("data-hovered"); expect(getHandle(paragraphs[1].pos).parentElement).toHaveAttribute("data-hovered"); - dispatchMouseEvent(mounted.view.dom, "mouseleave"); + dispatchMouseEvent(document.body, "mousemove"); expect(document.querySelector(".leafdown-block-gutter[data-hovered]")).toBeNull(); const firstHandle = getHandle(paragraphs[0].pos); - dispatchMouseEvent(firstHandle, "mouseover"); + dispatchMouseEvent(firstHandle, "mousemove"); expect(firstHandle.parentElement).toHaveAttribute("data-handle-hovered"); - dispatchMouseEvent(firstHandle, "mouseout", { relatedTarget: document.body }); + dispatchMouseEvent(document.body, "mouseover"); expect(firstHandle.parentElement).not.toHaveAttribute("data-handle-hovered"); }); diff --git a/src/features/editor/plugins/blockSelectionInteraction.ts b/src/features/editor/plugins/blockSelectionInteraction.ts index 5fb7ab86..90e5a326 100644 --- a/src/features/editor/plugins/blockSelectionInteraction.ts +++ b/src/features/editor/plugins/blockSelectionInteraction.ts @@ -191,6 +191,7 @@ class BlockSelectionView { >(); private animationFrame: number | null = null; private hoveredPos: number | null = null; + private hoveredHandleGutter: HTMLDivElement | null = null; private pendingCollapsePos: number | null = null; private pressedHandle: { x: number; y: number } | null = null; private resizeObserver: ResizeObserver | null = null; @@ -241,22 +242,22 @@ class BlockSelectionView { getOverlayOwner(view).append(this.overlay, this.status); this.overlay.addEventListener("mousedown", this.handleMouseDown); this.overlay.addEventListener("mouseup", this.handleMouseUp); - this.overlay.addEventListener("mouseover", this.handleHandleMouseOver); - this.overlay.addEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.addEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.addEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.addEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.addEventListener("click", this.openInsertionMenu); doc.addEventListener("mousemove", this.handleDragMove); + doc.addEventListener("mousemove", this.handleHoverPointer, true); + doc.addEventListener("mouseover", this.handleHoverPointer, true); doc.addEventListener("mousemove", this.handleInsertionPointer); doc.addEventListener("mouseover", this.handleInsertionPointer); doc.addEventListener("mouseup", this.handleDocumentMouseUp); doc.addEventListener("mouseleave", this.cancelPendingDrag); + doc.addEventListener("mouseleave", this.clearHover); doc.addEventListener("mouseleave", this.handleInsertionLeave); doc.defaultView?.addEventListener("blur", this.cancelPendingDrag); + doc.defaultView?.addEventListener("blur", this.clearHover); doc.defaultView?.addEventListener("blur", this.handleInsertionLeave); - view.dom.addEventListener("mousemove", this.handleEditorMouseMove); - view.dom.addEventListener("mouseleave", this.handleEditorMouseLeave); view.root.addEventListener("scroll", this.schedulePosition, true); view.dom.ownerDocument.defaultView?.addEventListener("resize", this.schedulePosition); @@ -289,22 +290,22 @@ class BlockSelectionView { this.localizationChange.dispose(); this.overlay.removeEventListener("mousedown", this.handleMouseDown); this.overlay.removeEventListener("mouseup", this.handleMouseUp); - this.overlay.removeEventListener("mouseover", this.handleHandleMouseOver); - this.overlay.removeEventListener("mouseout", this.handleHandleMouseOut); this.insertionButton.removeEventListener("mouseenter", this.showInsertionIndicator); this.insertionButton.removeEventListener("mouseleave", this.hideInsertionIndicator); this.insertionButton.removeEventListener("mousedown", this.preventInsertionMouseDown); this.insertionButton.removeEventListener("click", this.openInsertionMenu); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleDragMove); + this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleHoverPointer, true); + this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleHoverPointer, true); this.view.dom.ownerDocument.removeEventListener("mousemove", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseover", this.handleInsertionPointer); this.view.dom.ownerDocument.removeEventListener("mouseup", this.handleDocumentMouseUp); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.cancelPendingDrag); + this.view.dom.ownerDocument.removeEventListener("mouseleave", this.clearHover); this.view.dom.ownerDocument.removeEventListener("mouseleave", this.handleInsertionLeave); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.cancelPendingDrag); + this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.clearHover); this.view.dom.ownerDocument.defaultView?.removeEventListener("blur", this.handleInsertionLeave); - this.view.dom.removeEventListener("mousemove", this.handleEditorMouseMove); - this.view.dom.removeEventListener("mouseleave", this.handleEditorMouseLeave); this.view.root.removeEventListener("scroll", this.schedulePosition, true); this.view.dom.ownerDocument.defaultView?.removeEventListener("resize", this.schedulePosition); this.resizeObserver?.disconnect(); @@ -818,33 +819,27 @@ class BlockSelectionView { return null; } - private readonly handleEditorMouseMove = (event: MouseEvent) => { - this.setHoveredPosition(this.getBlockAt(event.target)?.pos ?? null); - }; + private setHoveredHandleGutter(gutter: HTMLDivElement | null) { + if (gutter === this.hoveredHandleGutter) return; + this.hoveredHandleGutter?.removeAttribute("data-handle-hovered"); + this.hoveredHandleGutter = gutter; + gutter?.setAttribute("data-handle-hovered", ""); + } - private readonly handleEditorMouseLeave = () => { - this.setHoveredPosition(null); - }; + private readonly handleHoverPointer = (event: MouseEvent) => { + const target = event.target; + if (!(target instanceof Element)) return this.clearHover(); - private readonly handleHandleMouseOver = (event: MouseEvent) => { - const handle = getHandle(event); + const block = this.view.dom.contains(target) ? this.getBlockAt(target) : null; + this.setHoveredPosition(block?.pos ?? null); + const handle = this.overlay.contains(target) ? getHandle(event) : null; const pos = handle ? readHandlePosition(handle) : null; - - if (pos !== null) { - this.gutters.get(pos)?.setAttribute("data-handle-hovered", ""); - } + this.setHoveredHandleGutter(pos === null ? null : (this.gutters.get(pos) ?? null)); }; - private readonly handleHandleMouseOut = (event: MouseEvent) => { - const handle = getHandle(event); - const pos = handle ? readHandlePosition(handle) : null; - - if ( - pos !== null && - !(event.relatedTarget instanceof Node && handle?.contains(event.relatedTarget)) - ) { - this.gutters.get(pos)?.removeAttribute("data-handle-hovered"); - } + private readonly clearHover = () => { + this.setHoveredPosition(null); + this.setHoveredHandleGutter(null); }; private updateSelectionPresentation() { From ead13f933faeb2be2a331861c2e8e91f78835d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 14:10:15 -0300 Subject: [PATCH 08/15] Refresh desktop test elements after navigator and popup remounts --- e2e/desktop/specs/document-tabs.spec.ts | 30 ++++++++++++++---------- e2e/desktop/specs/table-controls.spec.ts | 13 +++++----- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/e2e/desktop/specs/document-tabs.spec.ts b/e2e/desktop/specs/document-tabs.spec.ts index 886635ed..f431c2c2 100644 --- a/e2e/desktop/specs/document-tabs.spec.ts +++ b/e2e/desktop/specs/document-tabs.spec.ts @@ -54,6 +54,14 @@ const getTabGeometry = () => }), ); +const getFilenameGeometry = (item: WebdriverIO.Element) => + item.execute((row) => { + const range = document.createRange(); + range.selectNodeContents(row.querySelector(".truncate")!); + const { x, width } = range.getBoundingClientRect(); + return { x, width }; + }); + describe("desktop document tabs", () => { it("keeps each tab's unsaved edits and closes the window through one unsaved-documents dialog", async () => { const diagnostics = await getDiagnosticsSummary(); @@ -73,24 +81,20 @@ describe("desktop document tabs", () => { await expect(await findDocumentTab(separatorName)).toHaveAttribute("aria-selected", "true"); const tabGeometry = await getTabGeometry(); - const separatorRow = await findTreeItem(separatorName); - const getFilenameGeometry = () => - separatorRow.execute((row) => { - const range = document.createRange(); - range.selectNodeContents(row.querySelector(".truncate")!); - const { x, width } = range.getBoundingClientRect(); - return { x, width }; - }); - const filenameGeometry = await getFilenameGeometry(); + const filenameGeometry = await getFilenameGeometry(await findTreeItem(separatorName)); await appendToActiveEditor("Separator tab edit"); - await expect(separatorRow).toHaveAttribute("aria-description", "Unsaved changes"); + await expect(await findTreeItem(separatorName)).toHaveAttribute( + "aria-description", + "Unsaved changes", + ); await (await findDocumentTab(calloutsName)).click(); await expect(await findDocumentTab(calloutsName)).toHaveAttribute("aria-selected", "true"); expect(await getTabGeometry()).toEqual(tabGeometry); - await expect(separatorRow).toHaveAttribute("aria-selected", "false"); - await expect(separatorRow).toHaveAttribute("aria-description", "Unsaved changes"); - expect(await getFilenameGeometry()).toEqual(filenameGeometry); + const inactiveSeparatorRow = await findTreeItem(separatorName); + await expect(inactiveSeparatorRow).toHaveAttribute("aria-selected", "false"); + await expect(inactiveSeparatorRow).toHaveAttribute("aria-description", "Unsaved changes"); + expect(await getFilenameGeometry(inactiveSeparatorRow)).toEqual(filenameGeometry); await expect($(ACTIVE_EDITOR)).not.toHaveText(expect.stringContaining("Separator tab edit")); await appendToActiveEditor("Callouts tab edit"); diff --git a/e2e/desktop/specs/table-controls.spec.ts b/e2e/desktop/specs/table-controls.spec.ts index 4136b806..db407d9f 100644 --- a/e2e/desktop/specs/table-controls.spec.ts +++ b/e2e/desktop/specs/table-controls.spec.ts @@ -169,16 +169,16 @@ describe("desktop table controls", () => { ]); const before = await tableRect(); - const popup = $("[data-testid='editor-context-popup']"); + const headerPopup = $("[data-testid='editor-context-popup']"); await hover(await cellPoint(0, 0)); const headerGrip = await waitForControl(ROW_GRIP_SELECTOR); await dispatchPointerSequence([ { type: "mousedown", point: headerGrip, buttons: 1 }, { type: "mouseup", point: headerGrip, buttons: 0 }, ]); - await expect(popup.$("button=Header row")).toHaveAttribute("aria-pressed", "true"); + await expect(headerPopup.$("button=Header row")).toHaveAttribute("aria-pressed", "true"); await browser.keys(Key.Escape); - await expect(popup).not.toExist(); + await expect(headerPopup).not.toExist(); await hover(await cellPoint(1, 0)); const rowGrip = await waitForControl(ROW_GRIP_SELECTOR); @@ -196,10 +196,9 @@ describe("desktop table controls", () => { { type: "mousedown", point: rowGrip, buttons: 1 }, { type: "mouseup", point: rowGrip, buttons: 0 }, ]); - await expect($("[data-testid='editor-context-popup']")).toBeDisplayed(); - await expect( - $("[data-testid='editor-context-popup'] [aria-label='Delete row']"), - ).toBeDisplayed(); + const popup = $("[data-testid='editor-context-popup']"); + await expect(popup).toBeDisplayed(); + await expect(popup.$("[aria-label='Delete row']")).toBeDisplayed(); await expect(popup.$("button=Row 1")).toHaveAttribute("aria-pressed", "true"); await expect(popup.$("[aria-label='Add row below']")).toHaveText(""); const dividerGap = await browser.execute(() => { From 28fee86e1bec94d273a67b9ec0eb6b7284625d2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 14:34:03 -0300 Subject: [PATCH 09/15] Give Windows desktop CI time to finish teardown The serial suite finished just below the 20-minute job deadline, and GitHub cancelled the job as it completed cleanup. Reserve five more minutes for Windows build and teardown variation. --- .github/workflows/ci.yml | 2 +- CONTRIBUTING.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c50b608..7f8214b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,7 +121,7 @@ jobs: - changes - lint-workflows runs-on: windows-2025-vs2026 - timeout-minutes: 20 + timeout-minutes: 25 env: CARGO_PROFILE_DEV_DEBUG: 0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a46805c..5cbe6b1f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -189,7 +189,7 @@ Frontend checks enforce a coverage floor. It is a ratchet set just below the mea CI and release jobs share [the setup action](./.github/actions/setup/action.yml), which uses `pnpm/setup` to install manifest-selected pnpm and Node.js, cache the package store, and require a frozen lockfile. Rust jobs provide a cache workspace mapping to also install the pinned toolchain and restore the appropriate target directory; CI saves Rust caches only on `main`. -`Workflow Checks` runs pinned actionlint, including ShellCheck, before the application jobs. It checks all workflow files, including the release workflow. CI jobs have explicit time limits: five minutes for workflow linting and the gate, twenty minutes for each application job, and forty-five minutes for the release build. +`Workflow Checks` runs pinned actionlint, including ShellCheck, before the application jobs. It checks all workflow files, including the release workflow. Workflow linting and the gate have five minutes. Frontend and backend checks have twenty minutes each, Desktop E2E has twenty-five minutes including the Windows build and teardown, and the release build has forty-five minutes. `Change classification and documentation checks` compares the complete PR diff or pushed range. Only the maintenance prose named by [the documentation policy](./.github/ci/docs-only.json) can skip application jobs. Bundled `docs/help/`, `CHANGELOG.md`, fixtures, executable/configuration files, and unrecognized paths require full CI. Root maintenance docs, technical Markdown, and the named contribution templates use the lightweight route; images and other extensions are not implicitly exempt. Manual runs always use full CI. From 262eba7879acdf61c592aae586a6727773ccec94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 14:49:03 -0300 Subject: [PATCH 10/15] Wait for bookmarked folder close in the desktop scenario --- e2e/desktop/specs/named-folders-switch.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/e2e/desktop/specs/named-folders-switch.spec.ts b/e2e/desktop/specs/named-folders-switch.spec.ts index 48abd534..4efc2923 100644 --- a/e2e/desktop/specs/named-folders-switch.spec.ts +++ b/e2e/desktop/specs/named-folders-switch.spec.ts @@ -67,7 +67,9 @@ describe("desktop named folder switching", () => { await keepCurrentFolder("Personal notes"); await selectFileMenuItem("Close folder"); - expect(await countDocumentTabs()).toBe(0); + await browser.waitUntil(async () => (await countDocumentTabs()) === 0, { + timeoutMsg: "Closing the bookmarked folder did not clear its tabs.", + }); await openRecentPath(bookmarks.studiesPath); await dismissToasts(); From bb7017b3cf09076719ef10f62fc38e0c1b613f72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 16:45:55 -0300 Subject: [PATCH 11/15] Open Help and release notes at the top --- CHANGELOG.md | 1 + docs/specification.md | 4 ++-- e2e/desktop/specs/help-pages.spec.ts | 8 ++++++++ src/features/help/components/help-dialog.test.tsx | 10 +++++----- src/features/help/components/help-page.tsx | 14 +++++++++++--- .../components/release-notes-dialog.test.tsx | 4 +--- 6 files changed, 28 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f18f8bb6..0dfba30f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ Leafdown uses lightweight [Keep a Changelog](https://keepachangelog.com/en/1.1.0 - Keep article names steady when selected and mark articles with unsaved changes in the navigator. - Use the shared code-block toggle to collapse long blocks and add a selection grip to table headers. - Center the heading outline dots on the same axis and place notification actions below the message. +- Open Help guides, What's new, and Changelog at the top of their content. ## [0.1.0-alpha.5] - 2026-10-19 diff --git a/docs/specification.md b/docs/specification.md index f6e99373..0a9131fc 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -482,7 +482,7 @@ For editor input and clipboard ownership, see [Architecture](./architecture.md#e ### Help -The Help menu opens Getting started, Markdown reference, File and folder workflows, and Settings reference as bundled, read-only pages. Each command opens directly to its page without a network request. The dialog shows one page, titled with that page's name. It takes the window's height up to a limit and the width its page needs, narrowing with a narrower window, and stays clear of the titlebar. When the dialog is wide enough, a page with three or more sections lists them beside its text and marks the one being read; choosing one, or following a link to a section of the same page, scrolls to that section and moves focus to its heading. Links to another bundled page replace it in the same dialog and move focus to its content; explicit web links open through the system browser. Help does not send document text, paths, or diagnostics, and opening, navigating, or closing it does not change the document, selection, folder context, dirty state, or editor history. Focus enters the dialog and returns to the prior application control when it closes. Pages remain scrollable in a narrow window. +The Help menu opens Getting started, Markdown reference, File and folder workflows, and Settings reference as bundled, read-only pages. Each command opens directly to its page without a network request. The dialog shows one page, titled with that page's name. It takes the window's height up to a limit and the width its page needs, narrowing with a narrower window, and stays clear of the titlebar. When the dialog is wide enough, a page with three or more sections lists them beside its text and marks the one being read; choosing one, or following a link to a section of the same page, scrolls to that section and moves focus to its heading. Links to another bundled page replace it in the same dialog and move focus to its content; explicit web links open through the system browser. Help does not send document text, paths, or diagnostics, and opening, navigating, or closing it does not change the document, selection, folder context, dirty state, or editor history. Each opening starts at the top of the page with focus on the dialog itself. Closing it returns focus to the prior application control. Pages remain scrollable in a narrow window. The source pages under `docs/help/` are the user-facing explanation of shipped behavior. They follow this Specification and the command and settings inventory in Reference. @@ -498,7 +498,7 @@ See [Reference](./reference.md) for current and Deferred settings, command surfa - Browsing other pages records no version as seen and leaves automatic opening unchanged. - `Help > Changelog` opens the complete bundled `CHANGELOG.md` in a scrollable, read-only dialog: its introduction, then one section per release with notes, newest first, each naming its version and release date. In a wide enough window the releases are listed beside the text, as a help page lists its sections. Inline formatting, code, and links are rendered as content. External web links use the system browser through Leafdown's safe opener; the dialogs require no network access. - After a version change, What's new opens automatically once if Leafdown has a recorded previous version, the new version has usable notes, and those notes have not been shown before. First installation never opens it automatically. Showing it automatically or manually records that version as seen across restarts; the Help command remains available for manual reopening. A version without notes is recorded as launched without showing a dialog. -- Opening, browsing, scrolling, and closing release notes leave the active document, folder, recent items, and editor state unchanged. Escape and the Close control dismiss the dialog and return focus to the prior surface. +- Both dialogs open at the top of their content with focus on the dialog itself. Opening, browsing, scrolling, and closing release notes leave the active document, folder, recent items, and editor state unchanged. Escape and the Close control dismiss the dialog and return focus to the prior surface. ### Update Check diff --git a/e2e/desktop/specs/help-pages.spec.ts b/e2e/desktop/specs/help-pages.spec.ts index f91a74e1..1e97b206 100644 --- a/e2e/desktop/specs/help-pages.spec.ts +++ b/e2e/desktop/specs/help-pages.spec.ts @@ -26,6 +26,13 @@ describe("desktop Help pages", () => { await expect($("[role='dialog']")).toBeDisplayed(); await expect($("[data-slot='dialog-title']")).toHaveText("Getting started"); + await browser.waitUntil( + () => + browser.execute( + () => document.activeElement?.matches('[data-slot="dialog-content"][data-open]') ?? false, + ), + { timeoutMsg: "Getting started did not focus the dialog on open." }, + ); await browser.waitUntil( () => browser.execute(() => { @@ -76,6 +83,7 @@ describe("desktop Help pages", () => { if (!scrolling || scrolling.after <= 0) { throw new Error(`Help did not scroll: ${JSON.stringify(scrolling)}`); } + expect(scrolling.before).toBe(0); await $("article").$("button=Markdown reference").click(); await expect($("[data-slot='dialog-title']")).toHaveText("Markdown reference"); diff --git a/src/features/help/components/help-dialog.test.tsx b/src/features/help/components/help-dialog.test.tsx index 1698320a..35783e7e 100644 --- a/src/features/help/components/help-dialog.test.tsx +++ b/src/features/help/components/help-dialog.test.tsx @@ -4,7 +4,7 @@ import { openUrl } from "@tauri-apps/plugin-opener"; import { useState } from "react"; import { describe, expect, it, vi } from "vitest"; -import { renderWithUser, screen, within } from "@/test/utils/react"; +import { renderWithUser, screen, waitFor, within } from "@/test/utils/react"; import type { HelpPageId } from "../services/pages"; import { HelpDialog } from "./help-dialog"; @@ -50,12 +50,12 @@ describe("Help dialog", () => { ); }); - it("focuses the dialog and returns focus when closed", async () => { + it("initially focuses the dialog itself and returns focus when closed", async () => { const { user } = renderWithUser(); await user.click(screen.getByRole("button", { name: "Open Help" })); - expect( - screen.getByRole("dialog", { name: "Getting started" }).contains(document.activeElement), - ).toBe(true); + await waitFor(() => + expect(screen.getByRole("dialog", { name: "Getting started" })).toHaveFocus(), + ); await user.click(screen.getByRole("button", { name: "Close" })); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); diff --git a/src/features/help/components/help-page.tsx b/src/features/help/components/help-page.tsx index 8318c42e..4af18fd8 100644 --- a/src/features/help/components/help-page.tsx +++ b/src/features/help/components/help-page.tsx @@ -1,4 +1,4 @@ -import { useState, type ComponentProps, type ReactNode, type Ref } from "react"; +import { useRef, useState, type ComponentProps, type ReactNode, type Ref } from "react"; import { DialogContent, @@ -36,13 +36,21 @@ export function HelpPageContent({ kind, fitContent = false, className, + initialFocus, ...props -}: ComponentProps & { kind: HelpPageKind; fitContent?: boolean }) { +}: Omit, "ref"> & { + kind: HelpPageKind; + fitContent?: boolean; +}) { + const popupRef = useRef(null); + return ( { ); await user.click(screen.getByRole("button", { name: "Open changelog" })); - expect(screen.getByRole("dialog", { name: "Changelog" }).contains(document.activeElement)).toBe( - true, - ); + await waitFor(() => expect(screen.getByRole("dialog", { name: "Changelog" })).toHaveFocus()); await user.click(screen.getByRole("button", { name: "Close" })); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); From 6672f5d252841f463dbe1eab77afc0b001c81b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 17:41:29 -0300 Subject: [PATCH 12/15] Scroll Help previews into view in the desktop test --- e2e/desktop/specs/help-pages.spec.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/e2e/desktop/specs/help-pages.spec.ts b/e2e/desktop/specs/help-pages.spec.ts index 1e97b206..5cf29c06 100644 --- a/e2e/desktop/specs/help-pages.spec.ts +++ b/e2e/desktop/specs/help-pages.spec.ts @@ -141,7 +141,11 @@ describe("desktop Help pages", () => { await openMenu("Help"); await $(`aria/${page}`).click(); for await (const example of $$("article [data-help-example]")) { - await example.scrollIntoView(); + await browser.execute((element) => { + element + .querySelector(":scope > div > div:last-child")! + .scrollIntoView({ block: "center" }); + }, example); await browser.waitUntil( () => browser.execute((element) => { From e4df69d70ccd37043a04a416a979d466733857ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ademir=20Jos=C3=A9=20Ferreira=20J=C3=BAnior?= Date: Wed, 18 Nov 2026 19:37:49 -0300 Subject: [PATCH 13/15] Open editor context submenus on hover --- CHANGELOG.md | 1 + docs/specification.md | 1 + e2e/desktop/specs/callouts.spec.ts | 8 +++---- .../components/editor-context-popup.test.tsx | 22 +++++++++++++++++++ .../components/editor-context-popup.tsx | 21 ++++++++++++++++-- 5 files changed, 47 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dfba30f..2e1346e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ Leafdown uses lightweight [Keep a Changelog](https://keepachangelog.com/en/1.1.0 - Use the shared code-block toggle to collapse long blocks and add a selection grip to table headers. - Center the heading outline dots on the same axis and place notification actions below the message. - Open Help guides, What's new, and Changelog at the top of their content. +- Open editor context submenus on hover. ## [0.1.0-alpha.5] - 2026-10-19 diff --git a/docs/specification.md b/docs/specification.md index 0a9131fc..20cfa947 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -311,6 +311,7 @@ The editor is a unified hybrid Markdown surface. Behavior is governed by renderi - `Shift+F10` and the `Menu` key open the context popup around the caret or selection and move focus into it. A popup opened by right-click or by a selection leaves focus in the editor. - `Mod+Alt+P` previews the footnote definition the caret's reference names, or the document the caret's link resolves to, leaving focus in the editor; `Escape` dismisses it. A footnote reference inside a link label previews its definition. - The popup offers the actions of the context it opens in: a caret, a text selection, or a structural block selection. A code block, frontmatter, or table holding the caret or selection leaves out the actions that cannot change it. A table adds its row, column, and table commands, and a footnote, image, or fenced code block adds its own actions while they apply. [Reference](./reference.md#popup-contexts) lists each context's actions. A context keeps its unavailable commands visible but disabled, and every command a context leaves out stays in the menu bar and the command palette. The popup follows the selection to a new context, as it does to a new position. +- Hovering over a submenu trigger opens it after a short delay. The pointer can move from its trigger into the submenu to choose a command or open another submenu. Clicking a trigger also opens it. - The popup is one command toolbar, and focus enters it on its first available command: - `ArrowLeft` and `ArrowRight`: Move between commands in order, wrapping at either end. - `ArrowUp` and `ArrowDown`: Move between rows at the nearest available column, wrapping at either end and skipping a row whose commands are all unavailable. On a submenu, `ArrowDown` opens it instead. diff --git a/e2e/desktop/specs/callouts.spec.ts b/e2e/desktop/specs/callouts.spec.ts index be4ce60f..af88bd97 100644 --- a/e2e/desktop/specs/callouts.spec.ts +++ b/e2e/desktop/specs/callouts.spec.ts @@ -191,7 +191,7 @@ describe("desktop callouts", () => { }); } - it("inserts another dialect from the context popup and lists GitHub types first afterward", async () => { + it("inserts another dialect through hovered context submenus and lists GitHub types first afterward", async () => { const active = "[data-testid=active-document-host]"; await selectFileMenuItem("New"); @@ -213,9 +213,9 @@ describe("desktop callouts", () => { }); const popup = $("[data-testid=editor-context-popup]"); await expect(popup).toBeDisplayed(); - await popup.$("aria/Insert").click(); - await (await findMenuItem((text) => text === "Callout")).click(); - await (await findMenuItem((text) => text === "VitePress")).click(); + await popup.$("aria/Insert").moveTo(); + await (await findMenuItem((text) => text === "Callout")).moveTo(); + await (await findMenuItem((text) => text === "VitePress")).moveTo(); const details = await findMenuItem((text) => text === "Details"); await expect(details.$("[data-slot=callout-type-icon]")).toBeDisplayed(); await details.click(); diff --git a/src/features/editor/components/editor-context-popup.test.tsx b/src/features/editor/components/editor-context-popup.test.tsx index 6658be3d..2702d4b7 100644 --- a/src/features/editor/components/editor-context-popup.test.tsx +++ b/src/features/editor/components/editor-context-popup.test.tsx @@ -155,6 +155,28 @@ const controlLabels = () => .map((control) => control.getAttribute("aria-label") ?? control.textContent); describe("editor-context-popup", () => { + it("opens a submenu on hover while keeping focus in the editor", async () => { + const { user } = renderWithUser( + <> +