Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(md): add slash command for inline doc creation (#7505)

Seamus08c97e299fe5
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 07966642d3..94f631a055 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -37,6 +37,7 @@ import { EventComposerSplit } from '@block-calendar/components/EventComposerSpli
import { ChannelCompose } from '@block-channel/component/Compose';
import { ComposeSkill } from '@block-md/component/ComposeSkill';
import { ComposeTask } from '@block-md/component/ComposeTask';
+import { ComposeDocument } from '@block-md/views/compose-document';
import NotFound from '@core/component/AccessErrorViews/NotFound';
import { LoadingBlock } from '@core/component/LoadingBlock';
import {
@@ -329,6 +330,11 @@ registerComponent('routine-compose', (params) => (
}
/>
));
+registerComponent('document-compose', (params) => {
+ usePageViewTracking('document-compose');
+ return <ComposeDocument {...params} />;
+});
+
registerComponent('task-compose', (params) => {
usePageViewTracking('task-compose');
return <ComposeTask {...params} />;
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index 27c007f22a..a484667e0e 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -181,6 +181,7 @@ function isTitleSelectionAtStart() {
}
export function ComposeTaskTitleEditor(props: {
+ placeholder?: string;
value: Accessor<string>;
onChange: (value: string) => void;
disabled: Accessor<boolean>;
@@ -316,7 +317,7 @@ export function ComposeTaskTitleEditor(props: {
/>
<Show when={showPlaceholder()}>
<div class="pointer-events-none absolute top-0 text-xl/7 font-medium text-ink-placeholder">
- New task
+ {props.placeholder ?? 'New task'}
</div>
</Show>
</div>
diff --git a/apps/web/src/features/block-md/queries/create-document-with-tags.test.ts b/apps/web/src/features/block-md/queries/create-document-with-tags.test.ts
new file mode 100644
index 0000000000..5afb1912b6
--- /dev/null
+++ b/apps/web/src/features/block-md/queries/create-document-with-tags.test.ts
@@ -0,0 +1,128 @@
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ updateTags: vi.fn(),
+ refresh: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@core/util/create', () => ({ createMarkdownFile: mocks.create }));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure },
+}));
+vi.mock('@queries/soup/cache', () => ({ refetchSoupEntity: mocks.refresh }));
+vi.mock('@service-properties/client', () => ({
+ propertiesServiceClient: {
+ bulkUpdateEntityPropertyOptions: mocks.updateTags,
+ },
+}));
+
+import { createDocumentWithTags } from './create-document-with-tags';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.create.mockResolvedValue('document-id');
+ mocks.updateTags.mockResolvedValue(ok({}));
+});
+
+describe('slash document creation', () => {
+ it('starts optimism before the request and creates normal markdown without task defaults', async () => {
+ const start = vi.fn();
+ const history = vi.fn();
+ mocks.create.mockImplementation(async () => {
+ expect(start).toHaveBeenCalledOnce();
+ return 'document-id';
+ });
+ expect(
+ await createDocumentWithTags(
+ 'Title',
+ '**Body**',
+ [],
+ new Map(),
+ history,
+ { onMutate: start }
+ )
+ ).toEqual({ documentId: 'document-id' });
+ expect(mocks.create).toHaveBeenCalledWith({
+ title: 'Title',
+ content: '**Body**',
+ source: 'document_composer',
+ });
+ expect(history).toHaveBeenCalledWith({
+ itemId: 'document-id',
+ itemType: 'document',
+ });
+ expect(mocks.updateTags).not.toHaveBeenCalled();
+ });
+
+ it('persists personal and team tags and refreshes the created entity', async () => {
+ await createDocumentWithTags(
+ 'Title',
+ 'Body',
+ [
+ [
+ 'personal',
+ { valueType: 'SELECT_STRING', values: ['tag-1', 'tag-2'] },
+ ],
+ ['team', { valueType: 'SELECT_STRING', values: ['tag-3'] }],
+ ['empty', { valueType: 'SELECT_STRING', values: [] }],
+ ],
+ new Map(),
+ vi.fn()
+ );
+ expect(mocks.updateTags).toHaveBeenCalledWith({
+ entity_type: 'DOCUMENT',
+ entity_id: 'document-id',
+ body: {
+ properties: [
+ {
+ property_id: 'personal',
+ add_option_ids: ['tag-1', 'tag-2'],
+ remove_option_ids: [],
+ },
+ {
+ property_id: 'team',
+ add_option_ids: ['tag-3'],
+ remove_option_ids: [],
+ },
+ ],
+ },
+ });
+ expect(mocks.refresh).toHaveBeenCalledWith('document-id', 'document', {
+ refreshGraphql: true,
+ });
+ });
+
+ it('does not save tags or history after failed creation', async () => {
+ mocks.create.mockResolvedValue(undefined);
+ const history = vi.fn();
+ expect(
+ await createDocumentWithTags('Title', '', [], new Map(), history)
+ ).toBeNull();
+ expect(history).not.toHaveBeenCalled();
+ expect(mocks.updateTags).not.toHaveBeenCalled();
+ });
+
+ it.each(['result', 'throw'])(
+ 'keeps the created document when tag saving fails via %s',
+ async (failure) => {
+ if (failure === 'result')
+ mocks.updateTags.mockResolvedValue(err(new Error('offline')));
+ else mocks.updateTags.mockRejectedValue(new Error('offline'));
+ expect(
+ await createDocumentWithTags(
+ 'Title',
+ '',
+ [['personal', { valueType: 'SELECT_STRING', values: ['tag-1'] }]],
+ new Map(),
+ vi.fn()
+ )
+ ).toEqual({ documentId: 'document-id' });
+ expect(mocks.failure).toHaveBeenCalledWith(
+ expect.stringContaining('Document created, but tags')
+ );
+ expect(mocks.create).toHaveBeenCalledOnce();
+ }
+ );
+});
diff --git a/apps/web/src/features/block-md/queries/create-document-with-tags.ts b/apps/web/src/features/block-md/queries/create-document-with-tags.ts
new file mode 100644
index 0000000000..e18a90e311
--- /dev/null
+++ b/apps/web/src/features/block-md/queries/create-document-with-tags.ts
@@ -0,0 +1,92 @@
+import { toast } from '@core/component/Toast/Toast';
+import { createMarkdownFile } from '@core/util/create';
+import { propertyValueToApi } from '@property/api/converters';
+import type { PropertyApiValues } from '@property/types';
+import { refetchSoupEntity } from '@queries/soup/cache';
+import { propertiesServiceClient } from '@service-properties/client';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';
+
+/**
+ * Make a markdown document and apply any composer tags afterwards.
+ * Create → Document still uses {@link createMarkdownFile} directly.
+ */
+export async function createDocumentWithTags(
+ documentTitle: string,
+ documentContent: string,
+ properties: Array<[string, PropertyApiValues]>,
+ definitions: Map<
+ string,
+ PropertyDefinition | PropertyDefinitionDetailResponse
+ >,
+ upsertToHistory: (params: { itemId: string; itemType: 'document' }) => void,
+ options?: {
+ onMutate?: () => void;
+ }
+) {
+ options?.onMutate?.();
+
+ const documentId = await createMarkdownFile({
+ title: documentTitle,
+ content: documentContent,
+ source: 'document_composer',
+ });
+
+ if (!documentId) {
+ toast.failure('Failed to create Document');
+ return null;
+ }
+
+ upsertToHistory({
+ itemId: documentId,
+ itemType: 'document',
+ });
+
+ const tagUpdates = properties.flatMap(([id, value]) => {
+ const definition = definitions.get(id);
+ const isMultiSelect = definition
+ ? 'is_multi_select' in definition
+ ? definition.is_multi_select
+ : definition.isMultiSelect
+ : true;
+ const apiValue = propertyValueToApi(value, isMultiSelect);
+ if (apiValue === null) return [];
+ if (
+ apiValue.type !== 'multi_select_option' &&
+ apiValue.type !== 'select_option'
+ ) {
+ return [];
+ }
+ const optionIds =
+ apiValue.type === 'multi_select_option'
+ ? apiValue.option_ids
+ : [apiValue.option_id];
+ if (optionIds.length === 0) return [];
+ return [
+ {
+ property_id: id,
+ add_option_ids: optionIds,
+ remove_option_ids: [],
+ },
+ ];
+ });
+
+ if (tagUpdates.length > 0) {
+ try {
+ const result =
+ await propertiesServiceClient.bulkUpdateEntityPropertyOptions({
+ entity_type: 'DOCUMENT',
+ entity_id: documentId,
+ body: { properties: tagUpdates },
+ });
+ if (result.isErr()) throw result.error;
+ refetchSoupEntity(documentId, 'document', { refreshGraphql: true });
+ } catch {
+ toast.failure(
+ 'Document created, but tags could not be saved. Add them from the document.'
+ );
+ }
+ }
+
+ return { documentId };
+}
diff --git a/apps/web/src/features/block-md/util/documentComposerProperties.ts b/apps/web/src/features/block-md/util/documentComposerProperties.ts
new file mode 100644
index 0000000000..ab2d7f93d8
--- /dev/null
+++ b/apps/web/src/features/block-md/util/documentComposerProperties.ts
@@ -0,0 +1,57 @@
+import { useLocalDocTags } from '@property/tags';
+import type { PropertyApiValues } from '@property/types';
+import { useTagsQuery } from '@queries/properties/tags';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';
+import { createStore, reconcile, unwrap } from 'solid-js/store';
+
+/** Local tag state for the slash-command document composer. No system pills. */
+export function createDocumentComposerTags(
+ initialValues: Record<string, PropertyApiValues> = {}
+) {
+ const [propertyValues, setPropertyValues] =
+ createStore<Record<string, PropertyApiValues>>(initialValues);
+
+ const tagsQuery = useTagsQuery();
+
+ const composerTags = useLocalDocTags(
+ (definitionId) => {
+ const value = propertyValues[definitionId];
+ return value?.valueType === 'SELECT_STRING' && value.values
+ ? value.values
+ : [];
+ },
+ (definition, optionIds) => {
+ setPropertyValues(definition.id, {
+ valueType: 'SELECT_STRING',
+ values: optionIds,
+ });
+ }
+ );
+
+ const clearComposerTags = () => {
+ setPropertyValues(reconcile({}));
+ };
+
+ const createDefinitions = () => {
+ const map = new Map<
+ PropertyDefinition['id'],
+ PropertyDefinition | PropertyDefinitionDetailResponse
+ >();
+ for (const tagSet of tagsQuery.isSuccess ? tagsQuery.data : []) {
+ if (tagSet.definition) {
+ map.set(tagSet.definition.id, tagSet.definition);
+ }
+ }
+ return map;
+ };
+
+ return {
+ propertyValues,
+ setPropertyValues,
+ composerTags,
+ clearComposerTags,
+ tagEntries: () => structuredClone(Object.entries(unwrap(propertyValues))),
+ createDefinitions,
+ };
+}
diff --git a/apps/web/src/features/block-md/views/compose-document.tsx b/apps/web/src/features/block-md/views/compose-document.tsx
new file mode 100644
index 0000000000..f9c5cf7f19
--- /dev/null
+++ b/apps/web/src/features/block-md/views/compose-document.tsx
@@ -0,0 +1,232 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import { toast } from '@core/component/Toast/Toast';
+import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
+import ArrowsOutIcon from '@phosphor/arrows-out.svg';
+import XIcon from '@phosphor/x.svg';
+import { InlineTagsPill } from '@property/tags';
+import type { PropertyApiValues } from '@property/types';
+import { useUpsertToHistoryMutation } from '@queries/history/history';
+import { Button, EntityComposer, Scroll } from '@ui';
+import { createSignal, onMount, Show, Suspense } from 'solid-js';
+import type { ComposeTaskSuccess } from '../component/ComposeTask';
+import { ComposeTaskTitleEditor } from '../component/ComposeTask';
+import { createDocumentWithTags } from '../queries/create-document-with-tags';
+import { createDocumentComposerTags } from '../util/documentComposerProperties';
+
+export interface ComposeDocumentProps {
+ initialTitle?: string;
+ initialContent?: string;
+ initialTags?: Record<string, PropertyApiValues>;
+ onCreateStart?: (init: { title: string; content: string }) => void;
+ onCreateFailure?: () => void;
+ onSuccess?: (result: ComposeTaskSuccess) => void | Promise<void>;
+}
+
+/** Slash-command composer; the main Create → Document entry point stays direct. */
+export function ComposeDocument(props: ComposeDocumentProps) {
+ const panel = useSplitPanelOrThrow();
+ const { popoverSplit, openWithSplit } = useSplitLayout();
+ const [title, setTitle] = createSignal(props.initialTitle ?? '');
+ const [content, setContent] = createSignal(props.initialContent ?? '');
+ const [container, setContainer] = createSignal<HTMLDivElement>();
+ const [isCreating, setIsCreating] = createSignal(false);
+ const [attachHotkeys, scope] = useHotkeyDOMScope('compose-document', true);
+ const tags = createDocumentComposerTags(props.initialTags);
+ const history = useUpsertToHistoryMutation();
+ const portalScope = () => (panel.handle.isPopover() ? 'local' : 'block');
+
+ const submit = async (expand = false) => {
+ const documentTitle = title().trim() || (expand ? 'New Note' : '');
+ if (isCreating() || !documentTitle) return;
+ const documentContent = content().trim();
+ const entries = tags.tagEntries();
+ const definitions = tags.createDefinitions();
+ setIsCreating(true);
+ let split: ReturnType<typeof openWithSplit>['split'];
+
+ // Keep the original insertion callbacks when retrying a failed request.
+ const reopen = () => {
+ split?.goBack();
+ props.onCreateFailure?.();
+ popoverSplit({
+ type: 'component',
+ id: 'document-compose',
+ params: {
+ ...props,
+ initialTitle: documentTitle,
+ initialContent: documentContent,
+ initialTags: Object.fromEntries(entries),
+ },
+ });
+ };
+
+ let created: Awaited<ReturnType<typeof createDocumentWithTags>>;
+ try {
+ created = await createDocumentWithTags(
+ documentTitle,
+ documentContent,
+ entries,
+ definitions,
+ (params) => history.mutate(params),
+ {
+ onMutate: () => {
+ panel.handle.close();
+ props.onCreateStart?.({
+ title: documentTitle,
+ content: documentContent,
+ });
+ if (expand) {
+ split = openWithSplit(
+ { type: 'component', id: 'loading' },
+ { referredFrom: 'launcher', preferNewSplit: true }
+ ).split;
+ }
+ },
+ }
+ );
+ } catch {
+ toast.failure('Failed to create Document');
+ reopen();
+ return;
+ }
+ if (!created) {
+ reopen();
+ return;
+ }
+ split?.replace({
+ next: { type: 'md', id: created.documentId },
+ mergeHistory: true,
+ referredFrom: 'launcher',
+ });
+ await props.onSuccess?.({
+ documentId: created.documentId,
+ title: documentTitle,
+ content: documentContent,
+ });
+ };
+
+ let submitButton: HTMLButtonElement | undefined;
+ const editorConfig = buildConfig('markdown')
+ .withAppLinkResolver(useMacroMentionLinkResolver())
+ .withMentions()
+ .withTags({
+ applyTargetLabel: 'Document',
+ isApplied: (tag) => tags.composerTags.isApplied(tag.optionId),
+ onCreate: (tag) => {
+ void tags.composerTags.applyTag(tag.scope, tag.optionId);
+ },
+ })
+ .withEmojis()
+ .withActions()
+ .withCode()
+ .withMedia({ fileDrop: true })
+ .withSelectionData()
+ .withFloatingFormatMenu()
+ .withHistory()
+ .onChange(setContent)
+ .onFocusLeave({
+ onStart: () => titleRoot?.focus(),
+ onEnd: () => submitButton?.focus(),
+ })
+ .onEscape(() => {
+ container()?.focus();
+ return true;
+ });
+ const editor = editorConfig.buildHandle().lexical;
+ let titleRoot: HTMLDivElement | undefined;
+
+ onMount(() => {
+ panel.handle.setDisplayName('New document');
+ const root = container();
+ if (root) attachHotkeys(root);
+ });
+ registerHotkey({
+ hotkey: 'cmd+enter',
+ scopeId: scope,
+ description: 'Create document',
+ keyDownHandler: () => {
+ void submit();
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ return (
+ <EntityComposer.Root tabIndex={-1} ref={setContainer}>
+ <EntityComposer.Header>
+ <div class="flex-1 flex items-center">
+ <Show when={panel.handle.isPopover()}>
+ <Button
+ onMouseDown={() => void submit(true)}
+ disabled={isCreating()}
+ tabIndex={-1}
+ tooltip="Continue editing in split"
+ size="icon-composer"
+ >
+ <ArrowsOutIcon />
+ </Button>
+ </Show>
+ </div>
+ <Button
+ onClick={() => panel.handle.close()}
+ tabIndex={-1}
+ tooltip="Close"
+ size="icon-composer"
+ >
+ <XIcon />
+ </Button>
+ </EntityComposer.Header>
+ <EntityComposer.Main>
+ <EntityComposer.Title>
+ <ComposeTaskTitleEditor
+ placeholder="New document"
+ value={title}
+ onChange={setTitle}
+ disabled={isCreating}
+ bodyEditor={() => editor}
+ containerRef={container}
+ onUserInput={() => {}}
+ onTagSelected={(tag) => {
+ void tags.composerTags.applyTag(tag.scope, tag.optionId);
+ }}
+ onDeleteTagsAtStart={() => false}
+ portalScope={portalScope()}
+ ref={(root) => {
+ titleRoot = root;
+ }}
+ />
+ </EntityComposer.Title>
+ <EntityComposer.Body>
+ <Scroll>
+ <MarkdownShell
+ config={editorConfig}
+ initialValue={props.initialContent || undefined}
+ placeholder="Add content..."
+ portalScope={portalScope()}
+ />
+ </Scroll>
+ </EntityComposer.Body>
+ </EntityComposer.Main>
+ <EntityComposer.Footer class="items-center">
+ <Suspense fallback={<div class="h-7" />}>
+ <InlineTagsPill docTags={tags.composerTags} showPlaceholder />
+ </Suspense>
+ <EntityComposer.Submit
+ ref={(button) => {
+ submitButton = button;
+ }}
+ variant="strong"
+ onClick={() => void submit()}
+ disabled={!title().trim() || isCreating()}
+ hasContent={!!title().trim()}
+ >
+ Create Document
+ </EntityComposer.Submit>
+ </EntityComposer.Footer>
+ </EntityComposer.Root>
+ );
+}
diff --git a/apps/web/src/features/database-query/views/live-question.test.tsx b/apps/web/src/features/database-query/views/live-question.test.tsx
index 47dddfd334..cdcd5960eb 100644
--- a/apps/web/src/features/database-query/views/live-question.test.tsx
+++ b/apps/web/src/features/database-query/views/live-question.test.tsx
@@ -1,4 +1,5 @@
import { showDatabaseSql } from '@core/constant/featureFlags';
+import { Dialog } from '@kobalte/core/dialog';
import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -108,6 +109,40 @@ describe('live database charts', () => {
});
describe('answer titles', () => {
+ it('keeps a new question focused inside a modal composer until dismissed', async () => {
+ const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+ const discard = vi.fn();
+ const rendered = render(() => (
+ <Dialog open>
+ <Dialog.Portal>
+ <Dialog.Content class="portal-scope">
+ <Dialog.Title>Document composer</Dialog.Title>
+ <PlainAnswerDisplay>
+ <LiveQuestion
+ source={{ queryId: '', prompt: '', displayMode: 'scalar' }}
+ loading={false}
+ onRefresh={vi.fn()}
+ onDiscard={discard}
+ editor={() => <textarea aria-label="Ask your database" />}
+ />
+ </PlainAnswerDisplay>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog>
+ ));
+ const field = await screen.findByLabelText('Ask your database');
+ await waitFor(() => expect(document.activeElement).toBe(field));
+ expect(field.closest('.portal-scope')).not.toBeNull();
+ await fireEvent.input(field, { target: { value: 'How many tasks?' } });
+ expect(discard).not.toHaveBeenCalled();
+ await fireEvent.click(
+ screen.getByRole('button', { name: 'Close database answer' })
+ );
+ expect(discard).toHaveBeenCalledOnce();
+ rendered.unmount();
+ scrollTo.mockRestore();
+ });
+
it.each(['scalar', 'table'] as const)(
'renames a %s answer inline without changing its question',
async (displayMode) => {
diff --git a/apps/web/src/features/database-query/views/live-question.tsx b/apps/web/src/features/database-query/views/live-question.tsx
index 42a1007066..afe6152453 100644
--- a/apps/web/src/features/database-query/views/live-question.tsx
+++ b/apps/web/src/features/database-query/views/live-question.tsx
@@ -1,3 +1,4 @@
+import { ScopedPortal } from '@core/component/ScopedPortal';
import { isFeatureEnabled, showDatabaseSql } from '@core/constant/featureFlags';
import { Popover } from '@kobalte/core/popover';
import LightningIcon from '@phosphor/lightning.svg';
@@ -204,7 +205,7 @@ export function LiveQuestion(props: {
</ResizableAnswer>
</div>
</Show>
- <Popover.Portal>
+ <ScopedPortal scope="local">
<Popover.Content
ref={content}
class="z-action-menu w-[min(440px,calc(100vw-2rem))] max-h-[min(720px,var(--kb-popper-content-available-height,100dvh),calc(100dvh-1rem))] overflow-auto rounded-xl border border-edge-muted bg-panel text-ink shadow-xl"
@@ -267,7 +268,7 @@ export function LiveQuestion(props: {
{props.editor?.(() => setOpen(false))}
</Show>
</Popover.Content>
- </Popover.Portal>
+ </ScopedPortal>
</Popover>
);
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
index d90df4a798..d1ace0f072 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
@@ -20,6 +20,7 @@ import {
} from '@macro-inc/lexical-core';
import CheckSquare from '@phosphor/check-square.svg';
import CodeBlock from '@phosphor/code-block.svg';
+import FileText from '@phosphor/file-text.svg';
import VideoIcon from '@phosphor/file-video.svg';
import MathIcon from '@phosphor/function.svg';
import TableIcon from '@phosphor/grid-four.svg';
@@ -51,7 +52,7 @@ import { NODE_TRANSFORM } from '../node-transform';
import { TRY_INSERT_TABLE_PICKER_COMMAND } from '../tables';
import { type Action, ActionCategory, type ActionContext } from './types';
-async function trackSlashTaskMention(
+async function trackSlashCreatedMention(
context: ActionContext | undefined,
documentId: string
) {
@@ -67,6 +68,64 @@ async function trackSlashTaskMention(
return await trackMention(context.sourceDocumentId, 'document', documentId);
}
+function openCreationComposer(
+ editor: LexicalEditor,
+ context: ActionContext | undefined,
+ kind: 'task' | 'document'
+) {
+ const splitManager = globalSplitManager();
+ if (!splitManager) return;
+ const awaitId = nanoid(21);
+ let placeholderInserted = false;
+ splitManager.createPopoverSplit({
+ content: {
+ type: 'component',
+ id: kind === 'task' ? 'task-compose' : 'document-compose',
+ params: {
+ onCreateStart: ({ title }: { title: string }) => {
+ const handled = editor.dispatchCommand(INSERT_AWAIT_NODE_COMMAND, {
+ awaitId,
+ text: `Creating ${title}`,
+ });
+ placeholderInserted = handled;
+ },
+ onCreateFailure: () => {
+ if (!placeholderInserted) return;
+ editor.dispatchCommand(REPLACE_AWAIT_NODE_COMMAND, { awaitId });
+ placeholderInserted = false;
+ },
+ onSuccess: async (result: ComposeTaskSuccess) => {
+ const mentionUuid = await trackSlashCreatedMention(
+ context,
+ result.documentId
+ );
+ if (placeholderInserted) {
+ editor.dispatchCommand(REPLACE_AWAIT_NODE_COMMAND, {
+ awaitId,
+ $createReplacement: () =>
+ $createDocumentMentionNode({
+ documentId: result.documentId,
+ documentName: result.title,
+ blockName: kind === 'task' ? 'task' : 'md',
+ createdAt: Date.now(),
+ mentionUuid,
+ }),
+ });
+ placeholderInserted = false;
+ return;
+ }
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: result.documentId,
+ documentName: result.title,
+ blockName: kind === 'task' ? 'task' : 'md',
+ mentionUuid,
+ });
+ },
+ },
+ },
+ });
+}
+
export const ACTIONS: Action[] = [
{
id: 'database-query',
@@ -210,62 +269,17 @@ export const ACTIONS: Action[] = [
keywords: ['task', 'todo', 'create'],
category: ActionCategory.ELEMENT,
icon: CheckSquare,
- action: (editor: LexicalEditor, context?: ActionContext) => {
- const splitManager = globalSplitManager();
- if (!splitManager) return;
- const awaitId = nanoid(21);
- let placeholderInserted = false;
- splitManager.createPopoverSplit({
- content: {
- type: 'component',
- id: 'task-compose',
- params: {
- onCreateStart: ({ title }: { title: string }) => {
- const handled = editor.dispatchCommand(
- INSERT_AWAIT_NODE_COMMAND,
- {
- awaitId,
- text: `Creating ${title}`,
- }
- );
- placeholderInserted = handled;
- },
- onCreateFailure: () => {
- if (!placeholderInserted) return;
- editor.dispatchCommand(REPLACE_AWAIT_NODE_COMMAND, { awaitId });
- placeholderInserted = false;
- },
- onSuccess: async (result: ComposeTaskSuccess) => {
- const mentionUuid = await trackSlashTaskMention(
- context,
- result.documentId
- );
- if (placeholderInserted) {
- editor.dispatchCommand(REPLACE_AWAIT_NODE_COMMAND, {
- awaitId,
- $createReplacement: () =>
- $createDocumentMentionNode({
- documentId: result.documentId,
- documentName: result.title,
- blockName: 'task',
- createdAt: Date.now(),
- mentionUuid,
- }),
- });
- placeholderInserted = false;
- return;
- }
- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
- documentId: result.documentId,
- documentName: result.title,
- blockName: 'task',
- mentionUuid,
- });
- },
- },
- },
- });
- },
+ action: (editor, context) => openCreationComposer(editor, context, 'task'),
+ dependencies: [DocumentMentionNode, AwaitNode],
+ },
+ {
+ id: 'document',
+ name: 'Document',
+ keywords: ['document', 'doc', 'markdown', 'create'],
+ category: ActionCategory.ELEMENT,
+ icon: FileText,
+ action: (editor, context) =>
+ openCreationComposer(editor, context, 'document'),
dependencies: [DocumentMentionNode, AwaitNode],
},
{
diff --git a/apps/web/src/lib/core/component/ScopedPortal.tsx b/apps/web/src/lib/core/component/ScopedPortal.tsx
index 71fcc8d7cb..13c27f8832 100644
--- a/apps/web/src/lib/core/component/ScopedPortal.tsx
+++ b/apps/web/src/lib/core/component/ScopedPortal.tsx
@@ -1,7 +1,8 @@
import { getSplitPanelRef } from '@components/app/split-layout/layoutUtils';
import { isInBlock } from '@core/block';
import { blockElementSignal } from '@core/signal/blockElement';
-import type { ComponentProps } from 'solid-js';
+import { mergeRefs } from '@solid-primitives/refs';
+import { type ComponentProps, splitProps } from 'solid-js';
import { Portal, Show } from 'solid-js/web';
export type PortalScope = 'local' | 'block' | 'global' | 'split';
@@ -20,6 +21,7 @@ export function ScopedPortal(
show?: boolean;
}
) {
+ const [local, portalProps] = splitProps(props, ['ref']);
let searchRef!: HTMLDivElement;
const mountRef = () => {
@@ -45,7 +47,17 @@ export function ScopedPortal(
return (
<Show when={props.show !== false}>
<div class="hidden" ref={searchRef} />
- <Portal mount={mountRef()}>{props.children}</Portal>
+ <Portal
+ {...portalProps}
+ mount={mountRef()}
+ ref={mergeRefs(local.ref, (element) => {
+ // A local overlay must not add a flex/grid item (and an extra gap)
+ // to its host. The positioned children still own their layout.
+ if (props.scope === 'local') element.style.display = 'contents';
+ })}
+ >
+ {props.children}
+ </Portal>
</Show>
);
}
diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.md
index 0abd6514e3..915aeb8f9d 100644
--- a/docs/AGENT_GUIDE/databases.md
+++ b/docs/AGENT_GUIDE/databases.md
@@ -378,7 +378,8 @@ a scalar answer, or compatible bar, line, area, scatter, and pie charts. A saved
offers **Open view**, which opens that database/table and selects the created view.
The same tools are exposed to agent sessions through the Macro MCP server.
-In a document or channel composer, `/database` → **Database** opens the question box with the AI prompt focused
+In a document, channel composer, or the task/document creation composer,
+`/database` → **Database** opens the question box with the AI prompt focused
immediately. The empty input rotates through example questions; a selected database
uses its actual table and column names. Typing hides these hints, and reduced-motion
preferences keep them static. Use the searchable source picker below the question to
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 255720084c..cc15636076 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -27,6 +27,24 @@ deleting the shared property definition). Pins are saved with the document.
Markdown code blocks have a **Copy Code** button in both editable and read-only
views. Successful copies briefly animate the icon to a solid green check-circle;
they do not show a success toast.
+## Create a document from an editor
+
+Type `/document` in a Markdown slash menu and choose **Document**. The popover
+has a **New document** title, a Markdown body, and a **Tags** pill. It starts
+without task property pills. Tags can also be applied with `#` in the title or
+body. Tags sit on the left of the bottom row beside **Create Document**.
+Enter in the title moves into the body. Opening mentions keeps the composer at
+the same height.
+
+Choose **Create Document** or press Cmd/Ctrl+Enter. The composer closes and the
+source editor shows a creation placeholder at the insertion point, then replaces
+it with the new document mention. If creation fails, the placeholder is removed
+and the composer reopens with the title, body, and tags for retry.
+**Continue editing in split** creates the document with the current draft and
+tags, opens it in an adjacent split, and inserts its mention in the source editor.
+An empty title uses **New Note** when expanding.
+**Create → Document** continues to open a document directly.
+
## Markdown outline
On desktop, Markdown documents with at least three headings show a tick rail in