Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(md/tasks): checkbox -> task conversion plugin (#972)
teoeb3192b3d955
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsxindex 691b809eb8..447ff0b88c 100644--- a/js/app/packages/block-md/component/MarkdownEditor.tsx+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx@@ -3,7 +3,13 @@ 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 { type BlockName, useBlockId } from '@core/block';+import { useUserId } from '@service-gql/client';+import {+ type BlockName,+ useBlockId,+ useMaybeBlockAliasedName,+} from '@core/block';+import { IS_MAC } from '@core/constant/isMac';import type { DragEventWithData } from '@core/component/FileList/DraggableItem';import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';@@ -60,6 +66,10 @@ import {wordcountPlugin,} from '@core/component/LexicalMarkdown/plugins';import { actionsPlugin } from '@core/component/LexicalMarkdown/plugins/actions/actionsPlugin';+import {+ checkboxToTaskPlugin,+ CONVERT_CHECKBOXES_TO_TASKS,+} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task';import { codePlugin } from '@core/component/LexicalMarkdown/plugins/code/codePlugin';import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';import {@@ -178,6 +188,8 @@ const EDITOR_PADDING_BOTTOM = 200;export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {const blockData = blockDataSignal.get;const blockId = useBlockId();+ const userId = useUserId();+ const blockName = useMaybeBlockAliasedName();const mdDocumentName = useBlockDocumentName('');@@ -534,9 +546,30 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {.use(restoreFocusPlugin()).use(markdownPastePlugin()).use(normalizeEnterPlugin())+ .use(+ checkboxToTaskPlugin({+ currentUserId: userId(),+ parentTaskId: blockName === 'task' ? blockId : undefined,+ })+ ).use(keyboardShortcutsPlugin({- shortcuts: DefaultShortcuts,+ shortcuts: [+ ...DefaultShortcuts,+ {+ label: `${IS_MAC ? 'meta' : 'ctrl'}+shift+o`,+ test: (e) =>+ e.code === 'KeyO' &&+ e.shiftKey &&+ (IS_MAC ? e.metaKey : e.ctrlKey),+ handler: (editor) => {+ const userId = useUserId()();+ if (!userId) return;+ editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {});+ },+ priority: 0,+ },+ ],})).use(diff --git a/js/app/packages/block-md/component/MarkdownPopup.tsx b/js/app/packages/block-md/component/MarkdownPopup.tsxindex 5729e8785c..b25bc61f79 100644--- a/js/app/packages/block-md/component/MarkdownPopup.tsx+++ b/js/app/packages/block-md/component/MarkdownPopup.tsx@@ -26,6 +26,12 @@ import {RECOMPUTE_SELECTION_RECT,REMOVE_HIGHLIGHT_SELECTED_NODES,} from '@core/component/LexicalMarkdown/plugins/popup/popupPlugin';+import {+ $canConvertCheckboxesToTasks,+ CONVERT_CHECKBOXES_TO_TASKS,+ isCheckboxToTaskPluginEnabled,+} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task';+import { toast } from '@core/component/Toast/Toast';import { ScopedPortal } from '@core/component/ScopedPortal';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { isMobileWidth } from '@core/mobile/mobileWidth';@@ -36,6 +42,7 @@ import { debouncedDependent } from '@core/util/debounce';import { createFromMarkdownText } from '@core/util/md';import { getScrollParentElement } from '@core/util/scrollParent';import type { NodeIdMappings } from '@lexical-core';+import { useUserId } from '@service-gql/client';import MacroGridLoader from '@macro-icons/macro-grid-noise-loader-4.svg';import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';@@ -44,6 +51,7 @@ import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?componenimport PaperPlaneRight from '@phosphor-icons/core/fill/paper-plane-right-fill.svg?component-solid';import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';import PencilIcon from '@phosphor-icons/core/regular/pencil.svg?component-solid';+import CheckSquareIcon from '@phosphor-icons/core/regular/check-square.svg?component-solid';import { makeResizeObserver } from '@solid-primitives/resize-observer';import { createCallback } from '@solid-primitives/rootless';import { GlitchText } from '@ui/components/GlitchText';@@ -52,7 +60,7 @@ import {$getSelectionLocation,type PersistentLocation,} from 'core/component/LexicalMarkdown/plugins/location/locationPlugin';-import { $getRoot, COMMAND_PRIORITY_HIGH } from 'lexical';+import { $getRoot, COMMAND_PRIORITY_HIGH, type RangeSelection } from 'lexical';import {createEffect,createSignal,@@ -109,10 +117,13 @@ export function MarkdownPopup(props: {const canEdit = useCanEdit();const canComment = useCanComment();+ const currentUserId = useUserId();const [copied, setCopied] = createSignal(false);const [locationCopied, setLocationCopied] = createSignal(false);const [isLoading, setIsLoading] = createSignal<boolean>(false);+ const [isConverting, setIsConverting] = createSignal(false);+ const [hasCheckboxes, setHasCheckboxes] = createSignal(false);const { replaceOrInsertSplit } = useSplitLayout();let markdownRootRef!: HTMLDivElement;@@ -134,10 +145,12 @@ export function MarkdownPopup(props: {const selectedNodesText = () => selection()?.nodeText ?? undefined;const selectionType = () => selection()?.type ?? undefined;- // Reset location copied state on selection change.createEffect(on([selection], () => {setLocationCopied(false);+ editor.read(() => {+ setHasCheckboxes($canConvertCheckboxesToTasks());+ });}));@@ -323,6 +336,29 @@ export function MarkdownPopup(props: {setIsLoading(false);});+ const handleConvertToTasks = () => {+ const currentSelection = selection();+ const userId = currentUserId();+ if (!currentSelection?.lexicalSelection || !userId) {+ return;+ }++ setIsConverting(true);+ editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {+ selection: currentSelection.lexicalSelection as RangeSelection,+ onComplete: (results) => {+ setIsConverting(false);+ const successCount = results.filter((r) => r.isOk()).length;+ if (successCount > 0) {+ toast.success(+ `Created ${successCount} task${successCount > 1 ? 's' : ''}`+ );+ }+ setPopupVisible(false);+ },+ });+ };+const contentSize = () => {let charCount = 0;editor.getEditorState().read(() => {@@ -372,6 +408,15 @@ export function MarkdownPopup(props: {});});+ const shouldShowCheckboxToTaskButton = () => {+ return (+ isCheckboxToTaskPluginEnabled(editor) &&+ hasCheckboxes() &&+ canEdit() &&+ currentUserId()+ );+ };+return (<><div@@ -409,6 +454,16 @@ export function MarkdownPopup(props: {><FormatTools withinPopup /></Show>+ <Show when={shouldShowCheckboxToTaskButton()}>+ <DeprecatedTextButton+ width={'w-12'}+ theme="clear"+ icon={isConverting() ? LoadingIcon : CheckSquareIcon}+ text={isConverting() ? 'Converting...' : 'Tasks'}+ onClick={handleConvertToTasks}+ disabled={isConverting()}+ />+ </Show><DeprecatedTextButtonwidth={'w-12'}theme="clear"diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsxindex 659b84c17c..7e8314854d 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx@@ -40,6 +40,7 @@ import {selectionDataPlugin,tabIndentationPlugin,} from '../../plugins';+import { checkboxToTaskPlugin } from '../../plugins/checkbox-to-task';import { restoreFocusPlugin } from '../../plugins/restore-focus';import { createMenuOperations } from '../../shared/inlineMenu';import {@@ -180,6 +181,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {.state<string>(setMarkdownState, 'markdown').history(400).use(restoreFocusPlugin())+ .use(checkboxToTaskPlugin()).use(mediaPlugin()).use(props.formatState && props.setFormatStatediff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxDetection.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxDetection.tsnew file mode 100644index 0000000000..592c0654a7--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxDetection.ts@@ -0,0 +1,39 @@+import { $isListItemNode, type ListItemNode } from '@lexical/list';+import { $getRoot, type LexicalNode, type RangeSelection } from 'lexical';++/**+ * Check if a ListItemNode is a checkbox (has a checked state).+ * ListItemNodes in checklists have getChecked() returning a boolean,+ * while regular list items return undefined.+ */+export function $isCheckboxNode(node: LexicalNode): node is ListItemNode {+ if (!$isListItemNode(node)) return false;+ return typeof node.getChecked() === 'boolean';+}++/**+ * Find all checkbox ListItemNodes in the given selection.+ * Walks up from selected nodes to find their checkbox parents.+ */+export function $getSelectedCheckboxes(+ selection: RangeSelection+): ListItemNode[] {+ const selectedNodes = selection.getNodes();+ const checkboxes = new Set<ListItemNode>();+ const root = $getRoot();++ for (const node of selectedNodes) {+ let current: LexicalNode | null = node;++ // Walk up the tree to find ListItemNode ancestors+ while (current && current !== root) {+ if ($isCheckboxNode(current)) {+ checkboxes.add(current);+ break;+ }+ current = current.getParent();+ }+ }++ return Array.from(checkboxes);+}diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.test.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.test.tsnew file mode 100644index 0000000000..60ddcef18d--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it, vi } from 'vitest';++// Mock the Lexical utils to avoid JSX dependency chain+vi.mock('../../utils', () => ({+ $elementNodeToMarkdown: vi.fn(),+}));++import {+ extractUserMentions,+ extractDateMention,+ extractTitleFromMarkdown,+} from './checkboxParsing';++describe('Checkbox Parsing', () => {+ describe('extractUserMentions', () => {+ it('should extract single user mention', () => {+ const text =+ 'Fix bug <m-user-mention>{"userId":"user-123","email":"[email protected]"}</m-user-mention>';+ expect(extractUserMentions(text)).toEqual(['user-123']);+ });++ it('should extract multiple user mentions', () => {+ const text =+ '<m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention> and <m-user-mention>{"userId":"u2","email":"[email protected]"}</m-user-mention>';+ expect(extractUserMentions(text)).toEqual(['u1', 'u2']);+ });++ it('should return empty array when no mentions', () => {+ expect(extractUserMentions('Just plain text')).toEqual([]);+ });++ it('should handle malformed JSON gracefully', () => {+ const text = '<m-user-mention>{invalid json}</m-user-mention>';+ expect(extractUserMentions(text)).toEqual([]);+ });++ it('should handle missing userId field', () => {+ const text =+ '<m-user-mention>{"email":"[email protected]"}</m-user-mention>';+ expect(extractUserMentions(text)).toEqual([]);+ });+ });++ describe('extractDateMention', () => {+ it('should extract date from mention', () => {+ const text =+ 'Due <m-date-mention>{"date":"2024-03-15T00:00:00Z","displayFormat":"March 15, 2024"}</m-date-mention>';+ expect(extractDateMention(text)).toBe('2024-03-15T00:00:00Z');+ });++ it('should return null when no date mention', () => {+ expect(extractDateMention('No date here')).toBeNull();+ });++ it('should return first date when multiple present', () => {+ const text =+ '<m-date-mention>{"date":"2024-01-01","displayFormat":"Jan 1"}</m-date-mention> to <m-date-mention>{"date":"2024-12-31","displayFormat":"Dec 31"}</m-date-mention>';+ expect(extractDateMention(text)).toBe('2024-01-01');+ });++ it('should handle malformed JSON gracefully', () => {+ const text = '<m-date-mention>{invalid}</m-date-mention>';+ expect(extractDateMention(text)).toBeNull();+ });+ });++ describe('extractTitleFromMarkdown', () => {+ it('should remove user mentions (they become assignees)', () => {+ const text =+ 'Review by <m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('Review by');+ });++ it('should remove date mentions (they become due date)', () => {+ const text =+ 'Due <m-date-mention>{"date":"2024-03-15","displayFormat":"March 15"}</m-date-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('Due');+ });++ it('should remove both user and date mentions', () => {+ const text =+ '<m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention>: finish by <m-date-mention>{"date":"2024-01-01","displayFormat":"Jan 1"}</m-date-mention>';+ expect(extractTitleFromMarkdown(text)).toBe(': finish by');+ });++ it('should produce clean title with task description', () => {+ const text =+ 'Fix the login bug <m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention> <m-date-mention>{"date":"2024-03-15","displayFormat":"March 15"}</m-date-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('Fix the login bug');+ });++ it('should clean up extra whitespace', () => {+ const text = ' Too many spaces ';+ expect(extractTitleFromMarkdown(text)).toBe('Too many spaces');+ });++ it('should remove checkbox prefix', () => {+ const text = '- [ ] This is a todo item';+ expect(extractTitleFromMarkdown(text)).toBe('This is a todo item');+ });++ it('should remove checked checkbox prefix', () => {+ const text = '- [x] Completed item';+ expect(extractTitleFromMarkdown(text)).toBe('Completed item');+ });++ it('should handle document mentions', () => {+ const text =+ 'See <m-document-mention>{"documentId":"doc-123","documentName":"My Doc","blockName":"md"}</m-document-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('See My Doc');+ });++ it('should handle contact mentions', () => {+ const text =+ 'Contact <m-contact-mention>{"contactId":"c-1","name":"John Doe","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('Contact John Doe');+ });++ it('should handle group mentions', () => {+ const text =+ 'Notify <m-group-mention>{"groupAlias":"here"}</m-group-mention>';+ expect(extractTitleFromMarkdown(text)).toBe('Notify @here');+ });++ it('should return empty string for empty checkbox', () => {+ const text = '- [ ] ';+ expect(extractTitleFromMarkdown(text)).toBe('');+ });+ });+});diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.tsnew file mode 100644index 0000000000..d725f56727--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing.ts@@ -0,0 +1,94 @@+import type { ListItemNode } from '@lexical/list';+import {+ parseContactMentions,+ parseDocumentMentions,+ parseGroupMentions,+} from '@lexical-core/utils/parsers';+import { $elementNodeToMarkdown } from '../../utils';+import type { ParsedCheckbox } from './types';++// Patterns for extracting data from mentions (not for replacement)+const USER_MENTION_PATTERN = /<m-user-mention>(.*?)<\/m-user-mention>/;+const DATE_MENTION_PATTERN = /<m-date-mention>(.*?)<\/m-date-mention>/;++/**+ * Extract user IDs from user mention XML tags in markdown text+ */+export function extractUserMentions(markdownText: string): string[] {+ const userIds: string[] = [];+ const matches = markdownText.matchAll(new RegExp(USER_MENTION_PATTERN, 'g'));++ for (const match of matches) {+ try {+ const data = JSON.parse(match[1]);+ if (data.userId) {+ userIds.push(data.userId);+ }+ } catch {+ // Invalid JSON, skip this mention+ }+ }++ return userIds;+}++/**+ * Extract the first date mention from markdown text.+ * Returns ISO date string or null.+ */+export function extractDateMention(markdownText: string): string | null {+ const match = DATE_MENTION_PATTERN.exec(markdownText);+ if (!match) return null;++ try {+ const data = JSON.parse(match[1]);+ return data.date ?? null;+ } catch {+ return null;+ }+}++/**+ * Convert markdown text to plain text title.+ * Removes user/date mentions (they become task properties) and converts+ * other mentions to readable text using existing parsers.+ */+export function extractTitleFromMarkdown(markdownText: string): string {+ let title = markdownText;++ title = title.replace(new RegExp(USER_MENTION_PATTERN, 'g'), '');+ title = title.replace(new RegExp(DATE_MENTION_PATTERN, 'g'), '');++ title = parseDocumentMentions(title);+ title = parseContactMentions(title);+ title = parseGroupMentions(title);++ // Remove checkbox prefix if present (e.g., "- [ ] " or "- [x] ")+ title = title.replace(/^-\s*\[[ x]\]\s*/i, '');++ return title.trim().replace(/\s+/g, ' ');+}++/**+ * Parse a ListItemNode checkbox into structured data for task creation.+ * Must be called within Lexical update context (not read) because+ * $elementNodeToMarkdown requires update context.+ */+export function $parseCheckboxNode(node: ListItemNode): ParsedCheckbox {+ const rawMarkdown = $elementNodeToMarkdown(node, 'internal');++ return {+ nodeKey: node.getKey(),+ title: extractTitleFromMarkdown(rawMarkdown),+ rawMarkdown,+ assigneeUserIds: extractUserMentions(rawMarkdown),+ dueDate: extractDateMention(rawMarkdown),+ };+}++/**+ * Parse multiple checkbox nodes+ */+export function $parseCheckboxNodes(nodes: ListItemNode[]): ParsedCheckbox[] {+ return nodes.map($parseCheckboxNode);+}diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxToTaskPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxToTaskPlugin.tsnew file mode 100644index 0000000000..a91dc52281--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxToTaskPlugin.ts@@ -0,0 +1,254 @@+import { $createDocumentMentionNode } from '@lexical-core';+import { $isListItemNode } from '@lexical/list';+import {+ $createParagraphNode,+ $getNodeByKey,+ $getSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_NORMAL,+ createCommand,+ type LexicalCommand,+ type LexicalEditor,+} from 'lexical';+import { err, ok } from 'neverthrow';+import { SYSTEM_PROPERTY_IDS } from '../../../Properties/constants';+import { createTask } from '../../../../util/create';+import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';+import type {+ ConvertCheckboxesOptions,+ ConvertCheckboxesPluginOptions,+ ParsedCheckbox,+ TaskCreationResult,+} from './types';+import { $getSelectedCheckboxes } from './checkboxDetection';+import { $parseCheckboxNodes } from './checkboxParsing';++/**+ * Command to convert selected checkboxes to tasks+ */+export const CONVERT_CHECKBOXES_TO_TASKS: LexicalCommand<ConvertCheckboxesOptions> =+ createCommand('CONVERT_CHECKBOXES_TO_TASKS');++function maybeFallbackToCurrentAssignee(+ asigneeUserIds: string[],+ currentUserId?: string+): string[] {+ if (asigneeUserIds.length > 0) return asigneeUserIds;+ if (currentUserId) return [currentUserId];+ return [];+}++/**+ * Build PropertyInput array from parsed checkbox data.+ * Auto-assigns to current user when no assignees are extracted.+ */+function buildPropertyValues(+ checkbox: ParsedCheckbox,+ currentUserId?: string,+ parentTaskId?: string+): PropertyInput[] {+ const properties: PropertyInput[] = [];++ const assigneeIds = maybeFallbackToCurrentAssignee(+ checkbox.assigneeUserIds,+ currentUserId+ );++ if (assigneeIds) {+ properties.push({+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ value: {+ type: 'multi_entity_reference',+ references: assigneeIds.map((userId) => ({+ entity_id: userId,+ entity_type: 'USER' as const,+ })),+ },+ });+ }++ if (checkbox.dueDate) {+ properties.push({+ propertyId: SYSTEM_PROPERTY_IDS.DUE_DATE,+ value: {+ type: 'date',+ value: checkbox.dueDate,+ },+ });+ }++ if (parentTaskId) {+ properties.push({+ propertyId: SYSTEM_PROPERTY_IDS.PARENT_TASK,+ value: {+ type: 'entity_reference',+ reference: {+ entity_id: parentTaskId,+ entity_type: 'TASK' as const,+ },+ },+ });+ }++ return properties;+}++/**+ * Create a single task from a parsed checkbox+ */+async function createTaskFromCheckbox(+ checkbox: ParsedCheckbox,+ currentUserId?: string,+ parentTaskId?: string+): Promise<TaskCreationResult> {+ if (!checkbox.title.trim()) {+ return err({ tag: 'EmptyCheckbox', nodeKey: checkbox.nodeKey });+ }++ try {+ const propertyValues = buildPropertyValues(+ checkbox,+ currentUserId,+ parentTaskId+ );++ const documentId = await createTask({+ title: checkbox.title,+ content: '',+ propertyValues,+ });++ if (!documentId) {+ return err({ tag: 'NoDocumentId', nodeKey: checkbox.nodeKey });+ }++ return ok({+ nodeKey: checkbox.nodeKey,+ documentId,+ taskTitle: checkbox.title,+ });+ } catch (error) {+ return err({+ tag: 'ApiError',+ nodeKey: checkbox.nodeKey,+ message: error instanceof Error ? error.message : 'Unknown error',+ });+ }+}++/**+ * Replace a checkbox ListItemNode with a paragraph containing a task mention.+ * Must be called within Lexical update context.+ */+function $replaceCheckboxWithMention(+ nodeKey: string,+ documentId: string,+ taskTitle: string+): void {+ const node = $getNodeByKey(nodeKey);+ if (!node || !$isListItemNode(node)) return;++ const mentionNode = $createDocumentMentionNode({+ documentId,+ documentName: taskTitle,+ blockName: 'task',+ });++ const paragraph = $createParagraphNode();+ paragraph.append(mentionNode);+ node.replace(paragraph);+}++/**+ * Process checkboxes and create tasks in parallel, then batch replace all at once+ */+async function processCheckboxes(+ editor: LexicalEditor,+ checkboxes: ParsedCheckbox[],+ options: ConvertCheckboxesOptions,+ pluginOptions?: ConvertCheckboxesPluginOptions+): Promise<void> {+ const { onComplete } = options;++ const results = await Promise.all(+ checkboxes.map((checkbox) =>+ createTaskFromCheckbox(+ checkbox,+ pluginOptions?.currentUserId,+ pluginOptions?.parentTaskId+ )+ )+ );++ // Extract successful results for DOM replacement+ const successes = results.flatMap((r) => (r.isOk() ? [r.value] : []));++ if (successes.length > 0) {+ editor.update(+ () => {+ for (const { nodeKey, documentId, taskTitle } of successes) {+ $replaceCheckboxWithMention(nodeKey, documentId, taskTitle);+ }+ },+ { discrete: true }+ );+ }++ onComplete?.(results);+}++/**+ * Register the checkbox-to-task plugin+ */+function registerCheckboxToTaskPlugin(+ editor: LexicalEditor,+ pluginOptions?: ConvertCheckboxesPluginOptions+) {+ return editor.registerCommand(+ CONVERT_CHECKBOXES_TO_TASKS,+ (options: ConvertCheckboxesOptions) => {+ const selection = options.selection ?? $getSelection();+ if (!$isRangeSelection(selection)) {+ return false;+ }++ const nodes = $getSelectedCheckboxes(selection);+ const checkboxes = $parseCheckboxNodes(nodes);++ if (checkboxes.length === 0) {+ options.onComplete?.([]);+ return false;+ }++ processCheckboxes(editor, checkboxes, options, pluginOptions);++ return true;+ },+ COMMAND_PRIORITY_NORMAL+ );+}++/**+ * Plugin factory for checkbox-to-task conversion.+ * Registers the CONVERT_CHECKBOXES_TO_TASKS command.+ */+export function checkboxToTaskPlugin(+ pluginOptions?: ConvertCheckboxesPluginOptions+) {+ return (editor: LexicalEditor) =>+ registerCheckboxToTaskPlugin(editor, pluginOptions);+}++/**+ * Utility to check if conversion is available for current selection.+ * Must be called within Lexical read/update context.+ */+export function $canConvertCheckboxesToTasks(): boolean {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return false;+ return $getSelectedCheckboxes(selection).length > 0;+}++export function isCheckboxToTaskPluginEnabled(editor: LexicalEditor): boolean {+ return editor._commands.has(CONVERT_CHECKBOXES_TO_TASKS);+}diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/index.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/index.tsnew file mode 100644index 0000000000..72a8d5cfd1--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/index.ts@@ -0,0 +1,4 @@+export * from './checkboxToTaskPlugin';+export * from './types';+export * from './checkboxDetection';+export * from './checkboxParsing';diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/types.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/types.tsnew file mode 100644index 0000000000..f9857d9ef0--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/checkbox-to-task/types.ts@@ -0,0 +1,46 @@+import type { RangeSelection } from 'lexical';+import type { Result } from 'neverthrow';++/**+ * Represents a parsed checkbox/todo item ready for task creation+ */+export type ParsedCheckbox = {+ nodeKey: string;+ title: string;+ rawMarkdown: string;+ assigneeUserIds: string[];+ dueDate: string | null;+};++/** Successful task creation */+export type TaskCreationSuccess = {+ nodeKey: string;+ documentId: string;+ taskTitle: string;+};++/** Task creation error types */+export type TaskCreationError =+ | { tag: 'EmptyCheckbox'; nodeKey: string }+ | { tag: 'NoDocumentId'; nodeKey: string }+ | { tag: 'ApiError'; nodeKey: string; message: string };++/** Result of creating a task from a checkbox */+export type TaskCreationResult = Result<TaskCreationSuccess, TaskCreationError>;++export type ConvertCheckboxesPluginOptions = {+ /** Current user ID for auto-assignment */+ currentUserId?: string;+ /** Optionally pass a parent id to set the parent id property of the tasks **/+ parentTaskId?: string;+};++/**+ * Options for the checkbox-to-task conversion+ */+export type ConvertCheckboxesOptions = {+ /** The selection to use (from popup's stored selection) */+ selection?: RangeSelection;+ /** Callback when all tasks are created */+ onComplete?: (results: TaskCreationResult[]) => void;+};