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.

refactor(block-md): deblockify; remove dependency on block system (#6364)

dev-rb078dc2b230e4
diff --git a/apps/web/src/components/app/CollaborationStatusIndicator.tsx b/apps/web/src/components/app/CollaborationStatusIndicator.tsx
new file mode 100644
index 0000000000..eb53c935f4
--- /dev/null
+++ b/apps/web/src/components/app/CollaborationStatusIndicator.tsx
@@ -0,0 +1,48 @@
+import { SyncSourceStatus } from '@macro-inc/collaboration/collab/source';
+import CloudIcon from '@phosphor/cloud.svg';
+import CloudWarningIcon from '@phosphor/cloud-warning.svg';
+import { Tooltip } from '@ui';
+import { Match, Switch } from 'solid-js';
+
+export function isCollaborationStatusVisible(
+ status: SyncSourceStatus | undefined
+): boolean {
+ return (
+ status === SyncSourceStatus.Disconnected ||
+ status === SyncSourceStatus.Connecting
+ );
+}
+
+export function CollaborationStatusIndicator(props: {
+ status: SyncSourceStatus | undefined;
+}) {
+ return (
+ <Switch>
+ <Match when={props.status === SyncSourceStatus.Disconnected}>
+ <Tooltip
+ as="span"
+ label="You're offline. Changes will sync when you reconnect."
+ >
+ <span
+ role="status"
+ aria-label="Offline"
+ class="inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-alert/20 bg-alert-bg text-alert-ink [&>svg]:size-4"
+ >
+ <CloudWarningIcon />
+ </span>
+ </Tooltip>
+ </Match>
+ <Match when={props.status === SyncSourceStatus.Connecting}>
+ <Tooltip as="span" label="Reconnecting…">
+ <span
+ role="status"
+ aria-label="Reconnecting"
+ class="inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-transparent text-ink-extra-muted [&>svg]:size-4"
+ >
+ <CloudIcon class="animate-pulse" />
+ </span>
+ </Tooltip>
+ </Match>
+ </Switch>
+ );
+}
diff --git a/apps/web/src/components/app/side-panel/SidePanel.tsx b/apps/web/src/components/app/side-panel/SidePanel.tsx
index 5cf3c35a3a..be719b25b7 100644
--- a/apps/web/src/components/app/side-panel/SidePanel.tsx
+++ b/apps/web/src/components/app/side-panel/SidePanel.tsx
@@ -1,5 +1,6 @@
import { usePreference } from '@app/preferences/use-preference';
import { Resize, ResizeZoneContext } from '@core/component/Resize/Resize';
+import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -29,6 +30,7 @@ import {
} from 'solid-js';
import { HeaderIsland } from '../split-layout/components/HeaderIsland';
import { SplitHeaderRight } from '../split-layout/components/SplitHeader';
+import { useSplitPanel } from '../split-layout/layoutUtils';
import {
SidePanelContext,
type SidePanelContextType,
@@ -130,6 +132,20 @@ function Layout(
};
const hasSections = createMemo(() => sections().length > 0);
+ const splitPanel = useSplitPanel();
+ if (splitPanel?.splitHotkeyScope) {
+ registerHotkey({
+ hotkey: ']',
+ scopeId: splitPanel.splitHotkeyScope,
+ hotkeyToken: TOKENS.block.toggleSidePanel,
+ description: 'Toggle Side Panel',
+ keyDownHandler: () => {
+ if (!hasSections()) return false;
+ toggle();
+ return true;
+ },
+ });
+ }
const ctx: SidePanelContextType = {
register,
diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
index 9a5e711a67..b15def33da 100644
--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
@@ -10,14 +10,11 @@
* folded transcript (`state/session-summary.ts`).
*/
-import { SidePanel, useSidePanel } from '@components/app/side-panel';
-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
-import { registerHotkey } from '@core/hotkey/hotkeys';
-import { TOKENS } from '@core/hotkey/tokens';
+import { SidePanel } from '@components/app/side-panel';
import { formatDate } from '@core/util/date';
import { openExternalUrl } from '@core/util/url';
import GitBranch from '@phosphor/git-branch.svg';
-import { createMemo, For, onCleanup, Show } from 'solid-js';
+import { createMemo, For, Show } from 'solid-js';
import { useAgentSession } from '../../context/AgentSessionContext';
import {
activityCounts,
@@ -43,26 +40,6 @@ export function AgentSidePanelSections() {
deletions: files().reduce((sum, file) => sum + file.deletions, 0),
}));
- // `]` toggles the panel, registered at the split scope so it works from
- // anywhere in the split (the md block's TopBar registration, verbatim).
- const sidePanel = useSidePanel();
- const splitPanel = useSplitPanel();
- if (splitPanel?.splitHotkeyScope) {
- const reg = registerHotkey({
- hotkey: ']',
- scopeId: splitPanel.splitHotkeyScope,
- hotkeyToken: TOKENS.block.toggleSidePanel,
- description: 'Toggle Side Panel',
- keyDownHandler: () => {
- if (!sidePanel) return false;
- if (!sidePanel.hasSections()) return false;
- sidePanel.toggle();
- return true;
- },
- });
- onCleanup(() => reg.dispose());
- }
-
return (
<>
<SidePanel.Section id="details" title="Details" defaultOpen order={10}>
diff --git a/apps/web/src/features/block-email/component/TopBar.tsx b/apps/web/src/features/block-email/component/TopBar.tsx
index 40fa39c973..09eb3273c6 100644
--- a/apps/web/src/features/block-email/component/TopBar.tsx
+++ b/apps/web/src/features/block-email/component/TopBar.tsx
@@ -12,7 +12,6 @@ import {
} from '@app/features/next-soup/utils';
import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
import { ResponsiveBlockToolbar } from '@components/app/ResponsiveBlockToolbar';
-import { useSidePanel } from '@components/app/side-panel';
import {
SplitHeaderLeft,
SplitHeaderRight,
@@ -21,7 +20,6 @@ import {
SplitHeaderBadge,
StaticSplitLabel,
} from '@components/app/split-layout/components/SplitLabel';
-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
import {
getShareDrawerRecipientInput,
@@ -29,7 +27,6 @@ import {
useShareDialogContext,
} from '@core/component/TopBar/ShareButton';
import { ENABLE_EMAIL_SHARING } from '@core/constant/featureFlags';
-import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
import { isMobile } from '@core/mobile/isMobile';
@@ -47,7 +44,7 @@ import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-so
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
import { useEmailLinksQuery } from '@queries/email/link';
import { Button } from '@ui';
-import { onCleanup, Show } from 'solid-js';
+import { Show } from 'solid-js';
export function TopBar(props: {
id: string;
@@ -55,30 +52,12 @@ export function TopBar(props: {
isDraft?: boolean;
onCreateTask?: () => void;
}) {
- const splitPanel = useSplitPanel();
const shareCtx = useShareDialogContext();
const emailCtx = useEmailThreadState();
const soup = useMaybeSoup();
const linksQuery = useEmailLinksQuery();
- const sidePanel = useSidePanel();
const moveToProjectAction = makeMoveToProjectAction();
- if (splitPanel?.splitHotkeyScope) {
- const reg = registerHotkey({
- hotkey: ']',
- scopeId: splitPanel.splitHotkeyScope,
- hotkeyToken: TOKENS.block.toggleSidePanel,
- description: 'Toggle Side Panel',
- keyDownHandler: () => {
- if (!sidePanel) return false;
- if (!sidePanel.hasSections()) return false;
- sidePanel.toggle();
- return true;
- },
- });
- onCleanup(() => reg.dispose());
- }
-
const isInvite = () => {
const row = soup?.items.get(props.id);
const entity = row?.original;
diff --git a/apps/web/src/features/block-md/comments/CommentMargin.tsx b/apps/web/src/features/block-md/comments/CommentMargin.tsx
index 07a099a593..9a2cfd5571 100644
--- a/apps/web/src/features/block-md/comments/CommentMargin.tsx
+++ b/apps/web/src/features/block-md/comments/CommentMargin.tsx
@@ -1,12 +1,3 @@
-import {
- activeCommentThreadSignal,
- commentsStore,
- commentWidthSignal,
- highlightedCommentIdSignal,
- highlightedCommentThreadsSignal,
- threadStore,
-} from '@block-md/comments/commentStore';
-import { useBlockId } from '@core/block';
import { MinimizedThread } from '@core/comments/MinimizedThreads';
import {
CommentsContext,
@@ -15,7 +6,6 @@ import {
} 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 {
createEffect,
@@ -25,29 +15,27 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { CommentThreadDrawer } from './CommentThreadDrawer';
-import {
- notebookHeight,
- threadHeightStore,
- threadsPositionStore,
-} from './commentLayout';
+import { createCommentLayout } from './commentLayout';
import {
useCreateComment,
useDeleteComment,
useUpdateComment,
} from './commentOperations';
-const useCommentsContext = (): CommentsContextType => {
- const comments = commentsStore.get;
- const setActiveThread = activeCommentThreadSignal.set;
- const setThreadHeight = threadHeightStore.set;
+const useCommentsContext = (
+ setThreadHeight: CommentsContextType['setThreadHeight']
+): CommentsContextType => {
+ const { documentId, permissions, state } = useMarkdownDocument();
+ const { comments: commentState, setCommentState } = state;
const ownedCommentIds = createMemo(() => {
const userId = useUserId()();
if (!userId) {
console.error('User ID not found, cannot get owned comment placeables');
return [];
}
- const owned = Object.values(commentsStore.get)
+ const owned = Object.values(commentState.comments)
.filter((c) => !!c)
.filter((c) => c.owner === userId)
.map((c) => c.id);
@@ -62,19 +50,16 @@ const useCommentsContext = (): CommentsContextType => {
const updateComment = useUpdateComment();
const deleteComment = useDeleteComment();
- const documentId = useBlockId();
- const isDocumentOwner = useIsDocumentOwner();
- const canComment = useCanComment();
-
- const getCommentById = (id: number) => comments[id];
+ const getCommentById = (id: number) => commentState.comments[id];
const commentsContext: CommentsContextType = {
- setActiveThread,
+ setActiveThread: (threadId) =>
+ setCommentState('activeCommentThread', threadId),
setThreadHeight,
- canComment,
- isDocumentOwner,
+ canComment: permissions.canComment,
+ isDocumentOwner: permissions.isOwner,
getCommentById,
- documentId,
+ documentId: documentId(),
ownedComment: ownedCommentSelector,
commentOperations: {
createComment,
@@ -82,24 +67,24 @@ const useCommentsContext = (): CommentsContextType => {
updateComment,
},
inComment: true,
- highlightedCommentId: highlightedCommentIdSignal.get,
+ highlightedCommentId: () => commentState.highlightedCommentId,
};
return commentsContext;
};
-export const CommentMargin = () => {
- const threads = threadStore.get;
- const positions = threadsPositionStore.get;
- const maxHeight = createMemo(() => notebookHeight());
-
- const wideEnoughForComments = commentWidthSignal.get;
+export const CommentMargin = (props: { wideEnough: boolean }) => {
+ const { state } = useMarkdownDocument();
+ const commentState = state.comments;
+ const { notebookHeight, setThreadHeights, threadPositions } =
+ createCommentLayout();
+ const maxHeight = createMemo(() => notebookHeight() ?? undefined);
// NOTE: this is a big of a hack because you can select
// multiple threads at once from the editor but only one thread in the margin
const activeThreads = createMemo(() => {
- const highlighted = highlightedCommentThreadsSignal();
+ const highlighted = commentState.highlightedCommentThreads;
const set = new Set(highlighted);
- const active = activeCommentThreadSignal();
+ const active = commentState.activeCommentThread;
if (active != null) {
set.add(active);
}
@@ -115,22 +100,20 @@ export const CommentMargin = () => {
return ids.has(id);
});
- const commentsContext = useCommentsContext();
+ const commentsContext = useCommentsContext(setThreadHeights);
// Touch devices never expand floating thread cards; the active thread is
// presented in the CommentThreadDrawer instead.
- const isMinimized = createMemo(
- () => isTouchDevice() || !wideEnoughForComments()
- );
+ const isMinimized = createMemo(() => isTouchDevice() || !props.wideEnough);
return (
<CommentsContext.Provider value={commentsContext}>
<div class="relative h-full">
- <For each={Object.values(threads)}>
+ <For each={Object.values(commentState.threads)}>
{(thread) => (
<Show when={thread}>
{(thread) => {
- const layout = () => positions[thread().anchorId]?.layout;
+ const layout = () => threadPositions[thread().anchorId]?.layout;
return (
<Show when={layout()}>
{(layout) => (
diff --git a/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx b/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx
index 0d6be08ab6..72bd2d5de4 100644
--- a/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx
+++ b/apps/web/src/features/block-md/comments/CommentThreadDrawer.tsx
@@ -1,10 +1,3 @@
-import {
- activeCommentThreadSignal,
- highlightedCommentThreadsSignal,
- markStore,
- threadStore,
-} from '@block-md/comments/commentStore';
-import { mdStore } from '@block-md/signal/markdownBlockData';
import {
MobileDrawer,
scrollToFocusedInput,
@@ -26,6 +19,7 @@ import CaretRightIcon from '@phosphor/caret-right.svg';
import { Button } from '@ui';
import { $setSelection } from 'lexical';
import { createMemo, createSignal, Show, useContext } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
/**
* `baseCommentTheme` minus its `select-text` on message text. The drawer is
@@ -104,13 +98,9 @@ function PinnedReplyComposer(props: {
* 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 { state } = useMarkdownDocument();
+ const { comments: commentState, setCommentState } = state;
+ const md = state.editor.md;
const parentCommentsContext = useContext(CommentsContext);
// Messages report their inline-edit state; while any edit input is open,
@@ -132,18 +122,18 @@ export function CommentThreadDrawer() {
};
const activeRoot = createMemo<Root | undefined>(() => {
- const active = activeCommentThread();
- return active == null ? undefined : threads[active];
+ const active = commentState.activeCommentThread;
+ return active == null ? undefined : commentState.threads[active];
});
const firstMarkElement = (root: Root) =>
- Object.values(marks[root.anchorId]?.markNodes ?? {})[0];
+ Object.values(commentState.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)
+ return Object.values(commentState.threads)
.filter((root): root is Root => !!root && root.threadId !== -1)
.map((root) => {
const rect = firstMarkElement(root)?.getBoundingClientRect();
@@ -158,7 +148,7 @@ export function CommentThreadDrawer() {
});
const pagerIndex = createMemo(() => {
- const active = activeCommentThread();
+ const active = commentState.activeCommentThread;
return active == null ? -1 : orderedThreadIds().indexOf(active);
});
@@ -174,9 +164,9 @@ export function CommentThreadDrawer() {
// 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];
+ setCommentState('activeCommentThread', target);
+ setCommentState('highlightedCommentThreads', [target]);
+ const root = commentState.threads[target];
if (root) {
firstMarkElement(root)?.scrollIntoView({
behavior: 'smooth',
@@ -191,8 +181,8 @@ export function CommentThreadDrawer() {
// 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([]);
+ setCommentState('activeCommentThread', null);
+ setCommentState('highlightedCommentThreads', []);
};
return (
diff --git a/apps/web/src/features/block-md/comments/CommentsProvider.tsx b/apps/web/src/features/block-md/comments/CommentsProvider.tsx
index b3980a75b1..f12c55a391 100644
--- a/apps/web/src/features/block-md/comments/CommentsProvider.tsx
+++ b/apps/web/src/features/block-md/comments/CommentsProvider.tsx
@@ -23,18 +23,10 @@ import {
type VoidComponent,
} from 'solid-js';
import { reconcile } from 'solid-js/store';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { useMarkdownCommentsQuery } from '../queries/markdown-comments';
import { useDeleteComment, useDeleteNewComments } from './commentOperations';
-import {
- activeCommentThreadSignal,
- activeMarkIdsSignal,
- commentMarksInitializedSignal,
- commentsStore,
- highlightedCommentIdSignal,
- highlightedCommentThreadsSignal,
- markStore,
- threadStore,
-} from './commentStore';
-import { commentThreadsResource, sortComments } from './commentsResource';
+import { sortComments, useCommentRealtime } from './commentsResource';
import type { Mark, ThreadMetadata, ThreadStore } from './commentType';
const DISCUSSION_MARK_PREFIX = 'DISCUSSION:';
@@ -90,17 +82,16 @@ export const CommentsProvider: VoidComponent<{
return null;
}
const { plugins, editor } = wrapper;
+ const { documentId, state } = useMarkdownDocument();
+ const { comments: commentState, setCommentState } = state;
const currentPeerId = () => props.loroManager.peerIdStr;
- const [marks, setMarks] = markStore;
- const [commentThreadsData] = commentThreadsResource;
- const [, setCommentsInitialized] = commentMarksInitializedSignal;
- const [highlightedId, setHighlightedId] = highlightedCommentIdSignal;
- const setActiveMarkIds = activeMarkIdsSignal.set;
+ const commentThreadsQuery = useMarkdownCommentsQuery(documentId);
+ useCommentRealtime();
/** Communicates comment ready to block. */
- const initComments = () => setCommentsInitialized(true);
+ const initComments = () => setCommentState('commentMarksInitialized', true);
const addCommentMark = (
markId: string,
@@ -111,10 +102,10 @@ export const CommentsProvider: VoidComponent<{
isLocal: boolean
) => {
const markNodeKey = markNode.getKey();
- const existing = marks[markId];
+ const existing = commentState.marks[markId];
if (!isDraft && existing) {
- setMarks(markId, 'markNodes', markNodeKey, markElement);
+ setCommentState('marks', markId, 'markNodes', markNodeKey, markElement);
return;
}
@@ -122,7 +113,7 @@ export const CommentsProvider: VoidComponent<{
return;
}
- setMarks(markId, {
+ setCommentState('marks', markId, {
id: markId,
existsOnServer: hasServerThread,
isDraft,
@@ -136,12 +127,12 @@ export const CommentsProvider: VoidComponent<{
const deleteNewComments = useDeleteNewComments();
const removeCommentMark = (markId: string, markNodeKey: string) => {
- const existing = marks[markId];
+ const existing = commentState.marks[markId];
if (!existing) return;
if (existing) {
if (Object.keys(existing.markNodes).length <= 1) {
- setMarks(markId, undefined);
+ setCommentState('marks', markId, undefined);
const rootId = existing.thread?.rootId;
if (!rootId) {
return;
@@ -149,24 +140,24 @@ export const CommentsProvider: VoidComponent<{
deleteComment({ commentId: rootId });
return;
}
- setMarks(markId, 'markNodes', markNodeKey, undefined);
+ setCommentState('marks', markId, 'markNodes', markNodeKey, undefined);
return;
}
};
// Remove the temporary draft comment when the active thread is cleared
createEffect(() => {
- const activeThreadId = activeCommentThreadSignal();
+ const activeThreadId = commentState.activeCommentThread;
if (!activeThreadId) {
deleteNewComments(false);
return;
}
- const thread = threadStore.get[activeThreadId];
+ const thread = commentState.threads[activeThreadId];
if (!thread) return;
const markId = thread.anchorId;
- const existingMarkIds = untrack(activeMarkIdsSignal);
+ const existingMarkIds = untrack(() => commentState.activeMarkIds);
if (
existingMarkIds.length > 0 &&
existingMarkIds.every((id) => id === markId)
@@ -179,19 +170,19 @@ export const CommentsProvider: VoidComponent<{
// Sync active mark selections to thread signals
createEffect(() => {
- const activeMarkIds = activeMarkIdsSignal();
- if (activeMarkIds.length === 0) {
- activeCommentThreadSignal.set(null);
- highlightedCommentThreadsSignal.set([]);
+ const activeIds = commentState.activeMarkIds;
+ if (activeIds.length === 0) {
+ setCommentState('activeCommentThread', null);
+ setCommentState('highlightedCommentThreads', []);
return;
}
const threadIds: number[] = [];
- for (const id of activeMarkIds) {
- const mark = marks[id];
+ for (const id of activeIds) {
+ const mark = commentState.marks[id];
if (!mark) continue;
if (mark.thread == null) {
- activeCommentThreadSignal.set(-1);
+ setCommentState('activeCommentThread', -1);
return;
} else {
threadIds.push(mark.thread.threadId);
@@ -202,10 +193,10 @@ export const CommentsProvider: VoidComponent<{
// "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) =>
+ setCommentState('activeCommentThread', (current) =>
current != null && threadIds.includes(current) ? current : null
);
- highlightedCommentThreadsSignal.set(threadIds);
+ setCommentState('highlightedCommentThreads', threadIds);
});
// Compute visible comment threads from marks
@@ -213,7 +204,7 @@ export const CommentsProvider: VoidComponent<{
const highlightComments = createMemo(() => {
const currentUserId = userId();
const out: (Root | Reply)[] = [];
- for (const mark of Object.values(marks ?? {})) {
+ for (const mark of Object.values(commentState.marks)) {
if (!mark) continue;
if (!mark.existsOnServer) {
@@ -247,10 +238,7 @@ export const CommentsProvider: VoidComponent<{
// Sync highlight comments to commentsStore and threadStore
createEffect(() => {
- const setComments = commentsStore.set;
- const setThreads = threadStore.set;
-
- setComments(reconcile({}));
+ setCommentState('comments', reconcile({}));
const combinedComments = highlightComments() ?? [];
const serverThreads: ThreadStore = {};
@@ -259,18 +247,21 @@ export const CommentsProvider: VoidComponent<{
if (isRoot(comment)) {
serverThreads[comment.threadId] = comment;
}
- setComments(comment.id, comment);
+ setCommentState('comments', comment.id, comment);
}
- setThreads(reconcile(serverThreads, { merge: true, key: 'id' }));
+ setCommentState(
+ 'threads',
+ reconcile(serverThreads, { merge: true, key: 'id' })
+ );
});
// Map server comment threads to mark metadata once marks are initialized
createEffect(() => {
- if (!commentMarksInitializedSignal()) return;
- if (commentThreadsData.loading || commentThreadsData.error) return;
+ if (!commentState.commentMarksInitialized) return;
+ if (!commentThreadsQuery.isSuccess) return;
- const commentThreads = commentThreadsData() ?? [];
+ const commentThreads = commentThreadsQuery.data ?? [];
const validAnchorIds = new Set<string>();
const mappedAnchors = commentThreads.map((commentThread) => {
@@ -286,9 +277,9 @@ export const CommentsProvider: VoidComponent<{
}
validAnchorIds.add(anchorId);
- const sortedComments = commentThread.comments.sort(sortComments);
+ const sortedComments = [...commentThread.comments].sort(sortComments);
const rootComment = sortedComments[0];
- const markNodes = marks[anchorId]?.markNodes;
+ const markNodes = commentState.marks[anchorId]?.markNodes;
if (!markNodes) return undefined;
const highlight: Mark = {
@@ -311,7 +302,7 @@ export const CommentsProvider: VoidComponent<{
for (const anchor of mappedAnchors) {
if (!anchor) continue;
- setMarks(anchor.id, anchor);
+ setCommentState('marks', anchor.id, anchor);
}
editor.dispatchCommand(
@@ -336,11 +327,12 @@ export const CommentsProvider: VoidComponent<{
const rawId = pendingTargetCommentId;
if (!rawId) return;
- if (!commentMarksInitializedSignal()) return;
+ if (!commentState.commentMarksInitialized) return;
+ if (!commentThreadsQuery.isSuccess) return;
const commentId = Number(rawId);
if (isNaN(commentId)) return;
- const commentThreads = commentThreadsData() ?? [];
+ const commentThreads = commentThreadsQuery.data ?? [];
const targetThread = commentThreads.find((thread) =>
thread.comments.some((comment) => comment.commentId === commentId)
);
@@ -348,21 +340,21 @@ export const CommentsProvider: VoidComponent<{
| ThreadMetadata
| undefined;
if (targetMetadata?.markId?.startsWith(DISCUSSION_MARK_PREFIX)) {
- activeCommentThreadSignal.set(null);
- highlightedCommentIdSignal.set(null);
+ setCommentState('activeCommentThread', null);
+ setCommentState('highlightedCommentId', null);
pendingTargetCommentId = undefined;
return;
}
- const comment = commentsStore.get[commentId];
+ const comment = commentState.comments[commentId];
if (!comment) return;
- highlightedCommentIdSignal.set(commentId);
- const mark = marks[comment.anchorId];
+ setCommentState('highlightedCommentId', commentId);
+ const mark = commentState.marks[comment.anchorId];
if (mark) {
const firstEl = Object.values(mark.markNodes)[0];
firstEl?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
- activeCommentThreadSignal.set(comment.threadId);
+ setCommentState('activeCommentThread', comment.threadId);
pendingTargetCommentId = undefined;
});
@@ -370,8 +362,8 @@ export const CommentsProvider: VoidComponent<{
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
- if (highlightedId() === null) return false;
- setHighlightedId(null);
+ if (commentState.highlightedCommentId === null) return false;
+ setCommentState('highlightedCommentId', null);
return false;
},
COMMAND_PRIORITY_LOW
@@ -383,7 +375,7 @@ export const CommentsProvider: VoidComponent<{
ops: {
add: addCommentMark,
remove: removeCommentMark,
- setActiveIds: setActiveMarkIds,
+ setActiveIds: (markIds) => setCommentState('activeMarkIds', markIds),
init: initComments,
},
peerId: currentPeerId,
diff --git a/apps/web/src/features/block-md/comments/commentLayout.ts b/apps/web/src/features/block-md/comments/commentLayout.ts
index 4a173ca88f..06f77e8d79 100644
--- a/apps/web/src/features/block-md/comments/commentLayout.ts
+++ b/apps/web/src/features/block-md/comments/commentLayout.ts
@@ -6,14 +6,6 @@ import type {
ThreadHeights,
ThreadPositions,
} from '@block-md/comments/commentType';
-import { mdStore } from '@block-md/signal/markdownBlockData';
-import {
- createBlockEffect,
- createBlockMemo,
- createBlockSignal,
- createBlockStore,
- useBlockName,
-} from '@core/block';
import {
autoRegister,
registerEditorWidthObserver,
@@ -22,8 +14,15 @@ import {
import { getScrollParentElement } from '@core/util/scrollParent';
import { createElementSize } from '@solid-primitives/resize-observer';
import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';
-import { onCleanup, untrack } from 'solid-js';
-import { activeMarkIdsSignal, markStore } from './commentStore';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { useMarkdownDocument } from '../context/markdown-document-context';
// how much to pad the container for the "show more" buttons
const CONTAINER_PADDING = 0;
@@ -34,316 +33,302 @@ export const MIN_THREAD_GAP = 10;
// the throttle time for layout updates.
const LAYOUT_THROTTLE = 60;
-const notebookSize = createBlockMemo(() => {
- const notebook = mdStore.get.notebook;
- if (!notebook) return;
- const size = createElementSize(notebook);
- return size;
-});
-
-export const notebookHeight = createBlockMemo(() => {
- return notebookSize()?.height;
-});
-
-export const threadHeightStore = createBlockStore<ThreadHeights>({});
-export const threadsPositionStore = createBlockStore<ThreadPositions>({});
-const markLocationTopStore = createBlockStore<Partial<Record<MarkId, number>>>(
- {}
-);
-
-const marginTopSignal = createBlockSignal(0);
-const scrollYSignal = createBlockSignal(0);
-
-createBlockEffect(() => {
- const setMarginTop = marginTopSignal.set;
- const setScrollY = scrollYSignal.set;
- const commentMargin = mdStore.get.commentMargin;
-
- if (!commentMargin) {
- return;
- }
+export function createCommentLayout() {
+ const { state } = useMarkdownDocument();
+ const commentState = state.comments;
+ const md = state.editor.md;
- // Track the top of the bounding NON-scrolling element.
- const blockContent = commentMargin.closest('[data-block-content]');
- if (blockContent) {
- const resizeObserver = new ResizeObserver(() => {
- const top = blockContent?.getBoundingClientRect().top ?? 0;
- setMarginTop(top);
- });
- resizeObserver.observe(blockContent);
- onCleanup(() => {
- resizeObserver.disconnect();
- });
- }
+ const notebookSize = createElementSize(() => md.notebook);
+ const notebookHeight = createMemo(() => notebookSize.height);
- // Track the scroll top of the bounding scrolling element.
- const scrollParent = getScrollParentElement(commentMargin);
- if (scrollParent) {
- const updateScrollY = () => {
- const scrollTop = scrollParent.scrollTop;
- setScrollY(scrollTop);
- };
- scrollParent.addEventListener('scroll', updateScrollY, { passive: true });
- onCleanup(() => {
- scrollParent.removeEventListener('scroll', updateScrollY);
- });
- }
-});
-
-// Sort comments by their marks' positions.
-function markElementSort(a: HTMLElement, b: HTMLElement) {
- const { left: aLeft, top: aTop } = a.getBoundingClientRect();
- const { left: bLeft, top: bTop } = b.getBoundingClientRect();
- if (aTop === bTop) {
- return aLeft - bLeft;
- }
- return aTop - bTop;
-}
+ const [threadHeights, setThreadHeights] = createStore<ThreadHeights>({});
+ const [threadPositions, setThreadPositions] = createStore<ThreadPositions>(
+ {}
+ );
+ const [markLocationTops, setMarkLocationTops] = createStore<
+ Partial<Record<MarkId, number>>
+ >({});
-createBlockEffect(() => {
- const setMarkTop = markLocationTopStore.set;
- const marks = markStore.get;
- const md = mdStore.get;
- const scrollY = scrollYSignal.get;
+ const [marginTop, setMarginTop] = createSignal(0);
+ const [scrollY, setScrollY] = createSignal(0);
- const updateMarkPositions = () => {
- for (const markId in marks) {
- const mark = marks[markId];
- if (!mark) continue;
+ createEffect(() => {
+ const commentMargin = md.commentMargin;
- const markEls = Object.values(mark.markNodes).filter((el) => !!el);
- if (markEls.length === 0) continue;
+ if (!commentMargin) {
+ return;
+ }
- // attach the comment layout to the top element of the mark
- const topEl = markEls.sort(markElementSort)[0];
- const top = topEl.getBoundingClientRect().top + scrollY();
- setMarkTop(markId, top);
+ // Track the top of the bounding NON-scrolling element.
+ const blockContent = commentMargin.closest('[data-block-content]');
+ if (blockContent) {
+ const resizeObserver = new ResizeObserver(() => {
+ const top = blockContent?.getBoundingClientRect().top ?? 0;
+ setMarginTop(top);
+ });
+ resizeObserver.observe(blockContent);
+ onCleanup(() => {
+ resizeObserver.disconnect();
+ });
}
- };
- updateMarkPositions();
+ // Track the scroll top of the bounding scrolling element.
+ const scrollParent = getScrollParentElement(commentMargin);
+ if (scrollParent) {
+ const updateScrollY = () => {
+ const scrollTop = scrollParent.scrollTop;
+ setScrollY(scrollTop);
+ };
+ scrollParent.addEventListener('scroll', updateScrollY, { passive: true });
+ onCleanup(() => {
+ scrollParent.removeEventListener('scroll', updateScrollY);
+ });
+ }
+ });
- const throttledUpdate = leadingAndTrailing(
- throttle,
- updateMarkPositions,
- LAYOUT_THROTTLE
- );
+ // Sort comments by their marks' positions.
+ function markElementSort(a: HTMLElement, b: HTMLElement) {
+ const { left: aLeft, top: aTop } = a.getBoundingClientRect();
+ const { left: bLeft, top: bTop } = b.getBoundingClientRect();
+ if (aTop === bTop) {
+ return aLeft - bLeft;
+ }
+ return aTop - bTop;
+ }
- // Throttle updates on comment positions. Update on (1) editor updates, (2)
- // internal layout shifts causes by non-updating element height changed to
- // embeds and media and (3) editor width changes.
- if (md.editor) {
- autoRegister(
- md.editor.registerUpdateListener(() => {
- throttledUpdate();
- }),
- registerInternalLayoutShiftListener(md.editor, throttledUpdate),
- registerEditorWidthObserver(md.editor, throttledUpdate)
+ createEffect(() => {
+ const updateMarkPositions = () => {
+ for (const markId in commentState.marks) {
+ const mark = commentState.marks[markId];
+ if (!mark) continue;
+
+ const markEls = Object.values(mark.markNodes).filter((el) => !!el);
+ if (markEls.length === 0) continue;
+
+ // attach the comment layout to the top element of the mark
+ const topEl = markEls.sort(markElementSort)[0];
+ const top = topEl.getBoundingClientRect().top + scrollY();
+ setMarkLocationTops(markId, top);
+ }
+ };
+
+ updateMarkPositions();
+
+ const throttledUpdate = leadingAndTrailing(
+ throttle,
+ updateMarkPositions,
+ LAYOUT_THROTTLE
);
- }
-});
-type MarkLayout = {
- id: MarkId;
- layout?: {
- top: number;
- };
-};
+ // Throttle updates on comment positions. Update on (1) editor updates, (2)
+ // internal layout shifts causes by non-updating element height changed to
+ // embeds and media and (3) editor width changes.
+ if (md.editor) {
+ autoRegister(
+ md.editor.registerUpdateListener(() => {
+ throttledUpdate();
+ }),
+ registerInternalLayoutShiftListener(md.editor, throttledUpdate),
+ registerEditorWidthObserver(md.editor, throttledUpdate)
+ );
+ }
+ });
-const markLayoutsSignal = createBlockSignal<MarkLayout[]>([]);
+ type MarkLayout = {
+ id: MarkId;
+ layout?: {
+ top: number;
+ };
+ };
-createBlockEffect(() => {
- const setMarkLayouts = markLayoutsSignal.set;
- const marks = markStore.get;
- const marginTop = marginTopSignal();
+ const [markLayouts, setMarkLayouts] = createSignal<MarkLayout[]>([]);
+
+ createEffect(() => {
+ const layouts = Object.values(commentState.marks)
+ .filter((m) => m !== undefined)
+ .map((m) => {
+ const top = markLocationTops[m.id];
+ if (top != null) {
+ return {
+ id: m.id,
+ layout: {
+ top: top - marginTop(),
+ },
+ };
+ }
- const layouts = Object.values(marks)
- .filter((m) => m !== undefined)
- .map((m) => {
- const top = markLocationTopStore.get[m.id];
- if (top != null) {
return {
id: m.id,
- layout: {
- top: top - marginTop,
- },
};
+ });
+
+ setMarkLayouts(layouts);
+ });
+
+ function computeLayout<T>({
+ initialAnchor,
+ input,
+ direction,
+ containerHeight,
+ containerPadding = 0,
+ }: {
+ initialAnchor: number;
+ input: (CommentViewerInitialLayout<T> & { height: number })[];
+ direction: 'up' | 'down';
+ containerHeight: number;
+ containerPadding?: number;
+ }): Array<CommentLayout<T>> {
+ let anchor = initialAnchor;
+ if (direction === 'up') {
+ input.reverse();
+ }
+ const out = input.map((i): CommentLayout<T> => {
+ let calculatedYPos = 0;
+ if (direction === 'up') {
+ calculatedYPos = Math.min(
+ anchor - i.height - MIN_THREAD_GAP,
+ i.layout.originalYPosition
+ );
+ anchor = calculatedYPos;
+ } else {
+ calculatedYPos = Math.max(
+ anchor + MIN_THREAD_GAP,
+ i.layout.originalYPosition
+ );
+ anchor = calculatedYPos + i.height;
}
+ let overflow: Overflow = null;
+ if (calculatedYPos <= 0 + containerPadding) overflow = 'top';
+ if (anchor >= containerHeight - containerPadding) overflow = 'bottom';
return {
- id: m.id,
+ ...i,
+ layout: {
+ height: i.height,
+ calculatedYPos,
+ overflow,
+ },
};
});
-
- setMarkLayouts(layouts);
-});
-
-function computeLayout<T>({
- initialAnchor,
- input,
- direction,
- containerHeight,
- containerPadding = 0,
-}: {
- initialAnchor: number;
- input: (CommentViewerInitialLayout<T> & { height: number })[];
- direction: 'up' | 'down';
- containerHeight: number;
- containerPadding?: number;
-}): Array<CommentLayout<T>> {
- let anchor = initialAnchor;
- if (direction === 'up') {
- input.reverse();
- }
- const out = input.map((i): CommentLayout<T> => {
- let calculatedYPos = 0;
if (direction === 'up') {
- calculatedYPos = Math.min(
- anchor - i.height - MIN_THREAD_GAP,
- i.layout.originalYPosition
- );
- anchor = calculatedYPos;
- } else {
- calculatedYPos = Math.max(
- anchor + MIN_THREAD_GAP,
- i.layout.originalYPosition
- );
- anchor = calculatedYPos + i.height;
+ out.reverse();
}
-
- let overflow: Overflow = null;
- if (calculatedYPos <= 0 + containerPadding) overflow = 'top';
- if (anchor >= containerHeight - containerPadding) overflow = 'bottom';
- return {
- ...i,
- layout: {
- height: i.height,
- calculatedYPos,
- overflow,
- },
- };
- });
- if (direction === 'up') {
- out.reverse();
+ return out;
}
- return out;
-}
-createBlockEffect(() => {
- // TODO: use a createMdBlockEffect
- const blockName = useBlockName();
- if (blockName !== 'md') return;
+ createEffect(() => {
+ const pageHeight = notebookHeight();
- const setStore = threadsPositionStore.set;
- const activeMarkIds = activeMarkIdsSignal.get;
- const pageHeight = notebookHeight();
- const marks = markStore.get;
-
- // there are no bounds for the container, cant compute position
- if (!pageHeight) {
- console.error('no page height');
- return;
- }
-
- const markLayouts = markLayoutsSignal.get;
+ // there are no bounds for the container, cant compute position
+ if (!pageHeight) {
+ console.error('no page height');
+ return;
+ }
- const sortedThreadsByOriginalPosition = (markLayouts() ?? [])
- .flatMap((l) => {
- if (!l.layout) return [];
- let threadHeight = 0;
- const mark = marks[l.id];
- const threadId = mark?.thread?.threadId;
- if (threadId) {
- threadHeight = threadHeightStore.get[threadId] ?? 0;
- }
+ const sortedThreadsByOriginalPosition = markLayouts()
+ .flatMap((layout) => {
+ if (!layout.layout) return [];
+ let threadHeight = 0;
+ const mark = commentState.marks[layout.id];
+ const threadId = mark?.thread?.threadId;
+ if (threadId) {
+ threadHeight = threadHeights[threadId] ?? 0;
+ }
+
+ return [
+ {
+ id: layout.id,
+ height: threadHeight,
+ layout: { originalYPosition: layout.layout.top },
+ },
+ ];
+ })
+ .sort((a, b) => a.layout.originalYPosition - b.layout.originalYPosition);
- return [
- {
- id: l.id,
- height: threadHeight,
- layout: { originalYPosition: l.layout.top },
- },
- ];
- })
- .sort((a, b) => a.layout.originalYPosition - b.layout.originalYPosition);
+ // there are no comment threads on this page, cant position nothing
+ if (sortedThreadsByOriginalPosition.length === 0) {
+ return;
+ }
- // there are no comment threads on this page, cant position nothing
- if (sortedThreadsByOriginalPosition.length === 0) {
- return;
- }
+ // if no threads is active by default
+ // position threads as if the first one is active
+ const activeMarkIdsValue = untrack(() => commentState.activeMarkIds);
+ const middleMarkId =
+ activeMarkIdsValue[Math.floor(activeMarkIdsValue.length / 2)];
+ const anchorPositionId =
+ middleMarkId ?? sortedThreadsByOriginalPosition[0].id;
+ if (!anchorPositionId) return;
+
+ let sliceTo = sortedThreadsByOriginalPosition.findIndex(
+ (thread) => thread.id === anchorPositionId
+ );
+ if (sliceTo === -1) {
+ sliceTo = 0;
+ }
+ const sliceFrom = sliceTo + 1;
+
+ // all threads on page above the anchor with height
+ const sliceAboveAnchor = sortedThreadsByOriginalPosition.slice(0, sliceTo);
+ // all threads on page below the anchor with height
+ const sliceBelowAnchor = sortedThreadsByOriginalPosition.slice(sliceFrom);
+
+ // calculate closest fit for anchor within bounds of container
+ const anchorElement = sortedThreadsByOriginalPosition[sliceTo];
+ const anchorHeight = anchorElement.height;
+
+ // check if original y plus height fits inside bounds for anchor
+ const paddedHeight = pageHeight - CONTAINER_PADDING;
+ let anchorTop = anchorElement.layout.originalYPosition;
+ let anchorEnd = anchorTop + anchorHeight;
+ if (anchorEnd > paddedHeight) {
+ const anchorOverflow = anchorEnd - paddedHeight;
+ anchorTop -= anchorOverflow;
+ }
- // if no threads is active by default
- // position threads as if the first one is active
- const activeMarkIds_ = untrack(activeMarkIds);
- const middleMarkId = activeMarkIds_[Math.floor(activeMarkIds_.length / 2)];
- const anchorPositionId =
- middleMarkId ?? sortedThreadsByOriginalPosition[0].id;
- if (!anchorPositionId) return;
+ // handle edge case where anchor element is larger than container
+ if (anchorTop < 0) {
+ anchorTop = 0;
+ }
+ anchorEnd = anchorTop + anchorHeight;
+
+ const layoutAboveAnchor = computeLayout({
+ initialAnchor: anchorTop,
+ direction: 'up',
+ input: sliceAboveAnchor,
+ containerHeight: pageHeight,
+ containerPadding: CONTAINER_PADDING,
+ });
- let sliceTo = sortedThreadsByOriginalPosition.findIndex(
- (t) => t.id === anchorPositionId
- );
- if (sliceTo === -1) {
- sliceTo = 0;
- }
- const sliceFrom = sliceTo + 1;
-
- // all threads on page above the anchor with height
- const sliceAboveAnchor = sortedThreadsByOriginalPosition.slice(0, sliceTo);
- // all threads on page below the anchor with height
- const sliceBelowAnchor = sortedThreadsByOriginalPosition.slice(sliceFrom);
-
- // calculate closest fit for anchor within bounds of container
- const anchorElement = sortedThreadsByOriginalPosition[sliceTo];
- const anchorHeight = anchorElement.height;
-
- // check if original y plus height fits inside bounds for anchor
- const paddedHeight = pageHeight - CONTAINER_PADDING;
- let anchorTop = anchorElement.layout.originalYPosition;
- let anchorEnd = anchorTop + anchorHeight;
- if (anchorEnd > paddedHeight) {
- const anchorOverflow = anchorEnd - paddedHeight;
- anchorTop -= anchorOverflow;
- }
+ const layoutBelowAnchor = computeLayout({
+ initialAnchor: anchorEnd,
+ direction: 'down',
+ input: sliceBelowAnchor,
+ containerHeight: pageHeight,
+ containerPadding: CONTAINER_PADDING,
+ });
- // handle edge case where anchor element is larger than container
- if (anchorTop < 0) {
- anchorTop = 0;
- }
- anchorEnd = anchorTop + anchorHeight;
-
- const layoutAboveAnchor = computeLayout({
- initialAnchor: anchorTop,
- direction: 'up',
- input: sliceAboveAnchor,
- containerHeight: pageHeight,
- containerPadding: CONTAINER_PADDING,
- });
+ // the positioning of all threads on the page
+ const out: CommentLayout<{ id: MarkId }>[] = [
+ ...layoutAboveAnchor,
+ {
+ ...anchorElement,
+ layout: {
+ height: anchorHeight,
+ calculatedYPos: anchorTop,
+ overflow: null,
+ },
+ },
+ ...layoutBelowAnchor,
+ ];
- const layoutBelowAnchor = computeLayout({
- initialAnchor: anchorEnd,
- direction: 'down',
- input: sliceBelowAnchor,
- containerHeight: pageHeight,
- containerPadding: CONTAINER_PADDING,
+ for (const layout of out) {
+ setThreadPositions(layout.id, layout);
+ }
});
- // the positioning of all threads on the page
- const out: CommentLayout<{ id: MarkId }>[] = [
- ...layoutAboveAnchor,
- {
- ...anchorElement,
- layout: {
- height: anchorHeight,
- calculatedYPos: anchorTop,
- overflow: null,
- },
- },
- ...layoutBelowAnchor,
- ];
-
- for (const layout of out) {
- const markId = layout.id;
- setStore(markId, layout);
- }
-});
+ return {
+ notebookHeight,
+ setThreadHeights,
+ threadPositions,
+ };
+}
diff --git a/apps/web/src/features/block-md/comments/commentOperations.ts b/apps/web/src/features/block-md/comments/commentOperations.ts
index f75ec9e8b5..13a77518b3 100644
--- a/apps/web/src/features/block-md/comments/commentOperations.ts
+++ b/apps/web/src/features/block-md/comments/commentOperations.ts
@@ -1,6 +1,4 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { mdStore } from '@block-md/signal/markdownBlockData';
-import { useBlockId } from '@core/block';
import type { DeleteCommentInfo } from '@core/comments/commentType';
import { threadMeasureContainerId } from '@core/comments/Thread';
import {
@@ -10,7 +8,6 @@ import {
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,
@@ -19,12 +16,7 @@ import type { CreateCommentResponse } from '@service-storage/generated/schemas/c
import { until } from '@solid-primitives/promise';
import { createCallback } from '@solid-primitives/rootless';
import { onCleanup } from 'solid-js';
-import {
- activeCommentThreadSignal,
- commentsStore,
- markStore,
- threadStore,
-} from './commentStore';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import {
useCreateHighlightCommentResource,
useCreateThreadReplyResource,
@@ -38,10 +30,9 @@ export function useCreateComment() {
const deleteNewComments = useDeleteNewComments();
const createHighlightComment = useCreateHighlightCommentResource();
const createThreadReply = useCreateThreadReplyResource();
- const threads = threadStore.get;
+ const { state } = useMarkdownDocument();
+ const { comments: commentState, setCommentState } = state;
const updateNodeThreadId = useSetNodeCommentThreadId();
- const setActiveThread = activeCommentThreadSignal.set;
- const editor = mdStore.get.editor;
return createCallback(
async (info: CreateCommentRequest & { threadId: number }) => {
@@ -49,9 +40,9 @@ export function useCreateComment() {
const { threadId, text, mentions } = info;
if (threadId === -1) {
- setActiveThread(threadId);
+ setCommentState('activeCommentThread', threadId);
- const comment = threads[threadId];
+ const comment = commentState.threads[threadId];
if (!comment) {
console.error('Unable to comment');
return null;
@@ -66,7 +57,7 @@ export function useCreateComment() {
);
if (response) {
- editor?.dispatchCommand(CREATE_COMMENT_COMMAND, {
+ state.editor.md.editor?.dispatchCommand(CREATE_COMMENT_COMMAND, {
threadId: response.thread.threadId,
});
updateNodeThreadId({
@@ -104,8 +95,8 @@ export function useDeleteComment() {
const deleteComment = useDeleteCommentResource();
const deleteNewComments = useDeleteNewComments();
- const editor = mdStore.get.editor;
- const comments = commentsStore.get;
+ const { state } = useMarkdownDocument();
+ const editor = state.editor.md.editor;
return createCallback(async (info: DeleteCommentInfo) => {
analytics.track('comment_delete', { blockType: 'md' });
@@ -117,7 +108,7 @@ export function useDeleteComment() {
return true;
}
- const comment = comments[commentId];
+ const comment = state.comments.comments[commentId];
// this can happen when deleting the thread ->
// comment mark deleted -> comment server delete re-attempted
if (!comment) return true;
@@ -135,14 +126,15 @@ export function useDeleteComment() {
}
export function useDeleteNewComments() {
- const [marks, setMarks] = markStore;
- const editor = mdStore.get.editor;
+ const { state } = useMarkdownDocument();
+ const { comments: commentState, setCommentState } = state;
+ const editor = state.editor.md.editor;
return createCallback((discardPending = true) => {
// console.trace('delete new comments');
- for (const [markId, mark] of Object.entries(marks)) {
+ for (const [markId, mark] of Object.entries(commentState.marks)) {
if (!mark || !mark.existsOnServer) {
- setMarks(markId, undefined);
+ setCommentState('marks', markId, undefined);
editor?.dispatchCommand(DELETE_COMMENT_COMMAND, [markId, false]);
}
if (discardPending) {
@@ -153,11 +145,11 @@ export function useDeleteNewComments() {
}
export const useSetNodeCommentThreadId = () => {
- const editor = mdStore.get.editor;
+ const { state } = useMarkdownDocument();
return createCallback(
({ markId, threadId }: { markId: string; threadId: number }) => {
- editor?.dispatchCommand(SET_COMMENT_THREAD_ID_COMMAND, {
+ state.editor.md.editor?.dispatchCommand(SET_COMMENT_THREAD_ID_COMMAND, {
markId,
threadId,
});
@@ -166,12 +158,15 @@ export const useSetNodeCommentThreadId = () => {
};
export function useScrollToCommentThread() {
- const blockElement = blockElementSignal.get;
- const documentId = useBlockId();
+ const {
+ documentId: getDocumentId,
+ element: blockElement,
+ state,
+ } = useMarkdownDocument();
+ const commentState = state.comments;
+ const documentId = getDocumentId();
// 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
@@ -200,9 +195,9 @@ export function useScrollToCommentThread() {
if (isMobile()) {
disposePendingWait?.();
const wait = until(() => {
- const anchorId = threads[threadId]?.anchorId;
+ const anchorId = commentState.threads[threadId]?.anchorId;
return anchorId != null
- ? Object.values(marks[anchorId]?.markNodes ?? {})[0]
+ ? Object.values(commentState.marks[anchorId]?.markNodes ?? {})[0]
: undefined;
});
disposePendingWait = wait.dispose;
diff --git a/apps/web/src/features/block-md/comments/commentStore.ts b/apps/web/src/features/block-md/comments/commentStore.ts
deleted file mode 100644
index 227f2487b4..0000000000
--- a/apps/web/src/features/block-md/comments/commentStore.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { createBlockSignal, createBlockStore } from '@core/block';
-import type { NodeKey } from 'lexical';
-import type { CommentStore, MarkStore, ThreadStore } from './commentType';
-
-interface PendingComment {
- anchorKey: NodeKey;
- anchorOffset: number;
- focusKey: NodeKey;
- focusOffset: number;
-}
-
-export const markStore = createBlockStore<MarkStore>({});
-
-export const activeMarkIdsSignal = createBlockSignal<string[]>([]);
-
-export const activeCommentThreadSignal = createBlockSignal<number | null>(null);
-export const highlightedCommentIdSignal = createBlockSignal<number | null>(
- null
-);
-
-export const commentsStore = createBlockStore<CommentStore>({});
-
-export const threadStore = createBlockStore<ThreadStore>({});
-
-export const commentMarksInitializedSignal = createBlockSignal<boolean>(false);
-
-export const highlightedCommentThreadsSignal = createBlockSignal<number[]>([]);
-
-export const pendingCommentSignal = createBlockSignal<PendingComment[]>([]);
-
-export const commentWidthSignal = createBlockSignal(true);
diff --git a/apps/web/src/features/block-md/comments/commentsResource.ts b/apps/web/src/features/block-md/comments/commentsResource.ts
index 3c2d6d562e..1995832347 100644
--- a/apps/web/src/features/block-md/comments/commentsResource.ts
+++ b/apps/web/src/features/block-md/comments/commentsResource.ts
@@ -1,12 +1,6 @@
-import {
- createBlockMemo,
- createBlockResource,
- useBlockId,
- useBlockName,
-} from '@core/block';
import { compareDateAsc } from '@core/util/date';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
+import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import { storageServiceClient } from '@service-storage/client';
import type { AnnotationIncrementalUpdate } from '@service-storage/generated/schemas/annotationIncrementalUpdate';
import type { Comment } from '@service-storage/generated/schemas/comment';
@@ -18,15 +12,11 @@ import type { DeleteCommentRequest } from '@service-storage/generated/schemas/de
import type { DeleteCommentResponse } from '@service-storage/generated/schemas/deleteCommentResponse';
import type { EditCommentRequest } from '@service-storage/generated/schemas/editCommentRequest';
import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';
-import { batch } from 'solid-js';
+import { useQueryClient } from '@tanstack/solid-query';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { markdownCommentKeys } from '../queries/markdown-comments';
import type { MarkId, ThreadMetadata } from './commentType';
-const isMdBlock = createBlockMemo(() => useBlockName() === 'md');
-export const commentThreadsResource = createBlockResource(
- isMdBlock,
- fetchComments
-);
-
export const sortComments = (a: Comment, b: Comment) => {
if (a.order != null && b.order != null) {
return a.order - b.order;
@@ -38,29 +28,20 @@ export const sortComments = (a: Comment, b: Comment) => {
return compareDateAsc(a.createdAt, b.createdAt);
};
-async function fetchComments() {
- const documentId = useBlockId();
- const commentThreads = await storageServiceClient.annotations.getComments({
- documentId,
- });
- if (commentThreads.isErr()) {
- throw new Error('Unable to fetch comments');
- }
- return commentThreads.value.data;
-}
-
function useHandleCreateComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
+ const { documentId } = useMarkdownDocument();
+ const queryClient = useQueryClient();
- return async (response: CreateCommentResponse) => {
+ return (response: CreateCommentResponse) => {
const commentThread: CommentThread = {
thread: response.thread,
comments: response.comments,
};
- batch(() => {
- let mutatedExistingThread = false;
- mutateCommentThreads((prev) => {
- let out: CommentThread[] = [];
+ queryClient.setQueryData<CommentThread[]>(
+ markdownCommentKeys.document(documentId()).queryKey,
+ (prev = []) => {
+ let mutatedExistingThread = false;
+ const out: CommentThread[] = [];
for (const thread of prev) {
if (thread.thread.threadId === commentThread.thread.threadId) {
mutatedExistingThread = true;
@@ -73,18 +54,18 @@ function useHandleCreateComment() {
out.push(commentThread);
}
return out;
- });
- });
+ }
+ );
};
}
function useCreateComment() {
- const documentId = useBlockId();
+ const { documentId } = useMarkdownDocument();
const handleCreateComment = useHandleCreateComment();
return async (body: CreateCommentRequest) => {
const result = await storageServiceClient.annotations.createComment({
- documentId,
+ documentId: documentId(),
body,
});
@@ -102,30 +83,34 @@ function useCreateComment() {
}
function useHandleEditComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
-
- return async (response: EditCommentResponse) => {
- mutateCommentThreads((prev) => {
- let out: CommentThread[] = [];
- for (const thread of prev) {
- if (thread.thread.threadId === response.threadId) {
- const commentThread = {
- thread: thread.thread,
- comments: thread.comments.map((comment) => {
- if (comment.commentId === response.commentId) {
- const editedComment: Comment = response;
- return editedComment;
- }
- return comment;
- }),
- };
- out.push(commentThread);
- } else {
- out.push(thread);
+ const { documentId } = useMarkdownDocument();
+ const queryClient = useQueryClient();
+
+ return (response: EditCommentResponse) => {
+ queryClient.setQueryData<CommentThread[]>(
+ markdownCommentKeys.document(documentId()).queryKey,
+ (prev = []) => {
+ const out: CommentThread[] = [];
+ for (const thread of prev) {
+ if (thread.thread.threadId === response.threadId) {
+ const commentThread = {
+ thread: thread.thread,
+ comments: thread.comments.map((comment) => {
+ if (comment.commentId === response.commentId) {
+ const editedComment: Comment = response;
+ return editedComment;
+ }
+ return comment;
+ }),
+ };
+ out.push(commentThread);
+ } else {
+ out.push(thread);
+ }
}
+ return out;
}
- return out;
- });
+ );
};
}
@@ -152,38 +137,35 @@ export function useEditCommentResource() {
}
function useHandleDeleteComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
-
- return async (response: DeleteCommentResponse) => {
- return batch(() => {
- // either delete single comment or entire thread
- if (response.thread.deleted) {
- mutateCommentThreads((prev) =>
- prev.filter((t) => t.thread.threadId !== response.thread.threadId)
- );
- return {
- threadDeleted: true,
- };
- } else {
- mutateCommentThreads((prev) => {
- let out: CommentThread[] = [];
- for (const commentThread of prev) {
- if (commentThread.thread.threadId === response.thread.threadId) {
- const comments = commentThread.comments.filter(
- (c) => c.commentId !== response.commentId
- );
- out.push({ thread: commentThread.thread, comments });
- } else {
- out.push(commentThread);
- }
+ const { documentId } = useMarkdownDocument();
+ const queryClient = useQueryClient();
+
+ return (response: DeleteCommentResponse) => {
+ const threadDeleted = response.thread.deleted;
+ queryClient.setQueryData<CommentThread[]>(
+ markdownCommentKeys.document(documentId()).queryKey,
+ (prev = []) => {
+ if (threadDeleted) {
+ return prev.filter(
+ (thread) => thread.thread.threadId !== response.thread.threadId
+ );
+ }
+
+ const out: CommentThread[] = [];
+ for (const commentThread of prev) {
+ if (commentThread.thread.threadId === response.thread.threadId) {
+ const comments = commentThread.comments.filter(
+ (comment) => comment.commentId !== response.commentId
+ );
+ out.push({ thread: commentThread.thread, comments });
+ } else {
+ out.push(commentThread);
}
- return out;
- });
- return {
- threadDeleted: false,
- };
+ }
+ return out;
}
- });
+ );
+ return { threadDeleted };
};
}
@@ -243,47 +225,45 @@ export function useCreateThreadReplyResource() {
}
// TODO: enable for live updates when live collab is a thing
-createConnectionBlockWebsocketEffect((msg) => {
- const currentDocumentId = useBlockId();
- const blockName = useBlockName();
-
+export function useCommentRealtime() {
+ const { documentId } = useMarkdownDocument();
const handleCommentUpdate = useHandleCreateComment();
const handleEditComment = useHandleEditComment();
const handleDeleteComment = useHandleDeleteComment();
- if (blockName !== 'md') return;
-
- if (msg.type === 'comment') {
- let incrementalUpdate: AnnotationIncrementalUpdate;
- try {
- incrementalUpdate = JSON.parse(msg.data) as AnnotationIncrementalUpdate;
- if (incrementalUpdate.payload.documentId !== currentDocumentId) {
+ createConnectionWebsocketEffect((msg) => {
+ if (msg.type === 'comment') {
+ let incrementalUpdate: AnnotationIncrementalUpdate;
+ try {
+ incrementalUpdate = JSON.parse(msg.data) as AnnotationIncrementalUpdate;
+ if (incrementalUpdate.payload.documentId !== documentId()) {
+ return;
+ }
+ } catch (error) {
+ console.warn('unable to parse annotation incremental update', error);
return;
}
- } catch (e) {
- console.warn('unable to parse annotation incremental update', e);
- return;
- }
- switch (incrementalUpdate.updateType) {
- case 'create-comment':
- handleCommentUpdate(incrementalUpdate.payload.response);
- break;
- case 'create-anchor':
- break;
- case 'edit-comment':
- handleEditComment(incrementalUpdate.payload.response);
- break;
- case 'edit-anchor':
- break;
- case 'delete-comment':
- handleDeleteComment(incrementalUpdate.payload.response);
- break;
- case 'delete-anchor':
- break;
- default:
- console.error('unknown comment update type', msg);
- break;
+ switch (incrementalUpdate.updateType) {
+ case 'create-comment':
+ handleCommentUpdate(incrementalUpdate.payload.response);
+ break;
+ case 'create-anchor':
+ break;
+ case 'edit-comment':
+ handleEditComment(incrementalUpdate.payload.response);
+ break;
+ case 'edit-anchor':
+ break;
+ case 'delete-comment':
+ handleDeleteComment(incrementalUpdate.payload.response);
+ break;
+ case 'delete-anchor':
+ break;
+ default:
+ console.error('unknown comment update type', msg);
+ break;
+ }
}
- }
-});
+ });
+}
diff --git a/apps/web/src/features/block-md/comments/discussionResource.ts b/apps/web/src/features/block-md/comments/discussionResource.ts
index 05bc5d6f6e..43987a7cef 100644
--- a/apps/web/src/features/block-md/comments/discussionResource.ts
+++ b/apps/web/src/features/block-md/comments/discussionResource.ts
@@ -1,9 +1,9 @@
-import { createBlockMemo } from '@core/block';
import { compareDateAsc } from '@core/util/date';
import type { CommentThread } from '@service-storage/generated/schemas/commentThread';
import type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { useMarkdownCommentsQuery } from '../queries/markdown-comments';
import {
- commentThreadsResource,
sortComments,
useCreateHighlightCommentResource,
useCreateThreadReplyResource,
@@ -19,13 +19,16 @@ function isDiscussionThread(ct: CommentThread): boolean {
return meta?.markId?.startsWith(DISCUSSION_MARK_PREFIX) ?? false;
}
-export const discussionThreads = createBlockMemo(() => {
- const [data] = commentThreadsResource;
- const threads = data() ?? [];
- return threads
- .filter(isDiscussionThread)
- .sort((a, b) => compareDateAsc(a.thread.createdAt, b.thread.createdAt));
-});
+export function useDiscussionThreads() {
+ const { documentId } = useMarkdownDocument();
+ const commentsQuery = useMarkdownCommentsQuery(documentId);
+ return () => {
+ const threads = commentsQuery.isSuccess ? commentsQuery.data : [];
+ return threads
+ .filter(isDiscussionThread)
+ .sort((a, b) => compareDateAsc(a.thread.createdAt, b.thread.createdAt));
+ };
+}
export { sortComments };
diff --git a/apps/web/src/features/block-md/comments/documentDiscussionSource.ts b/apps/web/src/features/block-md/comments/documentDiscussionSource.ts
index 0d804f54a1..f7f50e6ef6 100644
--- a/apps/web/src/features/block-md/comments/documentDiscussionSource.ts
+++ b/apps/web/src/features/block-md/comments/documentDiscussionSource.ts
@@ -1,4 +1,3 @@
-import { useBlockAliasedName, useBlockId } from '@core/block';
import type {
DiscussionComment,
DiscussionSource,
@@ -7,19 +6,18 @@ import type {
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';
import { useUrlParams } from '@core/component/ParamsProvider';
import { useUserId } from '@core/context/user';
-import { useCanComment } from '@core/signal/permissions';
import { buildSimpleEntityUrl } from '@core/util/url';
import type { CommentThread } from '@service-storage/generated/schemas/commentThread';
import type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';
import { createMemo } from 'solid-js';
import { URL_PARAMS } from '../constants';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import {
- discussionThreads,
sortComments,
useCreateDiscussionReply,
useCreateDiscussionThread,
useDeleteDiscussionComment,
+ useDiscussionThreads,
useEditDiscussionComment,
} from './discussionResource';
@@ -58,13 +56,19 @@ function toViewThread(ct: CommentThread): DiscussionThread {
* `DISCUSSION:`-marked threads on a markdown document. Quarantines the numeric
* id ↔ string adaptation and the document-specific request shapes so the
* shared discussion UI stays backend-agnostic. Must be called within a
- * block/component owner (it wires the existing block resources).
+ * Markdown surface owner (it wires the surface-scoped resources).
*/
export function createDocumentDiscussionSource(): DiscussionSource {
- const blockId = useBlockId();
- const blockAliasedName = useBlockAliasedName();
+ const {
+ documentId: getDocumentId,
+ kind,
+ permissions,
+ state,
+ } = useMarkdownDocument();
+ const documentId = getDocumentId();
+ const documentKind = kind();
+ const entityBlockName = documentKind === 'document' ? 'md' : documentKind;
// Comment affordances gate on can-comment (main switched tasks off can-edit).
- const canComment = useCanComment();
const userId = useUserId();
const urlParams = useUrlParams(URL_PARAMS);
@@ -72,7 +76,7 @@ export function createDocumentDiscussionSource(): DiscussionSource {
const createReplyFn = useCreateDiscussionReply();
const editFn = useEditDiscussionComment();
const deleteFn = useDeleteDiscussionComment();
- const md = mdStore.get;
+ const discussionThreads = useDiscussionThreads();
const threads = createMemo(() =>
(discussionThreads() ?? []).map(toViewThread)
@@ -90,7 +94,7 @@ export function createDocumentDiscussionSource(): DiscussionSource {
const request = targetRequest();
if (!request) return null;
const { commentId } = request;
- if (!md.locationReady) return null;
+ if (!state.editor.md.locationReady) return null;
const currentThreads = threads();
const hasDiscussionComment = currentThreads.some((thread) =>
@@ -102,7 +106,7 @@ export function createDocumentDiscussionSource(): DiscussionSource {
return {
threads,
- canEdit: canComment,
+ canEdit: permissions.canComment,
currentUserId: userId,
targetCommentId,
targetRevision,
@@ -127,7 +131,7 @@ export function createDocumentDiscussionSource(): DiscussionSource {
},
buildCommentLink(comment) {
return buildSimpleEntityUrl(
- { type: blockAliasedName, id: blockId },
+ { type: entityBlockName, id: documentId },
{ [URL_PARAMS.commentId]: comment.id }
);
},
diff --git a/apps/web/src/features/block-md/component/Block.tsx b/apps/web/src/features/block-md/component/Block.tsx
index 34606c68e6..3471d425b9 100644
--- a/apps/web/src/features/block-md/component/Block.tsx
+++ b/apps/web/src/features/block-md/component/Block.tsx
@@ -1,333 +1,197 @@
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
+import {
+ CollaborationStatusIndicator,
+ isCollaborationStatusVisible,
+} from '@components/app/CollaborationStatusIndicator';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { SidePanel } from '@components/app/side-panel';
-import { useBlockId } from '@core/block';
+import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
+import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
+import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';
+import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';
+import { useBlockAliasedName, useBlockId } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { ENABLE_MARKDOWN_SIDE_PANEL } from '@core/constant/featureFlags';
-import { blockErrorSignal, blockSyncSourceSignal } from '@core/signal/load';
-import { useCanEdit } from '@core/signal/permissions';
-import {
- createLoroManager,
- type LoroManager,
-} from '@macro-inc/collaboration/collab/manager';
-import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';
+import { blockDataSignal as blockLoaderDataSignal } from '@core/internal/BlockLoader';
+import { createMethodRegistration } from '@core/orchestrator';
+import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import {
- IDBSnapshotStore,
- LORO_SNAPSHOT_DB_NAME,
-} from '@macro-inc/collaboration/collab/snapshot-store';
+ blockErrorSignal,
+ blockHandleSignal,
+ blockSourceSignal,
+} from '@core/signal/load';
import {
- BrowserWALStore,
- LORO_WAL_DB_NAME,
-} from '@macro-inc/collaboration/collab/wal';
-import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
-import type { Span } from '@macro-inc/observability';
+ useCanComment,
+ useCanEdit,
+ useIsDocumentOwner,
+} from '@core/signal/permissions';
+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { DocumentDebouncedNotificationReadMarker } from '@notifications';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
-import { storageServiceClient } from '@service-storage/client';
-import { Scroll } from '@ui';
-import {
- createEffect,
- createMemo,
- createSignal,
- on,
- Show,
- Suspense,
-} from 'solid-js';
-import type { MarkdownData } from '../definition';
-import { HistoryProvider } from '../history/HistoryContext';
+import { Show, Suspense } from 'solid-js';
+import { createMarkdownDocumentState } from '../context/markdown-document-state';
+import type { MarkdownBlockSpec, MarkdownData } from '../definition';
import { OldOverlay } from '../history/OldOverlay';
-import { resumeDocumentSpan, stampLoroSnapshotState } from '../observability';
-import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
+import { loadMarkdownCachedSnapshot } from '../queries/markdown-document-operations';
+import type { MarkdownDocumentKind, MarkdownDocumentSource } from '../types';
import { FindAndReplace } from './FindAndReplace';
-import { MarkdownNameProvider, useMarkdownName } from './MarkdownNameProvider';
+import { MarkdownDocument, MarkdownDocumentContent } from './MarkdownDocument';
+import { useMarkdownName } from './MarkdownNameProvider';
import { ModalsProvider } from './ModalsProvider';
-import { InstructionsNotebook, Notebook } from './Notebook';
import { MarkdownSidePanelSections } from './sidepanel/MarkdownSidePanelSections';
import { InstructionsTopBar, TopBar } from './TopBar';
+import { useTaskBranchNameHotkey } from './useTaskBranchNameHotkey';
export interface BlockMarkdownProps {
/**
- * A loro snapshot to load while we wait for a remote snapshot (from s3, dss, etc.).
+ * A Loro snapshot to load while waiting for a remote snapshot.
*/
optimisticSnapshot?: Uint8Array<ArrayBufferLike>;
}
-type MarkdownLoroManager = LoroManager<typeof MARKDOWN_LORO_SCHEMA>;
-type SnapshotResult = {
- outcome: 'seeded' | 'discarded' | 'unavailable' | 'error';
- bytes?: number;
-};
-
-const snapshotStepNames = {
- optimistic: 'doc.snapshot.optimistic',
- local: 'doc.snapshot.local-cache',
- s3: 'doc.snapshot.s3-cache',
- remote: 'doc.snapshot.remote-sync',
-} as const;
+function ManagedTopBar() {
+ const { displayName } = useMarkdownName();
+ return <TopBar name={displayName} />;
+}
-type SnapshotSource = keyof typeof snapshotStepNames;
+export default function MarkdownBlockAdapter(props: BlockMarkdownProps) {
+ useBlockEntityCommands();
-function startSnapshotIngest(
- parentSpan: Span | undefined,
- source: SnapshotSource,
- loroManager: MarkdownLoroManager,
- ingest: () => Promise<SnapshotResult>
-): void {
- parentSpan?.event('doc.snapshot.attempt', {
- 'snapshot.source': source,
+ const documentId = useBlockId();
+ const canAutofocus = useCanAutofocusSplitContent();
+ const { navigatedFromJK } = useNavigatedFromJK();
+ const currentBlockName = useBlockAliasedName();
+ const kind: MarkdownDocumentKind =
+ currentBlockName === 'task' ||
+ currentBlockName === 'snippet' ||
+ currentBlockName === 'skill'
+ ? currentBlockName
+ : 'document';
+ useTaskBranchNameHotkey({
+ documentId: () => documentId,
+ kind: () => kind,
+ scopeId: blockHotkeyScopeSignal.get,
});
-
- const operation = parentSpan
- ? parentSpan.span(snapshotStepNames[source], async (snapshotSpan) => {
- snapshotSpan.setAttr('snapshot.source', source);
- try {
- const result = await ingest();
- snapshotSpan.setAttr('outcome', result.outcome);
- if (result.bytes !== undefined) {
- snapshotSpan.setAttr('snapshot.bytes', result.bytes);
- }
- if (result.outcome === 'seeded') {
- stampLoroSnapshotState(snapshotSpan, loroManager.doc);
- } else if (result.outcome === 'error') {
- snapshotSpan.error('snapshot ingestion failed');
- }
- return result;
- } catch (error) {
- snapshotSpan.error(error);
- snapshotSpan.setAttr('outcome', 'error');
- throw error;
- }
- })
- : ingest();
-
- void operation
- .then(({ outcome, bytes }) => {
- parentSpan?.event('doc.snapshot.result', {
- 'snapshot.source': source,
- ...(bytes !== undefined && { 'snapshot.bytes': bytes }),
- outcome,
- });
- })
- .catch(() => {
- parentSpan?.event('doc.snapshot.result', {
- 'snapshot.source': source,
- outcome: 'error',
- });
- });
-}
-
-async function ingestLocalSnapshot(
- loroManager: MarkdownLoroManager,
- snapshotStore: IDBSnapshotStore<RawUpdate>,
- walStore: BrowserWALStore<RawUpdate>
-): Promise<SnapshotResult> {
- const localSnapshot = await snapshotStore.load();
- if (!localSnapshot) return { outcome: 'unavailable' };
- const walEntries = await walStore.getAll();
- const seeded = await loroManager.ingest({
- kind: 'local',
- snapshot: localSnapshot,
- walUpdates: walEntries.map((entry) => entry.update),
+ const persistedName = useBlockDocumentName('');
+ const fallbackName = useBlockDocumentName();
+ const instructionsMdId = useInstructionsMdIdQuery();
+ const isInstructions = () =>
+ instructionsMdId.isSuccess && documentId === instructionsMdId.data;
+ const markdownState = createMarkdownDocumentState();
+ const { setRevisions, setRewriting } = markdownState.rewrite;
+ createMethodRegistration(blockHandleSignal.get, {
+ goToLocationFromParams: markdownState.params.navigate,
+ setPatches: ({
+ patches,
+ }: Parameters<MarkdownBlockSpec['setPatches']>[0]) => {
+ setRewriting(false);
+ setRevisions(patches);
+ },
+ setIsRewriting: () => {
+ setRewriting(true);
+ },
});
+ const notificationSource = useGlobalNotificationSource();
- // Fold the replayed WAL edits into a fresh local snapshot so they don't have
- // to be replayed on the next cold load. This is for a race condition where
- // we recover from a snapshot and replay WAL logs, deleting the WAL logs as
- // we replay, and then reload, and now we are in a state where we have an old
- // document until the new one loads in
- if (walEntries.length >= 1) {
- const doc = loroManager.doc;
- const snapshot = doc.export({
- mode: 'shallow-snapshot',
- frontiers: doc.oplogFrontiers(),
- });
- await snapshotStore.save(snapshot);
- }
- return {
- outcome: seeded ? 'seeded' : 'discarded',
- bytes: localSnapshot.length,
+ const rawData = blockLoaderDataSignal.get;
+ const data = () => {
+ const value = rawData() as
+ | (MarkdownData & { __block?: string })
+ | undefined;
+ return value?.__block === 'md' ? value : undefined;
};
-}
+ const documentSource = (): MarkdownDocumentSource => {
+ const loaded = data();
+ if (!loaded) return { type: 'loading' };
-/**
- * Ingest the sync-service initial sync. `discarded` means the snapshot
- * arrived fine but lost the seed race.
- */
-async function ingestRemoteSnapshot(
- loroManager: MarkdownLoroManager,
- doInitialSync: MarkdownData['doInitialSync']
-): Promise<SnapshotResult> {
- const sync = await doInitialSync();
- if (sync.isErr()) {
- console.error('Failed to receive initial sync', sync.error);
- return { outcome: 'error' };
- }
- const bytes = sync.value.snapshot.length;
- const seeded = await loroManager.ingest({
- kind: 'dss',
- snapshot: sync.value.snapshot,
- });
- return { outcome: seeded ? 'seeded' : 'discarded', bytes };
-}
+ const source = blockSourceSignal.get();
+ if (source?.type === 'sync-service' && loaded.syncSource) {
+ return { type: 'sync', source: loaded.syncSource };
+ }
+ if (source?.type === 'dss' && loaded.dssFile) {
+ return { type: 'dss', file: loaded.dssFile };
+ }
-async function ingestS3Snapshot(
- loroManager: MarkdownLoroManager,
- blockId: string
-): Promise<SnapshotResult> {
- const result = await storageServiceClient.fetchCachedSnapshot(blockId);
- if (result.isErr()) return { outcome: 'unavailable' };
- const seeded = await loroManager.ingest({
- kind: 's3',
- snapshot: result.value,
- });
- return {
- outcome: seeded ? 'seeded' : 'discarded',
- bytes: result.value.length,
+ return { type: 'loading' };
+ };
+ const collaborationStatus = () => {
+ const source = documentSource();
+ return source.type === 'sync' ? source.source.status() : undefined;
};
-}
-
-export default function BlockMarkdown(props: BlockMarkdownProps) {
- return (
- <MarkdownNameProvider>
- <BlockMarkdownContent {...props} />
- </MarkdownNameProvider>
- );
-}
-
-function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
- useBlockEntityCommands();
- const [scrollRef, setScrollRef] = createSignal<HTMLDivElement>();
- const blockId = useBlockId();
-
- const _getSyncSource = blockSyncSourceSignal.get;
- const setBlockError = blockErrorSignal.set;
-
- const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, {
- documentId: blockId,
- });
-
- const snapshotStore = new IDBSnapshotStore<RawUpdate>(
- LORO_SNAPSHOT_DB_NAME,
- blockId
- );
- const walStore = new BrowserWALStore<RawUpdate>(LORO_WAL_DB_NAME, blockId);
-
- createEffect(
- on(blockDataSignal, (data) => {
- if (!data) {
- // TODO: if it's actually missing what do we do?
- // setBlockError('MISSING');
- return;
- }
- setBlockError(null);
-
- // optimistic is the "hard coded" snapshot like the golden one when you create a
- // new document
- const span = resumeDocumentSpan(blockId);
- if (optimisticSnapshot) {
- startSnapshotIngest(span, 'optimistic', loroManager, async () => {
- const seeded = await loroManager.ingest({
- kind: 'optimistic',
- snapshot: optimisticSnapshot,
- });
- return {
- outcome: seeded ? 'seeded' : 'discarded',
- bytes: optimisticSnapshot.length,
- };
- });
- }
-
- // First one wins automatically (loro manager takes care of ignoring the rest)
- startSnapshotIngest(span, 'local', loroManager, () =>
- ingestLocalSnapshot(loroManager, snapshotStore, walStore)
- );
- startSnapshotIngest(span, 's3', loroManager, () =>
- ingestS3Snapshot(loroManager, blockId)
- );
- startSnapshotIngest(span, 'remote', loroManager, () =>
- ingestRemoteSnapshot(loroManager, data.doInitialSync)
- );
- })
- );
- const instructionsMdId = useInstructionsMdIdQuery();
- const notificationSource = useGlobalNotificationSource();
+ const setLoadError = blockErrorSignal.set;
+ const canComment = useCanComment();
const canEdit = useCanEdit();
- const { displayName } = useMarkdownName();
- const isInstructionsMd = createMemo(() => blockId === instructionsMdId.data);
-
- createEffect(() => {
- const el = scrollRef();
- if (el) {
- mdStore.set({ scrollContainer: el });
- }
- });
+ const isOwner = useIsDocumentOwner();
return (
<DocumentBlockContainer>
- <div
- class="size-full select-none overscroll-none overflow-hidden flex flex-col relative"
- tabIndex={-1}
+ <MarkdownDocument
+ documentId={documentId}
+ kind={kind}
+ state={markdownState}
+ documentSource={documentSource()}
+ permissions={{
+ canComment: canComment(),
+ canEdit: canEdit(),
+ isOwner: isOwner(),
+ }}
+ persistedName={persistedName()}
+ fallbackName={fallbackName()}
>
<ModalsProvider>
- <HistoryProvider documentId={() => blockId}>
- <OldOverlay />
- <SidePanel.Layout>
- <Show when={ENABLE_MARKDOWN_SIDE_PANEL && !isInstructionsMd()}>
- <MarkdownSidePanelSections
- canEdit={canEdit()}
- documentName={displayName() ?? ''}
- />
- </Show>
- <div class="flex flex-col size-full">
- <div class="relative shrink-0">
- <Suspense>
- <Show
- when={!isInstructionsMd()}
- fallback={<InstructionsTopBar />}
- >
- <TopBar name={displayName} />
- </Show>
- </Suspense>
- <Suspense>
- <Show when={!isInstructionsMd()}>
- <div class="absolute right-4 top-1.5 z-action-menu flex justify-end">
- <FindAndReplace />
- </div>
- </Show>
- </Suspense>
- </div>
- <DocumentDebouncedNotificationReadMarker
- notificationSource={notificationSource}
- documentId={blockId}
- />
- <div
- class="w-full grow overflow-hidden relative"
- data-block-content
- >
- <Scroll class="relative" scrollRef={setScrollRef}>
- <div class="relative portal-scope touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)">
- <Suspense>
- <Show
- when={!isInstructionsMd()}
- fallback={
- <InstructionsNotebook loroManager={loroManager} />
- }
- >
- <Notebook
- loroManager={loroManager}
- documentId={blockId}
- />
- </Show>
- </Suspense>
+ <OldOverlay />
+ <SidePanel.Layout>
+ <Show when={ENABLE_MARKDOWN_SIDE_PANEL && !isInstructions()}>
+ <MarkdownSidePanelSections />
+ </Show>
+ <div class="flex flex-col size-full">
+ <div class="relative shrink-0">
+ <SplitHeaderRight>
+ <Show
+ when={isCollaborationStatusVisible(collaborationStatus())}
+ >
+ <HeaderIsland class="-order-1">
+ <CollaborationStatusIndicator
+ status={collaborationStatus()}
+ />
+ </HeaderIsland>
+ </Show>
+ </SplitHeaderRight>
+ <Suspense>
+ <Show when={isInstructions()} fallback={<ManagedTopBar />}>
+ <InstructionsTopBar />
+ </Show>
+ </Suspense>
+ <Suspense>
+ <Show when={!isInstructions()}>
+ <div class="absolute right-4 top-1.5 z-action-menu flex justify-end">
+ <FindAndReplace
+ hotkeyScope={blockHotkeyScopeSignal.get()}
+ />
</div>
- </Scroll>
- </div>
+ </Show>
+ </Suspense>
</div>
- </SidePanel.Layout>
- </HistoryProvider>
+ <DocumentDebouncedNotificationReadMarker
+ notificationSource={notificationSource}
+ documentId={documentId}
+ />
+ <MarkdownDocumentContent
+ isInstructions={isInstructions()}
+ hotkeyScope={blockHotkeyScopeSignal.get()}
+ autoFocus={canAutofocus && !navigatedFromJK()}
+ doInitialSync={data()?.doInitialSync}
+ optimisticSnapshot={props.optimisticSnapshot}
+ loadCachedSnapshot={() =>
+ loadMarkdownCachedSnapshot(documentId)
+ }
+ onDataReady={() => setLoadError(null)}
+ />
+ </div>
+ </SidePanel.Layout>
</ModalsProvider>
- </div>
+ </MarkdownDocument>
</DocumentBlockContainer>
);
}
diff --git a/apps/web/src/features/block-md/component/CollabStatus.tsx b/apps/web/src/features/block-md/component/CollabStatus.tsx
deleted file mode 100644
index 7a03156d0c..0000000000
--- a/apps/web/src/features/block-md/component/CollabStatus.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
-import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
-import { blockSyncSourceSignal } from '@core/signal/load';
-import { SyncSourceStatus } from '@macro-inc/collaboration/collab/source';
-import CloudIcon from '@phosphor/cloud.svg';
-import CloudWarningIcon from '@phosphor/cloud-warning.svg';
-import { Button } from '@ui';
-import { Match, Show, Switch } from 'solid-js';
-
-export function CollabStatus() {
- const syncSource = blockSyncSourceSignal.get;
-
- const status = () => syncSource()?.status() ?? SyncSourceStatus.Disconnected;
- const showStatus = () =>
- status() === SyncSourceStatus.Disconnected ||
- status() === SyncSourceStatus.Connecting;
-
- return (
- <SplitHeaderRight>
- {/* `mode="outin"` so a state fully fades out before the next fades in
- (one toolbar slot). The <Switch> renders nothing when Connected,
- which the Transition treats as an exit (fade out). */}
- <Show when={showStatus()}>
- <HeaderIsland class="-order-1">
- <Switch>
- <Match when={status() === SyncSourceStatus.Disconnected}>
- <Button
- variant="outline"
- size="icon-sm"
- aria-label="Offline"
- tooltip="You're offline. Changes will sync when you reconnect."
- class="bg-alert-bg border-alert/20"
- >
- <CloudWarningIcon class="text-alert-ink" />
- </Button>
- </Match>
- <Match when={status() === SyncSourceStatus.Connecting}>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label="Reconnecting"
- tooltip="Reconnecting to the document…"
- >
- <CloudIcon class="text-ink-extra-muted animate-pulse" />
- </Button>
- </Match>
- </Switch>
- </HeaderIsland>
- </Show>
- </SplitHeaderRight>
- );
-}
diff --git a/apps/web/src/features/block-md/component/DispatchAgentMenu.tsx b/apps/web/src/features/block-md/component/DispatchAgentMenu.tsx
index 34014d6485..08af3a6e41 100644
--- a/apps/web/src/features/block-md/component/DispatchAgentMenu.tsx
+++ b/apps/web/src/features/block-md/component/DispatchAgentMenu.tsx
@@ -1,11 +1,9 @@
import { openMacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';
import type { SplitFileMenuAction } from '@components/app/split-layout/context';
-import { useBlockId } from '@core/block';
import { editorStateAsMarkdown } from '@core/component/LexicalMarkdown/utils';
import { toast } from '@core/component/Toast/Toast';
import { macroIdToEmail, tryMacroId } from '@core/user';
import { copyBranchNameToClipboard } from '@core/util/branchName';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import ClaudeIcon from '@icon/wide-claude.svg';
import CodexIcon from '@icon/wide-codex-ide.svg';
import CursorIcon from '@icon/wide-cursor-ide.svg';
@@ -23,10 +21,11 @@ import { Button, ButtonGroup, Dropdown } from '@ui';
import { type Component, createSignal, For, type JSX, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import {
- discussionThreads,
sortComments,
+ useDiscussionThreads,
} from '../comments/discussionResource';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { useMarkdownName } from './MarkdownNameProvider';
const LAST_USED_KEY = 'dispatch-agent-last-used';
@@ -164,18 +163,18 @@ const [lastUsedKey, setLastUsedKey] = makePersisted(
);
export function useDispatchAgentAction() {
- const blockId = useBlockId();
- const name = useBlockDocumentName();
- const [store] = mdStore;
+ const { documentId, state } = useMarkdownDocument();
+ const blockId = documentId();
+ const { displayName: name } = useMarkdownName();
+ const discussionThreads = useDiscussionThreads();
const lastUsed = () =>
ALL_ACTIONS.find((a) => a.key === lastUsedKey()) ?? COPY_ACTION;
const buildPrompt = createCallback(() => {
- const docName = name();
- const content = store.editor
- ? editorStateAsMarkdown(store.editor, 'external')
- : '';
+ const docName = name() ?? '';
+ const editor = state.editor.md.editor;
+ const content = editor ? editorStateAsMarkdown(editor, 'external') : '';
const threads = discussionThreads() ?? [];
return generateTaskPrompt(blockId, docName, content, threads);
});
diff --git a/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
index faf1b9d634..0892a91100 100644
--- a/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
+++ b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
@@ -1,4 +1,3 @@
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import clickOutside from '@core/directive/clickOutside';
@@ -11,6 +10,7 @@ import {
} from '@service-ai-editing/client';
import { Button, ComposerSurface, SendButton } from '@ui';
import { createSignal, Show } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
false && clickOutside;
@@ -19,7 +19,7 @@ false && clickOutside;
* into a prompt card matching the Discussion composer.
*/
export function DocumentAiEditBar(props: { documentId: string }) {
- const md = mdStore.get;
+ const { state } = useMarkdownDocument();
const [expanded, setExpanded] = createSignal(false);
const [editing, setEditing] = createSignal(false);
@@ -32,7 +32,7 @@ export function DocumentAiEditBar(props: { documentId: string }) {
const collapse = () => {
setExpanded(false);
setPrompt('');
- md.editor?.focus();
+ state.editor.md.editor?.focus();
};
const submit = () => {
diff --git a/apps/web/src/features/block-md/component/FindAndReplace.tsx b/apps/web/src/features/block-md/component/FindAndReplace.tsx
index 7e211f1e83..764343b658 100644
--- a/apps/web/src/features/block-md/component/FindAndReplace.tsx
+++ b/apps/web/src/features/block-md/component/FindAndReplace.tsx
@@ -1,5 +1,3 @@
-import { FindAndReplaceStore } from '@block-md/signal/findAndReplaceStore';
-import { mdStore } from '@block-md/signal/markdownBlockData';
import {
DO_REPLACE_COMMAND,
DO_REPLACE_ONCE_COMMAND,
@@ -7,8 +5,6 @@ import {
} from '@core/component/LexicalMarkdown/plugins';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
-import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
-import { useCanEdit } from '@core/signal/permissions';
import ReplaceAll from '@phosphor/arrow-bend-double-up-right.svg';
import Replace from '@phosphor/arrow-bend-up-right.svg';
import CaretDown from '@phosphor/caret-down.svg';
@@ -20,19 +16,23 @@ import { createCallback } from '@solid-primitives/rootless';
import { cn, Panel, Tooltip } from '@ui';
import type { JSX } from 'solid-js';
import { createEffect, createSignal, on, onCleanup, Show } from 'solid-js';
-
-export function FindAndReplace() {
- const mdData = mdStore.get;
- const canEdit = useCanEdit();
+import { useMarkdownDocument } from '../context/markdown-document-context';
+
+export function FindAndReplace(props: { hotkeyScope?: string } = {}) {
+ const { permissions, state } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const {
+ md: mdData,
+ findAndReplace: findAndReplaceStore,
+ setFindAndReplace: setFindAndReplaceStore,
+ } = state.editor;
const editor = () => mdData.editor;
- const scopeId = blockHotkeyScopeSignal.get;
+ const scopeId = () => props.hotkeyScope;
let inputRef: HTMLInputElement | undefined;
let inputReplaceRef: HTMLInputElement | undefined;
let performSearchTimeout: ReturnType<typeof setTimeout>;
- const [findAndReplaceStore, setFindAndReplaceStore] = FindAndReplaceStore;
-
const closeSearch = () => {
setFindAndReplaceStore('searchIsOpen', false);
setFindAndReplaceStore('isSearching', false);
@@ -260,11 +260,12 @@ export function FindAndReplace() {
});
createEffect(() => {
- if (!scopeId()) return;
+ const currentScopeId = scopeId();
+ if (!currentScopeId) return;
const registration = registerHotkey({
hotkey: 'cmd+f',
- scopeId: scopeId(),
+ scopeId: currentScopeId,
hotkeyToken: TOKENS.md.find,
description: 'Find in Document',
runWithInputFocused: true,
diff --git a/apps/web/src/features/block-md/component/FormatTools.tsx b/apps/web/src/features/block-md/component/FormatTools.tsx
index cc1bf7a44f..5de211e4fa 100644
--- a/apps/web/src/features/block-md/component/FormatTools.tsx
+++ b/apps/web/src/features/block-md/component/FormatTools.tsx
@@ -1,4 +1,3 @@
-import { markdownBlockErrorSignal } from '@block-md/signal/error';
import {
INSERT_HORIZONTAL_RULE_COMMAND,
NODE_TRANSFORM,
@@ -13,7 +12,6 @@ import { editorFocusSignal } from '@core/component/LexicalMarkdown/utils';
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_MARKDOWN_COMMENTS } from '@core/constant/featureFlags';
import type { ValidHotkey } from '@core/hotkey/types';
-import { useCanComment, useCanEdit } from '@core/signal/permissions';
import DotsThreeLarge from '@icon/dots-three-large.svg';
import {
$isTableCellNode,
@@ -84,11 +82,7 @@ import {
Show,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import {
- generatedAndWaitingSignal,
- isGeneratingSignal,
-} from '../signal/generateSignal';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { MediaSelector } from './MediaSelector';
import { TableInsert } from './TableInsert';
@@ -361,12 +355,13 @@ export function FormatTools(props: {
size?: ButtonSize;
onRequestLink?: () => void;
}) {
- const mdData = mdStore.get;
+ const { permissions, state } = useMarkdownDocument();
+ const { md: mdData, error: editorError } = state.editor;
const buttonSize = () => props.size ?? 'icon-sm';
const editor = () => mdData.editor;
const titleEditor = () => mdData.titleEditor;
const selection = () => mdData.selection;
- const [editorError] = markdownBlockErrorSignal;
+ const { isGenerating, generatedAndWaiting } = state.generation;
const [editorHasFocus, setEditorHasFocus] = createSignal(false);
const [, setTitleEditorHasFocus] = createSignal(false);
@@ -376,24 +371,26 @@ export function FormatTools(props: {
const [lastFocusedEditor, setLastFocusedEditor] =
createSignal<LexicalEditor>();
- const editAccess = useCanEdit();
+ const editAccess = permissions.canEdit;
const canEdit = () => editAccess();
- const canComment = ENABLE_MARKDOWN_COMMENTS ? useCanComment() : () => false;
+ const canComment = ENABLE_MARKDOWN_COMMENTS
+ ? permissions.canComment
+ : () => false;
const buttonIsDisabled = createMemo(() => {
return !(
canEdit() &&
- !isGeneratingSignal() &&
- !generatedAndWaitingSignal() &&
+ !isGenerating() &&
+ !generatedAndWaiting() &&
editorError() === null
);
});
const commentButtonIsDisabled = createMemo(() => {
return !(
canComment() &&
- !isGeneratingSignal() &&
- !generatedAndWaitingSignal() &&
+ !isGenerating() &&
+ !generatedAndWaiting() &&
editorError() === null
);
});
diff --git a/apps/web/src/features/block-md/component/InlinePropertyValue.tsx b/apps/web/src/features/block-md/component/InlinePropertyValue.tsx
index 11345f11b4..49847aa640 100644
--- a/apps/web/src/features/block-md/component/InlinePropertyValue.tsx
+++ b/apps/web/src/features/block-md/component/InlinePropertyValue.tsx
@@ -1,4 +1,3 @@
-import { useMaybeBlockId } from '@core/block';
import { Property } from '@property';
import { usePropertiesContext } from '@property/context/PropertiesContext';
import type { Property as PropertyT } from '@property/types';
@@ -24,7 +23,6 @@ export const InlinePropertyValue: Component<InlinePropertyValueProps> = (
props
) => {
const ctx = usePropertiesContext();
- const blockId = useMaybeBlockId();
const isUserEntity = () =>
props.property.valueType === 'ENTITY' &&
@@ -71,7 +69,7 @@ export const InlinePropertyValue: Component<InlinePropertyValueProps> = (
<Property.PopoverEditor
entitySelfFilter={{
entityType: ctx.entityType,
- blockId: props.entityId ?? blockId,
+ blockId: props.entityId,
}}
/>
</Property.Root>
diff --git a/apps/web/src/features/block-md/component/InlineTaskGithubPullRequests.tsx b/apps/web/src/features/block-md/component/InlineTaskGithubPullRequests.tsx
index f0c210787d..50eea03cb2 100644
--- a/apps/web/src/features/block-md/component/InlineTaskGithubPullRequests.tsx
+++ b/apps/web/src/features/block-md/component/InlineTaskGithubPullRequests.tsx
@@ -1,5 +1,4 @@
import { GithubPullRequestStatusIcon } from '@components/app/side-panel';
-import { useBlockAliasedName, useBlockId } from '@core/block';
import { TOKENS } from '@core/hotkey/tokens';
import { copyBranchNameToClipboard } from '@core/util/branchName';
import GithubIcon from '@icon/mcp-github.svg';
@@ -9,6 +8,7 @@ import type { GithubPullRequest } from '@service-storage/generated/schemas';
import { Button, Layer } from '@ui';
import { cn } from '@ui/utils/classname';
import { createMemo, For, type JSX, Show, Suspense } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
const PILL_CLASS = cn(
'inline-flex items-center gap-1.5 min-w-0 border border-edge-muted',
@@ -152,8 +152,9 @@ function InlineTaskGithubPullRequestsContent(props: {
}
export function InlineTaskGithubPullRequests(): JSX.Element {
- const blockId = useBlockId();
- const isTask = useBlockAliasedName() === 'task';
+ const { documentId, kind } = useMarkdownDocument();
+ const blockId = documentId();
+ const isTask = kind() === 'task';
return (
<Show when={isTask}>
diff --git a/apps/web/src/features/block-md/component/InlineTaskProperties.tsx b/apps/web/src/features/block-md/component/InlineTaskProperties.tsx
index 93bdabe15f..cf3c9c78c2 100644
--- a/apps/web/src/features/block-md/component/InlineTaskProperties.tsx
+++ b/apps/web/src/features/block-md/component/InlineTaskProperties.tsx
@@ -1,12 +1,4 @@
-import {
- type BlockAlias,
- type BlockName,
- useBlockAliasedName,
- useBlockId,
-} from '@core/block';
import { ProgressChip } from '@core/component/LexicalMarkdown/component/status/Progress';
-import { useCanEdit } from '@core/signal/permissions';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { Modals } from '@property/component/modal';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import {
@@ -17,25 +9,22 @@ import { useEntityProperties } from '@property/hooks';
import { InlineFetchedEntityTagsPill } from '@property/tags';
import type { Property, PropertyApiValues } from '@property/types';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { createMemo, For, Show, Suspense } from 'solid-js';
-import { match } from 'ts-pattern';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { InlinePropertyValue } from './InlinePropertyValue';
+import { useMarkdownName } from './MarkdownNameProvider';
/**
* Inline task properties shown below the title when the side panel is closed.
* Displays status, priority, and assignees in a single row, editable like in list view.
*/
export function InlineTaskProperties() {
- const md = mdStore.get;
- const blockId = useBlockId();
- const blockName = useBlockAliasedName();
- const canEdit = useCanEdit();
- const documentName = useBlockDocumentName();
- const entityType = match<BlockName | BlockAlias, EntityType>(blockName)
- .with('task', () => 'TASK')
- .otherwise(() => 'DOCUMENT');
+ const { documentId, kind, permissions, state } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const blockId = documentId();
+ const documentKind = kind();
+ const { displayName: documentName } = useMarkdownName();
+ const entityType = documentKind === 'task' ? 'TASK' : 'DOCUMENT';
const { properties, refetch } = useEntityProperties(
blockId,
@@ -56,8 +45,8 @@ export function InlineTaskProperties() {
});
const shouldShowRow = createMemo(
() =>
- blockName === 'task' ||
- blockName === 'md' ||
+ documentKind === 'task' ||
+ documentKind === 'document' ||
inlineProperties().length > 0
);
@@ -91,6 +80,7 @@ export function InlineTaskProperties() {
{(property) => (
<InlinePropertyValue
property={property}
+ entityId={blockId}
class="bg-surface-2 border border-edge"
/>
)}
@@ -100,7 +90,7 @@ export function InlineTaskProperties() {
entityType={entityType}
class="bg-surface-2"
/>
- <Show when={blockName === 'task' && md.progressStats}>
+ <Show when={documentKind === 'task' && state.editor.md.progressStats}>
{(progressStats) => (
<Show when={progressStats().total > 0}>
<ProgressChip stats={progressStats()} />
diff --git a/apps/web/src/features/block-md/component/InstructionsEditor.tsx b/apps/web/src/features/block-md/component/InstructionsEditor.tsx
index cc3f7bcd22..8cbe660dcb 100644
--- a/apps/web/src/features/block-md/component/InstructionsEditor.tsx
+++ b/apps/web/src/features/block-md/component/InstructionsEditor.tsx
@@ -1,7 +1,4 @@
-import { markdownBlockErrorSignal } from '@block-md/signal/error';
-import { revisionsSignal, rewriteSignal } from '@block-md/signal/rewriteSignal';
import { SplitBottomPanel } from '@components/app/split-layout/components/SplitBottomPanel';
-import { useBlockId } from '@core/block';
import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';
import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';
import { LexicalStateDebugger } from '@core/component/LexicalMarkdown/component/debug/LexicalStateDebugger';
@@ -39,15 +36,6 @@ import {
setEditorStateFromMarkdown,
} from '@core/component/LexicalMarkdown/utils';
import { ENABLE_MARKDOWN_LIVE_COLLABORATION } from '@core/constant/featureFlags';
-import { createMethodRegistration } from '@core/orchestrator';
-import { blockElementSignal } from '@core/signal/blockElement';
-import {
- blockFileSignal,
- blockHandleSignal,
- blockSourceSignal,
-} from '@core/signal/load';
-import { useCanEdit } from '@core/signal/permissions';
-import { isSourceDSS, isSourceSyncService } from '@core/util/source';
import { bufToString } from '@core/util/string';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import {
@@ -69,9 +57,8 @@ import {
onCleanup,
Show,
} from 'solid-js';
-import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
-import type { MarkdownRewriteOutput } from '../signal/rewriteSignal';
-import { useBlockSave, useSaveMarkdownDocument } from '../signal/save';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { createSaveMarkdownDocumentMutation } from '../queries/markdown-document-operations';
import { EditorSystemMessage } from './EditorSystemMessage';
import { MarkdownCollabProvider } from './MarkdownCollabProvider';
@@ -82,41 +69,45 @@ export function InstructionsEditor(props: {
showLexicalStateDebugger?: boolean;
onLexicalStateDebuggerClose?: () => void;
}) {
- const blockData = blockDataSignal.get;
- const blockId = useBlockId();
-
- const saveMarkdownDocument = useSaveMarkdownDocument();
- const setMdStore = mdStore.set;
- const canEdit = useCanEdit();
- const [blockElement] = blockElementSignal;
- const docSource = blockSourceSignal.get;
-
- const blockHandle = blockHandleSignal.get;
- createMethodRegistration(blockHandle, {
- goToLocationFromParams: (_params: Record<string, any>) => {},
- });
-
- const IS_SYNC = () => {
- return docSource() && isSourceSyncService(docSource()!);
- };
+ const {
+ documentId,
+ documentSource,
+ element: blockElement,
+ permissions,
+ state: documentState,
+ } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const blockId = documentId();
+
+ const saveDocumentMutation = createSaveMarkdownDocumentMutation();
+ const {
+ setMd: setMdStore,
+ error: editorError,
+ setError: setEditorError,
+ } = documentState.editor;
+ const saveBlocked = () => documentState.comments.activeCommentThread === -1;
+
+ const IS_SYNC = () => documentSource().type === 'sync';
const debouncedSaveState = debounce(() => {
const state_ = state();
- if (!state_ || !canEdit()) return;
+ if (!state_ || !canEdit() || saveBlocked()) return;
const savableState = getSaveState(editor.getEditorState());
- saveMarkdownDocument(JSON.stringify(savableState));
+ saveDocumentMutation.mutate({
+ documentId: blockId,
+ text: JSON.stringify(savableState),
+ });
}, 500);
// flush save state after unblocking
- const blockSave = useBlockSave();
createEffect((prev) => {
- const blockSave_ = blockSave();
+ const saveBlocked_ = saveBlocked();
// no save on load
- if (!blockSave_ && prev !== undefined) {
+ if (!saveBlocked_ && prev !== undefined) {
debouncedSaveState();
}
- return blockSave_;
+ return saveBlocked_;
}, undefined);
let editorContainerRef!: HTMLDivElement;
@@ -124,7 +115,6 @@ export function InstructionsEditor(props: {
const [clickTargetHeight, setClickTargetHeight] = createSignal(0);
const [editorReady, setEditorReady] = createSignal<boolean>(false);
- const [editorError, setEditorError] = markdownBlockErrorSignal;
createEffect(() => {
// We still want the editor to be locked down (for certain things like click events on check
@@ -285,17 +275,14 @@ export function InstructionsEditor(props: {
const [fileArrayBuffer, setFileArrayBuffer] = createSignal<ArrayBuffer>();
createEffect(() => {
- const file = blockFileSignal();
- if (!file) return;
+ const source = documentSource();
+ if (source.type !== 'dss') return;
- file.arrayBuffer().then(setFileArrayBuffer);
+ source.file.arrayBuffer().then(setFileArrayBuffer);
});
createEffect(() => {
- const source = docSource();
- if (!source) return;
- if (!isSourceDSS(source)) return;
- if (!blockData()) return;
+ if (documentSource().type !== 'dss') return;
if (editorReady()) return;
const buf = fileArrayBuffer();
@@ -353,22 +340,6 @@ export function InstructionsEditor(props: {
setEditorReady(true);
});
- const setRewriteSignal = rewriteSignal.set;
- const setRevisionSignal = revisionsSignal.set;
-
- createMethodRegistration(blockHandle, {
- setPatches: (args: { patches: MarkdownRewriteOutput['diffs'] }) => {
- setRewriteSignal(false);
- setRevisionSignal(args.patches);
- },
- });
-
- createMethodRegistration(blockHandle, {
- setIsRewriting: () => {
- setRewriteSignal(true);
- },
- });
-
return (
<LexicalWrapperContext.Provider value={lexicalWrapper}>
<Show when={editorError()}>
diff --git a/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx b/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx
index 405e5531e6..64653fa0cb 100644
--- a/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx
@@ -1,16 +1,12 @@
-import { markdownBlockErrorSignal } from '@block-md/signal/error';
import { CollabProvider } from '@core/component/LexicalMarkdown/collaboration/CollabProvider';
import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';
import type { PluginManager } from '@core/component/LexicalMarkdown/plugins';
-import { blockSourceSignal, blockSyncSourceSignal } from '@core/signal/load';
-import { useCanComment, useCanEdit } from '@core/signal/permissions';
-import { isSourceSyncService } from '@core/util/source';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
import type { LexicalEditor } from 'lexical';
import type { Accessor, Setter } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { endDocumentSpan, resumeDocumentSpan } from '../observability';
-import { CollabStatus } from './CollabStatus';
// The sync tags and force-sync command live with the generic provider now;
// re-exported here so existing md-block imports keep working.
@@ -38,11 +34,11 @@ export type MarkdownCollabProviderProps = {
* the block's document tracing spans, with the CollabStatus chrome.
*/
export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
- const docSource = blockSourceSignal.get;
- const syncSource = blockSyncSourceSignal.get;
- const canEdit = useCanEdit();
- const canComment = useCanComment();
- const [editorError] = markdownBlockErrorSignal;
+ const { documentSource, permissions, state } = useMarkdownDocument();
+ const syncSource = () => {
+ const source = documentSource();
+ return source.type === 'sync' ? source.source : undefined;
+ };
return (
<CollabProvider
@@ -56,18 +52,14 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
setEditorError={props.setEditorError}
loroManager={props.loroManager}
syncSource={syncSource}
- sourceReady={() => {
- const source = docSource();
- return !!source && isSourceSyncService(source);
- }}
- canEdit={canEdit}
- canComment={canComment}
- editorError={editorError}
+ sourceReady={() => documentSource().type === 'sync'}
+ canEdit={permissions.canEdit}
+ canComment={permissions.canComment}
+ editorError={state.editor.error}
observability={{
resumeSpan: resumeDocumentSpan,
endSpan: endDocumentSpan,
}}
- statusChrome={<CollabStatus />}
/>
);
}
diff --git a/apps/web/src/features/block-md/component/MarkdownDocument.tsx b/apps/web/src/features/block-md/component/MarkdownDocument.tsx
new file mode 100644
index 0000000000..8d1f959e24
--- /dev/null
+++ b/apps/web/src/features/block-md/component/MarkdownDocument.tsx
@@ -0,0 +1,335 @@
+import {
+ createLoroManager,
+ type LoroManager,
+} from '@macro-inc/collaboration/collab/manager';
+import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';
+import {
+ IDBSnapshotStore,
+ LORO_SNAPSHOT_DB_NAME,
+} from '@macro-inc/collaboration/collab/snapshot-store';
+import type {
+ InitialSync,
+ TimeoutError,
+} from '@macro-inc/collaboration/collab/source';
+import {
+ BrowserWALStore,
+ LORO_WAL_DB_NAME,
+} from '@macro-inc/collaboration/collab/wal';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import type { Span } from '@macro-inc/observability';
+import { Scroll } from '@ui';
+import type { ResultAsync } from 'neverthrow';
+import {
+ createEffect,
+ createSignal,
+ on,
+ type ParentProps,
+ Show,
+ Suspense,
+} from 'solid-js';
+import {
+ type MarkdownDocumentContextValue,
+ MarkdownDocumentProvider,
+ useMarkdownDocument,
+} from '../context/markdown-document-context';
+import {
+ createMarkdownDocumentState,
+ type MarkdownDocumentState,
+} from '../context/markdown-document-state';
+import { HistoryProvider } from '../history/HistoryContext';
+import { resumeDocumentSpan, stampLoroSnapshotState } from '../observability';
+import type { MarkdownDocumentKind, MarkdownDocumentSource } from '../types';
+import { MarkdownNameProvider } from './MarkdownNameProvider';
+import { InstructionsNotebook, Notebook } from './Notebook';
+
+type MarkdownLoroManager = LoroManager<typeof MARKDOWN_LORO_SCHEMA>;
+type SnapshotResult = {
+ outcome: 'seeded' | 'discarded' | 'unavailable' | 'error';
+ bytes?: number;
+};
+
+const snapshotStepNames = {
+ optimistic: 'doc.snapshot.optimistic',
+ local: 'doc.snapshot.local-cache',
+ s3: 'doc.snapshot.s3-cache',
+ remote: 'doc.snapshot.remote-sync',
+} as const;
+
+type SnapshotSource = keyof typeof snapshotStepNames;
+
+async function recordSnapshotResult(
+ parentSpan: Span | undefined,
+ source: SnapshotSource,
+ operation: Promise<SnapshotResult>
+): Promise<void> {
+ try {
+ const { outcome, bytes } = await operation;
+ parentSpan?.event('doc.snapshot.result', {
+ 'snapshot.source': source,
+ ...(bytes !== undefined && { 'snapshot.bytes': bytes }),
+ outcome,
+ });
+ } catch {
+ parentSpan?.event('doc.snapshot.result', {
+ 'snapshot.source': source,
+ outcome: 'error',
+ });
+ }
+}
+
+function startSnapshotIngest(
+ parentSpan: Span | undefined,
+ source: SnapshotSource,
+ loroManager: MarkdownLoroManager,
+ ingest: () => Promise<SnapshotResult>
+): void {
+ parentSpan?.event('doc.snapshot.attempt', {
+ 'snapshot.source': source,
+ });
+
+ const operation = parentSpan
+ ? parentSpan.span(snapshotStepNames[source], async (snapshotSpan) => {
+ snapshotSpan.setAttr('snapshot.source', source);
+ try {
+ const result = await ingest();
+ snapshotSpan.setAttr('outcome', result.outcome);
+ if (result.bytes !== undefined) {
+ snapshotSpan.setAttr('snapshot.bytes', result.bytes);
+ }
+ if (result.outcome === 'seeded') {
+ stampLoroSnapshotState(snapshotSpan, loroManager.doc);
+ } else if (result.outcome === 'error') {
+ snapshotSpan.error('snapshot ingestion failed');
+ }
+ return result;
+ } catch (error) {
+ snapshotSpan.error(error);
+ snapshotSpan.setAttr('outcome', 'error');
+ throw error;
+ }
+ })
+ : ingest();
+
+ void recordSnapshotResult(parentSpan, source, operation);
+}
+
+async function ingestLocalSnapshot(
+ loroManager: MarkdownLoroManager,
+ snapshotStore: IDBSnapshotStore<RawUpdate>,
+ walStore: BrowserWALStore<RawUpdate>
+): Promise<SnapshotResult> {
+ const localSnapshot = await snapshotStore.load();
+ if (!localSnapshot) return { outcome: 'unavailable' };
+ const walEntries = await walStore.getAll();
+ const seeded = await loroManager.ingest({
+ kind: 'local',
+ snapshot: localSnapshot,
+ walUpdates: walEntries.map((entry) => entry.update),
+ });
+
+ if (walEntries.length >= 1) {
+ const doc = loroManager.doc;
+ const snapshot = doc.export({
+ mode: 'shallow-snapshot',
+ frontiers: doc.oplogFrontiers(),
+ });
+ await snapshotStore.save(snapshot);
+ }
+ return {
+ outcome: seeded ? 'seeded' : 'discarded',
+ bytes: localSnapshot.length,
+ };
+}
+
+async function ingestRemoteSnapshot(
+ loroManager: MarkdownLoroManager,
+ doInitialSync: () => ResultAsync<InitialSync, TimeoutError>
+): Promise<SnapshotResult> {
+ const sync = await doInitialSync();
+ if (sync.isErr()) {
+ console.error('Failed to receive initial sync', sync.error);
+ return { outcome: 'error' };
+ }
+ const bytes = sync.value.snapshot.length;
+ const seeded = await loroManager.ingest({
+ kind: 'dss',
+ snapshot: sync.value.snapshot,
+ });
+ return { outcome: seeded ? 'seeded' : 'discarded', bytes };
+}
+
+async function ingestS3Snapshot(
+ loroManager: MarkdownLoroManager,
+ loadCachedSnapshot: () => Promise<Uint8Array | undefined>
+): Promise<SnapshotResult> {
+ const snapshot = await loadCachedSnapshot();
+ if (!snapshot) return { outcome: 'unavailable' };
+ const seeded = await loroManager.ingest({
+ kind: 's3',
+ snapshot,
+ });
+ return {
+ outcome: seeded ? 'seeded' : 'discarded',
+ bytes: snapshot.length,
+ };
+}
+
+type MarkdownDocumentProps = {
+ documentId: string;
+ kind: MarkdownDocumentKind;
+ state?: MarkdownDocumentState;
+ documentSource: MarkdownDocumentSource;
+ permissions: {
+ canComment: boolean;
+ canEdit: boolean;
+ isOwner: boolean;
+ };
+ persistedName: string | undefined;
+ fallbackName: string | undefined;
+};
+
+export function MarkdownDocument(props: ParentProps<MarkdownDocumentProps>) {
+ const [surfaceElement, setSurfaceElement] = createSignal<HTMLElement>();
+
+ const state = props.state ?? createMarkdownDocumentState();
+
+ const context: MarkdownDocumentContextValue = {
+ documentId: () => props.documentId,
+ kind: () => props.kind,
+ documentSource: () => props.documentSource,
+ permissions: {
+ canComment: () => props.permissions.canComment,
+ canEdit: () => props.permissions.canEdit,
+ isOwner: () => props.permissions.isOwner,
+ },
+ persistedName: () => props.persistedName,
+ fallbackName: () => props.fallbackName,
+ state,
+ element: surfaceElement,
+ };
+
+ return (
+ <MarkdownDocumentProvider context={context}>
+ <MarkdownNameProvider>
+ <div
+ ref={setSurfaceElement}
+ class="size-full select-none overscroll-none overflow-hidden flex flex-col relative"
+ tabIndex={-1}
+ >
+ <HistoryProvider documentId={() => props.documentId}>
+ {props.children}
+ </HistoryProvider>
+ </div>
+ </MarkdownNameProvider>
+ </MarkdownDocumentProvider>
+ );
+}
+
+type MarkdownSnapshotIngestOptions = {
+ doInitialSync?: () => ResultAsync<InitialSync, TimeoutError>;
+ optimisticSnapshot?: Uint8Array<ArrayBufferLike>;
+ loadCachedSnapshot?: () => Promise<Uint8Array | undefined>;
+ onDataReady?: () => void;
+};
+
+function useMarkdownSnapshotIngest(
+ loroManager: MarkdownLoroManager,
+ options: MarkdownSnapshotIngestOptions
+) {
+ const { documentId: getDocumentId } = useMarkdownDocument();
+ const documentId = getDocumentId();
+ const snapshotStore = new IDBSnapshotStore<RawUpdate>(
+ LORO_SNAPSHOT_DB_NAME,
+ documentId
+ );
+ const walStore = new BrowserWALStore<RawUpdate>(LORO_WAL_DB_NAME, documentId);
+
+ createEffect(
+ on(
+ () => options.doInitialSync,
+ (doInitialSync) => {
+ if (!doInitialSync) return;
+ options.onDataReady?.();
+
+ const span = resumeDocumentSpan(documentId);
+ if (options.optimisticSnapshot) {
+ startSnapshotIngest(span, 'optimistic', loroManager, async () => {
+ const seeded = await loroManager.ingest({
+ kind: 'optimistic',
+ snapshot: options.optimisticSnapshot!,
+ });
+ return {
+ outcome: seeded ? 'seeded' : 'discarded',
+ bytes: options.optimisticSnapshot!.length,
+ };
+ });
+ }
+ startSnapshotIngest(span, 'local', loroManager, () =>
+ ingestLocalSnapshot(loroManager, snapshotStore, walStore)
+ );
+ startSnapshotIngest(span, 's3', loroManager, () =>
+ ingestS3Snapshot(
+ loroManager,
+ options.loadCachedSnapshot ?? (async () => undefined)
+ )
+ );
+ startSnapshotIngest(span, 'remote', loroManager, () =>
+ ingestRemoteSnapshot(loroManager, doInitialSync)
+ );
+ }
+ )
+ );
+}
+
+export type MarkdownDocumentContentProps = MarkdownSnapshotIngestOptions & {
+ isInstructions?: boolean;
+ hotkeyScope?: string;
+ autoFocus?: boolean;
+};
+
+export function MarkdownDocumentContent(props: MarkdownDocumentContentProps) {
+ const { documentId: getDocumentId, state } = useMarkdownDocument();
+ const documentId = getDocumentId();
+
+ const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, {
+ documentId,
+ });
+
+ useMarkdownSnapshotIngest(loroManager, props);
+
+ const isInstructions = () => props.isInstructions ?? false;
+
+ return (
+ <div class="w-full grow overflow-hidden relative" data-block-content>
+ <Scroll
+ class="relative"
+ scrollRef={(element) => {
+ state.editor.setMd({
+ scrollContainer: element,
+ });
+ }}
+ >
+ <div class="relative portal-scope touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)">
+ <Suspense>
+ <Show
+ when={!isInstructions()}
+ fallback={
+ <InstructionsNotebook
+ loroManager={loroManager}
+ hotkeyScope={props.hotkeyScope}
+ />
+ }
+ >
+ <Notebook
+ loroManager={loroManager}
+ documentId={documentId}
+ hotkeyScope={props.hotkeyScope}
+ autoFocus={props.autoFocus ?? false}
+ />
+ </Show>
+ </Suspense>
+ </div>
+ </Scroll>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
index 20457686ac..179f338364 100644
--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
@@ -2,15 +2,8 @@ import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { CommentsProvider } from '@block-md/comments/CommentsProvider';
import { URL_PARAMS } from '@block-md/constants';
import { keyNavigationPlugin } from '@block-md/plugins/keyboardNavigation';
-import { markdownBlockErrorSignal } from '@block-md/signal/error';
-import { FindAndReplaceStore } from '@block-md/signal/findAndReplaceStore';
-import { revisionsSignal, rewriteSignal } from '@block-md/signal/rewriteSignal';
import { SplitBottomPanel } from '@components/app/split-layout/components/SplitBottomPanel';
-import {
- type BlockName,
- useBlockId,
- useMaybeBlockAliasedName,
-} from '@core/block';
+import type { BlockName } from '@core/block';
import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';
import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';
import {
@@ -150,16 +143,7 @@ import { useUserId } from '@core/context/user';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { createMethodRegistration } from '@core/orchestrator';
-import {
- blockFileSignal,
- blockHandleSignal,
- blockSourceSignal,
-} from '@core/signal/load';
import { trackMention } from '@core/signal/mention';
-import { useCanComment, useCanEdit } from '@core/signal/permissions';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import { isSourceDSS, isSourceSyncService } from '@core/util/source';
import { bufToString } from '@core/util/string';
import { handleFileFolderDrop } from '@core/util/upload';
import { type EntityDragEvent, isEntityDragEvent } from '@entity';
@@ -192,17 +176,8 @@ import {
Suspense,
untrack,
} from 'solid-js';
-import {
- completionSignal,
- generateContentCallback,
- generateContextSignal,
- generatedAndWaitingSignal,
- generateMenuSignal,
- isGeneratingSignal,
-} from '../signal/generateSignal';
-import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
-import type { MarkdownRewriteOutput } from '../signal/rewriteSignal';
-import { useBlockSave, useSaveMarkdownDocument } from '../signal/save';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { createSaveMarkdownDocumentMutation } from '../queries/markdown-document-operations';
import { EditorSystemMessage } from './EditorSystemMessage';
import { MarkdownCollabProvider } from './MarkdownCollabProvider';
import { MarkdownPopup } from './MarkdownPopup';
@@ -232,60 +207,93 @@ export function MarkdownEditor(props: {
showLexicalStateDebugger?: boolean;
onLexicalStateDebuggerClose?: () => void;
}) {
- const blockData = blockDataSignal.get;
- const blockId = useBlockId();
+ const {
+ documentId,
+ kind,
+ documentSource,
+ persistedName: mdDocumentName,
+ permissions,
+ state: documentState,
+ } = useMarkdownDocument();
+ const { canEdit, canComment } = permissions;
+ const blockId = documentId();
const userId = useUserId();
- const blockName = useMaybeBlockAliasedName();
+ const documentKind = kind();
+ const sourceBlockName = documentKind === 'document' ? 'md' : documentKind;
const documentTags = useDocTags(
blockId,
- blockName === 'task' ? EntityType.TASK : EntityType.DOCUMENT
+ documentKind === 'task' ? EntityType.TASK : EntityType.DOCUMENT
);
const tagApplyTargetLabel = () =>
- blockName === 'task' ? 'Task' : 'Document';
-
- const mdDocumentName = useBlockDocumentName('');
-
- const blockHandle = blockHandleSignal.get;
- const saveMarkdownDocument = useSaveMarkdownDocument();
- const setMdStore = mdStore.set;
- const md = mdStore.get;
- const canEdit = useCanEdit();
- const canComment = useCanComment();
- const [findAndReplaceStore, setFindAndReplaceStore] = FindAndReplaceStore;
- const docSource = blockSourceSignal.get;
-
- const IS_SYNC = () => {
- return docSource() && isSourceSyncService(docSource()!);
- };
+ documentKind === 'task' ? 'Task' : 'Document';
+
+ const saveDocumentMutation = createSaveMarkdownDocumentMutation();
+ const {
+ md,
+ setMd: setMdStore,
+ error: editorError,
+ setError: setEditorError,
+ findAndReplace: findAndReplaceStore,
+ setFindAndReplace: setFindAndReplaceStore,
+ } = documentState.editor;
+ const { revisions, setRevisions } = documentState.rewrite;
+ const saveBlocked = () => documentState.comments.activeCommentThread === -1;
+
+ const IS_SYNC = () => documentSource().type === 'sync';
const debouncedSaveState = debounce(() => {
const state_ = state();
- if (!state_ || !canEdit()) return;
+ if (!state_ || !canEdit() || saveBlocked()) return;
const savableState = getSaveState(editor.getEditorState());
- saveMarkdownDocument(JSON.stringify(savableState));
+ saveDocumentMutation.mutate({
+ documentId: blockId,
+ text: JSON.stringify(savableState),
+ });
}, 500);
// flush save state after unblocking
- const blockSave = useBlockSave();
createEffect((prev) => {
- const blockSave_ = blockSave();
+ const saveBlocked_ = saveBlocked();
// no save on load
- if (!blockSave_ && prev !== undefined) {
+ if (!saveBlocked_ && prev !== undefined) {
debouncedSaveState();
}
- return blockSave_;
+ return saveBlocked_;
}, undefined);
let editorContainerRef!: HTMLDivElement;
const [clickTargetHeight, setClickTargetHeight] = createSignal(0);
- const [isGenerating, setIsGenerating] = isGeneratingSignal;
- const generatedAndWaiting = generatedAndWaitingSignal.get;
- const [generateMenuOpen, _setGenerateMenuOpen] = generateMenuSignal;
+ const {
+ isGenerating,
+ setIsGenerating,
+ generatedAndWaiting,
+ setGeneratedAndWaiting,
+ completion,
+ setCompletion,
+ generateMenuOpen,
+ setGenerateMenuOpen,
+ setGenerateContext,
+ } = documentState.generation;
+ const completionSignal = [completion, setCompletion] as [
+ typeof completion,
+ typeof setCompletion,
+ ];
+ const isGeneratingSignal = [isGenerating, setIsGenerating] as [
+ typeof isGenerating,
+ typeof setIsGenerating,
+ ];
+ const generatedAndWaitingSignal = [
+ generatedAndWaiting,
+ setGeneratedAndWaiting,
+ ] as [typeof generatedAndWaiting, typeof setGeneratedAndWaiting];
+ const generateMenuSignal = [generateMenuOpen, setGenerateMenuOpen] as [
+ typeof generateMenuOpen,
+ typeof setGenerateMenuOpen,
+ ];
const [editorReady, setEditorReady] = createSignal<boolean>(false);
- const [editorError, setEditorError] = markdownBlockErrorSignal;
const [highlightLayerRef, setHighlightLayerRef] =
createSignal<HTMLDivElement>();
@@ -625,7 +633,7 @@ export function MarkdownEditor(props: {
.use(
checkboxToTaskPlugin({
currentUserId: userId(),
- parentTaskId: blockName === 'task' ? blockId : undefined,
+ parentTaskId: documentKind === 'task' ? blockId : undefined,
})
)
.use(
@@ -675,7 +683,7 @@ export function MarkdownEditor(props: {
if (ENABLE_MARKDOWN_DIFF) {
plugins.use(
diffPlugin({
- revisionsSignal: revisionsSignal,
+ revisionsSignal: [revisions, setRevisions],
nodeIdMap: lexicalWrapper.mapping!,
})
);
@@ -689,7 +697,7 @@ export function MarkdownEditor(props: {
isGeneratingSignal,
generatedAndWaitingSignal,
menuSignal: generateMenuSignal,
- setContext: generateContextSignal[1],
+ setContext: setGenerateContext,
accessories: accessoryStore,
setAccessories: setAccessoryStore,
})
@@ -860,17 +868,14 @@ export function MarkdownEditor(props: {
const [fileArrayBuffer, setFileArrayBuffer] = createSignal<ArrayBuffer>();
createEffect(() => {
- const file = blockFileSignal();
- if (!file) return;
+ const source = documentSource();
+ if (source.type !== 'dss') return;
- file.arrayBuffer().then(setFileArrayBuffer);
+ source.file.arrayBuffer().then(setFileArrayBuffer);
});
createEffect(() => {
- const source = docSource();
- if (!source) return;
- if (!isSourceDSS(source)) return;
- if (!blockData()) return;
+ if (documentSource().type !== 'dss') return;
if (editorReady()) return;
const buf = fileArrayBuffer();
@@ -941,25 +946,9 @@ export function MarkdownEditor(props: {
}
});
- const _generateContentCallback = createCallback((userRequest: string) => {
+ // Temporarily disabled pending port to connection-gateway.
+ const _generateContentCallback = createCallback((_userRequest: string) => {
setIsGenerating(true);
- generateContentCallback(userRequest);
- });
-
- const setRewriteSignal = rewriteSignal.set;
- const setRevisionSignal = revisionsSignal.set;
-
- createMethodRegistration(blockHandle, {
- setPatches: (args: { patches: MarkdownRewriteOutput['diffs'] }) => {
- setRewriteSignal(false);
- setRevisionSignal(args.patches);
- },
- });
-
- createMethodRegistration(blockHandle, {
- setIsRewriting: () => {
- setRewriteSignal(true);
- },
});
const [blameTooltipStore, setBlameTooltipStore] = createBlameTooltipStore();
@@ -1127,26 +1116,35 @@ export function MarkdownEditor(props: {
menu={actionsMenuOperations}
actionContext={{
sourceDocumentId: blockId,
- sourceBlockName: blockName,
+ sourceBlockName,
}}
/>
<FloatingMenuGroup>
<FloatingLinkMenu autoLinkMatchMode="common-tlds" />
- <FloatingEquationMenu />
- <FloatingTableMenu />
+ <FloatingEquationMenu canEdit={canEdit} />
+ <FloatingTableMenu canEdit={canEdit} />
<MarkdownPopup
highlightLayerRef={highlightLayerRef() ?? editorContainerRef}
lexicalMapping={lexicalWrapper.mapping}
/>
</FloatingMenuGroup>
- <Show when={FindAndReplaceStore.get.searchIsOpen}>
+ <Show when={findAndReplaceStore.searchIsOpen}>
<SearchHighlight
anchorElem={highlightLayerRef() ?? editorContainerRef}
+ listOffset={findAndReplaceStore.listOffset}
+ onStylesChange={(styles) =>
+ setFindAndReplaceStore('styles', styles)
+ }
+ onMatchesChange={(matches) =>
+ setFindAndReplaceStore('matches', matches)
+ }
/>
<FloatingSearchHighlight
anchorElem={highlightLayerRef() ?? editorContainerRef}
+ styles={findAndReplaceStore.styles}
+ currentMatch={findAndReplaceStore.currentMatch}
/>
</Show>
@@ -1176,6 +1174,8 @@ export function MarkdownEditor(props: {
generateCallback={_generateContentCallback}
menuOpen={generateMenuSignal}
completionSignal={completionSignal[0]}
+ generatedAndWaiting={generatedAndWaiting}
+ isGenerating={isGenerating}
editor={editor}
/>
</Show>
diff --git a/apps/web/src/features/block-md/component/MarkdownNameProvider.tsx b/apps/web/src/features/block-md/component/MarkdownNameProvider.tsx
index 757c624921..7269eefcbb 100644
--- a/apps/web/src/features/block-md/component/MarkdownNameProvider.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownNameProvider.tsx
@@ -1,4 +1,3 @@
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import {
type Accessor,
createContext,
@@ -7,6 +6,7 @@ import {
type FlowComponent,
useContext,
} from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
type MarkdownNameContextValue = {
persistedName: Accessor<string | undefined>;
@@ -22,8 +22,7 @@ export const MarkdownNameProvider: FlowComponent = (props) => {
// title is a real editor value so TitleEditor can stay empty and show its
// placeholder, but surrounding UI should still display the block fallback
// such as "New Note" or "New Task".
- const persistedName = useBlockDocumentName('');
- const fallbackName = useBlockDocumentName();
+ const { persistedName, fallbackName } = useMarkdownDocument();
const [optimisticName, setOptimisticName] = createSignal<
string | undefined
>();
@@ -46,15 +45,7 @@ export const MarkdownNameProvider: FlowComponent = (props) => {
export function useMarkdownName() {
const context = useContext(MarkdownNameContext);
if (!context) {
- const persistedName = useBlockDocumentName('');
- const fallbackName = useBlockDocumentName();
- const displayName = () => persistedName() || fallbackName();
- return {
- persistedName,
- editorName: persistedName,
- displayName,
- setOptimisticName: () => {},
- };
+ throw new Error('MarkdownNameProvider is required');
}
return context;
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index a29bf01c9b..eec4118ba0 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -1,11 +1,6 @@
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 { useBlockId } from '@core/block';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
import { PopupPositioner } from '@core/component/GeneralizedPopup/PopupPositioner';
import { LocationHighlight } from '@core/component/LexicalMarkdown/component/core/Highlights';
@@ -54,7 +49,6 @@ import {
readNativePasteboardText,
setNativeEditMenuSuppressed,
} from '@core/mobile/nativeEditMenu';
-import { useCanComment, useCanEdit } from '@core/signal/permissions';
import { debouncedDependent } from '@core/util/debounce';
import { getScrollParentElement } from '@core/util/scrollParent';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
@@ -94,6 +88,7 @@ import {
useContext,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { FormatTools } from './FormatTools';
import { TouchSelectionToolbar } from './TouchSelectionToolbar';
@@ -103,7 +98,10 @@ export function MarkdownPopup(props: {
highlightLayerRef: HTMLDivElement;
lexicalMapping: NodeIdMappings;
}) {
- const blockId = useBlockId();
+ const { documentId, permissions, state } = useMarkdownDocument();
+ const { canEdit, canComment } = permissions;
+ const { comments: commentState, setCommentState } = state;
+ const blockId = documentId();
const { editor, plugins } = useContext(LexicalWrapperContext) ?? {};
if (!editor || !plugins) {
@@ -189,14 +187,9 @@ export function MarkdownPopup(props: {
setNativeEditMenuSuppressed(false);
});
- const canEdit = useCanEdit();
const inlineAiEditing = useFeatureFlag(enableInlineAiEditing);
- const canComment = useCanComment();
const currentUserId = useUserId();
- const highlightedCommentThreads = highlightedCommentThreadsSignal.get;
- const setActiveCommentThread = activeCommentThreadSignal.set;
-
const [locationCopied, setLocationCopied] = createSignal(false);
const [isConverting, setIsConverting] = createSignal(false);
const [hasCheckboxes, setHasCheckboxes] = createSignal(false);
@@ -475,8 +468,10 @@ export function MarkdownPopup(props: {
// clear the selection first.
editor.update(() => $setSelection(null));
editor.blur();
- const [threadId] = highlightedCommentThreads();
- if (threadId != null) setActiveCommentThread(threadId);
+ const [threadId] = commentState.highlightedCommentThreads;
+ if (threadId != null) {
+ setCommentState('activeCommentThread', threadId);
+ }
setPopupVisible(false);
};
@@ -731,7 +726,9 @@ export function MarkdownPopup(props: {
showTasksOption={shouldShowCheckboxToTaskButton()}
showTableOption={shouldShowTableButton()}
showEditWithAiOption={shouldShowEditWithAiButton()}
- showOpenCommentOption={highlightedCommentThreads().length > 0}
+ showOpenCommentOption={
+ commentState.highlightedCommentThreads.length > 0
+ }
locationCopied={locationCopied()}
setPopupVisible={setPopupVisible}
onConvertToTasks={handleConvertToTasks}
diff --git a/apps/web/src/features/block-md/component/MediaSelector.tsx b/apps/web/src/features/block-md/component/MediaSelector.tsx
index e93430ffa8..827adf271e 100644
--- a/apps/web/src/features/block-md/component/MediaSelector.tsx
+++ b/apps/web/src/features/block-md/component/MediaSelector.tsx
@@ -15,7 +15,7 @@ import { Dropdown } from '@ui';
import type { LexicalEditor } from 'lexical';
import type { Accessor } from 'solid-js';
import { createMemo, createSignal, For, Show } from 'solid-js';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
false && fileSelector;
false && fileDrop;
@@ -58,8 +58,8 @@ type MediaSelectorProps = {
export function MediaSelector(props: MediaSelectorProps) {
const { mediaTypes = ['image', 'video'] } = props;
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const { state } = useMarkdownDocument();
+ const editor = () => state.editor.md.editor;
const historyQuery = useHistoryQuery();
const [menuOpen, setMenuOpen] = createSignal(false);
diff --git a/apps/web/src/features/block-md/component/ModalsProvider.tsx b/apps/web/src/features/block-md/component/ModalsProvider.tsx
index 96ea77d799..08d2548b9f 100644
--- a/apps/web/src/features/block-md/component/ModalsProvider.tsx
+++ b/apps/web/src/features/block-md/component/ModalsProvider.tsx
@@ -1,28 +1,41 @@
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
-import { useBlockId, useBlockName } from '@core/block';
import { DetailsDrawer } from '@core/component/DetailsDrawer';
import { NotificationsDrawer } from '@core/component/NotificationsModal';
import { ReferencesDrawer } from '@core/component/ReferencesModal';
+import { Permissions } from '@core/component/SharePermissions';
import {
- ShareBlockModal,
ShareDialogContext,
+ ShareModal,
} from '@core/component/TopBar/ShareButton';
-import type { EntityType } from '@core/types';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import { blockNameToItemType } from '@service-storage/client';
-import { createSignal, type ParentProps } from 'solid-js';
+import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';
+import { createSignal, type ParentProps, Suspense } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import { useMarkdownName } from './MarkdownNameProvider';
export function ModalsProvider(props: ParentProps) {
- const blockId = useBlockId();
- const blockName = useBlockName();
- const name = useBlockDocumentName();
+ const {
+ documentId,
+ kind,
+ permissions: documentPermissions,
+ } = useMarkdownDocument();
+ const { displayName } = useMarkdownName();
const notificationSource = useGlobalNotificationSource();
+ const metadataQuery = useDocumentMetadataQuery(documentId);
+ const [shareOpen, setShareOpen] = createSignal(false);
- const itemType = blockNameToItemType(blockName);
- if (!itemType)
- throw new Error('Using functionality in an unknown item type.');
+ const blockAlias = (): 'md' | 'task' | 'snippet' | 'skill' => {
+ const documentKind = kind();
+ return documentKind === 'document' ? 'md' : documentKind;
+ };
+ const permissions = () => {
+ if (documentPermissions.isOwner()) return Permissions.OWNER;
+ if (documentPermissions.canEdit()) return Permissions.CAN_EDIT;
+ if (documentPermissions.canComment()) {
+ return Permissions.CAN_COMMENT;
+ }
+ return Permissions.CAN_VIEW;
+ };
- const [shareOpen, setShareOpen] = createSignal(false);
return (
<ShareDialogContext.Provider
value={{
@@ -33,12 +46,26 @@ export function ModalsProvider(props: ParentProps) {
>
{props.children}
<NotificationsDrawer
- entity={{ id: blockId, type: itemType as EntityType }}
+ entity={{ id: documentId(), type: 'document' }}
notificationSource={notificationSource}
/>
- <ReferencesDrawer documentId={blockId} documentName={name()} />
- <DetailsDrawer documentId={blockId} />
- <ShareBlockModal />
+ <ReferencesDrawer
+ documentId={documentId()}
+ documentName={displayName()}
+ />
+ <DetailsDrawer documentId={documentId()} />
+ <Suspense>
+ <ShareModal
+ isSharePermOpen={shareOpen()}
+ setIsSharePermOpen={setShareOpen}
+ id={documentId()}
+ blockAlias={blockAlias()}
+ itemType="document"
+ name={displayName() ?? ''}
+ userPermissions={permissions()}
+ owner={metadataQuery.data?.owner}
+ />
+ </Suspense>
</ShareDialogContext.Provider>
);
}
diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsx
index 07423a19b8..19ad135111 100644
--- a/apps/web/src/features/block-md/component/Notebook.tsx
+++ b/apps/web/src/features/block-md/component/Notebook.tsx
@@ -1,16 +1,6 @@
-import { AskMacroButton } from '@app/features/chat/ChatWithAgentButton';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';
import { CommentMargin } from '@block-md/comments/CommentMargin';
-import {
- commentsStore,
- commentWidthSignal,
-} from '@block-md/comments/commentStore';
-import { useGoToTempRedirect } from '@block-md/signal/location';
-import { mdStore } from '@block-md/signal/markdownBlockData';
-import { SidePanel } from '@components/app/side-panel';
-import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';
-import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';
-import { useBlockAliasedName, useBlockId } from '@core/block';
import {
editorFocusSignal,
getSaveState,
@@ -28,13 +18,6 @@ import { useIsMacroTeam } from '@core/context/team';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
-import {
- blockElementSignal,
- blockHotkeyScopeSignal,
-} from '@core/signal/blockElement';
-import { tempRedirectLocation } from '@core/signal/location';
-import { useCanEdit } from '@core/signal/permissions';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import { makePersisted } from '@solid-primitives/storage';
@@ -47,15 +30,16 @@ import {
Show,
untrack,
} from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { useHistory } from '../history/HistoryContext';
import { HistoryOverlay } from '../history/HistoryOverlay';
-import { DispatchAgentButton } from './DispatchAgentMenu';
import { DocumentAiEditBar } from './DocumentAiEditBar';
import { DocumentDiscussion } from './DocumentDiscussion';
import { InlineTaskGithubPullRequests } from './InlineTaskGithubPullRequests';
import { InlineTaskProperties } from './InlineTaskProperties';
import { InstructionsEditor } from './InstructionsEditor';
import { MarkdownEditor } from './MarkdownEditor';
+import { useMarkdownName } from './MarkdownNameProvider';
import {
MARKDOWN_OUTLINE_WIDTH,
MarkdownOutline,
@@ -93,19 +77,14 @@ enum CommentLayoutMode {
none = 'none',
}
-const BreaksPoints: Record<CommentLayoutMode, number> = {
- lg: NoteTargetWidth + 2 * CommentTargetWidth + 3 * GapTargetWidth,
- md: (3 / 4) * NoteTargetWidth + CommentTargetWidth + GapTargetWidth,
- xs: 0,
- none: 0,
-};
-
-const widthToMode = (width: number): CommentLayoutMode => {
- if (width >= BreaksPoints.lg) return CommentLayoutMode.lg;
- if (width >= BreaksPoints.md) return CommentLayoutMode.md;
- if (width >= BreaksPoints.xs) return CommentLayoutMode.xs;
- return CommentLayoutMode.none;
-};
+const CommentBreakpoints = {
+ lg: {
+ min: NoteTargetWidth + 2 * CommentTargetWidth + 3 * GapTargetWidth,
+ },
+ md: {
+ min: (3 / 4) * NoteTargetWidth + CommentTargetWidth + GapTargetWidth,
+ },
+} as const;
function useCanUseLexicalStateDebugger() {
const isMacroTeam = useIsMacroTeam();
@@ -118,20 +97,16 @@ function useCanUseLexicalStateDebugger() {
export function Notebook(props: {
loroManager: LoroManager;
documentId: string;
+ hotkeyScope: string | undefined;
+ autoFocus: boolean;
}) {
- const blockElement = blockElementSignal.get;
- const blockId = useBlockId();
- const blockAliasedName = useBlockAliasedName();
- const setStore = mdStore.set;
- const setWideEnoughForComments = commentWidthSignal.set;
- const documentName = useBlockDocumentName();
- const scopeId = blockHotkeyScopeSignal.get;
- const md = mdStore.get;
+ const { element: blockElement, permissions, state } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const { comments: commentState, params } = state;
+ const { md, setMd } = state.editor;
+ const { displayName: documentName } = useMarkdownName();
+ const scopeId = () => props.hotkeyScope;
const history = useHistory();
- const { navigatedFromJK } = useNavigatedFromJK();
- const canAutofocusSplitContent = useCanAutofocusSplitContent();
- const documentId = props.documentId;
- const canEdit = useCanEdit();
const inlineAiEditing = useFeatureFlag(enableInlineAiEditing);
let notebookRef!: HTMLDivElement;
@@ -142,25 +117,32 @@ export function Notebook(props: {
const outlinePortalMount = () =>
notebookRef.closest<HTMLElement>('.portal-scope') ?? notebookRef;
- const [layoutMode, setLayoutMode] = createSignal(CommentLayoutMode.none);
- const [width, setWidth] = createSignal(0);
+ const [width, setWidth] = createSignal<number>();
const [leftFloatX, setLeftFloatX] = createSignal(0);
+ const commentBreakpoints = createSizeBreakpoints(width, CommentBreakpoints);
const canUseLexicalStateDebugger = useCanUseLexicalStateDebugger();
const outline = useMarkdownOutline({
editor: () => md.editor,
enabled: () =>
- width() >= OutlineMinWidth && !history.isOpen() && !isMobile(),
+ (width() ?? 0) >= OutlineMinWidth && !history.isOpen() && !isMobile(),
});
- const comments = commentsStore.get;
const hasComment = createMemo(() => {
if (!ENABLE_MARKDOWN_COMMENTS) return false;
- return Object.keys(comments).length > 0;
+ return Object.keys(commentState.comments).length > 0;
});
// 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 layoutMode = (): CommentLayoutMode => {
+ if (!showComments() || width() === undefined) {
+ return CommentLayoutMode.none;
+ }
+ if (commentBreakpoints.lg()) return CommentLayoutMode.lg;
+ if (commentBreakpoints.md()) return CommentLayoutMode.md;
+ return CommentLayoutMode.xs;
+ };
const currentEditorState = () => {
const editor = md.editor;
@@ -169,20 +151,18 @@ export function Notebook(props: {
// Set the refs on the block store.
onMount(() => {
- setStore({
+ setMd({
notebook: notebookRef,
commentMargin: commentMarginRef,
contentRef: contentRef,
});
onCleanup(() => {
- setStore({ notebook: undefined, commentMargin: undefined });
+ setMd({ notebook: undefined, commentMargin: undefined });
});
const observeCallback = () => {
const { width, left } = notebookRef.getBoundingClientRect();
setWidth(width);
- const mode = showComments() ? widthToMode(width) : CommentLayoutMode.none;
- setLayoutMode(mode);
const leftFloat =
contentRef.getBoundingClientRect().right - left + GapTargetWidth;
setLeftFloatX(leftFloat);
@@ -192,43 +172,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 recentState = tempRedirectLocation();
- if (!recentState) return;
-
- setTimeout(() => {
- goToTempRedirect(documentId, recentState);
- }, 0);
- });
-
- createEffect(() => {
- if (!showComments()) {
- setLayoutMode(CommentLayoutMode.none);
- } else {
- setLayoutMode(widthToMode(untrack(width)));
- }
- });
-
createEffect(() => {
- if (showComments()) {
- setWideEnoughForComments(width() >= BreaksPoints.md);
- } else {
- setWideEnoughForComments(false);
- }
- });
-
- createEffect(() => {
- if (!scopeId()) return;
+ const currentScopeId = scopeId();
+ if (!currentScopeId) return;
untrack(() =>
registerHotkey({
hotkey: 'enter',
- scopeId: scopeId(),
+ scopeId: currentScopeId,
hotkeyToken: TOKENS.block.focus,
description: 'Focus Title or Markdown Editor',
keyDownHandler: () => {
@@ -260,12 +210,19 @@ export function Notebook(props: {
onCleanup(cleanup);
});
createEffect(() => {
- if (!scopeId()) return;
+ const currentScopeId = scopeId();
+ if (!currentScopeId) return;
const group = untrack(() =>
- registerMarkdownCommands(scopeId(), () => md.editor, editorHasFocus, {
- canUseStateDebugger: canUseLexicalStateDebugger,
- toggleStateDebugger: () => setShowLexicalStateDebugger((prev) => !prev),
- })
+ registerMarkdownCommands(
+ currentScopeId,
+ () => md.editor,
+ editorHasFocus,
+ {
+ canUseStateDebugger: canUseLexicalStateDebugger,
+ toggleStateDebugger: () =>
+ setShowLexicalStateDebugger((prev) => !prev),
+ }
+ )
);
onCleanup(() => group.dispose());
});
@@ -279,7 +236,7 @@ export function Notebook(props: {
let hasRun = false;
createEffect(() => {
if (hasRun) return;
- if (!canAutofocusSplitContent) return;
+ if (!props.autoFocus) return;
if (!blockElement()) return;
blockElement()?.focus();
hasRun = true;
@@ -365,36 +322,14 @@ export function Notebook(props: {
ref={contentRef}
classList={{ relative: true }}
>
- <SidePanel.Section
- id="document-ai-actions"
- title="Actions"
- defaultOpen
- order={0}
- >
- <div class="m-px flex items-center justify-start gap-2">
- <AskMacroButton
- entity={{
- type: 'document',
- id: blockId,
- name: documentName(),
- fileType: 'md',
- }}
- />
- <Show when={blockAliasedName === 'task' && !isMobile()}>
- <DispatchAgentButton showPrimaryLabel />
- </Show>
- </div>
- </SidePanel.Section>
- <TitleEditor
- autoFocusOnMount={canAutofocusSplitContent && !navigatedFromJK()}
- />
+ <TitleEditor autoFocusOnMount={props.autoFocus} />
<div class="spacer h-3" />
<div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden">
<InlineTaskProperties />
<InlineTaskGithubPullRequests />
<TaskDuplicateMatchPill />
</div>
- <ParamsProvider>
+ <ParamsProvider state={params}>
{/* Relative wrapper so the history overlay covers only the body region,
leaving the title + properties above it untouched and aligned. */}
<div class="relative">
@@ -444,15 +379,19 @@ export function Notebook(props: {
hidden: !showComments(),
}}
>
- <CommentMargin />
+ <CommentMargin wideEnough={showComments() && commentBreakpoints.md()} />
</div>
</div>
);
}
-export function InstructionsNotebook(props: { loroManager: LoroManager }) {
- const setStore = mdStore.set;
- const scopeId = blockHotkeyScopeSignal.get;
+export function InstructionsNotebook(props: {
+ loroManager: LoroManager;
+ hotkeyScope: string | undefined;
+}) {
+ const { state } = useMarkdownDocument();
+ const setMd = state.editor.setMd;
+ const scopeId = () => props.hotkeyScope;
const canUseLexicalStateDebugger = useCanUseLexicalStateDebugger();
let notebookRef!: HTMLDivElement;
@@ -460,13 +399,13 @@ export function InstructionsNotebook(props: { loroManager: LoroManager }) {
// Set the refs on the block store.
onMount(() => {
- setStore({
+ setMd({
notebook: notebookRef,
commentMargin: undefined,
contentRef: contentRef,
});
onCleanup(() => {
- setStore({
+ setMd({
notebook: undefined,
commentMargin: undefined,
});
@@ -474,9 +413,10 @@ export function InstructionsNotebook(props: { loroManager: LoroManager }) {
});
createEffect(() => {
- if (!scopeId()) return;
+ const currentScopeId = scopeId();
+ if (!currentScopeId) return;
const group = untrack(() =>
- registerLexicalStateDebuggerCommand(scopeId(), {
+ registerLexicalStateDebuggerCommand(currentScopeId, {
canUseStateDebugger: canUseLexicalStateDebugger,
toggleStateDebugger: () => setShowLexicalStateDebugger((prev) => !prev),
})
diff --git a/apps/web/src/features/block-md/component/TableInsert.tsx b/apps/web/src/features/block-md/component/TableInsert.tsx
index 0eb754c336..56ee269595 100644
--- a/apps/web/src/features/block-md/component/TableInsert.tsx
+++ b/apps/web/src/features/block-md/component/TableInsert.tsx
@@ -3,7 +3,7 @@ import { createCallback } from '@solid-primitives/rootless';
import { Button } from '@ui';
import { createSignal, Index, type ParentProps } from 'solid-js';
import { Portal } from 'solid-js/web';
-import { mdStore } from '../signal/markdownBlockData';
+import { useMarkdownDocument } from '../context/markdown-document-context';
const MAX_NUMBER_OF_ROWS = 50;
const MAX_NUMBER_OF_COLS = 20;
@@ -109,8 +109,7 @@ export function TableInsert(
onMenuClose?: () => void;
}>
) {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const { state } = useMarkdownDocument();
const [rows, setRows] = createSignal<number>();
const [cols, setCols] = createSignal<number>();
@@ -120,7 +119,7 @@ export function TableInsert(
const clampedCols = Math.min(cols, MAX_NUMBER_OF_COLS);
const clampedRows = Math.min(rows, MAX_NUMBER_OF_ROWS);
- editor()?.dispatchCommand(INSERT_TABLE_COMMAND, {
+ state.editor.md.editor?.dispatchCommand(INSERT_TABLE_COMMAND, {
columns: `${clampedCols}`,
rows: `${clampedRows}`,
includeHeaders: false,
diff --git a/apps/web/src/features/block-md/component/TaskDuplicateMatches.tsx b/apps/web/src/features/block-md/component/TaskDuplicateMatches.tsx
index 2eeec4458b..366193e79e 100644
--- a/apps/web/src/features/block-md/component/TaskDuplicateMatches.tsx
+++ b/apps/web/src/features/block-md/component/TaskDuplicateMatches.tsx
@@ -1,6 +1,5 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { SidePanel } from '@components/app/side-panel';
-import { useBlockId } from '@core/block';
import { DocumentMention } from '@core/component/LexicalMarkdown/component/decorator/DocumentMention';
import { toast } from '@core/component/Toast/Toast';
import { enableTaskDuplicates } from '@core/constant/featureFlags';
@@ -13,6 +12,7 @@ import {
import type { TaskDuplicate } from '@service-storage/client';
import { Button, cn, Dropdown } from '@ui';
import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';
+import { useMarkdownDocument } from '../context/markdown-document-context';
export function TaskDuplicateMatchPill() {
const flag = useFeatureFlag(enableTaskDuplicates);
@@ -77,7 +77,8 @@ export function TaskDuplicateMatchesSidePanelSection() {
type TaskDuplicateMatchesState = ReturnType<typeof useTaskDuplicateMatches>;
function useTaskDuplicateMatches() {
- const blockId = useBlockId();
+ const { documentId } = useMarkdownDocument();
+ const blockId = documentId();
const matchesQuery = useTaskDuplicatesQuery(() => blockId);
const dismissMutation = useDismissTaskDuplicatesMutation(() => blockId);
diff --git a/apps/web/src/features/block-md/component/TitleEditor.tsx b/apps/web/src/features/block-md/component/TitleEditor.tsx
index 0bee432dbb..cc5d5b7249 100644
--- a/apps/web/src/features/block-md/component/TitleEditor.tsx
+++ b/apps/web/src/features/block-md/component/TitleEditor.tsx
@@ -1,8 +1,3 @@
-import {
- createBlockSignal,
- useBlockAliasedName,
- useBlockId,
-} from '@core/block';
import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';
import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';
import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
@@ -21,7 +16,7 @@ import {
trimWhitespace,
} from '@core/component/LexicalMarkdown/utils';
import { blockNameToDefaultFile } from '@core/constant/allBlocks';
-import { useCanEdit } from '@core/signal/permissions';
+import { createRenameDssEntityMutation } from '@entity';
import { mergeRegister } from '@lexical/utils';
import { useDocTags } from '@property/tags';
import { EntityType } from '@service-properties/generated/schemas/entityType';
@@ -50,8 +45,7 @@ import {
Show,
untrack,
} from 'solid-js';
-import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
-import { useRenameMarkdownDocument } from '../signal/save';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { useMarkdownName } from './MarkdownNameProvider';
/**
@@ -136,15 +130,17 @@ function titleNavigationPlugin(
);
}
-export const TitlePlaceholderSignal = createBlockSignal<string | undefined>();
-
export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {
- const mdData = mdStore.get;
- const setMdData = mdStore.set;
- const blockData = blockDataSignal.get;
-
- const canEdit = useCanEdit();
- const renameMarkdownDocument = useRenameMarkdownDocument();
+ const {
+ documentId,
+ kind,
+ documentSource,
+ permissions,
+ state: documentState,
+ } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const { md: mdData, setMd: setMdData } = documentState.editor;
+ const renameDocumentMutation = createRenameDssEntityMutation();
const {
persistedName: persistedDocumentName,
editorName: mdDocumentName,
@@ -152,16 +148,17 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {
} = useMarkdownName();
const [showFallback, setShowFallback] = createSignal(true);
- const [titlePlaceholder, _setTitlePlaceholder] = TitlePlaceholderSignal;
+ const [titlePlaceholder] = createSignal<string>();
const [titleFocused, setTitleFocused] = createSignal(false);
- const blockId = useBlockId();
- const blockName = useBlockAliasedName();
+ const blockId = documentId();
+ const documentKind = kind();
+ const entityBlockName = documentKind === 'document' ? 'md' : documentKind;
const documentTags = useDocTags(
blockId,
- blockName === 'task' ? EntityType.TASK : EntityType.DOCUMENT
+ documentKind === 'task' ? EntityType.TASK : EntityType.DOCUMENT
);
- const titlePlaceholderFallback = blockNameToDefaultFile(blockName);
+ const titlePlaceholderFallback = blockNameToDefaultFile(entityBlockName);
let pendingRename:
| {
@@ -174,7 +171,14 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {
const next = pendingRename;
pendingRename = undefined;
if (!next || !canEdit()) return;
- void renameMarkdownDocument(next.newName, next.oldName);
+ renameDocumentMutation.mutate({
+ entity: {
+ type: 'document',
+ id: blockId,
+ name: next.oldName,
+ },
+ newName: next.newName,
+ });
};
const scheduleRename = (newName: string, oldName: string) => {
@@ -273,7 +277,7 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {
editor.setEditable(canEdit() ?? false);
});
- const dataReady = createMemo(() => blockData() !== undefined);
+ const dataReady = () => documentSource().type !== 'loading';
const hasLocalTitleEdit = createMemo(() => {
if (!titleFocused()) return false;
diff --git a/apps/web/src/features/block-md/component/TopBar.tsx b/apps/web/src/features/block-md/component/TopBar.tsx
index cb996a36d5..47172f9dbc 100644
--- a/apps/web/src/features/block-md/component/TopBar.tsx
+++ b/apps/web/src/features/block-md/component/TopBar.tsx
@@ -1,16 +1,7 @@
import {
- ChatWithAgentButton,
- ChatWithAgentIcon,
- openChatWithAgent,
-} from '@app/features/chat/ChatWithAgentButton';
-import { useDownloadDocumentAsMarkdownText } from '@block-md/signal/save';
-import {
- type BlockTool,
ResponsiveBlockToolbar,
ResponsivePermissionsBadge,
} from '@components/app/ResponsiveBlockToolbar';
-import { useSidePanel } from '@components/app/side-panel';
-import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';
import {
SplitHeaderLeft,
SplitHeaderRight,
@@ -19,188 +10,25 @@ import {
BlockItemSplitLabel,
StaticSplitLabel,
} from '@components/app/split-layout/components/SplitLabel';
-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import { useBlockAliasedName, useBlockId, useBlockName } from '@core/block';
import { BlockLiveIndicators } from '@core/component/LiveIndicators';
-import {
- getShareDrawerRecipientInput,
- ShareTrigger,
- useShareDialogContext,
-} from '@core/component/TopBar/ShareButton';
-import { registerHotkey } from '@core/hotkey/hotkeys';
-import { TOKENS } from '@core/hotkey/tokens';
-import { isMobile } from '@core/mobile/isMobile';
-import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
-import { copyBranchNameToClipboard } from '@core/util/branchName';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import Download from '@phosphor/download.svg';
-import GitBranch from '@phosphor/git-branch.svg';
-import IconLink from '@phosphor/link.svg';
-import TerminalWindowIcon from '@phosphor/terminal-window.svg';
import { blockNameToItemType } from '@service-storage/client';
-import { type Accessor, createEffect, on, onCleanup, Show } from 'solid-js';
-import { useHistory } from '../history/HistoryContext';
-import {
- DispatchAgentButton,
- useDispatchAgentSplitFileActions,
-} from './DispatchAgentMenu';
+import { type Accessor, Show } from 'solid-js';
+import { useMarkdownDocumentTools } from './useMarkdownDocumentTools';
export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
const blockName = useBlockName();
const blockId = useBlockId();
- const scopeId = blockHotkeyScopeSignal.get;
const fallbackName = useBlockDocumentName();
const name = () => props.name?.() ?? fallbackName();
const itemType = blockNameToItemType(blockName);
if (!itemType)
throw new Error('Using functionality in an unknown item type.');
- const downloadAsMarkdownText = useDownloadDocumentAsMarkdownText();
-
- const shareCtx = useShareDialogContext();
const blockAliasedName = useBlockAliasedName();
- const isTask = blockAliasedName === 'task';
const isSkill = blockAliasedName === 'skill';
- const dispatchAgentActions = useDispatchAgentSplitFileActions();
-
- const copyBranchName = () => copyBranchNameToClipboard(blockId);
-
- if (isTask) {
- let cleanupKbShortcut = () => {};
-
- createEffect(
- on(scopeId, (id) => {
- cleanupKbShortcut();
- registerHotkey({
- hotkey: 'shift+cmd+b',
- scopeId: id,
- hotkeyToken: TOKENS.entity.action.copyBranchName,
- description: 'Copy branch name',
- keyDownHandler: () => {
- copyBranchName();
- return true;
- },
- runWithInputFocused: true,
- });
- })
- );
- }
-
- const ops: FileOperation[] = [
- { op: 'copy' },
- { op: 'rename' },
- { op: 'moveToProject' },
- ...(isTask
- ? ([
- {
- group: 'sharing' as const,
- label: 'Copy Branch Name',
- icon: GitBranch,
- action: copyBranchName,
- },
- ] satisfies FileOperation[])
- : []),
- {
- group: 'file',
- label: 'Download',
- icon: Download,
- action: downloadAsMarkdownText,
- },
- { op: 'delete' },
- ];
-
- const sidePanel = useSidePanel();
- const splitPanel = useSplitPanel();
- const _history = useHistory();
-
- // Register at the split scope so `]` works from anywhere in the split
- // (header, toolbar, drawer), but tie disposal to this TopBar so the
- // registration disappears with the block.
- if (splitPanel?.splitHotkeyScope) {
- const reg = registerHotkey({
- hotkey: ']',
- scopeId: splitPanel.splitHotkeyScope,
- hotkeyToken: TOKENS.block.toggleSidePanel,
- description: 'Toggle Side Panel',
- keyDownHandler: () => {
- if (!sidePanel) return false;
- if (!sidePanel.hasSections()) return false;
- sidePanel.toggle();
- return true;
- },
- });
- onCleanup(() => reg.dispose());
- }
-
- const tools: BlockTool[] = [
- // {
- // label: 'Copy Branch Name',
- // icon: GitBranch,
- // action: copyBranchName,
- // condition: () => isTask,
- // hotkeyToken: TOKENS.entity.action.copyBranchName,
- // },
- {
- label: 'Dispatch to Agent',
- icon: TerminalWindowIcon,
- action: () => {},
- condition: () => isTask && !isMobile(),
- buttonComponent: () => <DispatchAgentButton />,
- },
- {
- label: 'Chat',
- icon: ChatWithAgentIcon,
- action: () =>
- openChatWithAgent({
- type: 'document',
- id: blockId,
- name: name(),
- fileType: 'md',
- }),
- buttonComponent: () => (
- <ChatWithAgentButton
- entity={{
- type: 'document',
- id: blockId,
- name: name(),
- fileType: 'md',
- }}
- />
- ),
- },
- {
- group: 'sharing',
- label: 'Share',
- icon: IconLink,
- action: () => shareCtx.open(),
- buttonComponent: () => <ShareTrigger />,
- focusTarget: getShareDrawerRecipientInput,
- },
- ];
-
- const menuTools: BlockTool[] = [
- {
- label: 'Ask Macro',
- icon: ChatWithAgentIcon,
- action: () =>
- openChatWithAgent({
- type: 'document',
- id: blockId,
- name: name(),
- fileType: 'md',
- }),
- },
- ...(isTask
- ? ([
- {
- label: 'Code Actions',
- icon: TerminalWindowIcon,
- action: () => {},
- children: dispatchAgentActions,
- },
- ] satisfies BlockTool[])
- : []),
- ];
+ const { fileOperations, menuTools, tools } = useMarkdownDocumentTools();
return (
<>
@@ -225,7 +53,7 @@ export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
<ResponsiveBlockToolbar
tools={tools}
menuTools={menuTools}
- ops={ops}
+ ops={fileOperations}
id={blockId}
itemType={itemType}
name={name()}
diff --git a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index 8dc9763039..89bcb9bff9 100644
--- a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -1,4 +1,5 @@
import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
+import { AskMacroButton } from '@app/features/chat/ChatWithAgentButton';
import {
EntityPropertiesSection,
EntityTagsSection,
@@ -10,7 +11,6 @@ import {
useSidePanel,
} from '@components/app/side-panel';
import { useSplitLayout } from '@components/app/split-layout/layout';
-import { useBlockAliasedName, useBlockId, useBlockName } from '@core/block';
import { EntityIcon } from '@core/component/EntityIcon';
import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
import { ProgressMeter } from '@core/component/LexicalMarkdown/component/status/Progress';
@@ -29,7 +29,8 @@ import {
USE_MACRO_PR_SUMMARY_BLOCK,
} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
-import type { Entity, EntityType } from '@core/types';
+import { isMobile } from '@core/mobile/isMobile';
+import type { Entity } from '@core/types';
import { getDisplayName, tryMacroId } from '@core/user';
import { type DateValue, formatDate } from '@core/util/date';
import { openExternalUrl } from '@core/util/url';
@@ -52,7 +53,6 @@ import {
useSetDocumentTeamShareMutation,
} from '@queries/storage/team-share';
import type { EntityType as PropertiesEntityType } from '@service-properties/generated/schemas/entityType';
-import { blockNameToItemType } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
import { cn, InlineCheckbox } from '@ui';
import {
@@ -63,49 +63,65 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import { useMarkdownDocument } from '../../context/markdown-document-context';
import { useHistory } from '../../history/HistoryContext';
import { HistoryScrubber } from '../../history/HistoryScrubber';
import { HistorySessionList } from '../../history/HistorySessionList';
-import { mdStore } from '../../signal/markdownBlockData';
+import { DispatchAgentButton } from '../DispatchAgentMenu';
+import { useMarkdownName } from '../MarkdownNameProvider';
import { TaskDuplicateMatchesSidePanelSection } from '../TaskDuplicateMatches';
-interface MarkdownSidePanelSectionsProps {
- canEdit: boolean;
- documentName: string;
-}
-
/**
* Renders all three SidePanel sections for the markdown block:
* - Properties (always shown)
* - Details (always shown)
* - Stats (hidden for tasks)
*/
-export function MarkdownSidePanelSections(
- props: MarkdownSidePanelSectionsProps
-) {
- const blockName = useBlockAliasedName();
- const rawBlockName = useBlockName();
- const blockId = useBlockId();
- const isTask = () => blockName === 'task';
- const isSnippet = () => blockName === 'snippet';
-
- const itemType = blockNameToItemType(rawBlockName);
- const entity = (): Entity => ({ id: blockId, type: itemType as EntityType });
+export function MarkdownSidePanelSections() {
+ const { documentId, kind, permissions } = useMarkdownDocument();
+ const canEdit = permissions.canEdit;
+ const { displayName } = useMarkdownName();
+ const isTask = () => kind() === 'task';
+ const isSnippet = () => kind() === 'snippet';
+ const entity = (): Entity => ({
+ id: documentId(),
+ type: 'document',
+ });
const propertiesEntityType = (): PropertiesEntityType =>
- blockName === 'task' ? 'TASK' : 'DOCUMENT';
+ isTask() ? 'TASK' : 'DOCUMENT';
return (
<>
+ <SidePanel.Section
+ id="document-ai-actions"
+ title="Actions"
+ defaultOpen
+ order={0}
+ >
+ <div class="m-px flex items-center justify-start gap-2">
+ <AskMacroButton
+ entity={{
+ type: 'document',
+ id: documentId(),
+ name: displayName() ?? '',
+ fileType: 'md',
+ }}
+ />
+ <Show when={isTask() && !isMobile()}>
+ <DispatchAgentButton showPrimaryLabel />
+ </Show>
+ </div>
+ </SidePanel.Section>
<SidePanel.Section id="details" title="Details" defaultOpen order={10}>
- <DetailsSectionContent />
+ <DetailsSectionContent documentId={documentId()} />
</SidePanel.Section>
<Show when={isSnippet()}>
- <SnippetSharingOwnerSectionConditional documentId={blockId} />
+ <SnippetSharingOwnerSectionConditional documentId={documentId()} />
</Show>
<EntityTagsSection
- entityId={blockId}
+ entityId={documentId()}
entityType={propertiesEntityType()}
- canEdit={props.canEdit}
+ canEdit={canEdit()}
order={20}
/>
<SidePanel.Section
@@ -115,8 +131,10 @@ export function MarkdownSidePanelSections(
order={25}
>
<PropertiesSectionContent
- canEdit={props.canEdit}
- documentName={props.documentName}
+ documentId={documentId()}
+ isTask={isTask()}
+ canEdit={canEdit()}
+ documentName={displayName() ?? ''}
/>
</SidePanel.Section>
<Show when={!isTask()}>
@@ -130,13 +148,13 @@ export function MarkdownSidePanelSections(
</SidePanel.Section>
</Show>
<EntityActivitySectionConditional
- entityId={blockId}
+ entityId={documentId()}
entityType={propertiesEntityType()}
order={40}
/>
- <GithubSectionConditional documentId={blockId} isTask={isTask()} />
+ <GithubSectionConditional documentId={documentId()} isTask={isTask()} />
<NotificationsSectionConditional entity={entity()} />
- <ReferencesSectionConditional documentId={blockId} />
+ <ReferencesSectionConditional documentId={documentId()} />
<Show when={isTask()}>
<TaskDuplicateMatchesSidePanelSection />
</Show>
@@ -327,9 +345,8 @@ function SnippetSharingSectionContent(props: { documentId: string }) {
// Details Section
// ─────────────────────────────────────────────────────────────────────────────
-function DetailsSectionContent() {
- const blockId = useBlockId();
- const query = useDocumentMetadataQuery(() => blockId);
+function DetailsSectionContent(props: { documentId: string }) {
+ const query = useDocumentMetadataQuery(() => props.documentId);
const metadata = createMemo(() => query.data);
return (
@@ -432,15 +449,15 @@ function DateValueDisplay(props: { value: DateValue }) {
// ─────────────────────────────────────────────────────────────────────────────
function PropertiesSectionContent(props: {
+ documentId: string;
+ isTask: boolean;
canEdit: boolean;
documentName: string;
}) {
- const blockId = useBlockId();
- const mdData = mdStore.get;
+ const { state } = useMarkdownDocument();
+ const mdData = state.editor.md;
- const blockName = useBlockAliasedName();
- const entityType: PropertiesEntityType =
- blockName === 'task' ? 'TASK' : 'DOCUMENT';
+ const entityType: PropertiesEntityType = props.isTask ? 'TASK' : 'DOCUMENT';
const [pinnedPropertyIds, setPinnedPropertyIds] = createSignal<string[]>([]);
@@ -479,11 +496,13 @@ function PropertiesSectionContent(props: {
return (
<EntityPropertiesSection
- entityId={blockId}
+ entityId={props.documentId}
entityType={entityType}
canEdit={props.canEdit}
documentName={props.documentName}
- defaultPinnedPropertyIds={() => getDefaultPinnedProperties(blockName)}
+ defaultPinnedPropertyIds={() =>
+ props.isTask ? getDefaultPinnedProperties('task') : []
+ }
pinnedPropertyIds={pinnedPropertyIds}
pinnedPropertyDefinitionOrder={PINNED_ORDER}
onPropertyPinned={handlePropertyPinned}
@@ -507,7 +526,8 @@ const PINNED_ORDER: readonly string[] = [
// ─────────────────────────────────────────────────────────────────────────────
function StatsSectionContent() {
- const md = mdStore.get;
+ const { state } = useMarkdownDocument();
+ const md = state.editor.md;
return (
<Show
diff --git a/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts b/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts
new file mode 100644
index 0000000000..d3a83039ca
--- /dev/null
+++ b/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts
@@ -0,0 +1,50 @@
+import {
+ editorStateAsMarkdown,
+ getSaveState,
+} from '@core/component/LexicalMarkdown/utils';
+import { createCallback } from '@solid-primitives/rootless';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+
+export function useDownloadDocumentAsMarkdownText() {
+ const { persistedName, fallbackName, state } = useMarkdownDocument();
+ const fileName = () => persistedName() || fallbackName();
+
+ return createCallback(() => {
+ const editor = state.editor.md.editor;
+ if (editor === undefined) return;
+
+ const fileNameWithExtension = `${fileName()}.md`;
+ const markdownString = editorStateAsMarkdown(editor, 'external');
+
+ const blob = new Blob([markdownString], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileNameWithExtension;
+ link.click();
+ URL.revokeObjectURL(url);
+ });
+}
+
+export function useDownloadDocumentAsJson() {
+ const { persistedName, fallbackName, state } = useMarkdownDocument();
+ const fileName = () => persistedName() || fallbackName();
+
+ return createCallback(() => {
+ const editor = state.editor.md.editor;
+ if (!editor) {
+ return;
+ }
+ const fileNameWithExtension = `${fileName()}.json`;
+ const json = getSaveState(editor.getEditorState());
+ const blob = new Blob([JSON.stringify(json, null, 2)], {
+ type: 'application/json',
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileNameWithExtension;
+ link.click();
+ URL.revokeObjectURL(url);
+ });
+}
diff --git a/apps/web/src/features/block-md/component/useMarkdownDocumentTools.tsx b/apps/web/src/features/block-md/component/useMarkdownDocumentTools.tsx
new file mode 100644
index 0000000000..fb2c3e0940
--- /dev/null
+++ b/apps/web/src/features/block-md/component/useMarkdownDocumentTools.tsx
@@ -0,0 +1,109 @@
+import {
+ ChatWithAgentButton,
+ ChatWithAgentIcon,
+ openChatWithAgent,
+} from '@app/features/chat/ChatWithAgentButton';
+import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
+import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';
+import {
+ getShareDrawerRecipientInput,
+ ShareTrigger,
+ useShareDialogContext,
+} from '@core/component/TopBar/ShareButton';
+import { isMobile } from '@core/mobile/isMobile';
+import { copyBranchNameToClipboard } from '@core/util/branchName';
+import Download from '@phosphor/download.svg';
+import GitBranch from '@phosphor/git-branch.svg';
+import IconLink from '@phosphor/link.svg';
+import TerminalWindowIcon from '@phosphor/terminal-window.svg';
+import { useMarkdownDocument } from '../context/markdown-document-context';
+import {
+ DispatchAgentButton,
+ useDispatchAgentSplitFileActions,
+} from './DispatchAgentMenu';
+import { useMarkdownName } from './MarkdownNameProvider';
+import { useDownloadDocumentAsMarkdownText } from './useMarkdownDocumentDownload';
+
+export function useMarkdownDocumentTools() {
+ const { documentId, kind } = useMarkdownDocument();
+ const { displayName } = useMarkdownName();
+ const downloadAsMarkdownText = useDownloadDocumentAsMarkdownText();
+ const shareDialog = useShareDialogContext();
+ const dispatchAgentActions = useDispatchAgentSplitFileActions();
+ const isTask = kind() === 'task';
+
+ const chatEntity = () => ({
+ type: 'document' as const,
+ id: documentId(),
+ name: displayName() ?? '',
+ fileType: 'md' as const,
+ });
+ const copyBranchName = () => copyBranchNameToClipboard(documentId());
+
+ const fileOperations: FileOperation[] = [
+ { op: 'copy' },
+ { op: 'rename' },
+ { op: 'moveToProject' },
+ ...(isTask
+ ? ([
+ {
+ group: 'sharing' as const,
+ label: 'Copy Branch Name',
+ icon: GitBranch,
+ action: copyBranchName,
+ },
+ ] satisfies FileOperation[])
+ : []),
+ {
+ group: 'file',
+ label: 'Download',
+ icon: Download,
+ action: downloadAsMarkdownText,
+ },
+ { op: 'delete' },
+ ];
+
+ const tools: BlockTool[] = [
+ {
+ label: 'Dispatch to Agent',
+ icon: TerminalWindowIcon,
+ action: () => {},
+ condition: () => isTask && !isMobile(),
+ buttonComponent: () => <DispatchAgentButton />,
+ },
+ {
+ label: 'Chat',
+ icon: ChatWithAgentIcon,
+ action: () => openChatWithAgent(chatEntity()),
+ buttonComponent: () => <ChatWithAgentButton entity={chatEntity()} />,
+ },
+ {
+ group: 'sharing',
+ label: 'Share',
+ icon: IconLink,
+ action: () => shareDialog.open(),
+ buttonComponent: () => <ShareTrigger />,
+ focusTarget: getShareDrawerRecipientInput,
+ },
+ ];
+
+ const menuTools: BlockTool[] = [
+ {
+ label: 'Ask Macro',
+ icon: ChatWithAgentIcon,
+ action: () => openChatWithAgent(chatEntity()),
+ },
+ ...(isTask
+ ? ([
+ {
+ label: 'Code Actions',
+ icon: TerminalWindowIcon,
+ action: () => {},
+ children: dispatchAgentActions,
+ },
+ ] satisfies BlockTool[])
+ : []),
+ ];
+
+ return { fileOperations, menuTools, tools };
+}
diff --git a/apps/web/src/features/block-md/component/useTaskBranchNameHotkey.ts b/apps/web/src/features/block-md/component/useTaskBranchNameHotkey.ts
new file mode 100644
index 0000000000..b5d80bf65d
--- /dev/null
+++ b/apps/web/src/features/block-md/component/useTaskBranchNameHotkey.ts
@@ -0,0 +1,31 @@
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import { copyBranchNameToClipboard } from '@core/util/branchName';
+import type { Accessor } from 'solid-js';
+import { createEffect, on, onCleanup } from 'solid-js';
+import type { MarkdownDocumentKind } from '../types';
+
+export function useTaskBranchNameHotkey(options: {
+ documentId: Accessor<string>;
+ kind: Accessor<MarkdownDocumentKind>;
+ scopeId: Accessor<string>;
+}) {
+ createEffect(
+ on([options.scopeId, options.kind], ([scopeId, kind]) => {
+ if (kind !== 'task') return;
+
+ const registration = registerHotkey({
+ hotkey: 'shift+cmd+b',
+ scopeId,
+ hotkeyToken: TOKENS.entity.action.copyBranchName,
+ description: 'Copy branch name',
+ keyDownHandler: () => {
+ copyBranchNameToClipboard(options.documentId());
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+ onCleanup(() => registration.dispose());
+ })
+ );
+}
diff --git a/apps/web/src/features/block-md/context/markdown-document-context.tsx b/apps/web/src/features/block-md/context/markdown-document-context.tsx
new file mode 100644
index 0000000000..f313a116e0
--- /dev/null
+++ b/apps/web/src/features/block-md/context/markdown-document-context.tsx
@@ -0,0 +1,37 @@
+import type { Accessor, ParentComponent } from 'solid-js';
+import { createContext, useContext } from 'solid-js';
+import type { MarkdownDocumentKind, MarkdownDocumentSource } from '../types';
+import type { MarkdownDocumentState } from './markdown-document-state';
+
+export type MarkdownDocumentContextValue = {
+ documentId: Accessor<string>;
+ kind: Accessor<MarkdownDocumentKind>;
+ documentSource: Accessor<MarkdownDocumentSource>;
+ permissions: {
+ canComment: Accessor<boolean>;
+ canEdit: Accessor<boolean>;
+ isOwner: Accessor<boolean>;
+ };
+ persistedName: Accessor<string | undefined>;
+ fallbackName: Accessor<string | undefined>;
+ state: MarkdownDocumentState;
+ element: Accessor<HTMLElement | undefined>;
+};
+
+const MarkdownDocumentContext = createContext<MarkdownDocumentContextValue>();
+
+export const MarkdownDocumentProvider: ParentComponent<{
+ context: MarkdownDocumentContextValue;
+}> = (props) => (
+ <MarkdownDocumentContext.Provider value={props.context}>
+ {props.children}
+ </MarkdownDocumentContext.Provider>
+);
+
+export function useMarkdownDocument(): MarkdownDocumentContextValue {
+ const context = useContext(MarkdownDocumentContext);
+ if (!context) {
+ throw new Error('MarkdownDocumentProvider is required');
+ }
+ return context;
+}
diff --git a/apps/web/src/features/block-md/context/markdown-document-state.tsx b/apps/web/src/features/block-md/context/markdown-document-state.tsx
new file mode 100644
index 0000000000..28f29d05cc
--- /dev/null
+++ b/apps/web/src/features/block-md/context/markdown-document-state.tsx
@@ -0,0 +1,141 @@
+import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';
+import type {
+ Completion,
+ GenerateMenuOpen,
+ NodekeyOffset,
+ PluginManager,
+ ProgressStats,
+ SelectionData,
+ WordcountStats,
+} from '@core/component/LexicalMarkdown/plugins';
+import type { FloatingStyle } from '@core/component/LexicalMarkdown/plugins/find-and-replace';
+import { createParamsState } from '@core/component/ParamsProvider';
+import type { NodeIdMappings } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
+import type { LexicalEditor } from 'lexical';
+import { createSignal } from 'solid-js';
+import { createStore, type Store } from 'solid-js/store';
+import type {
+ CommentStore,
+ MarkStore,
+ ThreadStore,
+} from '../comments/commentType';
+import type { Diff } from '../types';
+
+type MdData = {
+ editor?: LexicalEditor;
+ /** Durable nodeId <-> nodeKey mapping for the main editor (from the nodeId plugin). */
+ mapping?: NodeIdMappings;
+ titleEditor?: LexicalEditor;
+ plugins?: PluginManager;
+ selection?: Store<SelectionData>;
+ wordcountStats?: Store<WordcountStats>;
+ progressStats?: Store<ProgressStats>;
+ notebook?: HTMLElement;
+ scrollContainer?: HTMLElement;
+ commentMargin?: HTMLElement;
+ contentRef?: HTMLElement;
+ locationReady?: boolean;
+};
+
+type FindAndReplaceState = {
+ searchIsOpen: boolean;
+ isSearching: boolean;
+ searchInputText: string;
+ replaceInputOpen: boolean;
+ replaceInputText: string;
+ listOffset: NodekeyOffset[];
+ styles: { style: FloatingStyle; idx: number | undefined }[];
+ matches: number;
+ currentMatch: number;
+ currentQuery: string;
+};
+
+const initialFindAndReplaceState: FindAndReplaceState = {
+ searchIsOpen: false,
+ isSearching: false,
+ searchInputText: '',
+ replaceInputOpen: false,
+ replaceInputText: '',
+ listOffset: [],
+ styles: [],
+ matches: 0,
+ currentMatch: -1,
+ currentQuery: '',
+};
+
+type MarkdownCommentsState = {
+ marks: MarkStore;
+ activeMarkIds: string[];
+ activeCommentThread: number | null;
+ highlightedCommentId: number | null;
+ comments: CommentStore;
+ threads: ThreadStore;
+ commentMarksInitialized: boolean;
+ highlightedCommentThreads: number[];
+};
+
+export function createMarkdownDocumentState() {
+ const params = createParamsState();
+ const [md, setMd] = createStore<MdData>({});
+ const [error, setError] = createSignal<MarkdownEditorErrors | null>(null);
+ const [findAndReplace, setFindAndReplace] = createStore<FindAndReplaceState>(
+ structuredClone(initialFindAndReplaceState)
+ );
+
+ const [rewriting, setRewriting] = createSignal(false);
+ const [revisions, setRevisions] = createSignal<Diff[]>();
+
+ const [isGenerating, setIsGenerating] = createSignal(false);
+ const [generatedAndWaiting, setGeneratedAndWaiting] = createSignal(false);
+ const [completion, setCompletion] = createSignal<Completion>();
+ const [generateMenuOpen, setGenerateMenuOpen]: GenerateMenuOpen =
+ createSignal<boolean>();
+ const [generateContext, setGenerateContext] = createSignal<string>();
+
+ const [comments, setCommentState] = createStore<MarkdownCommentsState>({
+ marks: {},
+ activeMarkIds: [],
+ activeCommentThread: null,
+ highlightedCommentId: null,
+ comments: {},
+ threads: {},
+ commentMarksInitialized: false,
+ highlightedCommentThreads: [],
+ });
+
+ return {
+ params,
+ editor: {
+ md,
+ setMd,
+ error,
+ setError,
+ findAndReplace,
+ setFindAndReplace,
+ },
+ rewrite: {
+ rewriting,
+ setRewriting,
+ revisions,
+ setRevisions,
+ },
+ generation: {
+ isGenerating,
+ setIsGenerating,
+ generatedAndWaiting,
+ setGeneratedAndWaiting,
+ completion,
+ setCompletion,
+ generateMenuOpen,
+ setGenerateMenuOpen,
+ generateContext,
+ setGenerateContext,
+ },
+ comments,
+ setCommentState,
+ };
+}
+
+export type MarkdownDocumentState = ReturnType<
+ typeof createMarkdownDocumentState
+>;
diff --git a/apps/web/src/features/block-md/definition.ts b/apps/web/src/features/block-md/definition.ts
index f3c67c58d9..004b741225 100644
--- a/apps/web/src/features/block-md/definition.ts
+++ b/apps/web/src/features/block-md/definition.ts
@@ -21,7 +21,7 @@ import {
resumeDocumentSpan,
startDocumentSpan,
} from './observability';
-import type { MarkdownRewriteOutput } from './signal/rewriteSignal';
+import type { Diff } from './types';
export const definition = defineBlock({
name: 'md',
@@ -172,8 +172,6 @@ export const definition = defineBlock({
export type MarkdownData = ExtractLoadType<(typeof definition)['load']>;
export type MarkdownBlockSpec = {
- setPatches: (args: {
- patches: MarkdownRewriteOutput['diffs'];
- }) => Promise<void>;
+ setPatches: (args: { patches: Diff[] }) => Promise<void>;
setIsRewriting: () => Promise<void>;
};
diff --git a/apps/web/src/features/block-md/history/OldOverlay.tsx b/apps/web/src/features/block-md/history/OldOverlay.tsx
index 6034d0f60d..3f2bd930c3 100644
--- a/apps/web/src/features/block-md/history/OldOverlay.tsx
+++ b/apps/web/src/features/block-md/history/OldOverlay.tsx
@@ -1,20 +1,20 @@
import { useSplitLayout } from '@components/app/split-layout/layout';
-import { useBlockId } from '@core/block';
import { toast } from '@core/component/Toast/Toast';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import GitFork from '@phosphor-icons/core/regular/git-fork.svg?component-solid';
import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
import { storageServiceClient } from '@service-storage/client';
import { Button, Hotkey } from '@ui';
import { createSignal, Show } from 'solid-js';
+import { useMarkdownName } from '../component/MarkdownNameProvider';
+import { useMarkdownDocument } from '../context/markdown-document-context';
import { useHistory } from './HistoryContext';
const nameForkedDocument = (name: string) => `${name} (forked)`;
export function OldOverlay() {
const history = useHistory();
- const blockId = useBlockId();
- const documentName = useBlockDocumentName();
+ const { documentId } = useMarkdownDocument();
+ const { displayName } = useMarkdownName();
const { insertSplit } = useSplitLayout();
const [forking, setForking] = createSignal(false);
@@ -29,8 +29,8 @@ export function OldOverlay() {
if (!history.isLive() && !vid) return;
setForking(true);
const res = await storageServiceClient.copyDocument({
- documentId: blockId,
- documentName: nameForkedDocument(documentName() ?? ''),
+ documentId: documentId(),
+ documentName: nameForkedDocument(displayName() ?? ''),
syncServiceVersion: vid,
});
setForking(false);
diff --git a/apps/web/src/features/block-md/queries/markdown-comments.ts b/apps/web/src/features/block-md/queries/markdown-comments.ts
new file mode 100644
index 0000000000..a8f8d5612d
--- /dev/null
+++ b/apps/web/src/features/block-md/queries/markdown-comments.ts
@@ -0,0 +1,31 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+import { storageServiceClient } from '@service-storage/client';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+const MARKDOWN_COMMENTS_STALE_TIME = 60 * 1000;
+
+export const markdownCommentKeys = createQueryKeys('markdown-comments', {
+ document: (documentId: string) => [documentId],
+});
+
+async function fetchMarkdownComments(documentId: string) {
+ const commentThreads = await storageServiceClient.annotations.getComments({
+ documentId,
+ });
+ if (commentThreads.isErr()) {
+ throw new Error('Unable to fetch comments');
+ }
+ return commentThreads.value.data;
+}
+
+export function useMarkdownCommentsQuery(documentId: Accessor<string>) {
+ return useQuery(() => {
+ const id = documentId();
+ return {
+ queryKey: markdownCommentKeys.document(id).queryKey,
+ queryFn: () => fetchMarkdownComments(id),
+ staleTime: MARKDOWN_COMMENTS_STALE_TIME,
+ };
+ });
+}
diff --git a/apps/web/src/features/block-md/queries/markdown-document-operations.ts b/apps/web/src/features/block-md/queries/markdown-document-operations.ts
new file mode 100644
index 0000000000..39748fdb27
--- /dev/null
+++ b/apps/web/src/features/block-md/queries/markdown-document-operations.ts
@@ -0,0 +1,33 @@
+import { utf8Encode } from '@core/util/string';
+import { refetchHistory } from '@queries/history/history';
+import { storageServiceClient } from '@service-storage/client';
+import { useMutation } from '@tanstack/solid-query';
+
+export async function loadMarkdownCachedSnapshot(
+ documentId: string
+): Promise<Uint8Array | undefined> {
+ const result = await storageServiceClient.fetchCachedSnapshot(documentId);
+ return result.isOk() ? result.value : undefined;
+}
+
+async function saveMarkdownDocument(
+ documentId: string,
+ text: string
+): Promise<void> {
+ const result = await storageServiceClient.simpleSave({
+ documentId,
+ file: new Blob([utf8Encode(text)], { type: 'text/markdown' }),
+ });
+ if (result.isErr()) {
+ console.error('error on markdown save');
+ throw new Error('Unable to save markdown document');
+ }
+ await refetchHistory();
+}
+
+export function createSaveMarkdownDocumentMutation() {
+ return useMutation(() => ({
+ mutationFn: ({ documentId, text }: { documentId: string; text: string }) =>
+ saveMarkdownDocument(documentId, text),
+ }));
+}
diff --git a/apps/web/src/features/block-md/signal/error.ts b/apps/web/src/features/block-md/signal/error.ts
deleted file mode 100644
index a4f0b34547..0000000000
--- a/apps/web/src/features/block-md/signal/error.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { createBlockSignal } from '@core/block';
-import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';
-
-export const markdownBlockErrorSignal =
- createBlockSignal<MarkdownEditorErrors | null>(null);
diff --git a/apps/web/src/features/block-md/signal/findAndReplaceStore.ts b/apps/web/src/features/block-md/signal/findAndReplaceStore.ts
deleted file mode 100644
index 524b8cf461..0000000000
--- a/apps/web/src/features/block-md/signal/findAndReplaceStore.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { createBlockStore } from '@core/block';
-import type { NodekeyOffset } from '@core/component/LexicalMarkdown/plugins';
-import type { FloatingStyle } from '@core/component/LexicalMarkdown/plugins/find-and-replace';
-
-// Store Variables
-interface FindAndReplaceStore {
- searchIsOpen: boolean;
-
- isSearching: boolean;
- searchInputText: string;
-
- replaceInputOpen: boolean;
- replaceInputText: string;
-
- listOffset: NodekeyOffset[];
- styles: { style: FloatingStyle; idx: number | undefined }[];
- matches: number;
-
- currentMatch: number;
- currentQuery: string;
-}
-
-// Initial state
-const initialState: FindAndReplaceStore = {
- searchIsOpen: false,
-
- isSearching: false,
- searchInputText: '',
-
- replaceInputOpen: false,
- replaceInputText: '',
-
- listOffset: [],
- styles: [],
- matches: 0,
-
- currentMatch: -1,
- currentQuery: '',
-};
-
-// Create the store
-export const FindAndReplaceStore =
- createBlockStore<FindAndReplaceStore>(initialState);
diff --git a/apps/web/src/features/block-md/signal/generateSignal.ts b/apps/web/src/features/block-md/signal/generateSignal.ts
deleted file mode 100644
index b712a34023..0000000000
--- a/apps/web/src/features/block-md/signal/generateSignal.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- date: 02/19/2026
- note: Temporarily disabled pending port to connection-gateway
- guy: Eric Hayes
- */
-import { createBlockSignal } from '@core/block';
-// import { replaceCitations } from "@core/component/LexicalMarkdown/citationsUtils";
-import type { generateCallback } from '@core/component/LexicalMarkdown/component/menu/GenerateMenu';
-import type {
- Completion,
- GenerateMenuOpen,
-} from '@core/component/LexicalMarkdown/plugins';
-// import { cognitionWebsocketServiceClient } from '@service-cognition/client';
-// import { createCognitionWebsocketBlockEffect } from '@service-cognition/websocket';
-import { uuid } from 'short-uuid';
-
-// Generating simple completion
-export const isGeneratingSignal = createBlockSignal<boolean>(false);
-
-// Done generating and waiting for user input
-export const generatedAndWaitingSignal = createBlockSignal<boolean>(false);
-
-export const completionSignal = createBlockSignal<Completion>();
-export const generateMenuSignal: GenerateMenuOpen = createBlockSignal();
-export const generateContextSignal = createBlockSignal<string>();
-export const generateCompletionId = createBlockSignal('');
-
-export const generateNotesSignal = createBlockSignal<boolean>(false);
-
-export const generateContentCallback: generateCallback = (
- _userRequest: string
-) => {
- // const context = generateContextSignal() ?? "";
- // const id = uuid();
- // generateCompletionId.set(id.toString());
- // cognitionWebsocketServiceClient.streamSimpleCompletion({
- // prompt: `${PROMPT}${context}`,
- // user_request: userRequest,
- // completion_id: id,
- // });
-};
-
-// createCognitionWebsocketBlockEffect("completion_stream_chunk", (data) => {
-// if (!isGeneratingSignal()) {
-// return;
-// }
-// const setIsGeneratingSignal = isGeneratingSignal.set;
-// const setGeneratedAndWaitingSignal = generatedAndWaitingSignal.set;
-// const [, setCompletionSignal] = completionSignal;
-// let text = data.content;
-
-// if (data.done) {
-// replaceCitations(text).then((replacedText) => {
-// setCompletionSignal((prev) => {
-// if (prev) {
-// return {
-// ...prev,
-// text: replacedText,
-// doneGenerating: data.done,
-// };
-// }
-// });
-
-// setGeneratedAndWaitingSignal(true);
-// setIsGeneratingSignal(false);
-// });
-// } else {
-// text = text.replace(/\[\[.*?\]\]/g, "");
-// setCompletionSignal((prev) => {
-// if (prev) {
-// return {
-// ...prev,
-// text,
-// doneGenerating: data.done,
-// };
-// }
-// });
-// }
-// });
-
-export const generateNotesContentCallback = (_documentIds: string[]) => {
- const id = uuid();
- generateCompletionId.set(id);
- // cognitionWebsocketServiceClient.streamSimpleCompletion({
- // prompt: PROMPT,
- // user_request: NOTES_PROMPTS,
- // model: "anthropic/claude-sonnet-4",
- // content_document_ids: documentIds,
- // completion_id: id,
- // });
-};
-
-export const PROMPT = `You are a helpful writing assistant. You will use provided context with a user selection to answer user queries.
-Users will ask you to write things. Your response will be directly inserted into their document.
-Format your response in VALID Github Flavored Markdown (GFM) and respond directly to the user's request without comment.
-Do NOT use code fences for markdown. Only use code fences for code. Once again, do NOT use code fences for markdown.
-Your response will be directly inserted into the document so if you are unable to response, respond with an empty string.
-Your response will be directly inserted into the context where it is marked with [[SELECTION]].
-Your context is as follows:
-
-`;
-
-const _NOTES_PROMPTS = `Take the provided document and create clear, well-structured, and CONCISE notes that:
-Identify key concepts, themes, and their relationships.
-Organize ideas hierarchically with clear headings and subheadings.
-Use bullet points and numbered lists for readability.
-Provide relevant examples or applications when helpful.
-Summarize complex points in simple, concise, accessible language.
-Use latex equations and tables where helpful.
-Only use $$ for latex equations. \\(x_i\\) is NOT valid math, do NOT use it. Use $$x_i$$. Equations should also be in one line. Do NOT make them multiline.
-Make sure you include citations within the document of the format [[uuid]].
-End with 2-3 key takeaways or insights for quick review
-
-`;
diff --git a/apps/web/src/features/block-md/signal/location.ts b/apps/web/src/features/block-md/signal/location.ts
deleted file mode 100644
index 0e785910c1..0000000000
--- a/apps/web/src/features/block-md/signal/location.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useScrollToCommentThread } from '@block-md/comments/commentOperations';
-import { activeCommentThreadSignal } from '@block-md/comments/commentStore';
-import {
- setTempRedirectLocation,
- type TempRedirectLocation,
-} from '@core/signal/location';
-
-export const useGoToTempRedirect = () => {
- const [, setActiveThreadId] = activeCommentThreadSignal;
- const scrollToCommentThread = useScrollToCommentThread();
-
- return (documentId: string, state: TempRedirectLocation) => {
- if (state.itemId !== documentId) {
- return;
- }
- setTempRedirectLocation(undefined);
-
- const threadId = state.location?.threadId;
- if (!threadId) return;
-
- 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
- setActiveThreadId(threadId);
- });
- };
-};
diff --git a/apps/web/src/features/block-md/signal/markdownBlockData.ts b/apps/web/src/features/block-md/signal/markdownBlockData.ts
deleted file mode 100644
index 8a55fea55c..0000000000
--- a/apps/web/src/features/block-md/signal/markdownBlockData.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { blockDataSignalAs, createBlockStore } from '@core/block';
-import type {
- PluginManager,
- ProgressStats,
- SelectionData,
- WordcountStats,
-} from '@core/component/LexicalMarkdown/plugins';
-import type { NodeIdMappings } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
-import { createCallback } from '@solid-primitives/rootless';
-import type { LexicalEditor } from 'lexical';
-import type { Store } from 'solid-js/store';
-import type { MarkdownData } from '../definition';
-
-export const blockDataSignal = blockDataSignalAs<MarkdownData>('md');
-
-/**
- * Store for the data and helpful ui refs for the Notebook/MD block
- * @property editor The Editor instance
- * @property titleEditor The Editor instance for the title
- * @property plugins The plugin manager for the main editor
- * @property selection A store with the processed selection data
- * @property notebook The notbook ref which is the direct containing parent of the two editors and is
- * clamped to a max width.
- * @property scrollContainer The scroll container is the direct sibling of the top bar
- * and takes the full width of the block. This is where the scroll bar is attached.
- * @property locationReady True after the editor is initialized and the first
- * location-scroll window has opened.
- */
-export type MdData = {
- editor?: LexicalEditor;
- /** Durable nodeId <-> nodeKey mapping for the main editor (from the nodeId plugin). */
- mapping?: NodeIdMappings;
- titleEditor?: LexicalEditor;
- plugins?: PluginManager;
- selection?: Store<SelectionData>;
- wordcountStats?: Store<WordcountStats>;
- progressStats?: Store<ProgressStats>;
- notebook?: HTMLElement;
- scrollContainer?: HTMLElement;
- commentMargin?: HTMLElement;
- contentRef?: HTMLElement;
- locationReady?: boolean;
-};
-
-export const mdStore = createBlockStore<MdData>({});
-
-export const useIsTask = createCallback(() => {
- return () => blockDataSignal()?.documentMetadata.subType === 'task';
-});
diff --git a/apps/web/src/features/block-md/signal/rewriteSignal.ts b/apps/web/src/features/block-md/signal/rewriteSignal.ts
deleted file mode 100644
index 22c5ffd50c..0000000000
--- a/apps/web/src/features/block-md/signal/rewriteSignal.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { createBlockSignal } from '@core/block';
-
-export interface Diff {
- operation: string;
- node_key: string;
- markdown_text: string;
-}
-
-export type MarkdownRewriteOutput = {
- diffs: Diff[];
-};
-
-export const rewriteSignal = createBlockSignal<boolean>(false);
-export const isRewritingSignal = createBlockSignal<boolean>(false);
-
-export interface NodeWithText {
- key: string;
- markdown: string;
-}
-
-export const nodesAndTextSignal = createBlockSignal<NodeWithText[] | undefined>(
- undefined
-);
-
-export const revisionsSignal = createBlockSignal<Diff[] | undefined>(undefined);
diff --git a/apps/web/src/features/block-md/signal/save.ts b/apps/web/src/features/block-md/signal/save.ts
deleted file mode 100644
index 339b2cdcc8..0000000000
--- a/apps/web/src/features/block-md/signal/save.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { activeCommentThreadSignal } from '@block-md/comments/commentStore';
-import { useBlockId } from '@core/block';
-import {
- editorStateAsMarkdown,
- getSaveState,
-} from '@core/component/LexicalMarkdown/utils';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-
-import { utf8Encode } from '@core/util/string';
-import { createRenameDssEntityMutation } from '@entity';
-import { refetchHistory } from '@queries/history/history';
-import { storageServiceClient } from '@service-storage/client';
-import { createCallback } from '@solid-primitives/rootless';
-import { createMemo } from 'solid-js';
-import { mdStore } from './markdownBlockData';
-
-export const useBlockSave = () => {
- const pendingComment = createMemo(() => activeCommentThreadSignal() === -1);
-
- return pendingComment;
-};
-
-export function useSaveMarkdownDocument() {
- const blockSave = useBlockSave();
- const documentId = useBlockId();
-
- return createCallback(async (text: string) => {
- if (blockSave()) return;
-
- const buffer = utf8Encode(text);
-
- const saveRes = await storageServiceClient.simpleSave({
- documentId,
- file: new Blob([buffer], { type: 'text/markdown' }),
- });
-
- if (saveRes.isErr()) {
- console.error('error on markdown save');
- return;
- }
-
- await refetchHistory();
- });
-}
-
-export function useRenameMarkdownDocument() {
- const documentId = useBlockId();
- const renameMutation = createRenameDssEntityMutation();
-
- return (newName: string, oldName: string) => {
- renameMutation.mutate({
- entity: {
- type: 'document',
- name: oldName,
- id: documentId,
- },
- newName,
- });
- };
-}
-
-export function useDownloadDocumentAsMarkdownText() {
- const [store] = mdStore;
- const fileName = useBlockDocumentName();
-
- return createCallback(() => {
- const editor = store.editor;
- if (editor === undefined) return;
-
- const fileNameWithExtension = `${fileName()}.md`;
- const markdownString = editorStateAsMarkdown(editor, 'external');
-
- const blob = new Blob([markdownString], { type: 'text/plain' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.href = url;
- link.download = fileNameWithExtension;
- link.click();
- URL.revokeObjectURL(url);
- });
-}
-
-export function useDownloadDocumentAsJson() {
- const [store] = mdStore;
- const fileName = useBlockDocumentName();
-
- return createCallback(() => {
- const editor = store.editor;
- if (!editor) {
- return;
- }
- const fileNameWithExtension = `${fileName()}.json`;
- const json = getSaveState(editor.getEditorState());
- const blob = new Blob([JSON.stringify(json, null, 2)], {
- type: 'application/json',
- });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.href = url;
- link.download = fileNameWithExtension;
- link.click();
- URL.revokeObjectURL(url);
- });
-}
diff --git a/apps/web/src/features/block-md/types.ts b/apps/web/src/features/block-md/types.ts
new file mode 100644
index 0000000000..3b5ac86de7
--- /dev/null
+++ b/apps/web/src/features/block-md/types.ts
@@ -0,0 +1,15 @@
+import type { IDocumentStorageServiceFile } from '@filesystem/file';
+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';
+
+export interface Diff {
+ operation: string;
+ node_key: string;
+ markdown_text: string;
+}
+
+export type MarkdownDocumentKind = 'document' | 'task' | 'snippet' | 'skill';
+
+export type MarkdownDocumentSource =
+ | { type: 'loading' }
+ | { type: 'dss'; file: IDocumentStorageServiceFile }
+ | { type: 'sync'; source: LiveSyncSource };
diff --git a/apps/web/src/features/block-pdf/component/Document.tsx b/apps/web/src/features/block-pdf/component/Document.tsx
index beb6c510e8..4ab20e60d9 100644
--- a/apps/web/src/features/block-pdf/component/Document.tsx
+++ b/apps/web/src/features/block-pdf/component/Document.tsx
@@ -15,7 +15,7 @@ import {
isMultiPageSelection,
useResetSelection,
} from '@block-pdf/util/selectionUtils';
-import { useBlockId, useIsNestedBlock } from '@core/block';
+import { useIsNestedBlock } from '@core/block';
import { LoadingSpinner } from '@core/component/LoadingSpinner';
import {
ENABLE_PDF_LOCATION_AUTOSAVE,
@@ -25,7 +25,6 @@ import { IS_MAC } from '@core/constant/isMac';
import { observedSize } from '@core/directive/observedSize';
import { blockElementSignal } from '@core/signal/blockElement';
import { blockMetadataSignal } from '@core/signal/load';
-import { tempRedirectLocation } from '@core/signal/location';
import { isInDOMRect } from '@core/util/rect';
import { createCallback } from '@solid-primitives/rootless';
import { debounce } from '@solid-primitives/scheduled';
@@ -58,7 +57,6 @@ import {
locationChangedSignal,
URL_PARAMS,
useGoToLinkLocation,
- useGoToTempRedirect,
useSetLocationStore,
} from '../signal/location';
import {
@@ -471,17 +469,6 @@ export function Document() {
});
});
- createEffect(() => {
- const goToTempRedirect = useGoToTempRedirect();
- const documentId = useBlockId();
- const recentState = tempRedirectLocation();
- if (!documentId || !recentState) return;
-
- setTimeout(() => {
- goToTempRedirect(documentId, recentState);
- }, 0);
- });
-
createEffect(() => {
if (isNestedBlock) return;
diff --git a/apps/web/src/features/block-pdf/signal/location.ts b/apps/web/src/features/block-pdf/signal/location.ts
index e9f9b9d9c1..0c89f055e1 100644
--- a/apps/web/src/features/block-pdf/signal/location.ts
+++ b/apps/web/src/features/block-pdf/signal/location.ts
@@ -5,8 +5,6 @@ import {
type IUpdateFindControlStateEvent,
} from '@block-pdf/PdfViewer/EventBus';
import type { FindController } from '@block-pdf/PdfViewer/FindController';
-import { useScrollToCommentThread } from '@block-pdf/store/comments/commentOperations';
-import { activeCommentThreadSignal } from '@block-pdf/store/comments/commentStore';
import {
createBlockEffect,
createBlockSignal,
@@ -14,10 +12,6 @@ import {
useBlockId,
} from '@core/block';
import { useReferralCode } from '@core/context/user';
-import {
- setTempRedirectLocation,
- type TempRedirectLocation,
-} from '@core/signal/location';
import { buildSimpleEntityUrl } from '@core/util/url';
import { waitForSignal } from '@core/util/waitForSignal';
import { createCallback } from '@solid-primitives/rootless';
@@ -542,31 +536,6 @@ async function applyCustomHighlights(
viewer.markPageHighlightsSelected(pageIndex);
}
-export const useGoToTempRedirect = () => {
- const [activeThreadId, setActiveThreadId] = activeCommentThreadSignal;
- const scrollToCommentThread = useScrollToCommentThread();
-
- return (documentId: string, state: TempRedirectLocation) => {
- if (state.itemId !== documentId) {
- return;
- }
- setTempRedirectLocation(undefined);
-
- const threadId = state.location?.threadId;
- if (!threadId) return;
-
- const prevActiveThreadId = activeThreadId();
- setActiveThreadId(threadId);
-
- // if the thread is already active, scroll to it directly
- // Note that there is already a block effect in comment operations that will
- // scroll to a new active thread signal on change
- if (prevActiveThreadId === threadId) {
- scrollToCommentThread(threadId);
- }
- };
-};
-
/**
* Go to the given location in the pdf viewer
*
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
index 3cfb813426..7dcf22d630 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
@@ -1,5 +1,6 @@
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import {
+ isInBlock,
type PreviewState,
useBlockOwner,
useMaybeBlockName,
@@ -89,6 +90,7 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
const wrapper = useContext(LexicalWrapperContext);
const editor = () => wrapper?.editor;
const selection = () => wrapper?.selection;
+ const portalMount = isInBlock() ? blockElementSignal.get : () => undefined;
const currentBlockName = useMaybeBlockName();
@@ -424,7 +426,7 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
>
<DotsThree />
</Dropdown.Trigger>
- <Dropdown.Content mount={blockElementSignal.get()}>
+ <Dropdown.Content mount={portalMount()}>
<Dropdown.Group>
<Dropdown.Item onSelect={convertToMention}>
<Minimize class="size-4 shrink-0" />
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
index af8bb4f7fd..9df01630a8 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
@@ -1,4 +1,5 @@
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
+import { isInBlock } from '@core/block';
import { toast } from '@core/component/Toast/Toast';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import { blockElementSignal } from '@core/signal/blockElement';
@@ -31,6 +32,7 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
const wrapper = useContext(LexicalWrapperContext);
const editor = () => wrapper?.editor;
const selection = () => wrapper?.selection;
+ const portalMount = isInBlock() ? blockElementSignal.get : () => undefined;
const [open, setOpen] = createSignal(false);
const [menuOpen, setMenuOpen] = createSignal(false);
@@ -135,7 +137,7 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
<Dropdown.Trigger size="icon-sm" variant="ghost">
<DotsThree />
</Dropdown.Trigger>
- <Dropdown.Content mount={blockElementSignal.get()}>
+ <Dropdown.Content mount={portalMount()}>
<Dropdown.Group>
<Dropdown.Item onSelect={copyText}>
<Copy class="size-4 shrink-0" />
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingEquationMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingEquationMenu.tsx
index ed995c0d10..b1e4cb73de 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingEquationMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingEquationMenu.tsx
@@ -6,6 +6,7 @@ import { createCallback } from '@solid-primitives/rootless';
import { Tooltip } from '@ui';
import { $getNodeByKey } from 'lexical';
import {
+ type Accessor,
createEffect,
createSignal,
onCleanup,
@@ -32,8 +33,10 @@ false && floatWithSelection;
false && floatWithElement;
false && clickOutside;
-export function FloatingEquationMenu() {
- const canEdit = useCanEdit();
+export function FloatingEquationMenu(
+ props: { canEdit?: Accessor<boolean> } = {}
+) {
+ const canEdit = props.canEdit ?? useCanEdit();
const lexicalWrapper = useContext(LexicalWrapperContext);
const plugins = () => lexicalWrapper?.plugins;
const editor = () => lexicalWrapper?.editor;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx
index 93ab65d2a5..af4f7c4b9a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx
@@ -5,6 +5,7 @@ import { INSERT_TABLE_COMMAND } from '@lexical/table';
import { createCallback } from '@solid-primitives/rootless';
import { Layer } from '@ui';
import {
+ type Accessor,
createEffect,
createSignal,
Index,
@@ -36,8 +37,8 @@ const MAX_GRID_SIZE = 12;
* Arrow keys resize the selection, Enter inserts, Escape cancels. The mouse
* can hover/click the grid as well. The editor keeps focus throughout.
*/
-export function FloatingTableMenu() {
- const canEdit = useCanEdit();
+export function FloatingTableMenu(props: { canEdit?: Accessor<boolean> } = {}) {
+ const canEdit = props.canEdit ?? useCanEdit();
const lexicalWrapper = useContext(LexicalWrapperContext);
const plugins = () => lexicalWrapper?.plugins;
const editor = () => lexicalWrapper?.editor;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/GenerateMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/GenerateMenu.tsx
index d6af4a26cd..59af80d978 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/GenerateMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/GenerateMenu.tsx
@@ -1,7 +1,3 @@
-import {
- generatedAndWaitingSignal,
- isGeneratingSignal,
-} from '@block-md/signal/generateSignal';
import {
InlineInputDisabled,
InlineInputLoading,
@@ -36,6 +32,8 @@ type GenerateMenuProps = {
menuOpen: GenerateMenuOpen;
generateCallback: generateCallback;
completionSignal: Accessor<Completion | undefined>;
+ generatedAndWaiting: Accessor<boolean>;
+ isGenerating: Accessor<boolean>;
editor: LexicalEditor;
};
@@ -86,7 +84,7 @@ function GenerateActionMenu(props: GenerateMenuProps) {
props.editor.dispatchCommand(ACCEPT_COMPLETION, undefined);
break;
case 'Escape':
- if (!isGeneratingSignal()) {
+ if (!props.isGenerating()) {
props.editor.dispatchCommand(REJECT_COMPLETION, undefined);
}
break;
@@ -133,11 +131,8 @@ function InnerGenerateMenu(props: GenerateMenuProps) {
registerEditorWidthObserver(props.editor, setTargetWidth);
createEffect(() => console.log(targetWidth()));
- const generatedAndWaiting = generatedAndWaitingSignal.get;
- const isGenerating = isGeneratingSignal.get;
-
const keyHandler = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && !isGenerating()) {
+ if (e.key === 'Escape' && !props.isGenerating()) {
props.editor.dispatchCommand(REJECT_COMPLETION, undefined);
}
};
@@ -165,7 +160,7 @@ function InnerGenerateMenu(props: GenerateMenuProps) {
element: () => props.completionSignal()?.parentElement,
}}
use:clickOutside={() => {
- if (!generatedAndWaiting() && !isGenerating()) {
+ if (!props.generatedAndWaiting() && !props.isGenerating()) {
props.editor.dispatchCommand(REJECT_COMPLETION, undefined);
}
}}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
index 032b529460..384852188e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
@@ -10,13 +10,19 @@
* pointer captured so the drag survives leaving the editor; Escape /
* pointercancel restores the pre-drag width or height.
*/
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { $isTableCellNode, getDOMCellFromTarget } from '@lexical/table';
import { calculateZoomLevel } from '@lexical/utils';
import { $getNearestNodeFromDOMNode } from 'lexical';
-import { createMemo, createSignal, onCleanup, Show } from 'solid-js';
+import {
+ createMemo,
+ createSignal,
+ onCleanup,
+ Show,
+ useContext,
+} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { registerEditorWidthObserver } from '../../plugins/shared/utils';
import {
$applyResizeDrag,
@@ -53,8 +59,8 @@ const [dragEdge, setDragEdge] = createSignal<ResizeEdge>();
export const tableColumnResizeEdge = dragEdge;
export function TableCellResizer() {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
// Cell whose border carries the handle: the hovered cell on pointer
// devices, the touched cell during a touch drag. `activeCellKey` is set
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx
index 8c82c5bfe1..25ccad282e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx
@@ -1,4 +1,3 @@
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { ScopedPortal } from '@core/component/ScopedPortal';
import {
$computeTableMap,
@@ -14,7 +13,14 @@ import {
isHTMLElement,
type LexicalEditor,
} from 'lexical';
-import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ onCleanup,
+ Show,
+ useContext,
+} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import {
$deleteTableAtHover,
$selectionDeleteExtent,
@@ -117,8 +123,8 @@ function readSelectionDeletePixels(
}
export function TableDeleteButtons() {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
const [target, setTarget] = createSignal<DeleteTarget>();
const [hovered, setHovered] = createSignal<'row' | 'column' | 'table'>();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx
index fc44129374..7a82dc3cd3 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx
@@ -1,4 +1,3 @@
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { ScopedPortal } from '@core/component/ScopedPortal';
import {
$computeTableMapSkipCellCheck,
@@ -17,7 +16,14 @@ import {
$getNodeByKey,
isHTMLElement,
} from 'lexical';
-import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ onCleanup,
+ Show,
+ useContext,
+} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { tableColumnResizeEdge } from './TableCellResizer';
// How close (px) the pointer must be to a row/column border for the button to show.
@@ -36,8 +42,8 @@ type InsertTarget = {
};
export function TableInsertButton() {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
const [insertTarget, setInsertTarget] = createSignal<InsertTarget>();
const [buttonHovered, setButtonHovered] = createSignal(false);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx
index d1beea86b9..ed6547598e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx
@@ -1,7 +1,7 @@
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { ScopedPortal } from '@core/component/ScopedPortal';
import clickOutside from '@core/directive/clickOutside';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { getScrollParentElement } from '@core/util/scrollParent';
import {
$computeTableMap,
$createTableSelection,
@@ -47,7 +47,9 @@ import {
createSignal,
For,
Show,
+ useContext,
} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { floatWithElement } from '../../directive/floatWithElement';
import { lazyRegister } from '../../plugins';
import { $moveCellRange } from '../../plugins/tables/tableMove';
@@ -122,8 +124,8 @@ type DragShape = {
* pasting a copied range.
*/
export function TableMoveHandle() {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
const [anchorCellKey, setAnchorCellKey] = createSignal<string>();
const [focusCellKey, setFocusCellKey] = createSignal<string>();
@@ -238,7 +240,9 @@ export function TableMoveHandle() {
?.getBoundingClientRect();
// Vertical scroll viewport of the editor; its top is the highest the
// handle may sit before it would float over the gray area above.
- const scrollTop = mdData.scrollContainer?.getBoundingClientRect().top;
+ const scrollTop = getScrollParentElement(
+ currentEditor.getRootElement()
+ )?.getBoundingClientRect().top;
return {
// Clamp to the scroll wrapper's visible right edge so a cell scrolled
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx
index a6e1a0662c..d7ab4f54c1 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx
@@ -4,7 +4,6 @@
* menu for the clipboard and no format popup for table selections. On
* desktop, merge/split live in the normal selection popup (FormatTools).
*/
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { toast } from '@core/component/Toast/Toast';
import {
@@ -46,15 +45,17 @@ import {
createSignal,
onCleanup,
Show,
+ useContext,
} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { floatWithElement } from '../../directive/floatWithElement';
import { createLayoutTick } from './createLayoutTick';
false && floatWithElement;
export function TableSelectionActionBar() {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
const [anchorCellKey, setAnchorCellKey] = createSignal<string>();
const [focusCellKey, setFocusCellKey] = createSignal<string>();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/diff/diffPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/diff/diffPlugin.ts
index db6fce4501..90543225a4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/diff/diffPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/diff/diffPlugin.ts
@@ -1,4 +1,3 @@
-import type { createBlockSignal } from '@core/block';
import { useUserId } from '@core/context/user';
import { $wrapNodeInElement, mergeRegister } from '@lexical/utils';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
@@ -16,7 +15,7 @@ import {
COMMAND_PRIORITY_NORMAL,
createCommand,
} from 'lexical';
-import { createEffect } from 'solid-js';
+import { createEffect, type Signal } from 'solid-js';
import { mapRegisterDelete } from '../shared/utils';
interface Diff {
@@ -26,7 +25,7 @@ interface Diff {
}
type DiffPluginArgs = {
- revisionsSignal: ReturnType<typeof createBlockSignal<Diff[] | undefined>>;
+ revisionsSignal: Signal<Diff[] | undefined>;
nodeIdMap: NodeIdMappings;
};
@@ -49,13 +48,14 @@ const DELETE_DIFF_COMMAND = createCommand<string>('DELETE_DIFF_COMMAND');
function registerDiffPlugin(editor: LexicalEditor, props: DiffPluginArgs) {
const userId = useUserId();
+ const [revisions, setRevisions] = props.revisionsSignal;
createEffect(() => {
- const revisionsResponse = props.revisionsSignal();
+ const revisionsResponse = revisions();
if (!revisionsResponse) {
return;
}
- props.revisionsSignal.set(undefined);
+ setRevisions(undefined);
let cleanedRevisions: Diff[] = [];
for (const revision of revisionsResponse) {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
index bcb307fdcc..cfd64a834f 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
@@ -1,10 +1,9 @@
-import { FindAndReplaceStore } from '@block-md/signal/findAndReplaceStore';
-import { mdStore } from '@block-md/signal/markdownBlockData';
import { mergeRegister } from '@lexical/utils';
import { createCallback } from '@solid-primitives/rootless';
import { cn } from '@ui';
-import { createEffect, For } from 'solid-js';
+import { createEffect, For, useContext } from 'solid-js';
import { Portal } from 'solid-js/web';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import {
autoRegister,
lazyRegister,
@@ -33,13 +32,20 @@ function registerEventListener(
return () => target.removeEventListener(type, listener);
}
-export function SearchHighlight({
- anchorElem = document.body,
-}: {
+type SearchHighlightItem = {
+ style: FloatingStyle;
+ idx: number | undefined;
+};
+
+export function SearchHighlight(props: {
anchorElem?: HTMLElement;
+ listOffset: NodekeyOffset[];
+ onStylesChange: (styles: SearchHighlightItem[]) => void;
+ onMatchesChange: (matches: number) => void;
}): null {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = () => lexicalWrapper?.editor;
+ const anchorElem = () => props.anchorElem ?? document.body;
let stateListOffsetRef: NodekeyOffset[] = [];
let animationFrame: number | undefined;
@@ -60,7 +66,7 @@ export function SearchHighlight({
[...rects].map((rect) => {
const newStyle = getFloatingSearchHighlightPosition(
rect,
- anchorElem
+ anchorElem()
);
const styleWidth = newStyle.width;
if (
@@ -76,8 +82,8 @@ export function SearchHighlight({
}
});
- FindAndReplaceStore.set('styles', newStyles);
- FindAndReplaceStore.set('matches', matches);
+ props.onStylesChange(newStyles);
+ props.onMatchesChange(matches);
}
);
@@ -98,7 +104,7 @@ export function SearchHighlight({
});
createEffect(() => {
- stateListOffsetRef = FindAndReplaceStore.get.listOffset;
+ stateListOffsetRef = props.listOffset;
update();
});
@@ -120,7 +126,7 @@ export function SearchHighlight({
);
autoRegister(
- registerEventListener(anchorElem.parentElement, 'scroll', update),
+ registerEventListener(anchorElem().parentElement, 'scroll', update),
() => {
if (animationFrame !== undefined) {
cancelAnimationFrame(animationFrame);
@@ -131,18 +137,20 @@ export function SearchHighlight({
return null;
}
-export function FloatingSearchHighlight(props: { anchorElem?: HTMLElement }) {
+export function FloatingSearchHighlight(props: {
+ anchorElem?: HTMLElement;
+ styles: SearchHighlightItem[];
+ currentMatch: number;
+}) {
return (
<Portal mount={props.anchorElem}>
- <For each={FindAndReplaceStore.get.styles}>
+ <For each={props.styles}>
{(item) => (
<div
style={item.style}
class={cn(
'z-10 m-0 text-transparent h-4.5 absolute top-0 left-0 opacity-50 pointer-events-none',
- item.idx === FindAndReplaceStore.get.currentMatch + 1
- ? 'bg-accent'
- : 'bg-accent/50'
+ item.idx === props.currentMatch + 1 ? 'bg-accent' : 'bg-accent/50'
)}
/>
)}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/generate/generatePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/generate/generatePlugin.ts
index fdc808eeec..faf1541502 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/generate/generatePlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/generate/generatePlugin.ts
@@ -27,13 +27,18 @@ import {
type LexicalEditor,
type RangeSelection,
} from 'lexical';
-import { createEffect, createSignal, on, type Setter } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ on,
+ type Setter,
+ type Signal,
+} from 'solid-js';
import { theme } from '../../theme';
import { $traverseNodes, setEditorStateFromMarkdown } from '../../utils';
export {} from '@macro-inc/lexical-core';
-import type { createBlockSignal } from '@core/block';
import type { SetStoreFunction } from 'solid-js/store';
import { GenerateAccessory } from '../../component/accessory/GenerateAccessory';
import {
@@ -61,7 +66,7 @@ export type GenerateMenuOpen = ReturnType<
typeof createSignal<boolean | undefined>
>;
// done generating and waiting
-type BooleanSignal = ReturnType<typeof createBlockSignal<boolean>>;
+type BooleanSignal = Signal<boolean>;
const _IGNORE_COMPLETION_TYPES = ['inline-search'];
const MAKE_COMPLETION: LexicalCommand<Completion> =
diff --git a/apps/web/src/lib/core/component/LiveIndicators.tsx b/apps/web/src/lib/core/component/LiveIndicators.tsx
index 996b265dab..97c9f8aa65 100644
--- a/apps/web/src/lib/core/component/LiveIndicators.tsx
+++ b/apps/web/src/lib/core/component/LiveIndicators.tsx
@@ -1,3 +1,4 @@
+import { useBlockId } from '@core/block';
import { ENABLE_LIVE_INDICATORS } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { AvatarGroup } from '@ui';
@@ -40,7 +41,8 @@ export function LiveIndicators(props: {
}
export function BlockLiveIndicators() {
- const indicators = useUserIndicators();
+ const blockId = useBlockId();
+ const indicators = useUserIndicators(() => blockId);
const userId = useUserId();
return (
diff --git a/apps/web/src/lib/core/component/ParamsProvider.test.tsx b/apps/web/src/lib/core/component/ParamsProvider.test.tsx
index 74369c968f..8c56f92ff1 100644
--- a/apps/web/src/lib/core/component/ParamsProvider.test.tsx
+++ b/apps/web/src/lib/core/component/ParamsProvider.test.tsx
@@ -3,18 +3,18 @@
*/
import { render } from '@solidjs/testing-library';
-import { type Accessor, createEffect, on } from 'solid-js';
+import { createEffect, on } from 'solid-js';
import { createStore, type SetStoreFunction } from 'solid-js/store';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ParamsProvider, useUrlParams } from './ParamsProvider';
+import {
+ createParamsState,
+ ParamsProvider,
+ useUrlParams,
+} from './ParamsProvider';
type MockSearchParams = Record<string, string | string[] | undefined>;
const mocks = vi.hoisted(() => ({
- registeredMethods: {} as Record<
- string,
- (params: Record<string, string>) => void
- >,
searchParams: undefined as MockSearchParams | undefined,
setSearchParams: undefined as SetStoreFunction<MockSearchParams> | undefined,
}));
@@ -23,21 +23,6 @@ vi.mock('@solidjs/router', () => ({
useSearchParams: () => [mocks.searchParams, mocks.setSearchParams],
}));
-vi.mock('@core/orchestrator', () => ({
- createMethodRegistration: (
- _blockHandle: Accessor<unknown>,
- methods: Record<string, (params: Record<string, string>) => void>
- ) => {
- mocks.registeredMethods = methods;
- },
-}));
-
-vi.mock('@core/signal/load', () => ({
- blockHandleSignal: {
- get: () => ({}),
- },
-}));
-
const URL_PARAMS = {
nodeId: 'node_id',
location: 'location',
@@ -99,11 +84,12 @@ function renderHarness(initialSearchParams: MockSearchParams = {}) {
};
const [searchParams, setSearchParams] =
createStore<MockSearchParams>(initialSearchParams);
+ const paramsState = createParamsState();
mocks.searchParams = searchParams;
mocks.setSearchParams = setSearchParams;
const rendered = render(() => (
- <ParamsProvider>
+ <ParamsProvider state={paramsState}>
<Consumer counts={counts} values={values} />
</ParamsProvider>
));
@@ -112,12 +98,12 @@ function renderHarness(initialSearchParams: MockSearchParams = {}) {
...rendered,
counts,
values,
+ paramsState,
setSearchParams,
};
}
beforeEach(() => {
- mocks.registeredMethods = {};
mocks.searchParams = undefined;
mocks.setSearchParams = undefined;
});
@@ -172,14 +158,14 @@ describe('ParamsProvider', () => {
});
it('notifies an imperatively navigated param even when its value is unchanged', async () => {
- const { counts, values } = renderHarness({
+ const { counts, values, paramsState } = renderHarness({
node_id: 'node-1',
comment_id: 'comment-1',
});
await settle();
resetCounts(counts);
- mocks.registeredMethods.goToLocationFromParams({
+ paramsState.navigate({
comment_id: 'comment-1',
});
await settle();
@@ -193,7 +179,7 @@ describe('ParamsProvider', () => {
});
it('does not notify watched params when imperative navigation uses unrelated params', async () => {
- const { counts, values } = renderHarness({
+ const { counts, values, paramsState } = renderHarness({
node_id: 'node-1',
location: 'loc-1',
comment_id: 'comment-1',
@@ -201,7 +187,7 @@ describe('ParamsProvider', () => {
await settle();
resetCounts(counts);
- mocks.registeredMethods.goToLocationFromParams({
+ paramsState.navigate({
unrelated: 'value',
});
await settle();
diff --git a/apps/web/src/lib/core/component/ParamsProvider.tsx b/apps/web/src/lib/core/component/ParamsProvider.tsx
index 7307f9729a..07b7dbd4e5 100644
--- a/apps/web/src/lib/core/component/ParamsProvider.tsx
+++ b/apps/web/src/lib/core/component/ParamsProvider.tsx
@@ -1,5 +1,3 @@
-import { createMethodRegistration } from '@core/orchestrator';
-import { blockHandleSignal } from '@core/signal/load';
import { useSearchParams } from '@solidjs/router';
import {
type Accessor,
@@ -40,16 +38,17 @@ function flattenParamValue(
return Array.isArray(val) ? val[0] : val;
}
-export function ParamsProvider(props: ParentProps) {
- const [searchParams] = useSearchParams();
+export function createParamsState() {
const [blockParams, setBlockParams] = createStore<ParamMap>({});
const [navigationVersions, setNavigationVersions] =
createStore<ParamVersions>({});
- const blockHandle = blockHandleSignal.get;
-
- createMethodRegistration(blockHandle, {
- goToLocationFromParams: (params: Record<string, string>) => {
+ return {
+ getParam: (param: string) => () => {
+ navigationVersions[param];
+ return blockParams[param];
+ },
+ navigate: (params: Record<string, string>) => {
batch(() => {
const paramNames = new Set([
...Object.keys(blockParams),
@@ -65,16 +64,22 @@ export function ParamsProvider(props: ParentProps) {
}
});
},
- });
-
- const context: ParamsContextValue = {
- getParam: (param) => () => {
- navigationVersions[param];
+ };
+}
- const blockValue = blockParams[param];
- if (blockValue !== undefined) return blockValue;
+export type ParamsState = ReturnType<typeof createParamsState>;
- return flattenParamValue(searchParams[param]);
+export function ParamsProvider(
+ props: ParentProps<{
+ state?: ParamsState;
+ }>
+) {
+ const [searchParams] = useSearchParams();
+ const state = props.state ?? createParamsState();
+ const context: ParamsContextValue = {
+ getParam: (param) => {
+ const blockValue = state.getParam(param);
+ return () => blockValue() ?? flattenParamValue(searchParams[param]);
},
};
diff --git a/apps/web/src/lib/core/signal/location.ts b/apps/web/src/lib/core/signal/location.ts
deleted file mode 100644
index ccd5164542..0000000000
--- a/apps/web/src/lib/core/signal/location.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { DocumentMentionLocation } from '@service-notification/client';
-import { makePersisted } from '@solid-primitives/storage';
-import { createSignal } from 'solid-js';
-
-export type TempRedirectLocation = {
- itemId: string;
- location: DocumentMentionLocation;
-};
-
-export const [tempRedirectLocation, setTempRedirectLocation] = makePersisted(
- createSignal<TempRedirectLocation>(),
- {
- name: 'macro-temp-redirect-location',
- }
-);
diff --git a/apps/web/src/lib/core/state/liveIndicators.ts b/apps/web/src/lib/core/state/liveIndicators.ts
index d4c0e75e71..c54eddc862 100644
--- a/apps/web/src/lib/core/state/liveIndicators.ts
+++ b/apps/web/src/lib/core/state/liveIndicators.ts
@@ -1,7 +1,7 @@
-import { useBlockId } from '@core/block';
import { ENABLE_LIVE_INDICATORS } from '@core/constant/featureFlags';
import { createWebsocketEventEffect } from '@macro-inc/collaboration/websocket';
import { type FromWebsocketMessage, ws } from '@service-connection/websocket';
+import type { Accessor } from 'solid-js';
import { createStore, unwrap } from 'solid-js/store';
import { z } from 'zod';
@@ -24,8 +24,8 @@ createWebsocketEventEffect(
setIndicatorStore(update.entity_id, update.user_ids);
}
);
-export const useUserIndicators = () => {
+export const useUserIndicators = (entityId: Accessor<string>) => {
if (!ENABLE_LIVE_INDICATORS) return () => [];
- const indicators = () => unwrap(indicatorStore[useBlockId()]);
+ const indicators = () => unwrap(indicatorStore[entityId()]);
return indicators;
};