Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(notes): Keep the caret and empty-line toolbar clear of the note's bottom bar (#2516)
Chad Piha58bdc2897b80
diff --git a/CLAUDE.md b/CLAUDE.mdindex 485f894b2..105a6b169 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -206,10 +206,10 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- **WhisperModelPicker.tsx**: Model selection and download UI- **ConnectorsSection.tsx**: Integrations → Connectors: the "Draft emails in" picker (Automatic shows what it resolved to; Send from chat (Gmail) says to connect Gmail until it can send, and the card's description follows where drafts actually go), a paid-plan upsell, "turned off by your organization" for a resolved org block and "not available right now" while the policy is loading, failed or requires a newer app- **ui/**: Reusable UI components (buttons, cards, inputs, etc.)-- **ui/RichTextEditor.tsx**: Tiptap note editor. Note bodies (`content`, `enhanced_content`) are stored as Markdown via tiptap-markdown (`html: false`)+- **ui/RichTextEditor.tsx**: Tiptap note editor. Note bodies (`content`, `enhanced_content`) are stored as Markdown via tiptap-markdown (`html: false`). NoteBottomBar publishes its height in `--bottom-overlay-height`; the editor reads it for its bottom scroll margin and threshold, its bottom padding and the line menu's flip padding, so the caret and the menu stay clear of the bar- `RichTextEditorExtensions.ts` holds the extension list (`RichTextEditor` adds the mention extension in front of it); order matters: at equal priority, later extensions' keymaps and clipboard props run first- `RichTextEditorTable.ts` keeps every table to what a GFM pipe table can store: header first row, one single-line paragraph per cell, no merged cells, no alignment or column widths. Pasted cells are flattened while parsing, a normalizer fixes what commands and pastes leave behind, and the table serializer escapes `|` in cells. Tests: `test/components/richTextEditor.test.js` (happy-dom)- - Floating menus: `RichTextEditorFormatMenu.tsx` shows one formatting toolbar (marks, text style, lists, quote, insert table) above selected text (Tiptap `BubbleMenu`) and below the caret on an empty top-level line, flipping above when there's no room (`FloatingMenu`); `RichTextEditorTableMenu.tsx` is the table's `⋯` menu. They share `RichTextEditorMenus.ts`: a menu hides when focus leaves it, so dropdowns portal into the menu element itself, never into the editor's scroller (EditorContent moves the scroller's children when a note closes); `useHideOnFocusLeave` hides a menu when focus leaves from inside it or after a click on it, which Tiptap misses. The menus detach their element without unmounting it, so buttons use a native `title` rather than `<Tooltip>`, and a dropdown inside a menu is controlled and closed from the menu's `onHide` — otherwise it stays open over a scroll-locked page when the menu hides. Keep menu props stable, or each render dispatches an `updateOptions` transaction+ - Floating menus: `RichTextEditorFormatMenu.tsx` shows one formatting toolbar (marks, text style, lists, quote, insert table) above selected text (Tiptap `BubbleMenu`) and below the caret on an empty top-level line, flipping above when there's no room (`FloatingMenu`); `RichTextEditorTableMenu.tsx` is the table's `⋯` menu. They share `RichTextEditorMenus.ts`: a menu hides when focus leaves it, so dropdowns portal into the menu element itself, never into the editor's scroller (EditorContent moves the scroller's children when a note closes); `useHideOnFocusLeave` hides a menu when focus leaves from inside it or after a click on it, which Tiptap misses. The menus detach their element without unmounting it, so buttons use a native `title` rather than `<Tooltip>`, and a dropdown inside a menu is controlled and closed from the menu's `onHide` — otherwise it stays open over a scroll-locked page when the menu hides. Keep menu props stable, or each render dispatches an `updateOptions` transaction. The line menu is placed again in the frame after a transaction that scrolled the caret into view, since ProseMirror scrolls after the menu measured### React Hooks (src/hooks/)diff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsxindex 118cac829..215b1d558 100644--- a/src/components/notes/NoteBottomBar.tsx+++ b/src/components/notes/NoteBottomBar.tsx@@ -1,10 +1,10 @@-import { useCallback, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { ChatInput } from "../chat/ChatInput";import type { SlashCommand } from "../chat/slashCommands";import { cn } from "../lib/utils";import { hasLayerAbove } from "../ui/useDismissGuard";-import { observeFloatingChatMaxHeight } from "./floatingChatLayout";+import { observeBottomBarHeight, observeFloatingChatMaxHeight } from "./floatingChatLayout";const RECORDING_SURFACE = "bg-surface-2/95 shadow-(--shadow-glass)";// One curve for everything that moves as the chat opens, so it unfolds as one piece:@@ -56,6 +56,14 @@ export default function NoteBottomBar({const { t } = useTranslation();const [slashMenuOpen, setSlashMenuOpen] = useState(false);+ const barRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const bar = barRef.current;+ const container = bar?.parentElement;+ if (!bar || !container) return;+ return observeBottomBarHeight({ bar, container });+ }, []);+const attachPanel = useCallback((panel: HTMLDivElement | null) => {if (!panel) return;@@ -114,6 +122,7 @@ export default function NoteBottomBar({return (<div+ ref={barRef}className={cn("pointer-events-none absolute inset-x-0 bottom-0 z-20 px-5 pt-6",footnote ? "pb-1.5" : "pb-7"diff --git a/src/components/notes/floatingChatLayout.ts b/src/components/notes/floatingChatLayout.tsindex f2d4b35a4..0ca5720b3 100644--- a/src/components/notes/floatingChatLayout.ts+++ b/src/components/notes/floatingChatLayout.ts@@ -55,6 +55,34 @@ export function observeFloatingChatMaxHeight(return (): void => observer.disconnect();}+interface BottomBarHeightOptions {+ bar: HTMLElement;+ container: HTMLElement;+}++/**+ * Publishes how much of the note's bottom the bar covers, chips, callout and an+ * open chat included, in --bottom-overlay-height. The note editor scrolls the+ * caret clear of it.+ */+export function observeBottomBarHeight(+ { bar, container }: BottomBarHeightOptions,+ createResizeObserver: (callback: () => void) => ResizeObserverHandle = (callback) =>+ new ResizeObserver(callback)+): () => void {+ const publish = (): void =>+ container.style.setProperty("--bottom-overlay-height", `${bar.offsetHeight}px`);++ publish();+ const observer = createResizeObserver(publish);+ observer.observe(bar);++ return (): void => {+ observer.disconnect();+ container.style.removeProperty("--bottom-overlay-height");+ };+}+export function isNearScrollBottom(metrics: ScrollMetrics): boolean {return getScrollBottomDistance(metrics) <= SCROLL_BOTTOM_THRESHOLD_PX;}diff --git a/src/components/ui/RichTextEditor.tsx b/src/components/ui/RichTextEditor.tsxindex ad526d98d..c40ca64a5 100644--- a/src/components/ui/RichTextEditor.tsx+++ b/src/components/ui/RichTextEditor.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useCallback, type MutableRefObject } from "react";+import { useEffect, useRef, useCallback, useState, type MutableRefObject } from "react";import { useEditor, EditorContent, type Editor } from "@tiptap/react";import { cn } from "../lib/utils";import { createMentionExtension } from "./RichTextEditorMention";@@ -7,6 +7,31 @@ import { RichTextEditorFormatMenu } from "./RichTextEditorFormatMenu";import { RichTextEditorTableMenu } from "./RichTextEditorTableMenu";import type { MentionPerson } from "../../utils/mentionMarkdown";+/**+ * ProseMirror's scroll margin or threshold (`side` on every side), raised at the+ * bottom to whatever an ancestor overlays there: NoteBottomBar publishes its height+ * in --bottom-overlay-height. ProseMirror reads the sides each time it scrolls the+ * caret into view, so the getter follows the bar as it grows (action chips, the+ * summary callout, an open chat).+ */+function clearOfBottomOverlay(+ containerRef: MutableRefObject<HTMLElement | null>,+ side: number+): Record<"top" | "right" | "bottom" | "left", number> {+ return {+ top: side,+ right: side,+ left: side,+ get bottom(): number {+ const container = containerRef.current;+ const overlay = container+ ? parseFloat(getComputedStyle(container).getPropertyValue("--bottom-overlay-height"))+ : NaN;+ return Number.isFinite(overlay) ? Math.max(overlay, side) : side;+ },+ };+}+interface RichTextEditorProps {value: string;onChange?: (value: string) => void;@@ -51,6 +76,12 @@ export function RichTextEditor({}, [mentionPeople]);const withMentions = useRef(mentionPeople != null).current;+ const containerRef = useRef<HTMLDivElement>(null);+ const [scrollClearance] = useState(() => ({+ scrollMargin: clearOfBottomOverlay(containerRef, 5),+ scrollThreshold: clearOfBottomOverlay(containerRef, 0),+ }));+const editor = useEditor({extensions: [...(withMentions ? [createMentionExtension(() => mentionPeopleRef.current ?? [])] : []),@@ -73,6 +104,7 @@ export function RichTextEditor({class: "rich-text-editor-content",dir: "auto",},+ ...scrollClearance,},});@@ -120,18 +152,25 @@ export function RichTextEditor({}, [editor, disabled]);return (- <div className={cn("relative w-full h-full", className)} onClick={handleClick}>+ <div+ ref={containerRef}+ className={cn("relative w-full h-full", className)}+ onClick={handleClick}+ ><EditorContenteditor={editor}className={cn(// relative: the table menu positions against this scroller and scrolls with it."relative h-full overflow-y-auto",- disabled && "pointer-events-none opacity-70",- // Reserved by an ancestor via --floating-inset; 0 elsewhere.- "pb-[var(--floating-inset,0px)]"+ disabled && "pointer-events-none opacity-70")}/>- {editor && !disabled && <RichTextEditorFormatMenu editor={editor} />}+ {editor && !disabled && (+ <RichTextEditorFormatMenu+ editor={editor}+ lineMenuPadding={scrollClearance.scrollThreshold}+ />+ )}{editor && !disabled && <RichTextEditorTableMenu editor={editor} />}</div>);diff --git a/src/components/ui/RichTextEditorFormatMenu.tsx b/src/components/ui/RichTextEditorFormatMenu.tsxindex fe1f38a0d..58bae7f85 100644--- a/src/components/ui/RichTextEditorFormatMenu.tsx+++ b/src/components/ui/RichTextEditorFormatMenu.tsx@@ -1,6 +1,6 @@-import type { ReactNode } from "react";+import { useEffect, useMemo, type ReactNode } from "react";import type { Editor } from "@tiptap/core";-import { NodeSelection, type EditorState } from "@tiptap/pm/state";+import { NodeSelection, type EditorState, type Transaction } from "@tiptap/pm/state";import { isInTable } from "@tiptap/pm/tables";import { useEditorState } from "@tiptap/react";import {@@ -257,11 +257,48 @@ function FormatToolbar({);}-/** Marks, text style, lists and tables for selected text or an empty line. */-export function RichTextEditorFormatMenu({ editor }: { editor: Editor }) {+/**+ * Marks, text style, lists and tables for selected text or an empty line.+ * `lineMenuPadding` is space at the editor's edges that leaves the empty-line+ * toolbar no room, such as the note's bottom bar: it flips above the caret instead.+ */+export function RichTextEditorFormatMenu({+ editor,+ lineMenuPadding,+}: {+ editor: Editor;+ lineMenuPadding: Record<"top" | "right" | "bottom" | "left", number>;+}) {const onSelection = useMenuDropdown();- const onEmptyLine = useMenuDropdown(LINE_MENU_OPTIONS);+ const lineMenuOptions = useMemo(+ () => ({ ...LINE_MENU_OPTIONS, flip: { padding: lineMenuPadding } }),+ [lineMenuPadding]+ );+ const onEmptyLine = useMenuDropdown(lineMenuOptions);useHideOnFocusLeave(editor, MENU_KEYS);+ // ProseMirror scrolls the caret into view after the menus measured it, so a line+ // menu placed by a transaction that scrolled the note sits off by the scroll.+ // Tiptap's `scrollTarget` option would re-place it only 60 ms after the scroll,+ // so place it again in the next frame, before it is painted. The selection menu+ // waits for the selection to settle before it measures.+ useEffect(() => {+ let frame = 0;+ // Tiptap hides a menu by detaching its element.+ const isShown = (): boolean => !!onEmptyLine.menuRef.current?.isConnected;+ const onTransaction = ({ transaction }: { transaction: Transaction }): void => {+ if (!transaction.scrolledIntoView || !isShown()) return;+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ if (editor.isDestroyed || !isShown()) return;+ editor.view.dispatch(editor.state.tr.setMeta(LINE_MENU, "updatePosition"));+ });+ };+ editor.on("transaction", onTransaction);+ return () => {+ cancelAnimationFrame(frame);+ editor.off("transaction", onTransaction);+ };+ }, [editor, onEmptyLine.menuRef]);return (<><BubbleMenudiff --git a/src/index.css b/src/index.cssindex 3c309a826..79f2a33bb 100644--- a/src/index.css+++ b/src/index.css@@ -1705,7 +1705,9 @@ a:hover {.rich-text-editor-content {outline: none;unicode-bidi: plaintext;- padding-block: 0.75rem 5rem;+ /* The bottom lets the last line scroll clear of the note's bottom bar, chips, callout+ and an open chat included: NoteBottomBar publishes its height. */+ padding-block: 0.75rem max(5rem, var(--bottom-overlay-height, 0px));/* Centers the text in the page column (PAGE_CONTENT_WIDTH_CLASS) with padding, not amax-width, so the editable area spans the pane and a margin click places the caret. */padding-inline: max(1.25rem, calc((100% - var(--container-5xl)) / 2 + 1.25rem));diff --git a/test/components/floatingChatLayout.test.js b/test/components/floatingChatLayout.test.jsindex fed1895bd..2975b9ce6 100644--- a/test/components/floatingChatLayout.test.js+++ b/test/components/floatingChatLayout.test.js@@ -174,6 +174,42 @@ test("the in-view chat grows to fit, up to three-quarters height, whatever its cassert.equal(disconnected, true);});+test("the bottom bar publishes the height it covers, so the editor keeps the caret above it", async () => {+ const { observeBottomBarHeight } = await load();+ const bar = createElement({ offsetHeight: 138 });+ const container = createElement();+ const observed = [];+ let onResize;+ let disconnected = false;++ const cleanup = observeBottomBarHeight({ bar, container }, (callback) => {+ onResize = callback;+ return {+ observe(element) {+ observed.push(element);+ },+ disconnect() {+ disconnected = true;+ },+ };+ });++ assert.equal(container.style.getPropertyValue("--bottom-overlay-height"), "138px");+ assert.deepEqual(observed, [bar]);++ bar.offsetHeight = 186;+ onResize();+ assert.equal(+ container.style.getPropertyValue("--bottom-overlay-height"),+ "186px",+ "follows the bar as the summary callout or the chat grows it"+ );++ cleanup();+ assert.equal(disconnected, true);+ assert.equal(container.style.getPropertyValue("--bottom-overlay-height"), "");+});+test("the note viewport caps the in-view chat in a short window", async () => {const { observeFloatingChatMaxHeight } = await load();const panel = { style: { maxHeight: "" } };diff --git a/test/components/noteEditorSummaryDeletion.test.js b/test/components/noteEditorSummaryDeletion.test.jsindex ac2f1d6e7..f6a12b980 100644--- a/test/components/noteEditorSummaryDeletion.test.js+++ b/test/components/noteEditorSummaryDeletion.test.js@@ -778,6 +778,20 @@ test("each tab has its own body editor, so undo never carries over between tabs"await unmount();});+test("the body editor sits under the bottom bar's parent, which the bar publishes its height on", async (t) => {+ // The editor keeps the caret clear of the bar by inheriting --bottom-overlay-height.+ const { render, latest, unmount } = await loadNoteEditor(t);+ await render(ENHANCEMENT);+ let barParent = null;+ walk(latest(), (node) => {+ const children = React.Children.toArray(node.props.children);+ if (!barParent && children.some((child) => child.props?.onAskSubmit)) barParent = node;+ });+ assert.ok(barParent, "the note renders its bottom bar");+ assert.ok(bodyEditor(barParent), "the body editor is inside the bar's parent");+ await unmount();+});+const CONFLICT = {id: "cloud-1",client_note_id: NOTE.client_note_id,diff --git a/test/components/richTextEditor.test.js b/test/components/richTextEditor.test.jsindex 2a41ab038..f92e14815 100644--- a/test/components/richTextEditor.test.js+++ b/test/components/richTextEditor.test.js@@ -1156,9 +1156,113 @@ test("the menus mount without error on an editor useEditor already destroyed", aReact.createElement(React.Fragment,null,- React.createElement(RichTextEditorFormatMenu, { editor }),+ React.createElement(RichTextEditorFormatMenu, {+ editor,+ lineMenuPadding: { top: 0, right: 0, bottom: 0, left: 0 },+ }),React.createElement(RichTextEditorTableMenu, { editor }))));});++const VIEWPORT = 600;+const LINE = 24;+const LONG_NOTE = Array.from({ length: 30 }, (_, index) => `Line ${index + 1}`).join("\n\n");++/**+ * happy-dom has no layout. Gives the editor's scroller a 600px viewport and every+ * top-level block a 24px line, so ProseMirror's scrollIntoView and the menus find+ * the caret where a browser would. Returns the caret's rect, relative to the+ * scroller's top.+ */+function fakeLayout(t, editor) {+ const { view } = editor;+ const scroller = view.dom.parentElement;+ // Only the scroller scrolls. happy-dom keeps a scrollTop set on any element, so+ // ProseMirror would scroll the caret's paragraph into view inside itself.+ let proto = scroller;+ while (!Object.hasOwn(proto, "scrollTop")) proto = Object.getPrototypeOf(proto);+ const scrollTopDescriptor = Object.getOwnPropertyDescriptor(proto, "scrollTop");+ let scrollTop = 0;+ Object.defineProperty(proto, "scrollTop", {+ configurable: true,+ get() {+ return this === scroller ? scrollTop : 0;+ },+ set(value) {+ if (this === scroller) scrollTop = Math.max(0, value);+ },+ });+ // Floating UI keeps the menus inside the window, which happy-dom gives no size.+ // The scroller reaches the window's bottom, as the note view does.+ const { documentElement } = happyWindow.document;+ Object.defineProperty(documentElement, "clientWidth", { value: 1024, configurable: true });+ Object.defineProperty(documentElement, "clientHeight", { value: VIEWPORT, configurable: true });+ t.after(() => {+ Object.defineProperty(proto, "scrollTop", scrollTopDescriptor);+ delete documentElement.clientWidth;+ delete documentElement.clientHeight;+ });+ const box = { x: 0, y: 0, left: 0, top: 0, right: 800, bottom: VIEWPORT, width: 800 };+ scroller.getBoundingClientRect = () => ({ ...box, height: VIEWPORT });+ const size = {+ clientWidth: 800,+ offsetWidth: 800,+ clientHeight: VIEWPORT,+ offsetHeight: VIEWPORT,+ };+ for (const [name, value] of Object.entries(size)) {+ Object.defineProperty(scroller, name, { value, configurable: true });+ }+ view.coordsAtPos = (pos) => {+ const top = view.state.doc.resolve(pos).index(0) * LINE - scroller.scrollTop;+ return { left: 40, right: 40, top, bottom: top + LINE };+ };+ return () => view.coordsAtPos(view.state.selection.head);+}++test("typing at the end of a long note keeps the caret clear of the note's bottom bar", async (t) => {+ const notes = await mountNotes(t, LONG_NOTE);+ const caret = fakeLayout(t, notes.editor());+ const clearance = () => VIEWPORT - caret().bottom;+ const enter = () => notes.act(() => pressKey(notes.editor(), "Enter"));+ await notes.act(() => notes.editor().commands.focus("end"));++ await enter();+ assert.equal(clearance(), 5, "with nothing over the editor, ProseMirror's usual margin");++ // NoteBottomBar publishes its height on an ancestor, and a browser inherits it+ // down to the editor. happy-dom doesn't inherit custom properties.+ notes.host.firstElementChild.style.setProperty("--bottom-overlay-height", "138px");+ for (let line = 1; line <= 3; line++) {+ await enter();+ assert.equal(clearance(), 138, `new line ${line} sits just above the bar`);+ }+ assert.deepEqual(notes.errors, []);+});++test("the empty-line toolbar stays on the caret when Enter scrolls the note, above it over the bar", async (t) => {+ const notes = await mountNotes(t, LONG_NOTE);+ const caret = fakeLayout(t, notes.editor());+ const scroller = notes.editor().view.dom.parentElement;+ await notes.act(() => notes.editor().commands.focus("end"));+ const scrolledBefore = scroller.scrollTop;++ await notes.act(() => pressKey(notes.editor(), "Enter"));+ assert.ok(scroller.scrollTop > scrolledBefore, "Enter scrolled the editor");+ const menu = happyWindow.document.querySelector(".rich-text-editor-line-menu");+ assert.equal(!!menu?.isConnected, true, "the toolbar shows on the new empty line");+ // Floating UI finds no offset parent in happy-dom, so it places the toolbar in+ // viewport coordinates: below the caret, Tiptap's 8px offset away.+ const top = () => parseFloat(menu.style.top);+ assert.equal(top(), caret().bottom + 8);++ // The caret now stops just above the bar, which leaves the toolbar no room below.+ const height = 40;+ Object.defineProperty(menu, "offsetHeight", { value: height, configurable: true });+ notes.host.firstElementChild.style.setProperty("--bottom-overlay-height", "138px");+ await notes.act(() => pressKey(notes.editor(), "Enter"));+ assert.ok(top() + height <= caret().top, `above the caret, not under the bar (top ${top()})`);+ assert.deepEqual(notes.errors, []);+});