Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(mobile): comments in documents (#6121)

Peter Chinman7faf3da72985
diff --git a/apps/web/src/components/app/mobile/MobileDrawer.tsx b/apps/web/src/components/app/mobile/MobileDrawer.tsx
index 49bf6f23c8..fae61d8a58 100644
--- a/apps/web/src/components/app/mobile/MobileDrawer.tsx
+++ b/apps/web/src/components/app/mobile/MobileDrawer.tsx
@@ -87,10 +87,17 @@ function MobileDrawerContent(
}}
class={cn(
'portal-scope',
- 'bottom-(--virtual-keyboard-height,0) fixed inset-x-0 z-modal bg-surface rounded-t-2xl flex flex-col max-h-(--drawer-max-h) data-transitioning:transition-transform data-transitioning:duration-200 ease-out',
+ 'bottom-0 fixed inset-x-0 z-modal bg-surface rounded-t-2xl flex flex-col max-h-(--drawer-max-h) data-transitioning:transition-transform data-transitioning:duration-200 ease-out',
targetHeight() != null ? 'h-(--drawer-h)' : 'h-fit',
virtualKeyboardVisible()
- ? 'pb-0 max-h-[calc(var(--drawer-max-h)-var(--virtual-keyboard-height))] overflow-y-auto'
+ ? [
+ 'pb-(--virtual-keyboard-height) max-h-[calc(100vh-var(--safe-top))] overflow-y-auto',
+ // A fixed-height drawer grows by the keyboard so its content
+ // keeps its designed height; a fit-content drawer has no
+ // --drawer-h and just clamps.
+ targetHeight() != null &&
+ 'h-[min(calc(100vh-var(--safe-top)),calc(var(--drawer-h)+var(--virtual-keyboard-height)))]',
+ ]
: 'pb-(--safe-bottom) has-[[data-drawer-scroll-body]]:pb-0',
local.class
)}
diff --git a/apps/web/src/components/ui/components/Dropdown.tsx b/apps/web/src/components/ui/components/Dropdown.tsx
index 92dbeaa96c..3a7886c63e 100644
--- a/apps/web/src/components/ui/components/Dropdown.tsx
+++ b/apps/web/src/components/ui/components/Dropdown.tsx
@@ -1,3 +1,4 @@
+import { isModality } from '@core/mobile/inputModality';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { DropdownMenu as KobalteDropdownMenu } from '@kobalte/core/dropdown-menu';
import CheckIcon from '@phosphor/check.svg';
@@ -181,7 +182,8 @@ function DropdownContent(props: DropdownContentProps) {
]);
const handleOpenAutoFocus = (event: Event) => {
local.onOpenAutoFocus?.(event);
- if (!event.defaultPrevented && contentRef) {
+ // A tap-opened menu shouldn't start with a hover-like highlight
+ if (!event.defaultPrevented && contentRef && !isModality('touch')) {
highlightFirstMenuItemOnOpen(contentRef);
}
};
diff --git a/apps/web/src/features/block-md/comments/CommentMargin.tsx b/apps/web/src/features/block-md/comments/CommentMargin.tsx
index 7a090e013a..07a099a593 100644
--- a/apps/web/src/features/block-md/comments/CommentMargin.tsx
+++ b/apps/web/src/features/block-md/comments/CommentMargin.tsx
@@ -14,6 +14,7 @@ import {
Thread,
} from '@core/comments/Thread';
import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useCanComment, useIsDocumentOwner } from '@core/signal/permissions';
import { autoUpdate, computePosition } from '@floating-ui/dom';
import {
@@ -24,6 +25,7 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import { CommentThreadDrawer } from './CommentThreadDrawer';
import {
notebookHeight,
threadHeightStore,
@@ -115,7 +117,11 @@ export const CommentMargin = () => {
const commentsContext = useCommentsContext();
- const isMinimized = createMemo(() => !wideEnoughForComments());
+ // Touch devices never expand floating thread cards; the active thread is
+ // presented in the CommentThreadDrawer instead.
+ const isMinimized = createMemo(
+ () => isTouchDevice() || !wideEnoughForComments()
+ );
return (
<CommentsContext.Provider value={commentsContext}>
@@ -137,6 +143,7 @@ export const CommentMargin = () => {
layout={layout()}
isActive={isActiveSelector(thread().threadId)}
maxHeight={maxHeight()}
+ expandable={!isTouchDevice()}
/>
}
>
@@ -156,6 +163,9 @@ export const CommentMargin = () => {
)}
</For>
</div>
+ <Show when={isTouchDevice()}>
+ <CommentThreadDrawer />
+ </Show>
</CommentsContext.Provider>
);
};
diff --git a/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx b/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx
new file mode 100644
index 0000000000..19d47e1ca8
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx
@@ -0,0 +1,306 @@
+import {
+ activeCommentThreadSignal,
+ highlightedCommentThreadsSignal,
+ markStore,
+ threadStore,
+} from '@block-md/comments/commentStore';
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import {
+ MobileDrawer,
+ scrollToFocusedInput,
+} from '@components/app/mobile/MobileDrawer';
+import { getAndClearCommentMentions } from '@core/comments';
+import type { CommentOperations, Root } from '@core/comments/commentType';
+import { NewReplyInput } from '@core/comments/Inputs';
+import {
+ CommentsContext,
+ ThreadBody,
+ ThreadContext,
+} from '@core/comments/Thread';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { createTheme } from '@core/component/LexicalMarkdown/theme';
+import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
+import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import { Button } from '@ui';
+import { $setSelection } from 'lexical';
+import { createMemo, createSignal, Show, useContext } from 'solid-js';
+
+/**
+ * `baseCommentTheme` minus its `select-text` on message text. The drawer is
+ * `select-none` — a press-and-hold on message text would otherwise start the
+ * iOS selection gesture (magnifier loupe), and corvu aborts drag-to-dismiss
+ * while any DOM selection exists — but an explicit select-text on the text
+ * spans would win over the parent's select-none, so the theme must not
+ * stamp it. Typing areas opt back in via the drawer's contenteditable rule.
+ */
+const drawerCommentTheme = createTheme({ root: 'text-sm' });
+
+/**
+ * Focus target for the drawer's opening focus pass: the draft composer's
+ * editable, when one is mounted. An existing thread renders only the
+ * "Reply…" placeholder (no editable), so viewing a thread doesn't raise the
+ * keyboard while composing a new comment does.
+ */
+function getCommentComposerInput(): HTMLElement | null {
+ return document.querySelector<HTMLElement>(
+ '[data-comment-thread-drawer] [contenteditable="true"]'
+ );
+}
+
+/**
+ * The drawer's always-visible reply composer, pinned below the scrolling
+ * thread. Extracted so its state (text, mentions) resets when the pager
+ * switches threads (the host keys it by thread). Provides its own
+ * ThreadContext so @-mentions typed here are captured.
+ */
+function PinnedReplyComposer(props: {
+ root: Root;
+ createComment: CommentOperations['createComment'];
+}) {
+ const mentionsSignal = createSignal<UserMentionRecord[]>([]);
+ const [text, setText] = createSignal('');
+ const [editing, setEditing] = createSignal(false);
+
+ return (
+ <ThreadContext.Provider value={{ mentionsSignal }}>
+ <StaticMarkdownContext theme={drawerCommentTheme}>
+ <div
+ class="shrink-0 px-3"
+ classList={{ 'pb-(--safe-bottom)': !virtualKeyboardVisible() }}
+ >
+ <NewReplyInput
+ textValue={text()}
+ setTextValue={setText}
+ isEditing={editing()}
+ setEditing={setEditing}
+ deactivateThreadOnCancel={false}
+ createReply={(content) => {
+ if (content.trim() === '') return;
+ setEditing(false);
+ return props.createComment({
+ threadId: props.root.threadId,
+ text: content,
+ mentions: getAndClearCommentMentions(mentionsSignal),
+ });
+ }}
+ />
+ </div>
+ </StaticMarkdownContext>
+ </ThreadContext.Provider>
+ );
+}
+
+/**
+ * Bottom-sheet presentation of the active comment thread for touch devices,
+ * replacing the floating margin cards used with a pointer. Opens on explicit
+ * activation only — the selection toolbar's "Show comment", a minimized rail
+ * icon, creating a draft comment, or URL navigation; placing the caret in a
+ * commented range merely highlights it. When the document holds several
+ * threads, a pager bar steps between them in document order. Dismissing the
+ * drawer deactivates the thread, which also discards an unsent draft.
+ *
+ * Must be mounted inside the `CommentsContext` provider (see CommentMargin).
+ */
+export function CommentThreadDrawer() {
+ const threads = threadStore.get;
+ const [marks] = markStore;
+ const md = mdStore.get;
+
+ const activeCommentThread = activeCommentThreadSignal.get;
+ const setActiveCommentThread = activeCommentThreadSignal.set;
+ const setHighlightedCommentThreads = highlightedCommentThreadsSignal.set;
+
+ const parentCommentsContext = useContext(CommentsContext);
+ // Messages report their inline-edit state; while any edit input is open,
+ // the pinned reply composer hides so two inputs never compete.
+ const [editingMessageIds, setEditingMessageIds] = createSignal<
+ ReadonlySet<number>
+ >(new Set());
+ const messageEditing = () => editingMessageIds().size > 0;
+ const drawerCommentsContext = {
+ ...parentCommentsContext,
+ setMessageEditing: (commentId: number, editing: boolean) =>
+ setEditingMessageIds((prev) => {
+ if (prev.has(commentId) === editing) return prev;
+ const next = new Set(prev);
+ if (editing) next.add(commentId);
+ else next.delete(commentId);
+ return next;
+ }),
+ };
+
+ const activeRoot = createMemo<Root | undefined>(() => {
+ const active = activeCommentThread();
+ return active == null ? undefined : threads[active];
+ });
+
+ const firstMarkElement = (root: Root) =>
+ Object.values(marks[root.anchorId]?.markNodes ?? {})[0];
+
+ // Server threads in document order, from their marks' positions (viewport
+ // rects preserve relative document order; this works with the margin
+ // hidden, since marks live in the editor itself).
+ const orderedThreadIds = createMemo(() => {
+ return Object.values(threads)
+ .filter((root): root is Root => !!root && root.threadId !== -1)
+ .map((root) => {
+ const rect = firstMarkElement(root)?.getBoundingClientRect();
+ return {
+ threadId: root.threadId,
+ top: rect?.top ?? Number.MAX_SAFE_INTEGER,
+ left: rect?.left ?? 0,
+ };
+ })
+ .sort((a, b) => a.top - b.top || a.left - b.left)
+ .map((entry) => entry.threadId);
+ });
+
+ const pagerIndex = createMemo(() => {
+ const active = activeCommentThread();
+ return active == null ? -1 : orderedThreadIds().indexOf(active);
+ });
+
+ // The pager applies to saved threads only — a draft (-1) is mid-compose.
+ const showPager = () => pagerIndex() >= 0 && orderedThreadIds().length > 1;
+
+ const goToThread = (direction: 1 | -1) => {
+ const ids = orderedThreadIds();
+ const target = ids[pagerIndex() + direction];
+ if (target == null) return;
+ // Leaving the caret in the previous thread's mark would let the
+ // selection-sync effect null the newly activated thread on the next
+ // editor update (see CommentsProvider) — and the old selection has
+ // served its purpose anyway.
+ md.editor?.update(() => $setSelection(null));
+ setActiveCommentThread(target);
+ setHighlightedCommentThreads([target]);
+ const root = threads[target];
+ if (root) {
+ firstMarkElement(root)?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'center',
+ });
+ }
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ if (open) return;
+ // The dismissing tap lands on the drawer overlay, so the editor's
+ // selection still sits inside the comment mark. Clear it so tapping the
+ // highlight again registers as a selection change and reopens the drawer.
+ md.editor?.update(() => $setSelection(null));
+ setActiveCommentThread(null);
+ setHighlightedCommentThreads([]);
+ };
+
+ return (
+ <MobileDrawer
+ side="bottom"
+ // Opens only on explicit activation (the toolbar's "Show comment", a
+ // rail icon, a new draft, or URL navigation) — merely placing the
+ // caret inside a commented range only highlights the thread, and the
+ // selection toolbar offers to open it instead.
+ open={activeRoot() != null}
+ onOpenChange={handleOpenChange}
+ closeOnOutsidePointerStrategy="pointerdown"
+ preventScroll={false}
+ preventScrollbarShift={false}
+ initialFocusEl={getCommentComposerInput() ?? undefined}
+ >
+ <MobileDrawer.Portal>
+ <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />
+ <MobileDrawer.Content
+ aria-label="Comments"
+ // Viewing a thread opens at a fixed half-screen height — short
+ // threads leave space, long ones scroll inside. A new-comment
+ // draft is just the composer, so it fits its content instead.
+ targetHeight={activeRoot()?.isNew ? undefined : 50}
+ // select-none: a press-and-hold on message text would start an
+ // iOS text-selection gesture (magnifier loupe), which claims the
+ // touch and cancels corvu's drag-to-dismiss (corvu aborts drags
+ // while any DOM selection exists). Typing areas opt back in.
+ class="select-none [&_[contenteditable=true]]:select-text"
+ data-comment-thread-drawer
+ >
+ <MobileDrawer.Handle class="pb-1" />
+ <Show when={showPager()}>
+ <div class="flex shrink-0 items-center justify-center gap-2 pb-1">
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ aria-label="Previous comment thread"
+ disabled={pagerIndex() <= 0}
+ onClick={() => goToThread(-1)}
+ >
+ <CaretLeftIcon class="size-4" />
+ </Button>
+ <span class="text-xs text-ink-muted">
+ {pagerIndex() + 1} of {orderedThreadIds().length}
+ </span>
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ aria-label="Next comment thread"
+ disabled={pagerIndex() >= orderedThreadIds().length - 1}
+ onClick={() => goToThread(1)}
+ >
+ <CaretRightIcon class="size-4" />
+ </Button>
+ </div>
+ </Show>
+ <MobileDrawer.ScrollBody
+ class="px-3"
+ // The ScrollBody is the drawer's scroll container, so the
+ // built-in Content-level handler can't scroll it — bring a
+ // focused composer into view above the rising keyboard here
+ // (same pattern as the mobile email composer).
+ onFocusIn={(e: FocusEvent) => scrollToFocusedInput(e)}
+ >
+ <CommentsContext.Provider value={drawerCommentsContext}>
+ <Show when={activeRoot()} keyed>
+ {(root) => (
+ <div class="shrink-0">
+ <ThreadBody
+ comment={root}
+ isActive
+ theme={drawerCommentTheme}
+ hideReplyInput
+ actionsDropdown
+ />
+ </div>
+ )}
+ </Show>
+ </CommentsContext.Provider>
+ </MobileDrawer.ScrollBody>
+ <Show
+ when={
+ !activeRoot()?.isNew &&
+ parentCommentsContext.canComment() &&
+ activeRoot()
+ }
+ keyed
+ >
+ {(root) => (
+ // Hidden, not unmounted, while a message edit is open — an
+ // in-progress reply draft survives the edit.
+ <div classList={{ hidden: messageEditing() }}>
+ <PinnedReplyComposer
+ root={root}
+ createComment={
+ parentCommentsContext.commentOperations.createComment
+ }
+ />
+ </div>
+ )}
+ </Show>
+ </MobileDrawer.Content>
+ </MobileDrawer.Portal>
+ </MobileDrawer>
+ );
+}
diff --git a/apps/web/src/features/block-md/comments/CommentsProvider.tsx b/apps/web/src/features/block-md/comments/CommentsProvider.tsx
index 3cb733cdd4..b3980a75b1 100644
--- a/apps/web/src/features/block-md/comments/CommentsProvider.tsx
+++ b/apps/web/src/features/block-md/comments/CommentsProvider.tsx
@@ -198,7 +198,13 @@ export const CommentsProvider: VoidComponent<{
}
}
- activeCommentThreadSignal.set(null);
+ // Keep an explicitly activated thread (e.g. the touch toolbar's
+ // "Show comment") active while the caret still sits in its mark — this
+ // effect re-runs on every editor update, and clobbering it would snap
+ // the comment drawer shut right after it opens.
+ activeCommentThreadSignal.set((current) =>
+ current != null && threadIds.includes(current) ? current : null
+ );
highlightedCommentThreadsSignal.set(threadIds);
});
diff --git a/apps/web/src/features/block-md/comments/commentOperations.ts b/apps/web/src/features/block-md/comments/commentOperations.ts
index b58236132a..f75ec9e8b5 100644
--- a/apps/web/src/features/block-md/comments/commentOperations.ts
+++ b/apps/web/src/features/block-md/comments/commentOperations.ts
@@ -9,13 +9,16 @@ import {
DISCARD_DRAFT_COMMENT_COMMAND,
SET_COMMENT_THREAD_ID_COMMAND,
} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
+import { isMobile } from '@core/mobile/isMobile';
import { blockElementSignal } from '@core/signal/blockElement';
import type {
CreateCommentRequest,
EditCommentRequest,
} from '@service-storage/generated/schemas';
import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';
+import { until } from '@solid-primitives/promise';
import { createCallback } from '@solid-primitives/rootless';
+import { onCleanup } from 'solid-js';
import {
activeCommentThreadSignal,
commentsStore,
@@ -165,6 +168,17 @@ export const useSetNodeCommentThreadId = () => {
export function useScrollToCommentThread() {
const blockElement = blockElementSignal.get;
const documentId = useBlockId();
+ // Captured at setup: block stores resolve their block context at access
+ // time, which the returned callback no longer has.
+ const threads = threadStore.get;
+ const [marks] = markStore;
+ // At most one mobile wait-for-mark may be outstanding — a newer deep
+ // link supersedes an older still-pending one, so a slow-syncing thread
+ // can't later yank the scroll and the active thread away from the one
+ // the user navigated to last. Registered here at setup (under the
+ // component's owner) so an unresolved wait also dies with the block.
+ let disposePendingWait: (() => void) | undefined;
+ onCleanup(() => disposePendingWait?.());
const scrollIntoView = (el: HTMLElement) => {
el.scrollIntoView({
@@ -175,6 +189,31 @@ export function useScrollToCommentThread() {
};
return async (threadId: number) => {
+ // On phones the margin is display:none (the drawer is the only comment
+ // surface), so its measure containers can't be scrolled to. Scroll to
+ // the thread's mark in the editor itself. On a cold-load deep link the
+ // comment stores populate after this runs — `until` awaits exactly
+ // that: it re-evaluates the condition as the stores change and
+ // resolves once the thread's mark has a rendered element. Disposing
+ // the wait (a newer link superseding it, or the block unmounting via
+ // the onCleanup above) rejects it, which the catch turns into a no-op.
+ if (isMobile()) {
+ disposePendingWait?.();
+ const wait = until(() => {
+ const anchorId = threads[threadId]?.anchorId;
+ return anchorId != null
+ ? Object.values(marks[anchorId]?.markNodes ?? {})[0]
+ : undefined;
+ });
+ disposePendingWait = wait.dispose;
+ const markElement = await wait.catch(() => undefined);
+ // A cancelled wait resolves undefined — report it so the caller
+ // skips activating the superseded/unmounted link's thread.
+ if (!markElement) return false;
+ markElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ return true;
+ }
+
const measureContainerId = threadMeasureContainerId(documentId, threadId);
let measureContainer = document.getElementById(measureContainerId);
const blockEl = blockElement();
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index fb497e85df..9ae5e27e59 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -1,5 +1,10 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { applyAiOps } from '@block-md/ai-edit/applyAiOps';
+import {
+ activeCommentThreadSignal,
+ highlightedCommentThreadsSignal,
+} from '@block-md/comments/commentStore';
+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useIsAuthenticated } from '@core/auth';
import { useBlockId } from '@core/block';
@@ -25,6 +30,10 @@ import {
CONVERT_CHECKBOXES_TO_TASKS,
isCheckboxToTaskPluginEnabled,
} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task';
+import {
+ $getMarkIdsAtCaret,
+ CREATE_DRAFT_COMMENT_COMMAND,
+} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
import {
$getLocationUrl,
$getSelectionLocation,
@@ -44,7 +53,11 @@ import {
INLINE_AI_EDITING_OVERRIDE,
} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
-import { isMobile } from '@core/mobile/isMobile';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import {
+ readNativePasteboardText,
+ setNativeEditMenuSuppressed,
+} from '@core/mobile/nativeEditMenu';
import { useCanComment, useCanEdit } from '@core/signal/permissions';
import { createMarkdownFile } from '@core/util/create';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
@@ -72,7 +85,14 @@ import { generateTitle } from '@service-cognition/client';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import { createCallback } from '@solid-primitives/rootless';
import { Button, Layer } from '@ui';
-import { $getRoot, COMMAND_PRIORITY_HIGH, type RangeSelection } from 'lexical';
+import {
+ $getRoot,
+ $getSelection,
+ $isRangeSelection,
+ $setSelection,
+ COMMAND_PRIORITY_HIGH,
+ type RangeSelection,
+} from 'lexical';
import {
createEffect,
createMemo,
@@ -86,6 +106,7 @@ import {
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { FormatTools } from './FormatTools';
+import { TouchSelectionToolbar } from './TouchSelectionToolbar';
const MENU_ID = 'markdown-popup';
@@ -125,6 +146,10 @@ export function MarkdownPopup(props: {
createSignal<PersistentLocation | null>(null);
const [aiEditRunning, setAiEditRunning] = createSignal(false);
const [aiInputFocused, setAiInputFocused] = createSignal(false);
+ // On touch devices the AI-edit instruction is typed in a drawer instead of
+ // the popup's inline input; the drawer outlives the popup.
+ const [aiEditDrawerOpen, setAiEditDrawerOpen] = createSignal(false);
+ const [aiEditInput, setAiEditInput] = createSignal('');
onMount(() => {
const onKeyDown = (e: KeyboardEvent) => {
@@ -148,12 +173,33 @@ export function MarkdownPopup(props: {
popupPlugin({
setIsPopupVisible: setPopupVisible,
setSelection: setSelectionAndHighlight,
+ // On touch, a caret touching a commented range shows the toolbar so
+ // its "Show comment" can open the thread — tapping a highlight no
+ // longer opens it directly.
+ $allowEmptySelection: (lexicalSelection) => {
+ if (!isTouchDevice()) return false;
+ return (
+ $getMarkIdsAtCaret(
+ lexicalSelection.anchor.getNode(),
+ lexicalSelection.anchor.offset
+ ) != null
+ );
+ },
})
);
// The actual control value for showPopup lags.
const showPopup = debouncedDependent(popupVisible, 100);
+ // Keep the native iOS selection menu from stacking on top of the popup;
+ // the popup carries copy/cut/paste itself while suppression is active.
+ createEffect(() => {
+ setNativeEditMenuSuppressed(popupVisible());
+ });
+ onCleanup(() => {
+ setNativeEditMenuSuppressed(false);
+ });
+
const canEdit = useCanEdit();
const inlineAiEditing = useFeatureFlag(INLINE_AI_EDITING_FLAG, {
enabledOverride: INLINE_AI_EDITING_OVERRIDE,
@@ -161,6 +207,9 @@ export function MarkdownPopup(props: {
const canComment = useCanComment();
const currentUserId = useUserId();
+ const highlightedCommentThreads = highlightedCommentThreadsSignal.get;
+ const setActiveCommentThread = activeCommentThreadSignal.set;
+
const [copied, setCopied] = createSignal(false);
const [locationCopied, setLocationCopied] = createSignal(false);
const [isLoading, setIsLoading] = createSignal<boolean>(false);
@@ -253,6 +302,207 @@ export function MarkdownPopup(props: {
)
);
+ // Resolves the loro-mirror node ids of every top-level block touched by
+ // the selection, via the nodeIdPlugin's node state / key mapping.
+ const resolveSelectedNodeIds = (): string[] => {
+ const lexicalSelection = selection()?.lexicalSelection;
+ if (!lexicalSelection) return [];
+ return editor.read(() => {
+ const topNodes = new Set(
+ lexicalSelection
+ .getNodes()
+ .map((node) => node.getTopLevelElement() ?? node)
+ );
+ const ids = new Set<string>();
+ for (const node of topNodes) {
+ const id =
+ $getId(node) ??
+ props.lexicalMapping.nodeKeyToIdMap.get(node.getKey());
+ if (id) ids.add(id);
+ }
+ return [...ids];
+ });
+ };
+
+ // Shared by the desktop toolbar's inline AI row and the touch AI drawer:
+ // the autosizing prompt input and its submit-or-stop button.
+ const handleAiInput = (
+ e: InputEvent & { currentTarget: HTMLTextAreaElement }
+ ) => {
+ setAiEditInput(e.currentTarget.value);
+ e.currentTarget.style.height = 'auto';
+ e.currentTarget.style.height = `${e.currentTarget.scrollHeight}px`;
+ };
+
+ const AiEditSubmitButton = () => (
+ <Show
+ when={hasActiveAiEdit(blockId)}
+ fallback={
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Ask Macro"
+ disabled={!aiEditInput().trim()}
+ onClick={handleAiEditSubmit}
+ >
+ <CheckIcon class="size-4" />
+ </Button>
+ }
+ >
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Stop AI edit"
+ onClick={() => cancelAiEdit(blockId)}
+ >
+ <div class="size-2.5 rounded-xs bg-current" />
+ </Button>
+ </Show>
+ );
+
+ const handleAiEditSubmit = () => {
+ if (aiEditRunning()) return;
+ const instruction = aiEditInput().trim();
+ if (!instruction) return;
+ const nodeIds = resolveSelectedNodeIds();
+ if (nodeIds.length === 0) {
+ toast.failure('Could not resolve the selected nodes');
+ return;
+ }
+ // The highlight is already tracking the selection; flagging the run
+ // keeps it alive (as the loading indicator) after the popup closes.
+ setAiEditRunning(true);
+ // Apply ops locally so the edit lands in this client's undo stack.
+ requestAiEdit({
+ documentId: blockId,
+ prompt: `Request: ${instruction}\nUser is selecting nodes ${nodeIds.join(' ')}. Proceed with requested edit`,
+ onOps: (ops) => applyAiOps(editor, props.lexicalMapping, ops),
+ })
+ .then((result) => {
+ if (result === 'failed') toast.failure('AI edit failed');
+ })
+ .finally(() => {
+ setAiEditLocation(null);
+ setAiEditRunning(false);
+ });
+ setAiEditInput('');
+ setAiEditDrawerOpen(false);
+ setPopupVisible(false);
+ };
+
+ // Selection actions shared by the desktop and touch toolbars.
+ const shouldShowCheckboxToTaskButton = () => {
+ return Boolean(
+ isCheckboxToTaskPluginEnabled(editor) &&
+ hasCheckboxes() &&
+ canEdit() &&
+ currentUserId()
+ );
+ };
+
+ const shouldShowTableButton = () =>
+ Boolean(canEdit() && convertibleListKey());
+
+ const shouldShowEditWithAiButton = () =>
+ inlineAiEditing().enabled && canEdit();
+
+ const handleConvertToTasks = () => {
+ const currentSelection = selection();
+ const userId = currentUserId();
+ if (!currentSelection?.lexicalSelection || !userId) {
+ return;
+ }
+
+ setIsConverting(true);
+ editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {
+ selection: currentSelection.lexicalSelection as RangeSelection,
+ onComplete: (results) => {
+ setIsConverting(false);
+ const successCount = results.filter((r) => r.isOk()).length;
+ if (successCount > 0) {
+ toast.success(
+ `Created ${successCount} task${successCount > 1 ? 's' : ''}`
+ );
+ }
+ setPopupVisible(false);
+ },
+ });
+ };
+
+ const handleConvertListToTable = () => {
+ const listKey = convertibleListKey();
+ if (!listKey) return;
+ const converted = editor.dispatchCommand(LIST_TO_TABLE_COMMAND, listKey);
+ if (converted) setPopupVisible(false);
+ };
+
+ const handleShare = async () => {
+ const location = editor.read(() => $getLocationUrl('md', blockId));
+ if (!location) return;
+ await navigator.clipboard.writeText(location);
+ // Desktop gets the inline check-icon flip; on touch the toolbar is
+ // small and easily dismissed, so confirm with a toast as well.
+ if (isTouchDevice()) toast.success('Link copied to clipboard');
+ setLocationCopied(true);
+ setTimeout(() => setLocationCopied(false), 2000);
+ };
+
+ const handleInsertComment = () => {
+ const created = editor.dispatchCommand(
+ CREATE_DRAFT_COMMENT_COMMAND,
+ undefined
+ );
+ if (!created) {
+ toast.failure('Please highlight text to comment.');
+ return;
+ }
+ setPopupVisible(false);
+ };
+
+ const handlePaste = async () => {
+ // Reading the pasteboard is async, and the toolbar tap or the native call
+ // can move or drop the editor selection before it resolves. Snapshot the
+ // range now and restore it before inserting so the text lands where the
+ // user had selected.
+ const savedSelection = editor.read(() => {
+ const current = $getSelection();
+ return $isRangeSelection(current) ? current.clone() : null;
+ });
+ const text = await readNativePasteboardText();
+ if (!text) return;
+ editor.update(() => {
+ if (savedSelection) $setSelection(savedSelection);
+ const lexicalSelection = $getSelection();
+ if ($isRangeSelection(lexicalSelection)) {
+ lexicalSelection.insertRawText(text);
+ }
+ });
+ setPopupVisible(false);
+ };
+
+ const handleShowComment = () => {
+ // Viewing a thread doesn't take text input, and the caret kept the
+ // editor focused (the toolbar preserves the selection) — close the
+ // virtual keyboard. Blurring alone is not enough: a retained
+ // editor-state selection is re-applied to the DOM on the next lexical
+ // update, which refocuses the editor and brings the keyboard back, so
+ // clear the selection first.
+ editor.update(() => $setSelection(null));
+ editor.blur();
+ const [threadId] = highlightedCommentThreads();
+ if (threadId != null) setActiveCommentThread(threadId);
+ setPopupVisible(false);
+ };
+
+ const handleOpenAiEditDrawer = () => {
+ setAiEditDrawerOpen(true);
+ setPopupVisible(false);
+ };
+
const MarkdownPopupToolbar = () => {
const _isAuthenticated = useIsAuthenticated();
const [completion, _setCompletion] = createSignal<Completion | undefined>(
@@ -340,29 +590,6 @@ export function MarkdownPopup(props: {
setIsLoading(false);
});
- const handleConvertToTasks = () => {
- const currentSelection = selection();
- const userId = currentUserId();
- if (!currentSelection?.lexicalSelection || !userId) {
- return;
- }
-
- setIsConverting(true);
- editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {
- selection: currentSelection.lexicalSelection as RangeSelection,
- onComplete: (results) => {
- setIsConverting(false);
- const successCount = results.filter((r) => r.isOk()).length;
- if (successCount > 0) {
- toast.success(
- `Created ${successCount} task${successCount > 1 ? 's' : ''}`
- );
- }
- setPopupVisible(false);
- },
- });
- };
-
const _contentSize = () => {
let charCount = 0;
editor.getEditorState().read(() => {
@@ -375,64 +602,8 @@ export function MarkdownPopup(props: {
const handleRewrite = (_instructions: string) => {};
- const [aiEditInput, setAiEditInput] = createSignal('');
let aiInputRef: HTMLTextAreaElement | undefined;
- onCleanup(() => {
- if (!aiEditRunning()) setAiEditLocation(null);
- });
-
- // Resolves the loro-mirror node ids of every top-level block touched by
- // the selection, via the nodeIdPlugin's node state / key mapping.
- const resolveSelectedNodeIds = (): string[] => {
- const lexicalSelection = selection()?.lexicalSelection;
- if (!lexicalSelection) return [];
- return editor.read(() => {
- const topNodes = new Set(
- lexicalSelection
- .getNodes()
- .map((node) => node.getTopLevelElement() ?? node)
- );
- const ids = new Set<string>();
- for (const node of topNodes) {
- const id =
- $getId(node) ??
- props.lexicalMapping.nodeKeyToIdMap.get(node.getKey());
- if (id) ids.add(id);
- }
- return [...ids];
- });
- };
-
- const handleAiEditSubmit = () => {
- if (aiEditRunning()) return;
- const instruction = aiEditInput().trim();
- if (!instruction) return;
- const nodeIds = resolveSelectedNodeIds();
- if (nodeIds.length === 0) {
- toast.failure('Could not resolve the selected nodes');
- return;
- }
- // The highlight is already tracking the selection; flagging the run
- // keeps it alive (as the loading indicator) after the popup closes.
- setAiEditRunning(true);
- // Apply ops locally so the edit lands in this client's undo stack.
- requestAiEdit({
- documentId: blockId,
- prompt: `Request: ${instruction}\nUser is selecting nodes ${nodeIds.join(' ')}. Proceed with requested edit`,
- onOps: (ops) => applyAiOps(editor, props.lexicalMapping, ops),
- })
- .then((result) => {
- if (result === 'failed') toast.failure('AI edit failed');
- })
- .finally(() => {
- setAiEditLocation(null);
- setAiEditRunning(false);
- });
- setAiEditInput('');
- setPopupVisible(false);
- };
-
createEffect(
on([completionType, rewriteInputRef], () => {
if (highlightLocation()) {
@@ -470,15 +641,6 @@ export function MarkdownPopup(props: {
});
});
- const shouldShowCheckboxToTaskButton = () => {
- return (
- isCheckboxToTaskPluginEnabled(editor) &&
- hasCheckboxes() &&
- canEdit() &&
- currentUserId()
- );
- };
-
return (
<>
<div
@@ -508,7 +670,7 @@ export function MarkdownPopup(props: {
}}
/>
</Show>*/}
- <Show when={!isMobile() && (canEdit() || canComment())}>
+ <Show when={canEdit() || canComment()}>
<FormatTools withinPopup />
</Show>
<Show when={shouldShowCheckboxToTaskButton()}>
@@ -527,41 +689,25 @@ export function MarkdownPopup(props: {
{isConverting() ? 'Converting...' : 'Tasks'}
</Button>
</Show>
- <Show when={canEdit() && convertibleListKey()}>
- {(listKey) => (
- <Button
- size="sm"
- class="rounded-md"
- depth={3}
- variant="ghost"
- tooltip="Convert list to table"
- onClick={() => {
- const converted = editor.dispatchCommand(
- LIST_TO_TABLE_COMMAND,
- listKey()
- );
- if (converted) setPopupVisible(false);
- }}
- >
- <GridIcon class="size-4" />
- Table
- </Button>
- )}
+ <Show when={shouldShowTableButton()}>
+ <Button
+ size="sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Convert list to table"
+ onClick={handleConvertListToTable}
+ >
+ <GridIcon class="size-4" />
+ Table
+ </Button>
</Show>
<Button
size="sm"
class="px-2 text-xs rounded-md py-1.25"
depth={3}
variant="ghost"
- onClick={async () => {
- const location = editor.read(() =>
- $getLocationUrl('md', blockId)
- );
- if (!location) return;
- await navigator.clipboard.writeText(location);
- setLocationCopied(true);
- setTimeout(() => setLocationCopied(false), 2000);
- }}
+ onClick={() => void handleShare()}
>
<Dynamic
component={locationCopied() ? CheckIcon : LinkIcon}
@@ -571,7 +717,7 @@ export function MarkdownPopup(props: {
</Button>
</div>
- <Show when={inlineAiEditing().enabled && canEdit()}>
+ <Show when={shouldShowEditWithAiButton()}>
<div class="mt-1 flex w-full min-w-72 items-center gap-1 border-t border-edge p-1 pt-1.5 pr-2">
<SparkleIcon class="size-4 shrink-0 text-ink-extra-muted" />
<textarea
@@ -583,11 +729,7 @@ export function MarkdownPopup(props: {
}}
onFocus={() => setAiInputFocused(true)}
onBlur={() => setAiInputFocused(false)}
- onInput={(e) => {
- setAiEditInput(e.currentTarget.value);
- e.currentTarget.style.height = 'auto';
- e.currentTarget.style.height = `${e.currentTarget.scrollHeight}px`;
- }}
+ onInput={handleAiInput}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
@@ -600,33 +742,7 @@ export function MarkdownPopup(props: {
}
}}
/>
- <Show
- when={hasActiveAiEdit(blockId)}
- fallback={
- <Button
- size="icon-sm"
- class="rounded-md"
- depth={3}
- variant="ghost"
- tooltip="Ask Macro"
- disabled={!aiEditInput().trim()}
- onClick={handleAiEditSubmit}
- >
- <CheckIcon class="size-4" />
- </Button>
- }
- >
- <Button
- size="icon-sm"
- class="rounded-md"
- depth={3}
- variant="ghost"
- tooltip="Stop AI edit"
- onClick={() => cancelAiEdit(blockId)}
- >
- <div class="size-2.5 rounded-xs bg-current" />
- </Button>
- </Show>
+ <AiEditSubmitButton />
</div>
</Show>
@@ -788,6 +904,38 @@ export function MarkdownPopup(props: {
);
};
+ // Picks the toolbar for the device and owns the popup-lifetime cleanup
+ // shared by both: the AI-edit highlight survives the popup only while the
+ // drawer or a running edit has taken it over.
+ const PopupToolbar = () => {
+ onCleanup(() => {
+ if (!aiEditRunning() && !aiEditDrawerOpen()) setAiEditLocation(null);
+ });
+ return (
+ <Show when={isTouchDevice()} fallback={<MarkdownPopupToolbar />}>
+ <TouchSelectionToolbar
+ canEdit={canEdit()}
+ canComment={canComment()}
+ isConverting={isConverting()}
+ hasSelection={(selection()?.text ?? '') !== ''}
+ showTasksOption={shouldShowCheckboxToTaskButton()}
+ showTableOption={shouldShowTableButton()}
+ showEditWithAiOption={shouldShowEditWithAiButton()}
+ showOpenCommentOption={highlightedCommentThreads().length > 0}
+ locationCopied={locationCopied()}
+ setPopupVisible={setPopupVisible}
+ onConvertToTasks={handleConvertToTasks}
+ onConvertListToTable={handleConvertListToTable}
+ onOpenComment={handleShowComment}
+ onShare={() => void handleShare()}
+ onInsertComment={handleInsertComment}
+ onPaste={() => void handlePaste()}
+ onEditWithAi={handleOpenAiEditDrawer}
+ />
+ </Show>
+ );
+ };
+
const anchorRefPosition = () => {
const sel = selection();
const currentPortalScopeRect = portalScopeRect();
@@ -839,7 +987,7 @@ export function MarkdownPopup(props: {
<ScopedPortal scope="local">
<Layer depth={2}>
<GeneralizedPopup
- PopupComponents={MarkdownPopupToolbar}
+ PopupComponents={PopupToolbar}
anchor={{
ref: anchorRef()!,
blockId: `${blockId}`,
@@ -862,7 +1010,12 @@ export function MarkdownPopup(props: {
captureBoundingDomRect={setHighlightRect}
/>
</Show>
- <Show when={(aiInputFocused() || aiEditRunning()) && aiEditLocation()}>
+ <Show
+ when={
+ (aiInputFocused() || aiEditRunning() || aiEditDrawerOpen()) &&
+ aiEditLocation()
+ }
+ >
<style>{`
.ai-edit-highlight {
background: var(--color-accent);
@@ -890,6 +1043,47 @@ export function MarkdownPopup(props: {
}
/>
</Show>
+ <Show when={isTouchDevice()}>
+ <MobileDrawer
+ side="bottom"
+ open={aiEditDrawerOpen()}
+ onOpenChange={(open: boolean) => {
+ if (open) return;
+ setAiEditDrawerOpen(false);
+ if (!aiEditRunning()) setAiEditLocation(null);
+ }}
+ closeOnOutsidePointerStrategy="pointerdown"
+ preventScroll={false}
+ preventScrollbarShift={false}
+ >
+ <MobileDrawer.Portal>
+ <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />
+ <MobileDrawer.Content aria-label="Edit with AI">
+ <MobileDrawer.Handle class="pb-1" />
+ <div class="flex items-center gap-2 px-4 pb-3">
+ <SparkleIcon class="size-4 shrink-0 text-ink-extra-muted" />
+ <textarea
+ class="grow resize-none bg-transparent py-1.5 text-sm placeholder:text-ink-placeholder focus:outline-none"
+ rows={1}
+ placeholder="Ask Macro to edit this selection"
+ value={aiEditInput()}
+ ref={(el) => {
+ requestAnimationFrame(() => el.focus());
+ }}
+ onInput={handleAiInput}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleAiEditSubmit();
+ }
+ }}
+ />
+ <AiEditSubmitButton />
+ </div>
+ </MobileDrawer.Content>
+ </MobileDrawer.Portal>
+ </MobileDrawer>
+ </Show>
</>
);
}
diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsx
index f50fafdc53..d2a4482c8c 100644
--- a/apps/web/src/features/block-md/component/Notebook.tsx
+++ b/apps/web/src/features/block-md/component/Notebook.tsx
@@ -159,7 +159,10 @@ export function Notebook(props: {
if (!ENABLE_MARKDOWN_COMMENTS) return false;
return Object.keys(comments).length > 0;
});
- const showComments = () => hasComment() && !history.isOpen();
+ // On phones the margin is hidden entirely (no minimized rail); the touch
+ // comment drawer is the only comment surface. CommentMargin stays mounted
+ // inside the hidden wrapper — it hosts the drawer.
+ const showComments = () => hasComment() && !history.isOpen() && !isMobile();
const currentEditorState = () => {
const editor = md.editor;
@@ -191,8 +194,13 @@ export function Notebook(props: {
observe(notebookRef);
});
+ // Component scope on purpose: the hook registers an onCleanup that ends
+ // its pending wait-for-mark. Called inside the createEffect below, that
+ // cleanup would belong to the effect's computation and run on every
+ // re-run — tying the deep-link scroll's lifetime to re-run ordering.
+ const goToTempRedirect = useGoToTempRedirect();
+
createEffect(() => {
- const goToTempRedirect = useGoToTempRedirect();
const recentState = tempRedirectLocation();
if (!recentState) return;
diff --git a/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx b/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx
new file mode 100644
index 0000000000..9e2631afd5
--- /dev/null
+++ b/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx
@@ -0,0 +1,505 @@
+import { toast } from '@core/component/Toast/Toast';
+import { ENABLE_MARKDOWN_COMMENTS } from '@core/constant/featureFlags';
+import { hasNativeEditMenu } from '@core/mobile/nativeEditMenu';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import ChatTeardrop from '@phosphor/chat-teardrop.svg';
+import GridIcon from '@phosphor/grid-four.svg';
+import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
+import SparkleIcon from '@phosphor-icons/core/bold/sparkle-bold.svg?component-solid';
+import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
+import CheckSquareIcon from '@phosphor-icons/core/regular/check-square.svg?component-solid';
+import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';
+import { Button } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ Show,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+
+type TouchOption = {
+ key: string;
+ content: () => JSX.Element;
+ onSelect: () => void;
+ disabled?: () => boolean;
+};
+
+// Toolbar buttons give no touch-down feedback: the ghost variant's
+// hover/active overlays (and iOS's native tap flash) would light options up
+// on every touch and mid-swipe, so they are forcibly neutralized.
+const optionButtonClass =
+ 'px-2 text-xs rounded-md py-1.25 shrink-0 whitespace-nowrap hover:bg-none! active:bg-none! hover:text-ink-muted! [-webkit-tap-highlight-color:transparent]';
+const arrowButtonClass =
+ 'rounded-md shrink-0 hover:bg-none! active:bg-none! hover:text-ink-muted! [-webkit-tap-highlight-color:transparent]';
+
+/**
+ * The touch-device selection toolbar, mirroring the native edit menu (which
+ * is suppressed while the popup shows — see nativeEditMenu). Options are
+ * partitioned into mutually exclusive pages of whole options that fit the
+ * screen width (chevron widths included in the budget). The pages sit in a
+ * sliding track: swiping drags it with the finger (with resistance at the
+ * ends) and releasing past a threshold snaps one page over; chevrons move a
+ * page at a time.
+ *
+ * Desktop renders MarkdownPopupToolbar instead; see MarkdownPopup for the
+ * split.
+ */
+export function TouchSelectionToolbar(props: {
+ canEdit: boolean;
+ canComment: boolean;
+ isConverting: boolean;
+ /** False when the popup opened for a bare caret (inside a comment). */
+ hasSelection: boolean;
+ showTasksOption: boolean;
+ showTableOption: boolean;
+ showEditWithAiOption: boolean;
+ /** The caret/selection touches an existing comment thread. */
+ showOpenCommentOption: boolean;
+ locationCopied: boolean;
+ setPopupVisible: (visible: boolean) => void;
+ onConvertToTasks: () => void;
+ onConvertListToTable: () => void;
+ onOpenComment: () => void;
+ onShare: () => void;
+ onInsertComment: () => void;
+ onPaste: () => void;
+ onEditWithAi: () => void;
+}) {
+ const options = createMemo<TouchOption[]>(() => {
+ const list: TouchOption[] = [];
+ const pasteOption: TouchOption = {
+ key: 'paste',
+ content: () => <>Paste</>,
+ onSelect: () => props.onPaste(),
+ };
+ if (props.showOpenCommentOption) {
+ list.push({
+ key: 'open-comment',
+ content: () => (
+ <>
+ <ChatTeardrop class="size-4" />
+ Show comment
+ </>
+ ),
+ onSelect: () => props.onOpenComment(),
+ });
+ }
+ if (!props.hasSelection) {
+ // Caret mode: only opening the comment and pasting apply — Paste also
+ // stands in for the suppressed native caret menu.
+ if (props.canEdit && hasNativeEditMenu()) {
+ list.push(pasteOption);
+ }
+ return list;
+ }
+ if (props.showTasksOption) {
+ list.push({
+ key: 'tasks',
+ content: () => (
+ <>
+ <Dynamic
+ component={props.isConverting ? LoadingIcon : CheckSquareIcon}
+ class="size-4"
+ />
+ {props.isConverting ? 'Converting...' : 'Tasks'}
+ </>
+ ),
+ onSelect: () => props.onConvertToTasks(),
+ disabled: () => props.isConverting,
+ });
+ }
+ if (props.showTableOption) {
+ list.push({
+ key: 'table',
+ content: () => (
+ <>
+ <GridIcon class="size-4" />
+ Table
+ </>
+ ),
+ onSelect: () => props.onConvertListToTable(),
+ });
+ }
+ list.push({
+ key: 'copy',
+ content: () => <>Copy</>,
+ // execCommand is also lexical's own programmatic copy path: it routes
+ // through the editor's COPY_COMMAND handler, so the clipboard gets the
+ // rich (html + lexical) payload. The button's pointerdown is prevented,
+ // which keeps the editor selection alive for it.
+ onSelect: () => {
+ if (!document.execCommand('copy')) toast.failure('Could not copy');
+ props.setPopupVisible(false);
+ },
+ });
+ if (props.canEdit) {
+ list.push({
+ key: 'cut',
+ content: () => <>Cut</>,
+ onSelect: () => {
+ if (!document.execCommand('cut')) toast.failure('Could not cut');
+ props.setPopupVisible(false);
+ },
+ });
+ if (hasNativeEditMenu()) {
+ list.push(pasteOption);
+ }
+ }
+ if (ENABLE_MARKDOWN_COMMENTS && props.canComment) {
+ list.push({
+ key: 'comment',
+ content: () => (
+ <>
+ <ChatTeardrop class="size-4" />
+ Comment
+ </>
+ ),
+ onSelect: () => props.onInsertComment(),
+ });
+ }
+ list.push({
+ key: 'share',
+ content: () => (
+ <>
+ <Dynamic
+ component={props.locationCopied ? CheckIcon : LinkIcon}
+ class={props.locationCopied ? 'text-success-ink size-4' : 'size-4'}
+ />
+ Share
+ </>
+ ),
+ onSelect: () => props.onShare(),
+ });
+ if (props.showEditWithAiOption) {
+ list.push({
+ key: 'edit-with-ai',
+ content: () => (
+ <>
+ <SparkleIcon class="size-4" />
+ Edit with AI
+ </>
+ ),
+ onSelect: () => props.onEditWithAi(),
+ });
+ }
+ return list;
+ });
+
+ // --- Pagination ---------------------------------------------------------
+ // The options render once into a hidden measuring row; its widths drive a
+ // greedy partition into pages of whole options. Space for both chevrons is
+ // reserved on every multi-page layout so a page never clips.
+
+ /** Divider footprint: mx-1 (4px each side) around the 1px line. */
+ const DIVIDER_SPACE = 9;
+ /** Screen inset + popup chrome the row must leave free. */
+ const PAGE_MARGIN = 48;
+ /** Gap between pages in the sliding track. */
+ const PAGE_GAP = 24;
+ /** Drag distance at release that commits a page change. */
+ const SWIPE_THRESHOLD = 48;
+ /** Movement below this is a tap; above it, a drag (and the click is eaten). */
+ const CLICK_SLOP = 10;
+
+ type TouchPage = {
+ options: TouchOption[];
+ width: number;
+ };
+
+ let measureRowRef: HTMLDivElement | undefined;
+ let measureArrowRef: HTMLDivElement | undefined;
+ const [optionWidths, setOptionWidths] = createSignal<number[]>([]);
+ const [arrowWidth, setArrowWidth] = createSignal(28);
+ const [pageIndex, setPageIndex] = createSignal(0);
+
+ const measure = () => {
+ if (!measureRowRef) return false;
+ const widths = Array.from(
+ measureRowRef.querySelectorAll<HTMLElement>('button')
+ ).map((button) => button.offsetWidth);
+ if (widths.length === 0 || widths.some((width) => width === 0)) {
+ return false;
+ }
+ setOptionWidths(widths);
+ const arrow = measureArrowRef?.querySelector<HTMLElement>('button');
+ if (arrow && arrow.offsetWidth > 0) setArrowWidth(arrow.offsetWidth);
+ return true;
+ };
+
+ let lastOptionKeys: string | undefined;
+ createEffect(() => {
+ // Reset paging only when the option *set* changes (e.g. caret mode vs.
+ // selection mode) — a cosmetic rerender of the same options (the Share
+ // icon flipping to a check, the Tasks label while converting) keeps the
+ // user's page; the clamp effect below handles any repartition.
+ const keys = options()
+ .map((option) => option.key)
+ .join('\n');
+ if (keys !== lastOptionKeys) {
+ lastOptionKeys = keys;
+ setPageIndex(0);
+ }
+ // Measure synchronously (a forced layout read) so the very first paint
+ // already shows the paged layout — deferring to an animation frame lets
+ // one unmeasured, full-width frame flash. Falls back a frame if layout
+ // isn't ready yet, during which the toolbar renders nothing.
+ if (!measure()) requestAnimationFrame(measure);
+ });
+
+ const pages = createMemo<TouchPage[]>(() => {
+ const all = options();
+ const widths = optionWidths();
+ if (all.length === 0) return [];
+ if (widths.length !== all.length) return [];
+
+ const totalBudget = Math.max(120, window.innerWidth - PAGE_MARGIN);
+ const totalWidth = widths.reduce(
+ (sum, width, index) => sum + width + (index > 0 ? DIVIDER_SPACE : 0),
+ 0
+ );
+ if (totalWidth <= totalBudget) return [{ options: all, width: totalWidth }];
+ const pageBudget = Math.max(
+ 80,
+ totalBudget - 2 * (arrowWidth() + DIVIDER_SPACE)
+ );
+ const result: TouchPage[] = [];
+ let currentOptions: TouchOption[] = [];
+ let currentWidth = 0;
+ all.forEach((option, index) => {
+ const needed =
+ currentOptions.length === 0
+ ? widths[index]
+ : currentWidth + DIVIDER_SPACE + widths[index];
+ if (currentOptions.length > 0 && needed > pageBudget) {
+ result.push({ options: currentOptions, width: currentWidth });
+ currentOptions = [option];
+ currentWidth = widths[index];
+ } else {
+ currentOptions.push(option);
+ currentWidth = needed;
+ }
+ });
+ if (currentOptions.length > 0) {
+ result.push({ options: currentOptions, width: currentWidth });
+ }
+ return result;
+ });
+
+ createEffect(() => {
+ const maxIndex = pages().length - 1;
+ if (pageIndex() > maxIndex) setPageIndex(Math.max(0, maxIndex));
+ });
+
+ const clampedIndex = () =>
+ Math.max(0, Math.min(pageIndex(), pages().length - 1));
+ const canPagePrev = () => clampedIndex() > 0;
+ const canPageNext = () => clampedIndex() < pages().length - 1;
+
+ const page = (direction: 1 | -1) =>
+ setPageIndex(() =>
+ Math.max(0, Math.min(clampedIndex() + direction, pages().length - 1))
+ );
+
+ // --- Swipe paging -------------------------------------------------------
+ // The finger drags the track live; releasing past the threshold commits
+ // one page per gesture. The pointer is only captured once movement passes
+ // the slop, so plain taps reach the option buttons untouched — and the
+ // click trailing a real drag is eaten by a capture-phase listener.
+ const [dragDelta, setDragDelta] = createSignal<number | null>(null);
+ let dragPointerId: number | null = null;
+ let dragStartX = 0;
+ let dragRawDelta = 0;
+ let dragCaptured = false;
+ let suppressClick = false;
+
+ const handlePointerDown = (event: PointerEvent) => {
+ if (pages().length <= 1) return;
+ if (event.pointerType === 'mouse' && event.buttons !== 1) return;
+ dragPointerId = event.pointerId;
+ dragStartX = event.clientX;
+ dragRawDelta = 0;
+ dragCaptured = false;
+ setDragDelta(0);
+ };
+
+ const handlePointerMove = (event: PointerEvent) => {
+ if (dragPointerId !== event.pointerId) return;
+ dragRawDelta = event.clientX - dragStartX;
+ if (!dragCaptured && Math.abs(dragRawDelta) > CLICK_SLOP) {
+ dragCaptured = true;
+ suppressClick = true;
+ try {
+ (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
+ } catch {
+ // synthetic pointers cannot be captured
+ }
+ }
+ // Resist dragging past the first/last page.
+ const atStart = clampedIndex() === 0 && dragRawDelta > 0;
+ const atEnd = clampedIndex() === pages().length - 1 && dragRawDelta < 0;
+ setDragDelta(atStart || atEnd ? dragRawDelta * 0.25 : dragRawDelta);
+ };
+
+ const endDrag = () => {
+ if (dragPointerId == null) return;
+ dragPointerId = null;
+ setDragDelta(null);
+ if (Math.abs(dragRawDelta) >= SWIPE_THRESHOLD) {
+ page(dragRawDelta < 0 ? 1 : -1);
+ }
+ // The trailing click fires right after pointerup; let the capture
+ // listener see the flag first.
+ setTimeout(() => {
+ suppressClick = false;
+ }, 0);
+ };
+
+ const trackOffset = () => {
+ const allPages = pages();
+ let offset = 0;
+ for (let i = 0; i < clampedIndex(); i++) {
+ offset += (allPages[i].width ?? 0) + PAGE_GAP;
+ }
+ return -offset + (dragDelta() ?? 0);
+ };
+
+ const currentPageWidth = () => pages()[clampedIndex()]?.width ?? null;
+
+ return (
+ <div class="relative flex touch-pan-y flex-row items-center">
+ {/* Hidden measuring row: sizes every option and a chevron. Collapsed
+ to a zero-size clipped box — at natural width it would extend the
+ scroll parent's overflow area and make the document pannable
+ sideways. The w-max rows keep the buttons at natural width inside
+ the collapsed box so offsetWidth still measures correctly. */}
+ <div
+ class="pointer-events-none invisible absolute h-0 w-0 overflow-hidden"
+ aria-hidden="true"
+ >
+ <div class="flex w-max flex-row items-center" ref={measureRowRef}>
+ <For each={options()}>
+ {(option) => (
+ <Button
+ size="sm"
+ class={optionButtonClass}
+ depth={3}
+ variant="ghost"
+ >
+ {option.content()}
+ </Button>
+ )}
+ </For>
+ </div>
+ <div class="w-max" ref={measureArrowRef}>
+ <Button
+ size="icon-sm"
+ class={arrowButtonClass}
+ depth={3}
+ variant="ghost"
+ >
+ <CaretRightIcon class="size-4" />
+ </Button>
+ </div>
+ </div>
+ <Show when={canPagePrev()}>
+ <Button
+ size="icon-sm"
+ class={arrowButtonClass}
+ depth={3}
+ variant="ghost"
+ aria-label="Previous options"
+ onPointerDown={(e: PointerEvent) => e.preventDefault()}
+ onClick={() => page(-1)}
+ >
+ <CaretLeftIcon class="size-4" />
+ </Button>
+ <div class="mx-1 w-px shrink-0 self-stretch bg-edge" />
+ </Show>
+ <div
+ // The max-w mirrors PAGE_MARGIN and caps the not-yet-measured frame,
+ // where the viewport would otherwise render the full track width.
+ class="max-w-[calc(100vw-3rem)] shrink-0 overflow-hidden"
+ style={{
+ ...(currentPageWidth() != null
+ ? { width: `${currentPageWidth()}px` }
+ : {}),
+ transition: dragDelta() != null ? 'none' : 'width 200ms ease-out',
+ }}
+ ref={(el) => {
+ el.addEventListener(
+ 'click',
+ (event) => {
+ if (suppressClick) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ },
+ { capture: true }
+ );
+ }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={endDrag}
+ onPointerCancel={endDrag}
+ >
+ <div
+ class="flex flex-row items-center"
+ style={{
+ gap: `${PAGE_GAP}px`,
+ transform: `translateX(${trackOffset()}px)`,
+ transition:
+ dragDelta() != null ? 'none' : 'transform 200ms ease-out',
+ }}
+ >
+ <For each={pages()}>
+ {(touchPage, pageIdx) => (
+ <div
+ class="flex flex-none flex-row items-center"
+ inert={clampedIndex() !== pageIdx()}
+ >
+ <For each={touchPage.options}>
+ {(option, index) => (
+ <>
+ <Show when={index() > 0}>
+ <div class="mx-1 w-px shrink-0 self-stretch bg-edge" />
+ </Show>
+ <Button
+ size="sm"
+ class={optionButtonClass}
+ depth={3}
+ variant="ghost"
+ disabled={option.disabled?.()}
+ onPointerDown={(e: PointerEvent) => e.preventDefault()}
+ onClick={() => option.onSelect()}
+ >
+ {option.content()}
+ </Button>
+ </>
+ )}
+ </For>
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ <Show when={canPageNext()}>
+ <div class="mx-1 w-px shrink-0 self-stretch bg-edge" />
+ <Button
+ size="icon-sm"
+ class={arrowButtonClass}
+ depth={3}
+ variant="ghost"
+ aria-label="More options"
+ onPointerDown={(e: PointerEvent) => e.preventDefault()}
+ onClick={() => page(1)}
+ >
+ <CaretRightIcon class="size-4" />
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-md/signal/location.ts b/apps/web/src/features/block-md/signal/location.ts
index c971c6f3ed..0e785910c1 100644
--- a/apps/web/src/features/block-md/signal/location.ts
+++ b/apps/web/src/features/block-md/signal/location.ts
@@ -18,7 +18,11 @@ export const useGoToTempRedirect = () => {
const threadId = state.location?.threadId;
if (!threadId) return;
- scrollToCommentThread(threadId).then(() => {
+ scrollToCommentThread(threadId).then((completed) => {
+ // A mobile wait that was cancelled (superseded by a newer deep link,
+ // or the block unmounting) resolves false — activating its thread
+ // would overwrite the navigation that superseded it.
+ if (completed === false) return;
// NOTE: in commentStore.ts, we unset the active thread id
// if there are no active mark ids. By setting it after
// scroll we ensure that the active thread id is not unset
diff --git a/apps/web/src/lib/core/comments/Comment.tsx b/apps/web/src/lib/core/comments/Comment.tsx
index 8325ace781..bebf561843 100644
--- a/apps/web/src/lib/core/comments/Comment.tsx
+++ b/apps/web/src/lib/core/comments/Comment.tsx
@@ -8,6 +8,7 @@ import {
createEffect,
createMemo,
createSignal,
+ onCleanup,
type ParentProps,
Show,
untrack,
@@ -34,7 +35,10 @@ const CommentText = (props: { text: string; isThreaded?: boolean }) => {
};
function CommentContainer(
- props: ParentProps<{ isThreaded?: boolean; isHighlighted?: boolean }>
+ props: ParentProps<{
+ isThreaded?: boolean;
+ isHighlighted?: boolean;
+ }>
) {
return (
<div
@@ -68,13 +72,18 @@ export function Comment(
isOwned: boolean;
isActive: boolean;
isThreaded?: boolean;
+ actionsDropdown?: boolean;
}>
) {
const maybeBlockName = useMaybeBlockAliasedName();
const commentsContext = useContext(CommentsContext);
- const { commentOperations, setActiveThread, highlightedCommentId } =
- commentsContext;
+ const {
+ commentOperations,
+ setActiveThread,
+ setMessageEditing,
+ highlightedCommentId,
+ } = commentsContext;
const isHighlighted = createMemo(
() => highlightedCommentId() === props.comment.id
);
@@ -83,7 +92,14 @@ export function Comment(
const date = () => props.comment.createdAt;
const [textValue, setTextValue] = createSignal<string>(props.comment.text);
- const [isEditing, setIsEditing] = createSignal<boolean>(false);
+ const [isEditing, setIsEditingSignal] = createSignal<boolean>(false);
+ // Report each edit-state transition to the drawer host (it hides its
+ // pinned reply composer while an edit is open). A wrapper instead of an
+ // effect keeps the reporting explicit at every mutation site.
+ const setIsEditing = (editing: boolean) => {
+ setIsEditingSignal(editing);
+ setMessageEditing?.(props.comment.id, editing);
+ };
createEffect(() => {
if (!untrack(isEditing)) return;
@@ -92,6 +108,10 @@ export function Comment(
}
});
+ // The report must also retract on unmount (deletion mid-edit, or the
+ // drawer paging to another thread with an edit open).
+ onCleanup(() => setMessageEditing?.(props.comment.id, false));
+
const copyLink = () => {
if (!maybeBlockName) return;
return async () => {
@@ -128,6 +148,7 @@ export function Comment(
<MessageTopRow
isOwned={props.isOwned}
isActive={props.isActive}
+ actionsDropdown={props.actionsDropdown}
authorId={props.comment.author}
date={date()}
isNew={false}
@@ -155,6 +176,7 @@ export function Comment(
isOwned={props.isOwned}
isActive={props.isActive}
isEditing
+ actionsDropdown={props.actionsDropdown}
authorId={props.comment.author}
date={date()}
isResolved={false}
@@ -178,6 +200,7 @@ export function Comment(
handleCancel={() => {
setTextValue(textValue());
}}
+ deactivateThreadOnCancel={false}
setEditing={setIsEditing}
textValue={textValue()}
/>
@@ -197,11 +220,16 @@ export function CommentReply(
isOwned: boolean;
isActive: boolean;
isThreaded?: boolean;
+ actionsDropdown?: boolean;
}>
) {
const thisAuthor = useAuthor();
- const { getCommentById, highlightedCommentId, documentId } =
- useContext(CommentsContext);
+ const {
+ getCommentById,
+ highlightedCommentId,
+ documentId,
+ setMessageEditing,
+ } = useContext(CommentsContext);
const maybeBlockName = useMaybeBlockAliasedName();
const reply = createMemo(() => getCommentById(props.replyId));
const isHighlighted = createMemo(
@@ -228,11 +256,19 @@ export function CommentReply(
};
};
- const [isEditing, setIsEditing] = createSignal<boolean>(false);
+ const [isEditing, setIsEditingSignal] = createSignal<boolean>(false);
+ // As in Comment: explicit reporting at each mutation site, retracted on
+ // unmount.
+ const setIsEditing = (editing: boolean) => {
+ setIsEditingSignal(editing);
+ setMessageEditing?.(props.replyId, editing);
+ };
const [textValue, setTextValue] = createSignal<string>('');
createEffect(() => setTextValue(reply()?.text ?? ''));
+ onCleanup(() => setMessageEditing?.(props.replyId, false));
+
const authorId = createMemo(() => reply()?.author ?? thisAuthor() ?? '');
const date = () => reply()?.createdAt;
const isNew = createMemo(() => reply()?.isNew ?? true);
@@ -260,6 +296,7 @@ export function CommentReply(
hideBottomMargin
isOwned={props.isOwned}
isActive={props.isActive}
+ actionsDropdown={props.actionsDropdown}
/>
<CommentText text={reply()?.text ?? ''} />
{props.children}
@@ -275,6 +312,7 @@ export function CommentReply(
isEditing
isOwned={props.isOwned}
isActive={props.isActive}
+ actionsDropdown={props.actionsDropdown}
/>
<EditInput
handleCancel={() => {
@@ -288,6 +326,7 @@ export function CommentReply(
setTextValue(newText);
return result;
}}
+ deactivateThreadOnCancel={false}
hidePadding
isReply
setEditing={setIsEditing}
diff --git a/apps/web/src/lib/core/comments/Inputs.tsx b/apps/web/src/lib/core/comments/Inputs.tsx
index 5ddecd9482..b00d360199 100644
--- a/apps/web/src/lib/core/comments/Inputs.tsx
+++ b/apps/web/src/lib/core/comments/Inputs.tsx
@@ -41,6 +41,13 @@ export function EditInput(props: {
handleCancel: () => void;
onSend: (newText: string) => unknown | Promise<unknown>;
hidePadding?: boolean;
+ /**
+ * Cancel normally also deactivates the thread (dismissing a draft). Editing
+ * an existing message opts out — cancelling just returns to viewing it —
+ * and so does the drawer's pinned reply composer, where deactivating would
+ * close the whole drawer instead of collapsing back to the "Reply…" row.
+ */
+ deactivateThreadOnCancel?: boolean;
isNewReply?: boolean;
isNewThread?: boolean;
isReply?: boolean;
@@ -64,7 +71,9 @@ export function EditInput(props: {
e.stopPropagation();
props.handleCancel();
props.setEditing?.(false);
- setActiveThread(null);
+ if (props.deactivateThreadOnCancel ?? true) {
+ setActiveThread(null);
+ }
setMentions([]);
});
};
@@ -91,7 +100,7 @@ export function EditInput(props: {
return (
<div
- class={cn('p-2 pb-8')}
+ class={cn('relative p-2 pb-12')}
on:click={(e) => {
e.stopPropagation();
focusEditor();
@@ -134,12 +143,14 @@ export function EditInput(props: {
export function NewReplyInput(props: {
createReply: (message: string) => unknown | Promise<unknown>;
isEditing: boolean;
+ /** See EditInput.deactivateThreadOnCancel. */
+ deactivateThreadOnCancel?: boolean;
setEditing: (newVal: boolean) => void;
setTextValue: (newVal: string) => void;
textValue: string;
}) {
return (
- <div class="flex w-full flex-col mt-2">
+ <div class="flex w-full flex-col">
<div class="h-px bg-edge-muted w-[calc(100%+1rem)] -mx-2"></div>
<Show
when={props.isEditing}
@@ -158,6 +169,7 @@ export function NewReplyInput(props: {
<EditInput
textValue={props.textValue}
handleCancel={() => props.setTextValue('')}
+ deactivateThreadOnCancel={props.deactivateThreadOnCancel}
onSend={(message) => {
const result = props.createReply(message);
props.setTextValue('');
diff --git a/apps/web/src/lib/core/comments/MessageTopRow.tsx b/apps/web/src/lib/core/comments/MessageTopRow.tsx
index 91701de202..ec00898607 100644
--- a/apps/web/src/lib/core/comments/MessageTopRow.tsx
+++ b/apps/web/src/lib/core/comments/MessageTopRow.tsx
@@ -3,10 +3,11 @@ import { isMobileWidth } from '@core/mobile/mobileWidth';
import { idToDisplayName } from '@core/user';
import { type DateValue, formatDate } from '@core/util/date';
import Check from '@phosphor/check.svg';
+import DotsThreeIcon from '@phosphor/dots-three.svg';
import Link from '@phosphor/link.svg';
import NotePencil from '@phosphor/note-pencil.svg';
import Trash from '@phosphor-icons/core/regular/trash.svg?component-solid';
-import { Button, cn } from '@ui';
+import { Button, cn, Dropdown } from '@ui';
import { type ParentProps, Show, useContext } from 'solid-js';
import { CommentsContext } from './Thread';
@@ -26,6 +27,8 @@ function MessageRow(
hideBottomMargin?: boolean;
nameSlot?: any;
isActive: boolean;
+ actionsVisible?: boolean;
+ largeAvatar?: boolean;
}>
) {
return (
@@ -35,6 +38,8 @@ function MessageRow(
hideBottomMargin={props.hideBottomMargin}
nameSlot={props.nameSlot}
isActive={props.isActive}
+ actionsVisible={props.actionsVisible}
+ largeAvatar={props.largeAvatar}
children={props.children}
/>
);
@@ -48,6 +53,10 @@ function MessageRowUI(
nameSlot?: any;
hideBubble?: boolean;
isActive: boolean;
+ /** Keep the actions slot permanently visible instead of hover-revealed. */
+ actionsVisible?: boolean;
+ /** size-8 avatar instead of the compact size-4. */
+ largeAvatar?: boolean;
}>
) {
const displayName = () => {
@@ -62,25 +71,31 @@ function MessageRowUI(
>
<div
class={cn(
- 'flex w-full flex-row gap-2 group-hover:truncate',
+ 'flex items-center w-full flex-row gap-2 group-hover:truncate',
props.isActive && 'truncate'
)}
>
{!props.hideBubble && (
<div
- class={`size-4 relative flex items-center justify-center shrink-0 rounded-xs`}
+ class={cn(
+ 'relative flex items-center justify-center shrink-0 rounded-xs',
+ props.largeAvatar ? 'size-8' : 'size-4'
+ )}
>
<UserIcon
- size="sm"
+ // Avatar has no size-8 variant; "fill" adopts the wrapper size.
+ size={props.largeAvatar ? 'fill' : 'sm'}
suppressClick={true}
id={props.authorId}
isDeleted={false}
/>
</div>
)}
- <div class="text-xs text-ink truncate grow">{displayName()}</div>
+ <div class="text-xs touch:text-sm text-ink truncate grow">
+ {displayName()}
+ </div>
<Show when={props.date}>
- <div class="text-xs text-ink-placeholder">
+ <div class="text-xs touch:text-sm text-ink-placeholder">
{formatDate(props.date)}
</div>
</Show>
@@ -88,8 +103,10 @@ function MessageRowUI(
<Show when={props.children}>
<div
class={cn(
- 'items-center flex group-hover:opacity-100',
- isMobileWidth() && props.isActive ? 'opacity-100' : 'opacity-0'
+ 'items-center flex self-center group-hover:opacity-100',
+ props.actionsVisible || (isMobileWidth() && props.isActive)
+ ? 'opacity-100'
+ : 'opacity-0'
)}
>
{props.children}
@@ -112,9 +129,75 @@ export function MessageTopRow(props: {
isOwned: boolean;
isActive: boolean;
isEditing?: boolean;
+ /**
+ * Render the actions as an always-visible ellipsis dropdown at the row's
+ * end instead of the hover-revealed overlay (the touch comment drawer,
+ * where there is no hover).
+ */
+ actionsDropdown?: boolean;
}) {
const { canComment, isDocumentOwner } = useContext(CommentsContext);
+ const showEdit = () =>
+ canComment() && props.isOwned && props.enableEditing != null;
+ const showDelete = () =>
+ canComment() &&
+ !props.isEditing &&
+ (props.isOwned || isDocumentOwner()) &&
+ props.deleteMessage != null;
+
+ if (props.actionsDropdown) {
+ return (
+ <MessageRow
+ nameSlot={props.isNew && <NewTag />}
+ authorId={props.authorId}
+ date={props.date}
+ hideBottomMargin={props.hideBottomMargin}
+ isActive={props.isActive}
+ actionsVisible
+ largeAvatar
+ >
+ <Show when={props.copyLink != null || showEdit() || showDelete()}>
+ <Dropdown>
+ <Dropdown.Trigger
+ variant="ghost"
+ size="icon-sm"
+ class="-my-1"
+ aria-label="Comment actions"
+ >
+ <DotsThreeIcon />
+ </Dropdown.Trigger>
+ <Dropdown.Content portalScope="local">
+ <Dropdown.Group>
+ <Show when={props.copyLink}>
+ <Dropdown.Item onSelect={props.copyLink}>
+ <Link class="size-4" />
+ Copy link
+ </Dropdown.Item>
+ </Show>
+ <Show when={showEdit()}>
+ <Dropdown.Item onSelect={props.enableEditing}>
+ <NotePencil class="size-4" />
+ Edit comment
+ </Dropdown.Item>
+ </Show>
+ <Show when={showDelete()}>
+ <Dropdown.Item
+ class="text-failure-ink"
+ onSelect={props.deleteMessage}
+ >
+ <Trash class="size-4" />
+ Delete comment
+ </Dropdown.Item>
+ </Show>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ </MessageRow>
+ );
+ }
+
return (
<MessageRow
nameSlot={props.isNew && <NewTag />}
diff --git a/apps/web/src/lib/core/comments/MinimizedThreads.tsx b/apps/web/src/lib/core/comments/MinimizedThreads.tsx
index 9217274c08..3b17129273 100644
--- a/apps/web/src/lib/core/comments/MinimizedThreads.tsx
+++ b/apps/web/src/lib/core/comments/MinimizedThreads.tsx
@@ -18,18 +18,27 @@ export function MinimizedThread(props: {
isActive: boolean;
theme?: EditorThemeClasses;
maxHeight?: number;
+ /**
+ * When false, tapping only activates the thread instead of expanding the
+ * floating card in place — for hosts that present the active thread
+ * elsewhere (the touch comment drawer).
+ */
+ expandable?: boolean;
}) {
const [expanded, setExpanded] = createSignal<boolean>(false);
const [expandedThreadRef, setExpandedThreadRef] = createSignal<
HTMLDivElement | undefined
>(undefined);
- if (props.comment.isNew) {
+ const expandable = () => props.expandable !== false;
+
+ if (props.comment.isNew && expandable()) {
setExpanded(true);
}
- const { highlightedCommentId } = useContext(CommentsContext);
+ const { highlightedCommentId, setActiveThread } = useContext(CommentsContext);
createEffect(() => {
+ if (!expandable()) return;
const hId = highlightedCommentId();
if (hId === null) return;
if (hId === props.comment.id || props.comment.children.includes(hId)) {
@@ -68,7 +77,11 @@ export function MinimizedThread(props: {
const commentCount = () => 1 + props.comment.children.length;
const clickHandler = () => {
- setExpanded(true);
+ if (expandable()) {
+ setExpanded(true);
+ } else {
+ setActiveThread(props.comment.threadId);
+ }
};
return (
diff --git a/apps/web/src/lib/core/comments/Thread.tsx b/apps/web/src/lib/core/comments/Thread.tsx
index 1eb477f1ab..6d774f5eaf 100644
--- a/apps/web/src/lib/core/comments/Thread.tsx
+++ b/apps/web/src/lib/core/comments/Thread.tsx
@@ -54,10 +54,8 @@ export const threadMeasureContainerId = (
export const ThreadContext = createContext<{
mentionsSignal: Signal<UserMentionRecord[]>;
- measureContainerEl: Accessor<HTMLElement | null>;
}>({
mentionsSignal: [() => [], () => {}],
- measureContainerEl: () => null,
});
export type CommentsContextType = {
@@ -71,6 +69,11 @@ export type CommentsContextType = {
ownedComment: (id: number) => boolean;
inComment: boolean;
highlightedCommentId: Accessor<number | null>;
+ /**
+ * When set (the touch drawer), messages report their inline-edit state so
+ * the host can hide its pinned reply composer while an edit is open.
+ */
+ setMessageEditing?: (commentId: number, editing: boolean) => void;
};
export const CommentsContext = createContext<CommentsContextType>({
@@ -90,18 +93,27 @@ export const CommentsContext = createContext<CommentsContextType>({
highlightedCommentId: () => null,
});
-export function Thread(props: {
+/**
+ * The content of a comment thread: the root comment with its replies and the
+ * reply input, or the new-comment composer for a draft. Positioning-agnostic —
+ * `Thread` wraps it in the floating margin card, and the touch comment drawer
+ * renders it directly.
+ */
+export function ThreadBody(props: {
comment: Root;
- layout: Layout;
isActive: boolean;
theme?: EditorThemeClasses;
- maxHeight?: number;
- handleMouseDown?: (e: MouseEvent) => void;
- ref?: (el: HTMLDivElement) => void;
- width?: number;
+ /**
+ * Suppress the in-thread reply input — the touch drawer pins its own
+ * composer at the drawer bottom instead.
+ */
+ hideReplyInput?: boolean;
+ /**
+ * Render each message's actions as an always-visible ellipsis dropdown
+ * instead of hover-revealed buttons (the touch drawer has no hover).
+ */
+ actionsDropdown?: boolean;
}) {
- let measureContainerRef!: HTMLDivElement;
-
const {
canComment,
commentOperations,
@@ -168,154 +180,172 @@ export function Thread(props: {
}
});
- onMount(() => {
- if (!props.handleMouseDown) return;
- const handleMouseDown = props.handleMouseDown;
- measureContainerRef.addEventListener('mousedown', handleMouseDown);
- onCleanup(() => {
- measureContainerRef.removeEventListener('mousedown', handleMouseDown);
- });
- });
-
const mentionsSignal = createSignal<UserMentionRecord[]>([]);
return (
- <ThreadContext.Provider
- value={{
- mentionsSignal,
- measureContainerEl: () => measureContainerRef,
- }}
- >
+ <ThreadContext.Provider value={{ mentionsSignal }}>
<StaticMarkdownContext theme={props.theme ?? baseCommentTheme}>
- <MeasureContainer
- alignment="right"
- alignmentOffset={0}
- ref={measureContainerRef}
- top={props.layout.calculatedYPos}
- threadId={props.comment.threadId}
- maxHeight={props.maxHeight}
- isActive={props.isActive}
- forceWidth={props.width}
- transition={false}
- >
- <Layer depth={2}>
- <div
- // note: pdf-pointer-event-reset is a strange one-off class that mostly normalizes
- // pointer-events: none vs. all inside the .pdfOverlayInner div.
- class="shrink-0 border border-edge bg-surface p-2 shadow-md rounded-xl shadow-drop-shadow portal-scope pointer-events-auto pdf-pointer-event-reset"
- classList={{
- 'transition-transform duration-100': true,
- '-translate-x-8': props.isActive,
- }}
- style={{
- width: props.width ? `${props.width}px` : 'auto',
+ <Show
+ when={!props.comment.isNew}
+ fallback={
+ <EditInput
+ textValue={''}
+ handleCancel={() => {}}
+ onSend={(content: string) => {
+ if (content.trim() === '') return;
+ // NOTE: we need the server to return the thread id first
+ return commentOperations.createComment({
+ threadId: props.comment.threadId,
+ text: content,
+ mentions: getAndClearCommentMentions(mentionsSignal),
+ });
}}
- ref={props.ref}
+ isNewThread
+ />
+ }
+ >
+ <div
+ on:click={() => {
+ dispatch({ action: 'soft', editing: false });
+ }}
+ >
+ <Comment
+ comment={props.comment}
+ isOwned={ownedComment(props.comment.id)}
+ isActive={props.isActive}
+ isThreaded={replyIds().length > 0}
+ actionsDropdown={props.actionsDropdown}
>
- <Show
- when={!props.comment.isNew}
- fallback={
- <EditInput
- textValue={''}
- handleCancel={() => {}}
- onSend={(content: string) => {
- if (content.trim() === '') return;
- // NOTE: we need the server to return the thread id first
- return commentOperations.createComment({
- threadId: props.comment.threadId,
- text: content,
- mentions: getAndClearCommentMentions(mentionsSignal),
+ <Show when={replyIds().length > 0 && lastReplyId()}>
+ <Show when={collapsedCount() > 0}>
+ <button
+ class="text-xs text-ink-extra-muted hover:bg-hover text-left ml-5 rounded p-1 px-2 mb-2"
+ on:click={() => {
+ batch(() => {
+ setActiveThread(props.comment.threadId);
+ setAllRepliesVisible(true);
});
}}
- isNewThread
- />
- }
- >
- <div
- on:click={() => {
- dispatch({ action: 'soft', editing: false });
- }}
- >
- <Comment
- comment={props.comment}
- isOwned={ownedComment(props.comment.id)}
- isActive={props.isActive}
- isThreaded={replyIds().length > 0}
>
- <Show when={replyIds().length > 0 && lastReplyId()}>
- <Show when={collapsedCount() > 0}>
- <button
- class="text-xs text-ink-extra-muted hover:bg-hover text-left ml-5 rounded p-1 px-2 mb-2"
- on:click={() => {
- batch(() => {
- setActiveThread(props.comment.threadId);
- setAllRepliesVisible(true);
- });
- }}
- >
- {`Show ${collapsedCount()} ${collapsedCount() > 1 ? 'replies' : 'reply'}`}
- </button>
- </Show>
- </Show>
- </Comment>
- {
- <For each={replyIds()}>
- {(replyId) => {
- const hide = () =>
- collapseRepliesList() && replyId !== lastReplyId();
- return (
- <CommentReply
- hide={hide()}
- replyId={replyId}
- isOwned={ownedComment(replyId)}
- isActive={props.isActive}
- threadId={props.comment.threadId}
- isThreaded={replyId !== lastReplyId()}
- deleteReply={() =>
- commentOperations.deleteComment({
- commentId: replyId,
- })
- }
- updateReply={(content) => {
- return Promise.all([
- commentOperations.updateComment(replyId, {
- text: content,
- threadId: props.comment.threadId,
- mentions:
- getAndClearCommentMentions(mentionsSignal),
- }),
- ]);
- }}
- />
- );
- }}
- </For>
- }
- </div>
- <Show when={showNewReplyInput()}>
- <NewReplyInput
- textValue={textValue()}
- setTextValue={(val) => dispatch({ action: 'text', val })}
- createReply={(content) => {
- if (content.trim() === '') return;
- dispatch({ action: 'hard', editing: false });
- return commentOperations.createComment({
- threadId: props.comment.threadId,
- text: content,
- mentions: getAndClearCommentMentions(mentionsSignal),
- });
- }}
- isEditing={isEditingNewReply()}
- setEditing={(editing) =>
- dispatch({ action: 'hard', editing })
- }
- />
+ {`Show ${collapsedCount()} ${collapsedCount() > 1 ? 'replies' : 'reply'}`}
+ </button>
</Show>
</Show>
+ </Comment>
+ {
+ <For each={replyIds()}>
+ {(replyId) => {
+ const hide = () =>
+ collapseRepliesList() && replyId !== lastReplyId();
+ return (
+ <CommentReply
+ hide={hide()}
+ replyId={replyId}
+ isOwned={ownedComment(replyId)}
+ isActive={props.isActive}
+ threadId={props.comment.threadId}
+ isThreaded={replyId !== lastReplyId()}
+ actionsDropdown={props.actionsDropdown}
+ deleteReply={() =>
+ commentOperations.deleteComment({
+ commentId: replyId,
+ })
+ }
+ updateReply={(content) => {
+ return Promise.all([
+ commentOperations.updateComment(replyId, {
+ text: content,
+ threadId: props.comment.threadId,
+ mentions:
+ getAndClearCommentMentions(mentionsSignal),
+ }),
+ ]);
+ }}
+ />
+ );
+ }}
+ </For>
+ }
+ </div>
+ <Show when={showNewReplyInput() && !props.hideReplyInput}>
+ <div class="mt-2">
+ <NewReplyInput
+ textValue={textValue()}
+ setTextValue={(val) => dispatch({ action: 'text', val })}
+ createReply={(content) => {
+ if (content.trim() === '') return;
+ dispatch({ action: 'hard', editing: false });
+ return commentOperations.createComment({
+ threadId: props.comment.threadId,
+ text: content,
+ mentions: getAndClearCommentMentions(mentionsSignal),
+ });
+ }}
+ isEditing={isEditingNewReply()}
+ setEditing={(editing) => dispatch({ action: 'hard', editing })}
+ />
</div>
- </Layer>
- </MeasureContainer>
+ </Show>
+ </Show>
</StaticMarkdownContext>
</ThreadContext.Provider>
);
}
+
+export function Thread(props: {
+ comment: Root;
+ layout: Layout;
+ isActive: boolean;
+ theme?: EditorThemeClasses;
+ maxHeight?: number;
+ handleMouseDown?: (e: MouseEvent) => void;
+ ref?: (el: HTMLDivElement) => void;
+ width?: number;
+}) {
+ let measureContainerRef!: HTMLDivElement;
+
+ onMount(() => {
+ if (!props.handleMouseDown) return;
+ const handleMouseDown = props.handleMouseDown;
+ measureContainerRef.addEventListener('mousedown', handleMouseDown);
+ onCleanup(() => {
+ measureContainerRef.removeEventListener('mousedown', handleMouseDown);
+ });
+ });
+
+ return (
+ <MeasureContainer
+ alignment="right"
+ alignmentOffset={0}
+ ref={measureContainerRef}
+ top={props.layout.calculatedYPos}
+ threadId={props.comment.threadId}
+ maxHeight={props.maxHeight}
+ isActive={props.isActive}
+ forceWidth={props.width}
+ transition={false}
+ >
+ <Layer depth={2}>
+ <div
+ // note: pdf-pointer-event-reset is a strange one-off class that mostly normalizes
+ // pointer-events: none vs. all inside the .pdfOverlayInner div.
+ class="shrink-0 border border-edge bg-surface p-2 shadow-md rounded-xl shadow-drop-shadow portal-scope pointer-events-auto pdf-pointer-event-reset"
+ classList={{
+ 'transition-transform duration-100': true,
+ '-translate-x-8': props.isActive,
+ }}
+ style={{
+ width: props.width ? `${props.width}px` : 'auto',
+ }}
+ ref={props.ref}
+ >
+ <ThreadBody
+ comment={props.comment}
+ isActive={props.isActive}
+ theme={props.theme}
+ />
+ </div>
+ </Layer>
+ </MeasureContainer>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
index 8adff8b591..6adf21d62a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
@@ -22,6 +22,7 @@ import {
COMMAND_PRIORITY_EDITOR,
createCommand,
type LexicalEditor,
+ type LexicalNode,
type NodeKey,
} from 'lexical';
import { v7 } from 'uuid';
@@ -41,6 +42,39 @@ interface CommentOperations {
init: () => void;
}
+/**
+ * The comment mark ids a caret position sits in, covering the boundaries
+ * `$getMarkIDs` misses: it looks forward from a text node's end to a
+ * following mark, but never backward from a text node's start — yet a caret
+ * placed immediately after a commented range lands at offset 0 of the next
+ * node. From a reader's perspective both positions touch the comment, so
+ * both resolve to it. Must run inside an editor read/update.
+ */
+export function $getMarkIdsAtCaret(
+ anchorNode: LexicalNode,
+ offset: number
+): string[] | null {
+ if ($isTextNode(anchorNode)) {
+ const markIds = $getMarkIDs(anchorNode, offset);
+ if (markIds != null) return markIds;
+ if (offset === 0) {
+ const prevSibling = anchorNode.getPreviousSibling();
+ if ($isTextNode(prevSibling)) {
+ // Check to see if last position of previous text node has marks
+ return $getMarkIDs(prevSibling, prevSibling.getTextContentSize());
+ }
+ if ($isCommentNode(prevSibling)) {
+ return prevSibling.getIDs();
+ }
+ }
+ return null;
+ }
+ if ($isCommentNode(anchorNode)) {
+ return anchorNode.getIDs();
+ }
+ return null;
+}
+
export const CREATE_DRAFT_COMMENT_COMMAND = createCommand<void>(
'CREATE_DRAFT_COMMENT_COMMAND'
);
@@ -247,40 +281,13 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
let newActiveIds: string[] | undefined;
if ($isRangeSelection(selection)) {
- const anchorNode = selection.anchor.getNode();
-
- if ($isTextNode(anchorNode)) {
- const markIds = $getMarkIDs(anchorNode, selection.anchor.offset);
- if (markIds != null) {
- newActiveIds = markIds;
- hasActiveIds = true;
- }
- if (markIds === null && selection.anchor.offset === 0) {
- const prevSibling = anchorNode.getPreviousSibling();
- if ($isTextNode(prevSibling)) {
- // Check to see if last position of previous text node has marks
- const markIds = $getMarkIDs(
- prevSibling,
- prevSibling.getTextContentSize()
- );
- if (markIds != null) {
- newActiveIds = markIds;
- hasActiveIds = true;
- }
- } else if ($isCommentNode(prevSibling)) {
- const markIds = prevSibling.getIDs();
- if (markIds != null) {
- newActiveIds = markIds;
- hasActiveIds = true;
- }
- }
- }
- } else if ($isCommentNode(anchorNode)) {
- const markIds = anchorNode.getIDs();
- if (markIds != null) {
- newActiveIds = markIds;
- hasActiveIds = true;
- }
+ const markIds = $getMarkIdsAtCaret(
+ selection.anchor.getNode(),
+ selection.anchor.offset
+ );
+ if (markIds != null) {
+ newActiveIds = markIds;
+ hasActiveIds = true;
}
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
index 196b29163b..27c8523498 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
@@ -47,6 +47,12 @@ export const RECOMPUTE_SELECTION_RECT: LexicalCommand<void> = createCommand(
type PopupPluginProps = {
setIsPopupVisible: (value: boolean) => boolean;
setSelection: (value: any) => void;
+ /**
+ * Lets the host show the popup for an empty (collapsed) range selection it
+ * cares about — e.g. a caret inside a comment mark. Runs in a lexical read
+ * context. Without it, empty selections never show the popup.
+ */
+ $allowEmptySelection?: (selection: RangeSelection) => boolean;
};
function $tableSelectionToRect(selection: TableSelection) {
@@ -177,15 +183,18 @@ function registerPopupPlugin(editor: LexicalEditor, props: PopupPluginProps) {
return $enhanceTableSelection(selection);
}
- if (selection.getTextContent().length === 0) {
+ if (!$isRangeSelection(selection)) {
return null;
}
- if ($isRangeSelection(selection)) {
- return $enhanceRangeSelection(selection);
+ if (
+ selection.getTextContent().length === 0 &&
+ !props.$allowEmptySelection?.(selection)
+ ) {
+ return null;
}
- return null;
+ return $enhanceRangeSelection(selection);
}
return mergeRegister(
diff --git a/apps/web/src/lib/core/mobile/nativeEditMenu.ts b/apps/web/src/lib/core/mobile/nativeEditMenu.ts
new file mode 100644
index 0000000000..0a7507e134
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/nativeEditMenu.ts
@@ -0,0 +1,40 @@
+import { isPlatform } from '@core/util/platform';
+import { invoke } from '@tauri-apps/api/core';
+
+/**
+ * Whether the native iOS edit-menu integration applies: suppression of the
+ * system text-selection menu and pasteboard reads for the in-app Paste.
+ */
+export function hasNativeEditMenu(): boolean {
+ return isPlatform('ios');
+}
+
+/**
+ * Toggles suppression of the native iOS text-selection menu so it doesn't
+ * stack on top of the in-app selection popup. No-op outside the iOS app.
+ */
+export function setNativeEditMenuSuppressed(suppressed: boolean): void {
+ if (!hasNativeEditMenu()) return;
+ void invoke('plugin:edit-menu|set_native_menu_suppressed', {
+ suppressed,
+ }).catch((error) => {
+ console.error('failed to toggle native edit menu suppression', error);
+ });
+}
+
+/**
+ * Reads plain text from the system pasteboard. Returns null when unavailable
+ * (not the iOS app, or no text on the pasteboard).
+ */
+export async function readNativePasteboardText(): Promise<string | null> {
+ if (!hasNativeEditMenu()) return null;
+ try {
+ const result = await invoke<{ text: string | null }>(
+ 'plugin:pasteboard|read_pasteboard_text'
+ );
+ return result.text;
+ } catch (error) {
+ console.error('failed to read pasteboard text', error);
+ return null;
+ }
+}
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 3715440532..df01d213ee 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -216,6 +216,7 @@ dependencies = [
"tauri-plugin-call-kit",
"tauri-plugin-deep-link",
"tauri-plugin-device-info",
+ "tauri-plugin-edit-menu",
"tauri-plugin-haptics",
"tauri-plugin-http",
"tauri-plugin-input-accessory",
@@ -6410,6 +6411,15 @@ dependencies = [
"wmi",
]
+[[package]]
+name = "tauri-plugin-edit-menu"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "tauri",
+ "tauri-plugin",
+]
+
[[package]]
name = "tauri-plugin-fs"
version = "2.5.1"
diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.toml
index 6b33852299..1be3381205 100644
--- a/apps/web/tauri/Cargo.toml
+++ b/apps/web/tauri/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
members = [
"callkit_plugin",
+ "edit_menu_plugin",
"graphql_cache_plugin",
"input_accessory_plugin",
"logger",
diff --git a/apps/web/tauri/edit_menu_plugin/.gitignore b/apps/web/tauri/edit_menu_plugin/.gitignore
new file mode 100644
index 0000000000..a2ba4dd574
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/.gitignore
@@ -0,0 +1,6 @@
+# Swift Package Manager build artifacts
+ios/.build/
+ios/Package.resolved
+
+# Tauri-generated Swift API (placed here by `cargo tauri ios build`)
+.tauri/
diff --git a/apps/web/tauri/edit_menu_plugin/Cargo.toml b/apps/web/tauri/edit_menu_plugin/Cargo.toml
new file mode 100644
index 0000000000..7961622acf
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "tauri-plugin-edit-menu"
+version = "0.1.0"
+edition = "2024"
+links = "tauri-plugin-edit-menu"
+
+[build-dependencies]
+tauri-plugin = { version = "2.4", features = ["build"] }
+
+[dependencies]
+serde = { workspace = true, features = ["derive"] }
+tauri = { workspace = true }
+
+[target.'cfg(target_os = "ios")'.dependencies]
+tauri = { workspace = true, features = ["wry"] }
diff --git a/apps/web/tauri/edit_menu_plugin/build.rs b/apps/web/tauri/edit_menu_plugin/build.rs
new file mode 100644
index 0000000000..41d9343fc0
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/build.rs
@@ -0,0 +1,6 @@
+fn main() {
+ tauri_plugin::Builder::new(&["set_native_menu_suppressed"])
+ .ios_path("ios")
+ .try_build()
+ .unwrap();
+}
diff --git a/apps/web/tauri/edit_menu_plugin/ios/Package.swift b/apps/web/tauri/edit_menu_plugin/ios/Package.swift
new file mode 100644
index 0000000000..36343d824c
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/ios/Package.swift
@@ -0,0 +1,29 @@
+// swift-tools-version:5.3
+import PackageDescription
+
+let package = Package(
+ name: "tauri-plugin-edit-menu",
+ platforms: [
+ .macOS(.v10_13),
+ .iOS(.v14),
+ ],
+ products: [
+ .library(
+ name: "tauri-plugin-edit-menu",
+ type: .static,
+ targets: ["tauri-plugin-edit-menu"]
+ )
+ ],
+ dependencies: [
+ .package(name: "Tauri", path: "../.tauri/tauri-api")
+ ],
+ targets: [
+ .target(
+ name: "tauri-plugin-edit-menu",
+ dependencies: [
+ .byName(name: "Tauri")
+ ],
+ path: "Sources"
+ )
+ ]
+)
diff --git a/apps/web/tauri/edit_menu_plugin/ios/Sources/EditMenuPlugin.swift b/apps/web/tauri/edit_menu_plugin/ios/Sources/EditMenuPlugin.swift
new file mode 100644
index 0000000000..54f8e3d825
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/ios/Sources/EditMenuPlugin.swift
@@ -0,0 +1,135 @@
+import UIKit
+import WebKit
+import Tauri
+
+private struct SetNativeMenuSuppressedArgs: Decodable {
+ let suppressed: Bool
+}
+
+/// Suppresses the native text-selection edit menu (Copy | Look Up | Share …)
+/// while the in-app selection popup is showing, so the two don't stack.
+///
+/// iOS (16+) assembles the edit menu through the responder chain's
+/// `buildMenu(with:)`. WKWebView offers no delegate for customizing it — the
+/// `editMenuForTextIn:` delegate is UITextView-only — so, like
+/// InputAccessoryPlugin, this swizzles an override onto WebKit's content view
+/// class (the first responder during text selection) that strips the system
+/// menus whenever the frontend has flagged suppression. Selection handles,
+/// the magnifier, dictation, and hardware-keyboard shortcuts (which build
+/// through `UIMenuSystem.main`) are unaffected.
+class EditMenuPlugin: Plugin {
+ fileprivate static var suppressNativeEditMenu = false
+ fileprivate static weak var contentView: UIView?
+ private static var isSwizzled = false
+
+ override public func load(webview: WKWebView) {
+ guard let contentView = findContentView(in: webview) else { return }
+ EditMenuPlugin.contentView = contentView
+ if !EditMenuPlugin.isSwizzled, let cls = object_getClass(contentView),
+ swizzleBuildMenu(on: cls)
+ {
+ EditMenuPlugin.isSwizzled = true
+ }
+ }
+
+ @objc public func setNativeMenuSuppressed(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(SetNativeMenuSuppressedArgs.self)
+ EditMenuPlugin.suppressNativeEditMenu = args.suppressed
+ if args.suppressed {
+ // The flag only gates the next `buildMenu` pass; a menu that
+ // presented before it crossed the JS→native bridge is already
+ // on screen and must be taken down explicitly.
+ DispatchQueue.main.async {
+ dismissPresentedEditMenu()
+ }
+ }
+ invoke.resolve()
+ }
+}
+
+private func findContentView(in rootView: UIView) -> UIView? {
+ var queue = rootView.subviews
+ while !queue.isEmpty {
+ let view = queue.removeFirst()
+ if NSStringFromClass(type(of: view)).hasPrefix("WKContent") {
+ return view
+ }
+ queue.append(contentsOf: view.subviews)
+ }
+ return nil
+}
+
+private func dismissPresentedEditMenu() {
+ if #available(iOS 16.0, *) {
+ // WKContentView presents the modern edit menu through a
+ // UIEditMenuInteraction it adds to itself.
+ for interaction in EditMenuPlugin.contentView?.interactions ?? [] {
+ (interaction as? UIEditMenuInteraction)?.dismissMenu()
+ }
+ } else {
+ UIMenuController.shared.hideMenu()
+ }
+}
+
+private typealias BuildMenuIMP = @convention(c) (AnyObject, Selector, UIMenuBuilder) -> Void
+
+private func swizzleBuildMenu(on cls: AnyClass) -> Bool {
+ let selector = #selector(UIResponder.buildMenu(with:))
+ guard let method = class_getInstanceMethod(cls, selector) else { return false }
+ let inheritedIMP = method_getImplementation(method)
+ var replacedIMP: IMP?
+
+ let overrideBlock: @convention(block) (AnyObject, UIMenuBuilder) -> Void = { target, builder in
+ let original = unsafeBitCast(replacedIMP ?? inheritedIMP, to: BuildMenuIMP.self)
+ original(target, selector, builder)
+ guard
+ EditMenuPlugin.suppressNativeEditMenu,
+ builder.system !== UIMenuSystem.main
+ else { return }
+ removeEditMenus(from: builder)
+ }
+
+ // If the content view class implements `buildMenu` itself, the original
+ // implementation is swapped in place (and returned for chaining);
+ // otherwise an override is added and the inherited implementation is
+ // chained instead.
+ replacedIMP = class_replaceMethod(
+ cls,
+ selector,
+ imp_implementationWithBlock(overrideBlock),
+ method_getTypeEncoding(method)
+ )
+ return true
+}
+
+private func removeEditMenus(from builder: UIMenuBuilder) {
+ // Known edit-menu groups as of iOS 18; new OS releases can introduce more
+ // (e.g. Writing Tools), so expect an occasional device pass to extend
+ // this list.
+ var identifiers: [UIMenu.Identifier] = [
+ .standardEdit, // Cut / Copy / Paste
+ .lookup, // Look Up / Search Web / Translate
+ .share,
+ .replace, // autocorrect "Replace…"
+ .learn,
+ .textStyle, // Bold / Italics / Underline
+ .spelling,
+ .substitutions,
+ .transformations,
+ .speech, // Speak / Spell Out
+ ]
+ if #available(iOS 16.0, *) {
+ identifiers.append(.find)
+ }
+ if #available(iOS 17.0, *) {
+ identifiers.append(.autoFill)
+ }
+ for identifier in identifiers {
+ builder.remove(menu: identifier)
+ }
+}
+
+@_cdecl("init_plugin_edit_menu")
+func initPlugin() -> Plugin {
+ return EditMenuPlugin()
+}
diff --git a/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/commands/set_native_menu_suppressed.toml b/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/commands/set_native_menu_suppressed.toml
new file mode 100644
index 0000000000..ad401cad62
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/commands/set_native_menu_suppressed.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-set-native-menu-suppressed"
+description = "Enables the set_native_menu_suppressed command without any pre-configured scope."
+commands.allow = ["set_native_menu_suppressed"]
+
+[[permission]]
+identifier = "deny-set-native-menu-suppressed"
+description = "Denies the set_native_menu_suppressed command without any pre-configured scope."
+commands.deny = ["set_native_menu_suppressed"]
diff --git a/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/reference.md
new file mode 100644
index 0000000000..d12c4b3ee7
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/permissions/autogenerated/reference.md
@@ -0,0 +1,35 @@
+## Permission Table
+
+<table>
+<tr>
+<th>Identifier</th>
+<th>Description</th>
+</tr>
+
+
+<tr>
+<td>
+
+`edit-menu:allow-set-native-menu-suppressed`
+
+</td>
+<td>
+
+Enables the set_native_menu_suppressed command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`edit-menu:deny-set-native-menu-suppressed`
+
+</td>
+<td>
+
+Denies the set_native_menu_suppressed command without any pre-configured scope.
+
+</td>
+</tr>
+</table>
diff --git a/apps/web/tauri/edit_menu_plugin/permissions/schemas/schema.json b/apps/web/tauri/edit_menu_plugin/permissions/schemas/schema.json
new file mode 100644
index 0000000000..bdd3ffd916
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/permissions/schemas/schema.json
@@ -0,0 +1,312 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the set_native_menu_suppressed command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-set-native-menu-suppressed",
+ "markdownDescription": "Enables the set_native_menu_suppressed command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the set_native_menu_suppressed command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-set-native-menu-suppressed",
+ "markdownDescription": "Denies the set_native_menu_suppressed command without any pre-configured scope."
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/web/tauri/edit_menu_plugin/src/lib.rs b/apps/web/tauri/edit_menu_plugin/src/lib.rs
new file mode 100644
index 0000000000..3f36a611a5
--- /dev/null
+++ b/apps/web/tauri/edit_menu_plugin/src/lib.rs
@@ -0,0 +1,80 @@
+//! Suppresses the native iOS text-selection edit menu (Copy | Look Up |
+//! Share …) on demand, so it doesn't stack on top of the in-app selection
+//! popup. The frontend toggles suppression while its own popup is showing.
+#![deny(missing_docs)]
+
+#[cfg(target_os = "ios")]
+use serde::Serialize;
+use tauri::{
+ AppHandle, Manager, Runtime, command,
+ plugin::{Builder, PluginHandle, TauriPlugin},
+};
+
+#[cfg(target_os = "ios")]
+tauri::ios_plugin_binding!(init_plugin_edit_menu);
+
+#[cfg(target_os = "ios")]
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetNativeMenuSuppressedPayload {
+ suppressed: bool,
+}
+
+/// Access to the edit-menu plugin.
+pub struct EditMenu<R: Runtime>(PluginHandle<R>);
+
+impl<R: Runtime> EditMenu<R> {
+ #[cfg(target_os = "ios")]
+ fn set_native_menu_suppressed(&self, suppressed: bool) -> Result<(), String> {
+ self.0
+ .run_mobile_plugin::<()>(
+ "setNativeMenuSuppressed",
+ SetNativeMenuSuppressedPayload { suppressed },
+ )
+ .map_err(|error| error.to_string())
+ }
+}
+
+/// Extension trait to access the edit-menu plugin from an app handle.
+pub trait EditMenuExt<R: Runtime> {
+ /// Returns the edit-menu plugin handle.
+ fn edit_menu(&self) -> &EditMenu<R>;
+}
+
+impl<R: Runtime, T: Manager<R>> EditMenuExt<R> for T {
+ fn edit_menu(&self) -> &EditMenu<R> {
+ self.state::<EditMenu<R>>().inner()
+ }
+}
+
+#[command]
+async fn set_native_menu_suppressed<R: Runtime>(
+ app: AppHandle<R>,
+ suppressed: bool,
+) -> Result<(), String> {
+ #[cfg(not(target_os = "ios"))]
+ {
+ let _ = (app, suppressed);
+ Ok(())
+ }
+
+ #[cfg(target_os = "ios")]
+ {
+ app.edit_menu().set_native_menu_suppressed(suppressed)
+ }
+}
+
+/// Initializes the edit-menu plugin.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ Builder::new("edit-menu")
+ .invoke_handler(tauri::generate_handler![set_native_menu_suppressed])
+ .setup(|_app, _api| {
+ #[cfg(target_os = "ios")]
+ {
+ let handle = _api.register_ios_plugin(init_plugin_edit_menu)?;
+ _app.manage(EditMenu(handle));
+ }
+ Ok(())
+ })
+ .build()
+}
diff --git a/apps/web/tauri/pasteboard_plugin/build.rs b/apps/web/tauri/pasteboard_plugin/build.rs
index 05e84a3e7d..d5a3f17537 100644
--- a/apps/web/tauri/pasteboard_plugin/build.rs
+++ b/apps/web/tauri/pasteboard_plugin/build.rs
@@ -1,5 +1,5 @@
fn main() {
- tauri_plugin::Builder::new(&["stage_pasteboard_image"])
+ tauri_plugin::Builder::new(&["read_pasteboard_text", "stage_pasteboard_image"])
.ios_path("ios")
.try_build()
.unwrap();
diff --git a/apps/web/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift b/apps/web/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift
index d9ea7a186e..47c83303e1 100644
--- a/apps/web/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift
+++ b/apps/web/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift
@@ -7,6 +7,16 @@ private struct StagePasteboardImagePayload: Decodable {
}
class PasteboardPlugin: Plugin {
+ @objc public func readPasteboardText(_ invoke: Invoke) throws {
+ DispatchQueue.main.async {
+ if let text = UIPasteboard.general.string {
+ invoke.resolve(["text": text])
+ } else {
+ invoke.resolve(["text": NSNull()])
+ }
+ }
+ }
+
@objc public func stagePasteboardImage(_ invoke: Invoke) throws {
let payload = try invoke.parseArgs(StagePasteboardImagePayload.self)
let stagingDirectory = URL(
diff --git a/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/commands/read_pasteboard_text.toml b/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/commands/read_pasteboard_text.toml
new file mode 100644
index 0000000000..e08b9d3888
--- /dev/null
+++ b/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/commands/read_pasteboard_text.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-read-pasteboard-text"
+description = "Enables the read_pasteboard_text command without any pre-configured scope."
+commands.allow = ["read_pasteboard_text"]
+
+[[permission]]
+identifier = "deny-read-pasteboard-text"
+description = "Denies the read_pasteboard_text command without any pre-configured scope."
+commands.deny = ["read_pasteboard_text"]
diff --git a/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/reference.md
index 0fccbd8bee..2a2b9289a6 100644
--- a/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/reference.md
+++ b/apps/web/tauri/pasteboard_plugin/permissions/autogenerated/reference.md
@@ -7,6 +7,32 @@
</tr>
+<tr>
+<td>
+
+`pasteboard:allow-read-pasteboard-text`
+
+</td>
+<td>
+
+Enables the read_pasteboard_text command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`pasteboard:deny-read-pasteboard-text`
+
+</td>
+<td>
+
+Denies the read_pasteboard_text command without any pre-configured scope.
+
+</td>
+</tr>
+
<tr>
<td>
diff --git a/apps/web/tauri/pasteboard_plugin/permissions/schemas/schema.json b/apps/web/tauri/pasteboard_plugin/permissions/schemas/schema.json
index 1d57c8c12a..a162118de3 100644
--- a/apps/web/tauri/pasteboard_plugin/permissions/schemas/schema.json
+++ b/apps/web/tauri/pasteboard_plugin/permissions/schemas/schema.json
@@ -294,6 +294,18 @@
"PermissionKind": {
"type": "string",
"oneOf": [
+ {
+ "description": "Enables the read_pasteboard_text command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-read-pasteboard-text",
+ "markdownDescription": "Enables the read_pasteboard_text command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the read_pasteboard_text command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-read-pasteboard-text",
+ "markdownDescription": "Denies the read_pasteboard_text command without any pre-configured scope."
+ },
{
"description": "Enables the stage_pasteboard_image command without any pre-configured scope.",
"type": "string",
diff --git a/apps/web/tauri/pasteboard_plugin/src/lib.rs b/apps/web/tauri/pasteboard_plugin/src/lib.rs
index df3cfeeb5a..29404a241a 100644
--- a/apps/web/tauri/pasteboard_plugin/src/lib.rs
+++ b/apps/web/tauri/pasteboard_plugin/src/lib.rs
@@ -15,6 +15,12 @@ struct StagePasteboardImagePayload {
token_prefix: &'static str,
}
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PasteboardText {
+ pub text: Option<String>,
+}
+
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StagedPasteboardImage {
@@ -28,6 +34,13 @@ pub struct StagedPasteboardImage {
pub struct Pasteboard<R: Runtime>(PluginHandle<R>);
impl<R: Runtime> Pasteboard<R> {
+ #[cfg(target_os = "ios")]
+ fn read_pasteboard_text(&self) -> Result<PasteboardText, String> {
+ self.0
+ .run_mobile_plugin("readPasteboardText", ())
+ .map_err(|error| error.to_string())
+ }
+
#[cfg(target_os = "ios")]
fn stage_pasteboard_image(
&self,
@@ -55,6 +68,20 @@ impl<R: Runtime, T: Manager<R>> PasteboardExt<R> for T {
}
}
+#[command]
+async fn read_pasteboard_text<R: Runtime>(app: AppHandle<R>) -> Result<PasteboardText, String> {
+ #[cfg(not(target_os = "ios"))]
+ {
+ let _ = app;
+ Err("pasteboard plugin is only available on iOS".to_string())
+ }
+
+ #[cfg(target_os = "ios")]
+ {
+ app.pasteboard().read_pasteboard_text()
+ }
+}
+
#[command]
async fn stage_pasteboard_image<R: Runtime>(
app: AppHandle<R>,
@@ -82,7 +109,10 @@ async fn stage_pasteboard_image<R: Runtime>(
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("pasteboard")
- .invoke_handler(tauri::generate_handler![stage_pasteboard_image])
+ .invoke_handler(tauri::generate_handler![
+ read_pasteboard_text,
+ stage_pasteboard_image
+ ])
.setup(|_app, _api| {
#[cfg(target_os = "ios")]
{
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index 6aea7caa6e..b27acba33b 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -79,6 +79,7 @@ tauri-plugin-haptics = "2"
[target.'cfg(target_os = "ios")'.dependencies]
tauri-plugin-call-kit = { path = "../callkit_plugin" }
+tauri-plugin-edit-menu = { path = "../edit_menu_plugin" }
tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }
tauri-plugin-network-status = { path = "../network_status_plugin" }
tauri-plugin-pasteboard = { path = "../pasteboard_plugin" }
diff --git a/apps/web/tauri/src-tauri/capabilities/mobile.json b/apps/web/tauri/src-tauri/capabilities/mobile.json
index 03b7fb135c..7b5afdd16f 100644
--- a/apps/web/tauri/src-tauri/capabilities/mobile.json
+++ b/apps/web/tauri/src-tauri/capabilities/mobile.json
@@ -15,6 +15,8 @@
"log:default",
"auth:allow-authenticate",
"device-info:default",
+ "edit-menu:allow-set-native-menu-suppressed",
+ "pasteboard:allow-read-pasteboard-text",
"network-status:allow-watch-status",
"pasteboard:allow-stage-pasteboard-image",
"photo-library:allow-pick-photo-library-images",
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 6b35135a24..ce6628e829 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -161,6 +161,7 @@ pub fn run() {
{
builder = builder
.plugin(tauri_plugin_haptics::init())
+ .plugin(tauri_plugin_edit_menu::init())
.plugin(tauri_plugin_input_accessory::init())
.plugin(tauri_plugin_network_status::init())
.plugin(tauri_plugin_pasteboard::init())