Files
outline/app/editor/components/SelectionToolbar.tsx
T
Tom MoorandClaude Opus 5 f6ad3cb6e1 Improvements to mobile formatting toolbar (#13533)
* fix: Selection toolbar not displaying on mobile

The mobile branch of FloatingToolbar rendered nothing until `position.visible`
was true, but `usePosition` only reports a visible position once the menu
element has been measured through `menuRef`. On desktop the wrapper is always
mounted (it animates in via opacity) so the ref is populated on first render,
while on mobile the toolbar is the only thing that mounts the ref — leaving it
permanently null and the bar never displayed.

Gate the mobile bar on there being toolbar content instead. Position is
irrelevant on mobile: the bar is fixed to the bottom of the viewport and its
vertical offset is owned by useKeyboardStickyOffset.

Also size the bar with border-box and center its content vertically, so the
declared 60px is the height of the bar rather than 60px of content plus
padding with the buttons pinned to the top.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhGyxA663bMFZ1NxBhLAoF

* fix: Keep the mobile selection toolbar visible while editing

On mobile the toolbar is a bar docked above the on-screen keyboard rather than
a floating menu anchored to the selection, but it was only rendered while
something was selected — so it appeared and vanished as the selection came and
went while typing.

The formatting menu was already written for this: `canFormatBlock` shows
headings, quotes, toggles and list indent/outdent precisely when the selection
is empty on mobile, mirroring `canFormatInline` for selected text. That branch
was unreachable, as an empty selection always resolved the toolbar to nothing.

Show the menu whenever the editor is focused on mobile, so the bar carries
block formatting for a bare cursor and swaps to inline formatting on selection.
Visibility is derived at render rather than folded into `activeToolbar` so that
focus moving into the link editor's input cannot tear down a toolbar the user
opened. Focus is threaded to widgets through WidgetProps.

Tapping the bar now also prevents the default action of mousedown, keeping
focus (and the keyboard) in the editor. Without it a tap would blur the editor
and unmount the bar before the tap became a click; fields inside the bar are
excluded so the link editor still takes focus.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhGyxA663bMFZ1NxBhLAoF

* fix: Mobile toolbar is not visible

* Update mobile toolbar styling
fix: Does not account for stored marks

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-23 11:20:30 -04:00

341 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { EditorState, Selection } from "prosemirror-state";
import Suggestion from "~/editor/extensions/Suggestion";
import { NodeSelection, TextSelection } from "prosemirror-state";
import * as React from "react";
import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators";
import { buildSelectionContext } from "@shared/editor/lib/buildSelectionContext";
import {
getMarkRange,
getMarkRangeNodeSelection,
} from "@shared/editor/queries/getMarkRange";
import { isInCode } from "@shared/editor/queries/isInCode";
import { isInNotice } from "@shared/editor/queries/isInNotice";
import { MenuType, type MenuItem } from "@shared/editor/types";
import useBoolean from "~/hooks/useBoolean";
import useEventListener from "~/hooks/useEventListener";
import useMobile from "~/hooks/useMobile";
import {
columnDragPluginKey,
rowDragPluginKey,
} from "@shared/editor/plugins/TableDragState";
import { useEditor } from "./EditorContext";
import { MediaLinkEditor } from "./MediaLinkEditor";
import FloatingToolbar from "./FloatingToolbar";
import LinkEditor from "./LinkEditor";
import ToolbarMenu from "./ToolbarMenu";
import InlineMenu from "./InlineMenu";
import StickyBlockToolbar from "./StickyBlockToolbar";
import { isModKey } from "@shared/utils/keyboard";
type Props = {
/** Whether the text direction is right-to-left */
rtl: boolean;
/** Whether the current document is a template */
isTemplate: boolean;
/** Whether the toolbar is currently active/visible */
isActive: boolean;
/** Whether the editor currently holds focus */
isEditorFocused: boolean;
/** The current selection */
selection?: Selection;
/** Whether the editor is in read-only mode */
readOnly?: boolean;
/** Whether the user has permission to add comments */
canComment?: boolean;
/** Whether the user has permission to update the document */
canUpdate?: boolean;
};
function useIsDragging(state: EditorState) {
const [isDragging, setDragging, setNotDragging] = useBoolean();
useEventListener("dragstart", setDragging);
useEventListener("dragend", setNotDragging);
useEventListener("drop", setNotDragging);
const columnDragState = columnDragPluginKey.getState(state);
const rowDragState = rowDragPluginKey.getState(state);
const isTableDragging =
columnDragState?.isDragging || rowDragState?.isDragging;
return isDragging || isTableDragging;
}
enum Toolbar {
Link = "link",
Media = "media",
Menu = "menu",
}
export function SelectionToolbar(props: Props) {
const { readOnly = false, isEditorFocused } = props;
const { view, extensions, commands, selectionToolbarMenus } = useEditor();
const menuRef = React.useRef<HTMLDivElement | null>(null);
const isMobile = useMobile();
const isActive = props.isActive || isMobile;
// On mobile the toolbar is docked above the on-screen keyboard, so it stays
// visible for as long as the editor is being edited rather than only while
// there is a selection.
const isMobileEditing = isMobile && !readOnly && isEditorFocused;
const { state } = view;
const [autoFocusLinkInput, setAutoFocusLinkInput] = React.useState(false);
const isDragging = useIsDragging(state);
const { selection } = state;
const [activeToolbar, setActiveToolbar] = React.useState<Toolbar | null>(
null
);
const linkMark =
selection instanceof NodeSelection
? getMarkRangeNodeSelection(selection, state.schema.marks.link)
: getMarkRange(selection.$from, state.schema.marks.link);
const isEmbedSelection =
selection instanceof NodeSelection && selection.node.type.name === "embed";
const isCodeSelection = isInCode(state, { onlyBlock: true });
const isNoticeSelection = isInNotice(state);
React.useLayoutEffect(() => {
if (!isActive) {
setActiveToolbar(null);
return;
}
if (isEmbedSelection && !readOnly) {
setActiveToolbar(Toolbar.Media);
} else if (
linkMark &&
(activeToolbar === null || activeToolbar === Toolbar.Link) &&
!readOnly
) {
setActiveToolbar(Toolbar.Link);
} else if (isCodeSelection) {
setActiveToolbar(Toolbar.Menu);
} else if (!selection.empty) {
setActiveToolbar(Toolbar.Menu);
} else if (isNoticeSelection && selection.empty) {
setActiveToolbar(Toolbar.Menu);
} else if (selection.empty) {
setActiveToolbar(null);
}
// `activeToolbar` is read to decide whether the link toolbar should stay
// open, re-running when it changes would fight the user's own selection.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
readOnly,
isActive,
selection,
linkMark,
isEmbedSelection,
isCodeSelection,
isNoticeSelection,
]);
// Focus is re-armed when the link editor closes rather than whenever the
// active toolbar isn't the link editor – the two pieces of state are not
// always updated in the same render.
const prevActiveToolbar = React.useRef(activeToolbar);
React.useLayoutEffect(() => {
if (
prevActiveToolbar.current === Toolbar.Link &&
activeToolbar !== Toolbar.Link
) {
setAutoFocusLinkInput(false);
if (!readOnly && isActive) {
view.focus();
}
}
prevActiveToolbar.current = activeToolbar;
}, [activeToolbar, readOnly, isActive, view]);
React.useLayoutEffect(() => {
const handleClickOutside = (ev: MouseEvent): void => {
if (
ev.target instanceof HTMLElement &&
menuRef.current &&
menuRef.current.contains(ev.target)
) {
return;
}
if (view.dom.contains(ev.target as HTMLElement)) {
return;
}
if (!isActive || document.activeElement?.tagName === "INPUT") {
return;
}
const isSuggestionMenuOpen = extensions.extensions.some(
(ext) => ext instanceof Suggestion && ext.isOpen
);
if (isSuggestionMenuOpen) {
return;
}
if (!window.getSelection()?.isCollapsed) {
return;
}
const { dispatch } = view;
dispatch(
view.state.tr.setSelection(
TextSelection.near(view.state.doc.resolve(0))
)
);
};
window.addEventListener("mouseup", handleClickOutside);
return () => {
window.removeEventListener("mouseup", handleClickOutside);
};
}, [isActive, readOnly, view, extensions]);
useEventListener(
"keydown",
(ev: KeyboardEvent) => {
if (
isModKey(ev) &&
ev.key.toLowerCase() === "k" &&
!view.state.selection.empty
) {
ev.preventDefault();
ev.stopPropagation();
setAutoFocusLinkInput(true);
setActiveToolbar(Toolbar.Link);
}
},
view.dom,
{ capture: true }
);
if (isDragging) {
return null;
}
const { isTemplate, rtl, canComment, canUpdate, ...rest } = props;
// Build selection context once, shared across all menu matchers
const ctx = buildSelectionContext(state, { readOnly, isTemplate, rtl });
// Find the first matching menu from the registry (sorted by priority)
const matched = selectionToolbarMenus.find((menu) => menu.matches(ctx));
let items: MenuItem[] = matched ? matched.getItems(ctx) : [];
const align = matched?.align ?? "center";
// Filter out items for disabled extensions or invisible items
items = items.filter((item) => {
if (item.name === "separator") {
return true;
}
if (item.name === "dimensions") {
return item.visible ?? false;
}
if (item.name && !commands[item.name]) {
return false;
}
if (item.visible === false) {
return false;
}
return true;
});
items = filterExcessSeparators(items);
items = items.map((item) => {
if (item.children && Array.isArray(item.children)) {
item.children = item.children.map((child) => {
if (child.name === "editImageUrl") {
child.onClick = () => {
setActiveToolbar(Toolbar.Media);
};
}
return child;
});
}
if (item.name === "linkOnImage" || item.name === "addLink") {
item.onClick = () => {
setAutoFocusLinkInput(true);
setActiveToolbar(Toolbar.Link);
};
}
return item;
});
const handleClickOutsideLinkEditor = (ev: MouseEvent | TouchEvent) => {
if (ev.target instanceof Element && ev.target.closest(".image-wrapper")) {
return;
}
setActiveToolbar(null);
};
// Inline menus render as a vertical menu anchored to the selection rather
// than as a horizontal toolbar with trigger buttons.
if (
matched?.variant === MenuType.inline &&
activeToolbar === Toolbar.Menu &&
items.length
) {
return <InlineMenu items={items} rtl={rtl} />;
}
// Block toolbars (code, notice) stick to the top of the viewport as the block
// scrolls instead of floating at a position fixed on selection. On mobile the
// floating toolbar renders as a bottom bar, so the sticky path is desktop only.
if (
matched?.sticky &&
!isMobile &&
activeToolbar === Toolbar.Menu &&
items.length
) {
return <StickyBlockToolbar ref={menuRef} items={items} rtl={rtl} />;
}
return (
<FloatingToolbar
align={align}
active={isActive}
ref={menuRef}
width={
activeToolbar === Toolbar.Link || activeToolbar === Toolbar.Media
? 336
: undefined
}
>
{activeToolbar === Toolbar.Link ? (
<LinkEditor
key={`link-${selection.anchor}`}
autoFocus={autoFocusLinkInput}
view={view}
mark={linkMark ? linkMark.mark : undefined}
onLinkAdd={() => setActiveToolbar(null)}
onLinkUpdate={() => setActiveToolbar(null)}
onLinkRemove={() => setActiveToolbar(null)}
onEscape={() => setActiveToolbar(Toolbar.Menu)}
onClickOutside={handleClickOutsideLinkEditor}
onClickBack={() => setActiveToolbar(Toolbar.Menu)}
/>
) : activeToolbar === Toolbar.Media ? (
<MediaLinkEditor
key={`embed-${selection.anchor}`}
node={
"node" in selection ? (selection as NodeSelection).node : undefined
}
view={view}
onLinkUpdate={() => setActiveToolbar(null)}
onLinkRemove={() => setActiveToolbar(null)}
onEscape={() => setActiveToolbar(Toolbar.Menu)}
onClickOutside={handleClickOutsideLinkEditor}
/>
) : (activeToolbar === Toolbar.Menu || isMobileEditing) &&
items.length ? (
<ToolbarMenu items={items} {...rest} />
) : null}
</FloatingToolbar>
);
}