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.

fix(snipets): only one snippet parse editor, various special case icons (#3967)

Seamusdd2df90d5d1a
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index 33f223ae56..ac0cf8c274 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -521,29 +521,14 @@ export const LauncherInner = (props: LauncherInnerProps) => {
const focusMenuItem = (label: string) => {
const menuItem = document.querySelector<HTMLElement>(
- `.create-menu-${label}`
+ `.create-menu-${label.toLowerCase()}`
);
- if (menuItem) {
- menuItem.focus();
- }
+ if (!menuItem) return false;
- return true;
- };
+ menuItem.focus();
- // Mirrors the grid-cols-2 / sm:grid-cols-4 / xl:grid-cols-N classes in the JSX
- const getColumnCount = () => {
- const width = window.innerWidth;
- const length = blocks().length;
- if (width >= 1280) {
- if (length >= 8) return 8;
- if (length >= 7) return 7;
- if (length >= 6) return 6;
- if (length >= 5) return 5;
- return 4;
- }
- if (width >= 640) return 4;
- return 2;
+ return true;
};
const moveFocus = (delta: number) => {
@@ -569,6 +554,26 @@ export const LauncherInner = (props: LauncherInnerProps) => {
return true;
};
+ const getGridColumnCount = () => {
+ const columns = window.getComputedStyle(ref).gridTemplateColumns;
+ return Math.max(columns.split(' ').filter(Boolean).length, 1);
+ };
+
+ const moveFocusRow = (direction: -1 | 1) => {
+ const columnCount = getGridColumnCount();
+ const nextIndex = focusedIndex() + columnCount * direction;
+
+ if (nextIndex < 0 || nextIndex >= blocks().length) return false;
+
+ const nextEl = tabbable(ref)[nextIndex];
+ if (!nextEl) return false;
+
+ nextEl.focus();
+ setFocusedIndex(nextIndex);
+
+ return true;
+ };
+
blocks().forEach((item) => {
registerHotkey({
hotkeyToken: item.hotkeyToken,
@@ -628,7 +633,7 @@ export const LauncherInner = (props: LauncherInnerProps) => {
description: 'Navigate Up',
keyDownHandler: (e) => {
e?.preventDefault();
- return moveFocus(-getColumnCount());
+ return moveFocusRow(-1);
},
}).withGroup(hkGroup);
@@ -638,7 +643,7 @@ export const LauncherInner = (props: LauncherInnerProps) => {
description: 'Navigate Down',
keyDownHandler: (e) => {
e?.preventDefault();
- return moveFocus(getColumnCount());
+ return moveFocusRow(1);
},
}).withGroup(hkGroup);
@@ -703,19 +708,9 @@ export const LauncherInner = (props: LauncherInnerProps) => {
onCleanup(hkGroup.dispose);
- // horrible but tailwind requires the full strings
- const gridColsClass = () => {
- const length = blocks().length;
- if (length >= 8) return 'xl:grid-cols-8';
- if (length >= 7) return 'xl:grid-cols-7';
- if (length >= 6) return 'xl:grid-cols-6';
- if (length >= 5) return 'xl:grid-cols-5';
- return '';
- };
-
return (
- <div class="bg-surface ring-1 ring-edge-muted rounded-xl">
- <div class="flex items-center justify-between p-2 px-6 border-b border-edge-muted">
+ <div class="bg-surface ring-1 ring-edge-muted rounded-xl max-w-[calc(100vw-2rem)]">
+ <div class="flex items-center justify-between p-2 px-4 sm:px-6 border-b border-edge-muted">
<h1 class="font-bold text-ink-muted">Create New</h1>
<p class="gap-2 text-ink-extra-muted text-xs items-center hidden touch:hidden md:flex">
<style>{`
@@ -748,10 +743,7 @@ export const LauncherInner = (props: LauncherInnerProps) => {
</p>
</div>
<div
- class={cn(
- 'relative grid grid-cols-2 sm:grid-cols-4 gap-3 p-6 isolate brackets-never',
- gridColsClass()
- )}
+ class="relative grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 justify-items-center gap-3 p-4 sm:p-6 isolate brackets-never"
ref={ref}
>
<For each={blocks()}>
diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.ts
index 6d004becae..9cbee97e1a 100644
--- a/js/app/packages/app/component/command/useCommandItems.ts
+++ b/js/app/packages/app/component/command/useCommandItems.ts
@@ -236,7 +236,7 @@ function useQuickAccessBuckets(): Record<
all: allWithCommands,
channels: quickAccess.useList('channel'),
dms: quickAccess.useList('dm'),
- documents: quickAccess.useList('note', 'document'),
+ documents: quickAccess.useList('note', 'document', 'snippet'),
tasks: quickAccess.useList('task'),
chats: quickAccess.useList('chat'),
projects: quickAccess.useList('project'),
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-create-button.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-create-button.tsx
index 26073627b1..2d7d91b296 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-create-button.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-create-button.tsx
@@ -21,7 +21,7 @@ import { NewCallButton } from './NewCallButton';
const VIEW_CREATE_BLOCKNAMES: Partial<
Record<ListView, (BlockName | BlockAlias)[]>
> = {
- documents: ['md', 'canvas', 'code'],
+ documents: ['md', 'snippet', 'canvas', 'code'],
tasks: ['task'],
agents: ['chat', 'automation'],
mail: ['email'],
@@ -56,7 +56,7 @@ const VIEW_ONLY_BLOCK_LABELS: Partial<Record<BlockName | BlockAlias, string>> =
const VIEW_CREATE_LABELS: Partial<Record<ListView, string>> = {
agents: 'Agent',
channels: 'Channel',
- documents: 'Document',
+ documents: 'New',
folders: 'Folder',
mail: 'Email',
tasks: 'Task',
diff --git a/js/app/packages/block-canvas/component/nodes/TextBox.tsx b/js/app/packages/block-canvas/component/nodes/TextBox.tsx
index a3e751942c..c160345163 100644
--- a/js/app/packages/block-canvas/component/nodes/TextBox.tsx
+++ b/js/app/packages/block-canvas/component/nodes/TextBox.tsx
@@ -223,6 +223,7 @@ function TextBoxEditor(props: {
editor={editor}
menu={menu()}
useBlockBoundary={true}
+ sourceDocumentId={props.blockId}
/>
)}
</Show>
diff --git a/js/app/packages/block-md/component/InstructionsEditor.tsx b/js/app/packages/block-md/component/InstructionsEditor.tsx
index 8a4396becd..322e949276 100644
--- a/js/app/packages/block-md/component/InstructionsEditor.tsx
+++ b/js/app/packages/block-md/component/InstructionsEditor.tsx
@@ -17,6 +17,7 @@ import {
LexicalWrapperContext,
} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import {
+ awaitPlugin,
CLOSE_INLINE_SEARCH_COMMAND,
DefaultShortcuts,
documentMetadataPlugin,
@@ -192,10 +193,12 @@ export function InstructionsEditor(props: {
snippetsPlugin({
menu: snippetsMenuOperations,
peerIdValidator: peerIdValidator(),
+ sourceDocumentId: blockId,
})
)
.use(textPastePlugin())
.use(markdownPastePlugin())
+ .use(awaitPlugin())
.use(
keyboardShortcutsPlugin({
shortcuts: DefaultShortcuts,
@@ -436,6 +439,7 @@ export function InstructionsEditor(props: {
editor={editor}
menu={snippetsMenuOperations}
useBlockBoundary={true}
+ sourceDocumentId={blockId}
/>
<Show when={DEBUG}>
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 8c4fd9ec0a..534058de57 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -202,6 +202,19 @@ const EDITOR_PADDING_BOTTOM = 200;
// For tasks, the click target is a small fixed pad so the activity section stays visible.
const TASK_EDITOR_PADDING_BOTTOM = 48;
+function getBlankMarkdownPlaceholder(canEdit: boolean) {
+ if (!canEdit) return 'This document is blank...';
+
+ const hints = [
+ "'/' for commands",
+ "'@' to reference files",
+ "';' for snippets",
+ ];
+ if (ENABLE_MARKDOWN_AI_GENERATE) hints.push("'space' for AI writing");
+
+ return `Press ${hints.join(', ')}...`;
+}
+
export function MarkdownEditor(props: {
autoFocusOnMount?: boolean;
loroManager: Accessor<LoroManager | undefined>;
@@ -532,6 +545,7 @@ export function MarkdownEditor(props: {
snippetsPlugin({
menu: snippetsMenuOperations,
peerIdValidator: peerIdValidator(),
+ sourceDocumentId: blockId,
})
)
.use(
@@ -979,9 +993,7 @@ export function MarkdownEditor(props: {
/>
<Show when={isBlankMarkdown()}>
<div class="pointer-events-none text-ink-placeholder absolute top-0">
- {canEdit()
- ? `Press '/' for commands, '@' to reference files${ENABLE_MARKDOWN_AI_GENERATE ? ", 'space' for AI writing..." : '...'}`
- : `This document is blank...`}
+ {getBlankMarkdownPlaceholder(canEdit())}
</div>
</Show>
<DecoratorRenderer editor={editor} />
@@ -1032,6 +1044,7 @@ export function MarkdownEditor(props: {
editor={editor}
menu={snippetsMenuOperations}
useBlockBoundary={true}
+ sourceDocumentId={blockId}
/>
<ActionMenu editor={editor} menu={actionsMenuOperations} />
diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
index 049aa06f1b..95445006b0 100644
--- a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
@@ -304,6 +304,7 @@ export const MarkdownShell: Component<
menu={menu()}
useBlockBoundary={false}
portalScope={props.portalScope}
+ sourceDocumentId={builderConfig.mentions?.sourceDocumentId}
/>
)}
</Show>
diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
index 60c24f9497..e06805180b 100644
--- a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
@@ -168,7 +168,12 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
}
if (snippetsMenuOps) {
- plugins.use(snippetsPlugin({ menu: snippetsMenuOps }));
+ plugins.use(
+ snippetsPlugin({
+ menu: snippetsMenuOps,
+ sourceDocumentId: config.mentions?.sourceDocumentId,
+ })
+ );
}
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index e5c62851e9..cb3b84bfc9 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -30,6 +30,7 @@ import {
} from '../../context/LexicalWrapperContext';
import {
autoRegister,
+ awaitPlugin,
codePlugin,
createAccessoryStore,
customSelectionDataPlugin,
@@ -211,6 +212,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
})
)
.use(emojisPlugin({ menu: emojisMenuOperations }))
+ .use(awaitPlugin())
.use(snippetsPlugin({ menu: snippetsMenuOperations }));
if (props.onPasteFilesAndDirs) {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
index b80bff140e..0d81269fed 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
@@ -4,14 +4,8 @@ import type { EntityItem } from '@core/context/quickAccess';
import clickOutside from '@core/directive/clickOutside';
import { debouncedDependent } from '@core/util/debounce';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
-import { syncServiceClient } from '@service-sync/client';
import { Surface } from '@ui';
-import {
- $insertNodes,
- $parseSerializedNode,
- createEditor,
- type LexicalEditor,
-} from 'lexical';
+import type { LexicalEditor } from 'lexical';
import {
createEffect,
createSignal,
@@ -22,18 +16,12 @@ import {
Suspense,
untrack,
} from 'solid-js';
-import { createLexicalWrapper } from '../../../context/LexicalWrapperContext';
import { floatWithSelection } from '../../../directive/floatWithSelection';
import {
CLOSE_SNIPPET_SEARCH_COMMAND,
- REMOVE_SNIPPET_SEARCH_COMMAND,
+ INSERT_SNIPPET_COMMAND,
} from '../../../plugins/snippets';
import type { MenuOperations } from '../../../shared/inlineMenu';
-import {
- editorStateAsMarkdown,
- initializeEditorWithState,
- setEditorStateFromMarkdown,
-} from '../../../utils';
import { MentionsMenuItem } from '../MentionsMenu/components/MentionsMenuItem';
import { useEntityMention } from '../MentionsMenu/hooks/useEntityMention';
import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';
@@ -50,30 +38,9 @@ type SnippetsMenuProps = {
/** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */
useBlockBoundary?: boolean;
portalScope?: PortalScope;
+ sourceDocumentId?: string;
};
-/**
- * Fetch a snippet document's content and render it to internal markdown.
- * Content lives in sync-service; a throwaway markdown editor converts the
- * serialized state to a markdown string the target editor can ingest.
- */
-async function fetchSnippetMarkdown(documentId: string): Promise<string> {
- const rawState = await syncServiceClient.getRaw({ documentId });
-
- const { editor, cleanup } = createLexicalWrapper({
- type: 'markdown',
- namespace: 'snippet-markdown-extractor',
- isInteractable: () => false,
- });
-
- try {
- initializeEditorWithState(editor, rawState);
- return editorStateAsMarkdown(editor, 'internal');
- } finally {
- cleanup();
- }
-}
-
/**
* Typeahead menu opened by typing `;` in a markdown area. Lists snippet
* documents the user can access (their own + team-shared); selecting one
@@ -96,6 +63,8 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
buckets: ['snippet'],
searchTerm,
});
+ const filteredSnippets = () =>
+ snippets().filter((snippet) => snippet.id !== props.sourceDocumentId);
const [selectedIndex, setSelectedIndex] = createSignal(0);
const [mountSelection, setMountSelection] = createSignal<Selection | null>();
@@ -127,7 +96,7 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
});
createEffect(() => {
- const count = snippets().length;
+ const count = filteredSnippets().length;
if (count > 0 && selectedIndex() >= count) {
setSelectedIndex(count - 1);
}
@@ -138,54 +107,27 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
setMenuOpen(false);
};
- const insertSnippet = async (item: EntityItem) => {
+ const insertSnippet = (item: EntityItem) => {
analytics.track('snippets_menu_use', {});
- props.editor.dispatchCommand(REMOVE_SNIPPET_SEARCH_COMMAND, undefined);
- props.menu.setSearchTerm('');
- setMenuOpen(false);
-
- let markdown: string;
- try {
- markdown = await fetchSnippetMarkdown(item.id);
- } catch (error) {
- console.error('failed to load snippet content', error);
- return;
- }
- if (!markdown.trim()) return;
-
- // Same technique as the markdown paste plugin: parse the markdown with a
- // throwaway editor restricted to the target editor's nodes, then insert
- // the resulting nodes at the cursor.
- props.editor.update(() => {
- const parseEditor = createEditor({
- namespace: 'snippet-parser',
- editable: false,
- nodes: [
- ...Array.from(props.editor._nodes.values()).map((node) => node.klass),
- ],
- });
- setEditorStateFromMarkdown(parseEditor, markdown, 'both');
- const state = parseEditor.getEditorState().toJSON();
- const nodes = state.root.children.map((node) =>
- $parseSerializedNode(node)
- );
- $insertNodes(nodes);
+ props.editor.dispatchCommand(INSERT_SNIPPET_COMMAND, {
+ documentId: item.id,
+ sourceDocumentId: props.sourceDocumentId,
});
};
const itemAction = (item: EntityItem) => {
- void insertSnippet(item);
+ insertSnippet(item);
};
useMenuKeyboardNavigation({
isActive: menuOpen,
onUp: () => {
- const items = snippets();
+ const items = filteredSnippets();
if (items.length === 0) return;
setSelectedIndex((selectedIndex() - 1 + items.length) % items.length);
},
onDown: () => {
- const items = snippets();
+ const items = filteredSnippets();
if (items.length === 0) return;
setSelectedIndex((selectedIndex() + 1) % items.length);
},
@@ -196,7 +138,7 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
// block horizontal arrows
},
onSelect: () => {
- const selectedItem = snippets()[selectedIndex()];
+ const selectedItem = filteredSnippets()[selectedIndex()];
if (selectedItem) {
itemAction(selectedItem);
} else {
@@ -265,7 +207,7 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
Snippets
</div>
<Show
- when={snippets().length > 0}
+ when={filteredSnippets().length > 0}
fallback={
<div class="px-3.5 pb-1 text-ink-extra-muted">
{searchTerm() ? 'No results' : 'No snippets yet'}
@@ -276,7 +218,7 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
class="overflow-y-auto scrollbar-hidden"
style={{ 'max-height': `${contentMaxHeight()}px` }}
>
- <For each={snippets()}>
+ <For each={filteredSnippets()}>
{(item, index) => (
<MentionsMenuItem
item={item}
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts
index 0aebd6b70f..1400157f1b 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts
@@ -1,28 +1,44 @@
import { ENABLE_SNIPPETS } from '@core/constant/featureFlags';
-import { mergeRegister } from '@lexical/utils';
+import { $dfsIterator, mergeRegister } from '@lexical/utils';
import type { PeerIdValidator } from '@lexical-core';
import {
$collapseInlineSearch,
+ $createAwaitNode,
$createInlineSearchNode,
$handleInlineSearchNodeMutation,
$handleInlineSearchNodeTransform,
+ $isAwaitNode,
+ $isInlineSearchNode,
$removeInlineSearch,
+ HISTORY_MERGE_TAG,
InlineSearchNode,
InlineSearchNodesType,
validTriggerPosition,
} from '@lexical-core';
+import { fetchSnippetRaw } from '@queries/storage/snippets';
import {
+ $getNodeByKey,
$insertNodes,
+ $parseSerializedNode,
COMMAND_PRIORITY_CRITICAL,
COMMAND_PRIORITY_HIGH,
COMMAND_PRIORITY_LOW,
createCommand,
+ createEditor,
KEY_ENTER_COMMAND,
KEY_ESCAPE_COMMAND,
type LexicalCommand,
type LexicalEditor,
+ type LexicalNode,
} from 'lexical';
+import { nanoid } from 'nanoid';
+import { createLexicalWrapper } from '../../context/LexicalWrapperContext';
import type { MenuOperations } from '../../shared/inlineMenu';
+import {
+ editorStateAsMarkdown,
+ initializeEditorWithState,
+ setEditorStateFromMarkdown,
+} from '../../utils';
const TYPE_SNIPPET_SYMBOL_COMMAND: LexicalCommand<void> = createCommand(
'SNIPPET_SYMBOL_COMMAND'
@@ -35,11 +51,50 @@ export const CLOSE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> = createCommand(
export const REMOVE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> =
createCommand('REMOVE_SNIPPET_SEARCH_COMMAND');
+export const INSERT_SNIPPET_COMMAND: LexicalCommand<{
+ documentId: string;
+ sourceDocumentId?: string;
+}> = createCommand('INSERT_SNIPPET_COMMAND');
+
type SnippetsPluginProps = {
menu: MenuOperations;
peerIdValidator?: PeerIdValidator;
+ sourceDocumentId?: string;
};
+function $isSnippetSearchNode(
+ node: LexicalNode | null | undefined
+): node is InlineSearchNode {
+ return (
+ $isInlineSearchNode(node) &&
+ node.getTextContent().trim().charAt(0) === InlineSearchNodesType.Snippets
+ );
+}
+
+function $getActiveSnippetSearchNode(): InlineSearchNode | null {
+ for (const { node } of $dfsIterator()) {
+ if ($isSnippetSearchNode(node)) {
+ return node;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Fetch a snippet document's content and render it to internal markdown.
+ * Content lives in sync-service; a plugin-scoped markdown editor converts the
+ * serialized state to a markdown string the target editor can ingest.
+ */
+async function fetchSnippetMarkdown(
+ documentId: string,
+ extractionEditor: LexicalEditor
+): Promise<string> {
+ const rawState = await fetchSnippetRaw({ documentId });
+ initializeEditorWithState(extractionEditor, rawState);
+ return editorStateAsMarkdown(extractionEditor, 'internal');
+}
+
/**
* Registers the `;` trigger for the snippets menu. Typing `;` at a valid
* trigger position (start of line or after whitespace) opens a typeahead
@@ -68,6 +123,110 @@ function registerSnippetsPlugin(
}
const { menu } = props;
+ const parseEditor = createEditor({
+ namespace: 'snippet-parser',
+ editable: false,
+ nodes: [...Array.from(editor._nodes.values()).map((node) => node.klass)],
+ });
+ const { editor: extractionEditor, cleanup: cleanupExtractionEditor } =
+ createLexicalWrapper({
+ type: 'markdown',
+ namespace: 'snippet-markdown-extractor',
+ isInteractable: () => false,
+ });
+
+ function insertSnippet(payload: {
+ documentId: string;
+ sourceDocumentId?: string;
+ }) {
+ const sourceDocumentId = payload.sourceDocumentId ?? props.sourceDocumentId;
+ if (sourceDocumentId === payload.documentId) {
+ return;
+ }
+
+ const replaceAwaitNode = (
+ insertedAwaitNodeKey: string,
+ $createReplacement?: () => LexicalNode[] | null | undefined
+ ) => {
+ editor.update(
+ () => {
+ const target = $getNodeByKey(insertedAwaitNodeKey);
+ if (!$isAwaitNode(target)) {
+ return;
+ }
+
+ const nodes = $createReplacement?.() ?? [];
+ if (nodes.length === 0) {
+ const next = target.getNextSibling();
+ const prev = target.getPreviousSibling();
+ target.remove();
+ if (next) next.selectStart();
+ else if (prev) prev.selectEnd();
+ return;
+ }
+
+ const first = nodes[0]!;
+ target.replace(first);
+ let cursor = first;
+ for (let i = 1; i < nodes.length; i++) {
+ const next = nodes[i]!;
+ cursor.insertAfter(next);
+ cursor = next;
+ }
+ cursor.selectEnd();
+ },
+ { tag: HISTORY_MERGE_TAG }
+ );
+ };
+
+ const fetchAndReplaceSnippet = async (insertedAwaitNodeKey: string) => {
+ try {
+ const markdown = await fetchSnippetMarkdown(
+ payload.documentId,
+ extractionEditor
+ );
+ if (!markdown.trim()) {
+ replaceAwaitNode(insertedAwaitNodeKey);
+ return;
+ }
+
+ replaceAwaitNode(insertedAwaitNodeKey, () => {
+ // Same technique as the markdown paste plugin: parse the markdown with
+ // a throwaway editor restricted to the target editor's nodes, then
+ // insert the resulting nodes at the await placeholder.
+ setEditorStateFromMarkdown(parseEditor, markdown, 'both');
+ const state = parseEditor.getEditorState().toJSON();
+ return state.root.children.map((node) => $parseSerializedNode(node));
+ });
+ } catch (error) {
+ console.error('failed to insert snippet content', error);
+ replaceAwaitNode(insertedAwaitNodeKey);
+ }
+ };
+
+ const awaitId = nanoid(21);
+
+ menu.setSearchTerm('');
+ menu.setIsOpen(false);
+
+ editor.update(() => {
+ const insertionNode = $getActiveSnippetSearchNode();
+ if (!insertionNode) {
+ return;
+ }
+
+ insertionNode.selectEnd();
+ insertionNode.remove();
+ const awaitNode = $createAwaitNode({
+ awaitId,
+ text: 'Inserting snippet...',
+ inline: true,
+ });
+ const awaitNodeKey = awaitNode.getKey();
+ $insertNodes([awaitNode]);
+ void fetchAndReplaceSnippet(awaitNodeKey);
+ });
+ }
function typeSymbolCommand() {
// Checked per keystroke so the PostHog flag applies without a reload;
@@ -83,7 +242,7 @@ function registerSnippetsPlugin(
return false;
}
- return mergeRegister(
+ const cleanup = mergeRegister(
registerSymbolListener(),
// When you type ;
editor.registerCommand(
@@ -107,6 +266,14 @@ function registerSnippetsPlugin(
() => $removeInlineSearch(props.peerIdValidator),
COMMAND_PRIORITY_HIGH
),
+ editor.registerCommand(
+ INSERT_SNIPPET_COMMAND,
+ (payload) => {
+ void insertSnippet(payload);
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH
+ ),
// Menu ENTERS should not propagate to the editor.
editor.registerCommand(
KEY_ENTER_COMMAND,
@@ -135,6 +302,11 @@ function registerSnippetsPlugin(
)
)
);
+
+ return () => {
+ cleanup();
+ cleanupExtractionEditor();
+ };
}
export function snippetsPlugin(props: SnippetsPluginProps) {
diff --git a/js/app/packages/entity/src/extractors/entity-icon.tsx b/js/app/packages/entity/src/extractors/entity-icon.tsx
index 046abb27ce..faa5b48f4a 100644
--- a/js/app/packages/entity/src/extractors/entity-icon.tsx
+++ b/js/app/packages/entity/src/extractors/entity-icon.tsx
@@ -21,6 +21,7 @@ import {
isCallEntity,
isChannelEntity,
isChannelMessageEntity,
+ isSnippetEntity,
isTaskEntity,
} from '../types/entity';
@@ -110,6 +111,7 @@ export function EntityIcon(props: EntityIconProps) {
.when(isChannelEntity, ({ channelType }) => channelType)
.when(isChannelMessageEntity, ({ channelType }) => channelType)
.when(isTaskEntity, () => 'task')
+ .when(isSnippetEntity, () => 'snippet')
.with({ type: 'document' }, ({ fileType }) => {
return fileType ?? 'default';
})
diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.ts
index e7201e5ed7..f2a02913f3 100644
--- a/js/app/packages/entity/src/types/entity.ts
+++ b/js/app/packages/entity/src/types/entity.ts
@@ -359,12 +359,16 @@ const _isMarkdownEntity = (entity: EntityData): entity is MarkdownEntity => {
const _isPureDocumentEntity = (
entity: EntityData
): entity is DocumentEntity => {
- return entity.type === 'document' && entity.subType?.type !== 'task';
+ return (
+ entity.type === 'document' &&
+ entity.subType?.type !== 'task' &&
+ entity.subType?.type !== 'snippet'
+ );
};
export type EntityType = EntityData['type'];
-export type ExpandedEntityType = EntityType | 'task';
+export type ExpandedEntityType = EntityType | 'task' | 'snippet';
export type EntityWithProperties<T extends EntityData> = T & {
properties?: SoupProperty[];
diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.ts
index 10700b67d2..59d2fcd908 100644
--- a/js/app/packages/queries/storage/keys.ts
+++ b/js/app/packages/queries/storage/keys.ts
@@ -31,6 +31,12 @@ export const binaryDocumentKeys = createQueryKeys('binaryDocument', {
}),
});
+export const snippetRawKeys = createQueryKeys('snippetRaw', {
+ document: (documentId: string) => ({
+ queryKey: [documentId],
+ }),
+});
+
export const documentGithubPullRequestsKeys = createQueryKeys(
'documentGithubPullRequests',
{
diff --git a/js/app/packages/queries/storage/snippets.ts b/js/app/packages/queries/storage/snippets.ts
new file mode 100644
index 0000000000..6d948345c9
--- /dev/null
+++ b/js/app/packages/queries/storage/snippets.ts
@@ -0,0 +1,22 @@
+import { storageServiceClient } from '@service-storage/client';
+import type { SerializedEditorState } from 'lexical';
+import { queryClient } from '../client';
+import { snippetRawKeys } from './keys';
+
+type SnippetRawArgs = {
+ documentId: string;
+};
+
+function snippetRawQueryOptions(args: SnippetRawArgs) {
+ return {
+ queryKey: snippetRawKeys.document(args.documentId).queryKey,
+ queryFn: () => storageServiceClient.getSnippetRaw(args),
+ staleTime: 60 * 1000,
+ };
+}
+
+export function fetchSnippetRaw(
+ args: SnippetRawArgs
+): Promise<SerializedEditorState> {
+ return queryClient.fetchQuery(snippetRawQueryOptions(args));
+}
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index f92d9c6cab..9fa7b934ff 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -12,6 +12,7 @@ import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import {
SERVER_HOSTS,
SYNC_PERMISSION_TOKEN_DSS_HOST,
+ SYNC_SERVICE_HOSTS,
} from '@core/constant/servers';
import type { FetchError } from '@core/service';
import { cache } from '@core/util/cache';
@@ -20,11 +21,13 @@ import {
fetchWithToken,
} from '@core/util/fetchWithToken';
import { registerClient } from '@core/util/mockClient';
+import { isTauri } from '@core/util/platform';
import type { ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import { platformFetch } from 'core/util/platformFetch';
+import type { SerializedEditorState } from 'lexical';
import { err, ok, type Result } from 'neverthrow';
import type { ApiChannelWithLatest } from './channel-list-types';
import type {
@@ -149,6 +152,11 @@ function normalizeLocationResponseV3(response: LocationResponseV3) {
const MINUTES_BEFORE_PRESIGNED_EXPIRES = 14;
const dssHost = SERVER_HOSTS['document-storage-service'];
+const syncServiceWorkerHost = SYNC_SERVICE_HOSTS.worker;
+const syncOrigin =
+ import.meta.env.MODE === 'development'
+ ? 'https://dev.macro.com'
+ : 'https://macro.com';
export function dssFetch(
url: string,
@@ -167,6 +175,22 @@ export function dssFetch<T extends Record<string, any> = never>(
return fetchWithToken<T>(`${dssHost}${url}`, init);
}
+async function getDocumentPermissionToken(documentId: string): Promise<string> {
+ const token = await fetchWithToken<GetDocumentPermissionsTokenResponse>(
+ `${SYNC_PERMISSION_TOKEN_DSS_HOST}/documents/permissions_token/${documentId}`,
+ {
+ method: 'POST',
+ }
+ );
+
+ if (token.isErr()) {
+ console.error('Failed to create permission token:', token.error);
+ throw new Error('Failed to create permission token');
+ }
+
+ return token.value.token;
+}
+
type Success = {
id: string | null | undefined;
success: boolean;
@@ -1063,6 +1087,34 @@ export const storageServiceClient = {
return ok(response);
},
+ async getSnippetRaw(args: {
+ documentId: string;
+ }): Promise<SerializedEditorState> {
+ const token = await getDocumentPermissionToken(args.documentId);
+ const response = await platformFetch(
+ `${syncServiceWorkerHost}/document/${args.documentId}/raw`,
+ {
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`,
+ ...(isTauri() && { Origin: syncOrigin }),
+ },
+ method: 'GET',
+ }
+ );
+
+ if (!response.ok) {
+ try {
+ console.error('Failed to fetch raw snippet', await response.text());
+ } catch (_e) {
+ console.error('Failed to fetch raw snippet');
+ }
+ throw new Error('Failed to fetch raw snippet');
+ }
+
+ return await response.json();
+ },
+
/**
* Gets the team-share state of a document (resolved against the owner's team).
*/