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(markdown): create a task from a highlighted snippet (#8672)

gbirman3891a9799787
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index 6f46ff3db5..3a0286fa66 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -61,6 +61,7 @@ import {
} from '../util/taskComposerProperties';
import {
clearTaskComposerDraft,
+ createTaskComposerLinkInSource,
createTaskComposerSharing,
loadTaskComposerDraft,
saveTaskComposerDraft,
@@ -125,6 +126,14 @@ export interface ComposeTaskProps {
* Pairs with onCreateStart for placeholder cleanup.
*/
onCreateFailure?: () => void;
+ /**
+ * Offers a toggle that links the created task back where it was composed
+ * from; `insert` runs after creation while the toggle is on.
+ */
+ linkInSource?: {
+ label: string;
+ insert: (result: ComposeTaskSuccess) => void;
+ };
}
export function ComposeTask(props: ComposeTaskProps) {
@@ -231,6 +240,11 @@ export function ComposeTask(props: ComposeTaskProps) {
const [shareWithTeam, setShareWithTeam] = createTaskComposerSharing(
recovered?.shareWithTeam
);
+ const [linkInSourceEnabled, setLinkInSourceEnabled] =
+ createTaskComposerLinkInSource();
+ const linkCreatedTask = (result: ComposeTaskSuccess) => {
+ if (linkInSourceEnabled()) props.linkInSource?.insert(result);
+ };
const [errorMessage, setErrorMessage] = createSignal<string>('');
const userTeams = useUserTeamsQuery();
const team = () =>
@@ -578,6 +592,7 @@ export function ComposeTask(props: ComposeTaskProps) {
'compose-task'
);
}
+ linkCreatedTask({ documentId, title: taskTitle, content: taskContent });
props.onCreateTask?.(taskTitle, taskContent);
};
const handleCreateTask = () => createTask(false);
@@ -925,6 +940,16 @@ export function ComposeTask(props: ComposeTaskProps) {
)}
</Show>
<div class="ml-auto flex items-center gap-3">
+ <Show when={props.linkInSource}>
+ {(linkInSource) => (
+ <ToggleSwitch
+ labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"
+ onChange={setLinkInSourceEnabled}
+ checked={linkInSourceEnabled()}
+ label={linkInSource().label}
+ />
+ )}
+ </Show>
<ToggleSwitch
labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"
onChange={setCreateMore}
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index a0673aa947..fb5d04a5e3 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -1,4 +1,5 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { globalSplitManager } from '@app/signal/splitLayout';
import { applyAiOps } from '@block-md/ai-edit/applyAiOps';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
@@ -20,7 +21,8 @@ import {
registerRootEventListener,
} from '@core/component/LexicalMarkdown/plugins';
import {
- $canConvertCheckboxesToTasks,
+ $extractTitleFromNode,
+ $getSelectedCheckboxes,
CONVERT_CHECKBOXES_TO_TASKS,
isCheckboxToTaskPluginEnabled,
} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task';
@@ -32,6 +34,7 @@ import {
$getLocationUrl,
$getSelectionLocation,
type PersistentLocation,
+ serializePersistentLocation,
} from '@core/component/LexicalMarkdown/plugins/location/locationPlugin';
import {
popupPlugin,
@@ -49,6 +52,7 @@ import {
readNativePasteboardText,
setNativeEditMenuSuppressed,
} from '@core/mobile/nativeEditMenu';
+import { trackMention, untrackMention } from '@core/signal/mention';
import { debouncedDependent } from '@core/util/debounce';
import { fireAndForget } from '@core/util/fireAndForget';
import { getScrollParentElement } from '@core/util/scrollParent';
@@ -59,12 +63,17 @@ import ChatTeardrop from '@icon/system/regular/chat-teardrop.svg';
import CheckSquareIcon from '@icon/system/regular/check-square.svg?component-solid';
import GridIcon from '@icon/system/regular/grid-four.svg';
import LinkIcon from '@icon/system/regular/link.svg?component-solid';
-import type { NodeIdMappings } from '@macro-inc/lexical-core';
+import {
+ $createDocumentMentionNode,
+ buildMentionMarkdownString,
+ type NodeIdMappings,
+} from '@macro-inc/lexical-core';
import { $getId } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
import { Telemetry } from '@macro-inc/observability';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import { Button, SendButton, Toolbar } from '@ui';
import {
+ $createTextNode,
$getSelection,
$isRangeSelection,
$setSelection,
@@ -83,22 +92,28 @@ import {
useContext,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
+import { URL_PARAMS } from '../constants';
import { useMarkdownDocument } from '../context/markdown-document-context';
import {
cancelAiEdit,
hasActiveAiEdit,
requestAiEditWithToast,
} from '../queries/ai-edit';
+import {
+ $insertAtSavedPoint,
+ type SavedPoint,
+} from '../util/insertAtSavedPoint';
+import type { ComposeTaskSuccess } from './ComposeTask';
import { FormatTools } from './FormatTools';
import { TouchSelectionToolbar } from './TouchSelectionToolbar';
const MENU_ID = 'markdown-popup';
-
export function MarkdownPopup(props: {
highlightLayerRef: HTMLDivElement;
lexicalMapping: NodeIdMappings;
}) {
- const { documentId, permissions, state } = useMarkdownDocument();
+ const { documentId, permissions, state, persistedName, fallbackName } =
+ useMarkdownDocument();
const { canEdit, canComment } = permissions;
const { comments: commentState, setCommentState } = state;
const blockId = documentId();
@@ -191,11 +206,11 @@ export function MarkdownPopup(props: {
const currentUserId = useUserId();
const [locationCopied, setLocationCopied] = createSignal(false);
- const [isConverting, setIsConverting] = createSignal(false);
- const [hasCheckboxes, setHasCheckboxes] = createSignal(false);
const [convertibleListKey, setConvertibleListKey] = createSignal<
string | null
>(null);
+ const [selectedCheckboxCount, setSelectedCheckboxCount] = createSignal(0);
+ const [isConverting, setIsConverting] = createSignal(false);
const _selectedText = () => selection()?.text ?? undefined;
const _selectedNodesText = () => selection()?.nodeText ?? undefined;
@@ -205,10 +220,18 @@ export function MarkdownPopup(props: {
on([selection], () => {
setLocationCopied(false);
editor.read(() => {
- setHasCheckboxes($canConvertCheckboxesToTasks());
setConvertibleListKey(
$getConvertibleListFromSelection()?.getKey() ?? null
);
+ const lexicalSelection = $getSelection();
+ // Empty items create no task, so they don't count toward "N tasks".
+ setSelectedCheckboxCount(
+ $isRangeSelection(lexicalSelection)
+ ? $getSelectedCheckboxes(lexicalSelection).filter(
+ $extractTitleFromNode
+ ).length
+ : 0
+ );
});
})
);
@@ -367,13 +390,42 @@ export function MarkdownPopup(props: {
};
// Selection actions shared by the desktop and touch toolbars.
- const shouldShowCheckboxToTaskButton = () => {
- return Boolean(
- isCheckboxToTaskPluginEnabled(editor) &&
- hasCheckboxes() &&
- canEdit() &&
- currentUserId()
- );
+ const shouldShowCreateTaskButton = () =>
+ Boolean(currentUserId() && selection()?.text);
+
+ // A selection spanning several checklist items makes one task per item.
+ const convertsCheckboxes = () =>
+ canEdit() &&
+ isCheckboxToTaskPluginEnabled(editor) &&
+ selectedCheckboxCount() > 1;
+
+ const createTaskLabel = () => {
+ if (isConverting()) return 'Converting...';
+ return convertsCheckboxes() ? `${selectedCheckboxCount()} tasks` : 'Task';
+ };
+
+ const handleConvertToTasks = () => {
+ const lexicalSelection = editor.read($getSelection);
+ if (!$isRangeSelection(lexicalSelection)) return;
+ setIsConverting(true);
+ editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {
+ selection: lexicalSelection,
+ onComplete: (results) => {
+ setIsConverting(false);
+ const created = results.filter((result) => result.isOk()).length;
+ if (created > 0) {
+ toast.success(`Created ${created} task${created > 1 ? 's' : ''}`);
+ }
+ if (
+ results.some(
+ (result) => result.isErr() && result.error.tag !== 'EmptyCheckbox'
+ )
+ ) {
+ toast.failure('Some checklist items could not become tasks');
+ }
+ setPopupVisible(false);
+ },
+ });
};
const shouldShowTableButton = () =>
@@ -382,27 +434,106 @@ export function MarkdownPopup(props: {
const shouldShowEditWithAiButton = () =>
inlineAiEditing().enabled && canEdit();
- const handleConvertToTasks = () => {
- const currentSelection = selection();
- const userId = currentUserId();
- if (!currentSelection?.lexicalSelection || !userId) {
+ /** Resolves to the point after the inserted mention, or null if it failed. */
+ const insertTaskMention = async (
+ point: SavedPoint,
+ task: { documentId: string; title: string }
+ ): Promise<SavedPoint | null> => {
+ // Tracking only records the backlink; the mention still links without it.
+ let mentionUuid: string | undefined;
+ try {
+ mentionUuid = await trackMention(blockId, 'document', task.documentId);
+ } catch (error) {
+ Telemetry.error(error, { surface: 'markdown-create-task' });
+ }
+ let next: SavedPoint | null = null;
+ editor.update(
+ () => {
+ next = $insertAtSavedPoint(point, [
+ $createTextNode(' '),
+ $createDocumentMentionNode({
+ documentId: task.documentId,
+ documentName: task.title,
+ blockName: 'task',
+ createdAt: Date.now(),
+ mentionUuid,
+ }),
+ ]);
+ },
+ { discrete: true }
+ );
+ if (next) return next;
+ toast.failure('Could not link the task in this document');
+ if (mentionUuid) {
+ fireAndForget(
+ untrackMention(blockId, mentionUuid, 'document'),
+ 'markdown-create-task'
+ );
+ }
+ return null;
+ };
+
+ // Opens the task composer on the highlighted snippet, as a channel
+ // message's "Create task" does, and can link the task after the snippet.
+ const handleCreateTask = () => {
+ if (convertsCheckboxes()) {
+ handleConvertToTasks();
return;
}
+ const snippet = editor.read(() => {
+ const lexicalSelection = $getSelection();
+ const location = $getSelectionLocation();
+ if (!$isRangeSelection(lexicalSelection) || !location) return null;
+ const { key, offset, type } = lexicalSelection.isBackward()
+ ? lexicalSelection.anchor
+ : lexicalSelection.focus;
+ return {
+ text: lexicalSelection.getTextContent(),
+ location,
+ end: { key, offset, type },
+ };
+ });
+ const splitManager = globalSplitManager();
+ if (!snippet || !splitManager) return;
- setIsConverting(true);
- editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {
- selection: currentSelection.lexicalSelection as RangeSelection,
- onComplete: (results) => {
- setIsConverting(false);
- const successCount = results.filter((r) => r.isOk()).length;
- if (successCount > 0) {
- toast.success(
- `Created ${successCount} task${successCount > 1 ? 's' : ''}`
- );
- }
- setPopupVisible(false);
+ const text = snippet.text.replace(/\s+/g, ' ').trim();
+ // Create More links each task after the previous one, in creation order.
+ let linking = Promise.resolve<SavedPoint>(snippet.end);
+ const linkTask = (task: ComposeTaskSuccess) => {
+ const previous = linking;
+ linking = (async () => {
+ const point = await previous;
+ return (await insertTaskMention(point, task)) ?? point;
+ })();
+ fireAndForget(linking, 'markdown-create-task');
+ };
+ splitManager.createPopoverSplit({
+ content: {
+ type: 'component',
+ id: 'task-compose',
+ params: {
+ initialTitle: text.length > 70 ? `${text.slice(0, 70)}...` : text,
+ initialContent: buildMentionMarkdownString({
+ type: 'document',
+ documentId: blockId,
+ documentName: persistedName() ?? fallbackName() ?? '',
+ blockName: 'md',
+ blockParams: {
+ [URL_PARAMS.location]: serializePersistentLocation(
+ snippet.location
+ ),
+ },
+ }),
+ linkInSource: canEdit()
+ ? {
+ label: 'Link in document',
+ insert: linkTask,
+ }
+ : undefined,
+ },
},
});
+ setPopupVisible(false);
};
const handleConvertListToTable = () => {
@@ -543,7 +674,7 @@ export function MarkdownPopup(props: {
when={activePrompt() !== 'none'}
fallback={
<Toolbar ref={measureToolbar}>
- {/* Selection actions: AI edit + convert to tasks. */}
+ {/* Selection actions: AI edit + create task. */}
<Show when={shouldShowEditWithAiButton()}>
<Toolbar.Button
size="sm"
@@ -553,23 +684,28 @@ export function MarkdownPopup(props: {
AI edit
</Toolbar.Button>
</Show>
- <Show when={shouldShowCheckboxToTaskButton()}>
+ <Show when={shouldShowCreateTaskButton()}>
<Toolbar.Button
size="sm"
depth={3}
- onClick={handleConvertToTasks}
+ tooltip={
+ convertsCheckboxes()
+ ? 'Create a task for each checklist item'
+ : 'Create task from snippet'
+ }
+ onClick={handleCreateTask}
disabled={isConverting()}
>
<Dynamic
component={isConverting() ? LoadingIcon : CheckSquareIcon}
class="size-4"
/>
- {isConverting() ? 'Converting...' : 'Tasks'}
+ {createTaskLabel()}
</Toolbar.Button>
</Show>
<Show
when={
- shouldShowEditWithAiButton() || shouldShowCheckboxToTaskButton()
+ shouldShowEditWithAiButton() || shouldShowCreateTaskButton()
}
>
<Toolbar.Divider />
@@ -723,9 +859,10 @@ export function MarkdownPopup(props: {
<TouchSelectionToolbar
canEdit={canEdit()}
canComment={canComment()}
- isConverting={isConverting()}
hasSelection={(selection()?.text ?? '') !== ''}
- showTasksOption={shouldShowCheckboxToTaskButton()}
+ showCreateTaskOption={shouldShowCreateTaskButton()}
+ createTaskLabel={createTaskLabel()}
+ isConverting={isConverting()}
showTableOption={shouldShowTableButton()}
showEditWithAiOption={shouldShowEditWithAiButton()}
showOpenCommentOption={
@@ -733,7 +870,7 @@ export function MarkdownPopup(props: {
}
locationCopied={locationCopied()}
setPopupVisible={setPopupVisible}
- onConvertToTasks={handleConvertToTasks}
+ onCreateTask={handleCreateTask}
onConvertListToTable={handleConvertListToTable}
onOpenComment={handleShowComment}
onShare={() => fireAndForget(handleShare(), 'markdown-editor')}
diff --git a/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx b/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx
index 327cb4df7c..2b682cfe80 100644
--- a/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx
+++ b/apps/web/src/features/block-md/component/TouchSelectionToolbar.tsx
@@ -25,7 +25,6 @@ type TouchOption = {
key: string;
content: () => JSX.Element;
onSelect: () => void;
- disabled?: () => boolean;
};
// Toolbar buttons give no touch-down feedback: the ghost variant's
@@ -51,17 +50,18 @@ const arrowButtonClass =
export function TouchSelectionToolbar(props: {
canEdit: boolean;
canComment: boolean;
- isConverting: boolean;
/** False when the popup opened for a bare caret (inside a comment). */
hasSelection: boolean;
- showTasksOption: boolean;
+ showCreateTaskOption: boolean;
+ createTaskLabel: string;
+ isConverting: boolean;
showTableOption: boolean;
showEditWithAiOption: boolean;
/** The caret/selection touches an existing comment thread. */
showOpenCommentOption: boolean;
locationCopied: boolean;
setPopupVisible: (visible: boolean) => void;
- onConvertToTasks: () => void;
+ onCreateTask: () => void;
onConvertListToTable: () => void;
onOpenComment: () => void;
onShare: () => void;
@@ -96,20 +96,21 @@ export function TouchSelectionToolbar(props: {
}
return list;
}
- if (props.showTasksOption) {
+ if (props.showCreateTaskOption) {
list.push({
- key: 'tasks',
+ key: 'task',
content: () => (
<>
<Dynamic
component={props.isConverting ? LoadingIcon : CheckSquareIcon}
class="size-4"
/>
- {props.isConverting ? 'Converting...' : 'Tasks'}
+ {props.createTaskLabel}
</>
),
- onSelect: () => props.onConvertToTasks(),
- disabled: () => props.isConverting,
+ onSelect: () => {
+ if (!props.isConverting) props.onCreateTask();
+ },
});
}
if (props.showTableOption) {
@@ -234,7 +235,7 @@ export function TouchSelectionToolbar(props: {
createEffect(() => {
// Reset paging only when the option *set* changes (e.g. caret mode vs.
// selection mode) — a cosmetic rerender of the same options (the Share
- // icon flipping to a check, the Tasks label while converting) keeps the
+ // icon flipping to a check, the Task label while converting) keeps the
// user's page; the clamp effect below handles any repartition.
const keys = options()
.map((option) => option.key)
@@ -484,7 +485,6 @@ export function TouchSelectionToolbar(props: {
class={optionButtonClass}
depth={3}
variant="ghost"
- disabled={option.disabled?.()}
onClick={() => option.onSelect()}
>
{option.content()}
diff --git a/apps/web/src/features/block-md/util/insertAtSavedPoint.test.ts b/apps/web/src/features/block-md/util/insertAtSavedPoint.test.ts
new file mode 100644
index 0000000000..e0cdc3b6b8
--- /dev/null
+++ b/apps/web/src/features/block-md/util/insertAtSavedPoint.test.ts
@@ -0,0 +1,150 @@
+import {
+ $createListItemNode,
+ $createListNode,
+ $isListNode,
+ ListItemNode,
+ ListNode,
+} from '@lexical/list';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $isTextNode,
+ createEditor,
+ type LexicalEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { $insertAtSavedPoint, type SavedPoint } from './insertAtSavedPoint';
+
+function editorWithText(text: string): {
+ editor: LexicalEditor;
+ key: string;
+} {
+ const editor = createEditor({
+ onError: (error) => {
+ throw error;
+ },
+ });
+ let key = '';
+ editor.update(
+ () => {
+ const textNode = $createTextNode(text);
+ key = textNode.getKey();
+ $getRoot().append($createParagraphNode().append(textNode));
+ // The live caret sits at the start, away from the saved point.
+ textNode.select(0, 0);
+ },
+ { discrete: true }
+ );
+ return { editor, key };
+}
+
+function insert(
+ editor: LexicalEditor,
+ point: SavedPoint,
+ label = '[task]'
+): SavedPoint | null {
+ let next: SavedPoint | null = null;
+ editor.update(
+ () => {
+ // Token text never merges with its neighbours, like a mention chip.
+ next = $insertAtSavedPoint(point, [
+ $createTextNode(label).setMode('token'),
+ ]);
+ },
+ { discrete: true }
+ );
+ return next;
+}
+
+const text = (editor: LexicalEditor) =>
+ editor.read(() => $getRoot().getTextContent());
+
+function checklist(): { editor: LexicalEditor; key: string } {
+ const editor = createEditor({
+ nodes: [ListNode, ListItemNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ let key = '';
+ editor.update(
+ () => {
+ const list = $createListNode('check');
+ key = list.getKey();
+ for (const item of ['a', 'b', 'c']) {
+ list.append($createListItemNode(false).append($createTextNode(item)));
+ }
+ $getRoot().append(list);
+ },
+ { discrete: true }
+ );
+ return { editor, key };
+}
+
+const itemTexts = (editor: LexicalEditor) =>
+ editor.read(() =>
+ $getRoot()
+ .getChildren()
+ .flatMap((list) => ($isListNode(list) ? list.getChildren() : []))
+ .map((item) => item.getTextContent())
+ );
+
+describe('$insertAtSavedPoint', () => {
+ it('inserts at the saved point, not at the live selection', () => {
+ const { editor, key } = editorWithText('buy milk today.');
+
+ expect(insert(editor, { key, offset: 14, type: 'text' })).not.toBeNull();
+
+ expect(text(editor)).toBe('buy milk today[task].');
+ });
+
+ it('keeps successive inserts in creation order via the returned point', () => {
+ const { editor, key } = editorWithText('buy milk today.');
+
+ const next = insert(editor, { key, offset: 14, type: 'text' }, '[one]');
+ if (!next) throw new Error('first insert failed');
+ insert(editor, next, '[two]');
+
+ expect(text(editor)).toBe('buy milk today[one][two].');
+ });
+
+ it('inserts at the start and end of a text node', () => {
+ const start = editorWithText('today');
+ insert(start.editor, { key: start.key, offset: 0, type: 'text' });
+ expect(text(start.editor)).toBe('[task]today');
+
+ const end = editorWithText('today');
+ insert(end.editor, { key: end.key, offset: 5, type: 'text' });
+ expect(text(end.editor)).toBe('today[task]');
+ });
+
+ it('links after the item text when the point sits between checklist items', () => {
+ const { editor, key } = checklist();
+
+ expect(insert(editor, { key, offset: 2, type: 'element' })).not.toBeNull();
+
+ expect(itemTexts(editor)).toEqual(['a', 'b[task]', 'c']);
+ });
+
+ it('adds no list items when the point is before the first item', () => {
+ const { editor, key } = checklist();
+
+ expect(insert(editor, { key, offset: 0, type: 'element' })).toBeNull();
+
+ expect(itemTexts(editor)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('returns null when the saved node was removed', () => {
+ const { editor, key } = editorWithText('today');
+ editor.update(
+ () => {
+ const node = $getRoot().getFirstDescendant();
+ if ($isTextNode(node)) node.remove();
+ },
+ { discrete: true }
+ );
+
+ expect(insert(editor, { key, offset: 2, type: 'text' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-md/util/insertAtSavedPoint.ts b/apps/web/src/features/block-md/util/insertAtSavedPoint.ts
new file mode 100644
index 0000000000..ff8e975792
--- /dev/null
+++ b/apps/web/src/features/block-md/util/insertAtSavedPoint.ts
@@ -0,0 +1,68 @@
+import {
+ $getNodeByKey,
+ $isElementNode,
+ $isTextNode,
+ type LexicalNode,
+ type PointType,
+} from 'lexical';
+
+export type SavedPoint = Pick<PointType, 'key' | 'offset' | 'type'>;
+
+function $pointAfter(node: LexicalNode): SavedPoint {
+ return {
+ key: node.getParentOrThrow().getKey(),
+ offset: node.getIndexWithinParent() + 1,
+ type: 'element',
+ };
+}
+
+function $insertAfter(node: LexicalNode, nodes: LexicalNode[]) {
+ let previous = node;
+ for (const inserted of nodes) {
+ previous.insertAfter(inserted);
+ previous = inserted;
+ }
+ return $pointAfter(previous);
+}
+
+const $isBlock = (node: LexicalNode | null) =>
+ $isElementNode(node) && !node.isInline();
+
+/**
+ * Inserts inline nodes at a point saved from an earlier selection, without
+ * touching the live selection (Lexical's insertNodes inserts at the live
+ * selection whenever one exists). Returns the point just after the inserted
+ * nodes, or null when the point's node is gone or the point has no inline
+ * position to insert at.
+ */
+export function $insertAtSavedPoint(
+ point: SavedPoint,
+ nodes: LexicalNode[]
+): SavedPoint | null {
+ const last = nodes.at(-1);
+ if (!last) return null;
+ const node = $getNodeByKey(point.key);
+ if (point.type === 'text' && $isTextNode(node)) {
+ const offset = Math.min(point.offset, node.getTextContentSize());
+ if (offset === 0) {
+ for (const inserted of nodes) node.insertBefore(inserted);
+ return $pointAfter(last);
+ }
+ return $insertAfter(node.splitText(offset)[0], nodes);
+ }
+ if (point.type !== 'element' || !$isElementNode(node)) return null;
+
+ const offset = Math.min(point.offset, node.getChildrenSize());
+ const before = offset > 0 ? node.getChildAtIndex(offset - 1) : null;
+ // Between blocks, e.g. after a checklist item: follow the block's text.
+ if ($isElementNode(before) && !before.isInline()) {
+ const leaf = before.getLastDescendant();
+ return leaf !== null && !$isElementNode(leaf)
+ ? $insertAfter(leaf, nodes)
+ : null;
+ }
+ // Lists, tables and the root hold only blocks.
+ if ($isBlock(node.getFirstChild()) || node.getParent() === null) return null;
+ node.splice(offset, 0, nodes);
+ return $pointAfter(last);
+}
diff --git a/apps/web/src/features/block-md/util/taskComposerStorage.ts b/apps/web/src/features/block-md/util/taskComposerStorage.ts
index 0af5be61ba..d2a12be171 100644
--- a/apps/web/src/features/block-md/util/taskComposerStorage.ts
+++ b/apps/web/src/features/block-md/util/taskComposerStorage.ts
@@ -30,6 +30,18 @@ export function createTaskComposerSharing(recoveredShare?: boolean) {
});
}
+/** Whether tasks link back into the document they were composed from. */
+export function createTaskComposerLinkInSource() {
+ return makePersistedState(createSignal(false), {
+ storages: {
+ restore: () =>
+ localStorage.getItem('task-composer-link-in-source') === 'true',
+ write: (value) =>
+ localStorage.setItem('task-composer-link-in-source', String(value)),
+ },
+ });
+}
+
/** Context drafts use their own key; the global composer retains its original key. */
export function taskComposerContextStorage(
key: string
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts
index 4bda18ef4c..89ef57dcd4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts
@@ -81,9 +81,10 @@ export function extractTitleFromMarkdown(markdownText: string): string {
/**
* Get plain text title from a ListItemNode, collecting text from all children
- * except user/date mentions (which become task properties instead).
+ * except user/date mentions (which become task properties instead). Safe in a
+ * read context.
*/
-function $extractTitleFromNode(node: ListItemNode): string {
+export function $extractTitleFromNode(node: ListItemNode): string {
return $collectTextContent(node).trim().replace(/\s+/g, ' ');
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/location/locationPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/location/locationPlugin.ts
index 3d1ed1d660..7f9fa6ac58 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/location/locationPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/location/locationPlugin.ts
@@ -87,7 +87,7 @@ function _getNodesFromEphemeralLocation(
* anchorNodeId.anchorOffset,focusNodeId.focusOffset
* or anchorAndFocusId.anchorOffset.focusOffset if the focusNodeId is the same as the anchorNodeId.
*/
-function serializePersistentLocation(location: PersistentLocation) {
+export function serializePersistentLocation(location: PersistentLocation) {
if (location.focus.id === location.anchor.id) {
return `${location.anchor.id}.${location.anchor.offset}.${location.focus.offset}`;
}
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 553abd1aa0..b58c6c9ed3 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -270,6 +270,23 @@ tags, opens it in an adjacent split, and inserts its mention in the source edito
An empty title uses **New Note** when expanding.
**Create → Document** continues to open a document directly.
+## Create a task from a Markdown selection
+
+Select text in a Markdown document and choose **Task** in the selection toolbar
+(desktop) or touch toolbar. The task composer opens with the selected text as
+the title (truncated to 70 characters) and a **Snippet** mention of the
+selection as the body; opening that mention scrolls to and highlights the
+range. Editors also see a **Link in document** toggle beside **Create More**;
+it is remembered and starts off. While on, creating the task inserts its
+mention right after the selected text, inside the same checklist item when the
+selection is in one; a selection ending between list items links after the
+preceding item's text and never adds list items. Verify both toggle states and
+that other text edited while the composer was open is preserved.
+
+When an editor's selection spans two or more checklist items, the button reads
+**N tasks** and creates one task per item without opening the composer; each
+item is replaced by its task mention and a **Created N tasks** toast appears.
+
## Markdown outline
On desktop, Markdown documents with at least three headings show a tick rail in