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(channels): ability to create tasks directly inside of channels. (#1025)

teoe374806da299
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/BaseInput.tsx
index 8df6c1cd58..6c870da190 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/BaseInput.tsx
@@ -8,6 +8,11 @@ import {
expandGroupParticipants,
toSimpleMention,
} from '@block-channel/utils/mentionExpansion';
+import {
+ createTasksFromPotential,
+ replaceCheckboxesWithMentions,
+} from '@block-channel/utils/taskModeConversion';
+import { useTaskMode } from '@block-channel/utils/useTaskMode';
import { isInBlock } from '@core/block';
import { LabelAndHotKey } from '@core/component/Tooltip';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
@@ -27,12 +32,14 @@ import type { UploadInput } from '@core/util/upload';
import { handleFileFolderDrop } from '@core/util/upload';
import ArrowUp from '@icon/bold/arrow-up-bold.svg';
import Spinner from '@icon/bold/spinner-gap-bold.svg';
+import CheckSquareIcon from '@icon/regular/check-square.svg';
import PlusIcon from '@icon/regular/plus.svg';
import FormatIcon from '@icon/regular/text-aa.svg';
import Trash from '@icon/regular/trash.svg';
import XIcon from '@icon/regular/x.svg';
import { logger } from '@observability';
import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
+import { useUserId } from '@service-gql/client';
import { staticFileClient } from '@service-static-files/client';
import { createCallback } from '@solid-primitives/rootless';
import { leading, throttle } from '@solid-primitives/scheduled';
@@ -50,6 +57,7 @@ import {
onCleanup,
onMount,
Show,
+ Suspense,
} from 'solid-js';
import type { SetStoreFunction } from 'solid-js/store';
import { tabbable } from 'tabbable';
@@ -57,6 +65,7 @@ import { AttachMenu } from './AttachMenu';
import { Attachment } from './Attachment';
import { FormatRibbon } from './FormatRibbon';
import { useChannelMarkdownArea } from './MarkdownArea';
+import { TaskPreviewPanel } from './TaskPreviewPanel';
false && fileFolderDrop;
@@ -110,6 +119,7 @@ const REMOTE_ACTIVITY_TIMEOUT_MS = 2000;
const LOCAL_ACTIVITY_TIMEOUT_MS = 500;
export function BaseInput(props: BaseInputProps) {
+ const userId = useUserId();
let containerRef!: HTMLDivElement;
const key = props.inputAttachments.key;
const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);
@@ -197,6 +207,13 @@ export function BaseInput(props: BaseInputProps) {
ref,
} = useChannelMarkdownArea();
+ const {
+ taskModeEnabled,
+ toggleTaskMode,
+ potentialTasks,
+ updateTaskPropertyValue,
+ } = useTaskMode(markdownState);
+
createRenderEffect(() => {
const currentRef = ref();
if (currentRef) props.domRef?.(currentRef);
@@ -341,10 +358,22 @@ export function BaseInput(props: BaseInputProps) {
props.onChange(markdownState());
}
- function handleSend() {
+ async function handleSend() {
if (isPendingSend()) return false;
setIsPendingSend(true);
- const content = markdownState();
+ let content = markdownState();
+ const originalContent = content;
+
+ if (taskModeEnabled() && potentialTasks().length > 0) {
+ const results = await createTasksFromPotential(potentialTasks(), {
+ currentUserId: userId(),
+ });
+
+ if (results.successes.length > 0) {
+ content = replaceCheckboxesWithMentions(content, results.successes);
+ toast.success(`Created ${results.successes.length} task(s)`);
+ }
+ }
const args = {
content: content,
@@ -366,7 +395,7 @@ export function BaseInput(props: BaseInputProps) {
// Restore the stashed editor state
clearMarkdownArea();
try {
- setEditorStateFromMarkdown(editor, content);
+ setEditorStateFromMarkdown(editor, originalContent);
} catch (e) {
logger.error('Failed to restore editor state after send error', {
error: e,
@@ -478,7 +507,8 @@ export function BaseInput(props: BaseInputProps) {
if (hasPendingAttachments() || isPendingSend()) {
return true;
}
- return handleSend();
+ handleSend();
+ return true;
}
}
onBlur={() => {
@@ -530,6 +560,14 @@ export function BaseInput(props: BaseInputProps) {
</For>
</div>
</Show>
+ <Show when={taskModeEnabled() && potentialTasks().length > 0}>
+ <Suspense>
+ <TaskPreviewPanel
+ tasks={potentialTasks()}
+ onUpdatePropertyValue={updateTaskPropertyValue}
+ />
+ </Suspense>
+ </Show>
<div class="flex flex-row w-full h-8 justify-between items-center p-2 mb-2 space-x-2 allow-css-brackets">
<Show when={showAttachMenu()}>
<AttachMenu
@@ -569,6 +607,16 @@ export function BaseInput(props: BaseInputProps) {
>
<FormatIcon width={20} height={20} />
</Button>
+ <Button
+ tooltip={<LabelAndHotKey label="Task Mode" />}
+ onClick={(e) => {
+ e.preventDefault();
+ toggleTaskMode();
+ }}
+ classList={{ 'bg-active': taskModeEnabled() }}
+ >
+ <CheckSquareIcon width={20} height={20} />
+ </Button>
<Show when={props.isReplyInput && props.closeDraft}>
<Button
tooltip={<LabelAndHotKey label="Delete reply" />}
diff --git a/js/app/packages/block-channel/component/TaskPreviewPanel.tsx b/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
new file mode 100644
index 0000000000..5e76f3d2fe
--- /dev/null
+++ b/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
@@ -0,0 +1,46 @@
+import type { PropertyApiValues } from '@core/component/Properties/types';
+import type { TaskWithProperties } from '@block-channel/utils/useTaskMode';
+import { For } from 'solid-js';
+import { TaskPreviewRow } from './TaskPreviewRow';
+
+type TaskPreviewPanelProps = {
+ tasks: TaskWithProperties[];
+ onUpdatePropertyValue: (
+ lineIndex: number,
+ propertyDefinitionId: string,
+ value: PropertyApiValues
+ ) => void;
+};
+
+/**
+ * Preview panel displaying tasks that will be created when sending a message
+ * with Task Mode enabled. Shows task titles with editable property pills.
+ */
+export function TaskPreviewPanel(props: TaskPreviewPanelProps) {
+ return (
+ <div class="w-full border-t border-edge-muted bg-surface-secondary px-3 py-2">
+ <div class="flex items-center gap-2 text-xs text-ink-muted mb-2">
+ <span>Tasks</span>
+ <span class="bg-surface px-1.5 py-0.5 rounded text-xs font-medium">
+ {props.tasks.length}
+ </span>
+ </div>
+ <div class="flex flex-col gap-0.5 max-h-32 overflow-y-auto">
+ <For each={props.tasks}>
+ {(task) => (
+ <TaskPreviewRow
+ task={task}
+ onUpdatePropertyValue={(propertyDefinitionId, value) =>
+ props.onUpdatePropertyValue(
+ task.lineIndex,
+ propertyDefinitionId,
+ value
+ )
+ }
+ />
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/block-channel/component/TaskPreviewRow.tsx b/js/app/packages/block-channel/component/TaskPreviewRow.tsx
new file mode 100644
index 0000000000..6ce966fba2
--- /dev/null
+++ b/js/app/packages/block-channel/component/TaskPreviewRow.tsx
@@ -0,0 +1,219 @@
+import type { TaskWithProperties } from '@block-channel/utils/useTaskMode';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { propertyApiValuesToNormalized } from '@core/component/Properties/api/converters';
+import { Modals } from '@core/component/Properties/component/modal';
+import { PropertyValue } from '@core/component/Properties/component/propertyValue/PropertyValue';
+import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
+import {
+ PropertiesProvider,
+ usePropertiesContext,
+ type PropertySaveHandler,
+} from '@core/component/Properties/context/PropertiesContext';
+import type {
+ Property,
+ PropertyApiValues,
+ PropertyOption,
+} from '@core/component/Properties/types';
+import { filterMap } from '@core/util/list';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
+import { useListPropertiesQuery } from '@queries/properties/definitions';
+import { queryReadyGate } from '@queries/gate';
+import { createMemo, For, Show } from 'solid-js';
+
+const PREVIEW_PROPERTIES = [
+ SYSTEM_PROPERTY_IDS.STATUS,
+ SYSTEM_PROPERTY_IDS.PRIORITY,
+ SYSTEM_PROPERTY_IDS.DUE_DATE,
+ SYSTEM_PROPERTY_IDS.ASSIGNEES,
+];
+
+type TaskPreviewRowProps = {
+ task: TaskWithProperties;
+ onUpdatePropertyValue: (
+ propertyDefinitionId: string,
+ value: PropertyApiValues
+ ) => void;
+};
+
+function extractPropertyValue(
+ definition: PropertyDefinition,
+ savedValues: Record<string, PropertyApiValues>,
+ options: Map<string, PropertyOption[]>
+) {
+ const { type, value } = propertyApiValuesToNormalized(
+ savedValues[definition.id]
+ );
+ if (type === 'EMPTY') return null;
+ if (
+ definition.data_type === 'SELECT_NUMBER' ||
+ definition.data_type === 'SELECT_STRING'
+ ) {
+ const opts = options.get(definition.id);
+ if (!opts) return null;
+ if (Array.isArray(value)) {
+ return filterMap(value as string[], (id) => {
+ const opt = opts.find((opt) => opt.id === id);
+ return opt ? opt.id : undefined;
+ });
+ }
+ } else {
+ return value;
+ }
+}
+
+function TaskPropertyRow(props: {
+ task: TaskWithProperties;
+ properties: Property[];
+}) {
+ const { openDatePicker, openPropertyEditor } = usePropertiesContext();
+
+ const handleEdit = (property: Property, anchor?: HTMLElement) => {
+ if (property.valueType === 'DATE') {
+ openDatePicker(property as Property & { valueType: 'DATE' }, anchor);
+ } else {
+ openPropertyEditor(property, anchor);
+ }
+ };
+
+ return (
+ <div class="flex items-center gap-2 text-sm py-1">
+ <EntityIcon targetType="task" size="sm" class="flex-shrink-0" />
+ <span class="truncate flex-1 text-ink min-w-0">
+ {props.task.title || '(empty)'}
+ </span>
+ <div class="flex items-center gap-0.5 flex-shrink-0">
+ <For each={props.properties}>
+ {(property) => (
+ <PropertyValue
+ property={property}
+ condensed={property.valueType !== 'DATE'}
+ onEdit={handleEdit}
+ />
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
+
+export function TaskPreviewRow(props: TaskPreviewRowProps) {
+ const systemPropertiesQuery = useListPropertiesQuery(
+ () => ({
+ scope: 'system',
+ includeOptions: true,
+ forEntityType: 'TASK',
+ }),
+ () => true
+ );
+
+ const definitions = createMemo(() => {
+ if (!queryReadyGate(systemPropertiesQuery))
+ return new Map<string, PropertyDefinition>();
+ return new Map(
+ systemPropertiesQuery.data.map((p) => {
+ const definition = 'definition' in p ? p.definition : p;
+ return [definition.id, definition];
+ })
+ );
+ });
+
+ const options = createMemo(() => {
+ if (!queryReadyGate(systemPropertiesQuery))
+ return new Map<string, PropertyOption[]>();
+ return new Map(
+ systemPropertiesQuery.data.map((p) => {
+ const definition = 'definition' in p ? p.definition : p;
+ const opts = 'property_options' in p ? p.property_options : [];
+ return [definition.id, opts];
+ })
+ );
+ });
+
+ const mergedPropertyValues = createMemo(
+ (): Record<string, PropertyApiValues> => {
+ const values: Record<string, PropertyApiValues> = {};
+
+ if (props.task.assigneeUserIds.length > 0) {
+ values[SYSTEM_PROPERTY_IDS.ASSIGNEES] = {
+ valueType: 'ENTITY',
+ refs: props.task.assigneeUserIds.map((id) => ({
+ entity_id: id,
+ entity_type: 'USER' as const,
+ })),
+ };
+ }
+
+ if (props.task.dueDate) {
+ values[SYSTEM_PROPERTY_IDS.DUE_DATE] = {
+ valueType: 'DATE',
+ value: props.task.dueDate,
+ };
+ }
+
+ return { ...values, ...props.task.propertyValues };
+ }
+ );
+
+ // Cast needed: Property is a discriminated union, but we build it dynamically
+ // from definition.data_type which TypeScript can't narrow statically
+ const properties = createMemo(() => {
+ return filterMap(PREVIEW_PROPERTIES, (id) => {
+ const definition = definitions().get(id);
+ if (!definition) return;
+ return {
+ propertyId: `preview-${props.task.lineIndex}-${definition.id}`,
+ propertyDefinitionId: definition.id,
+ displayName: definition.display_name,
+ isMultiSelect: definition.is_multi_select,
+ owner: definition.owner,
+ specificEntityType: definition.specific_entity_type ?? null,
+ updatedAt: '',
+ createdAt: '',
+ valueType: definition.data_type,
+ value: extractPropertyValue(
+ definition,
+ mergedPropertyValues(),
+ options()
+ ),
+ options: options().get(definition.id),
+ } as Property;
+ });
+ });
+
+ const saveHandler: PropertySaveHandler = {
+ saveProperty: async (property: Property, value: PropertyApiValues) => {
+ props.onUpdatePropertyValue(property.propertyDefinitionId, value);
+ },
+ saveDate: async (property: Property, date: Date) => {
+ props.onUpdatePropertyValue(property.propertyDefinitionId, {
+ valueType: 'DATE',
+ value: date.toISOString(),
+ });
+ },
+ };
+
+ return (
+ <Show
+ when={queryReadyGate(systemPropertiesQuery)}
+ fallback={
+ <div class="flex items-center gap-2 text-sm py-1 text-ink-muted">
+ <EntityIcon targetType="task" size="sm" class="flex-shrink-0" />
+ <span class="truncate flex-1">{props.task.title || '(empty)'}</span>
+ </div>
+ }
+ >
+ <PropertiesProvider
+ entityType="TASK"
+ canEdit={true}
+ properties={properties}
+ onRefresh={() => {}}
+ onPropertyAdded={() => {}}
+ onPropertyDeleted={() => {}}
+ saveHandler={saveHandler}
+ >
+ <TaskPropertyRow task={props.task} properties={properties()} />
+ <Modals />
+ </PropertiesProvider>
+ </Show>
+ );
+}
diff --git a/js/app/packages/block-channel/utils/taskModeConversion.ts b/js/app/packages/block-channel/utils/taskModeConversion.ts
new file mode 100644
index 0000000000..9558477f3b
--- /dev/null
+++ b/js/app/packages/block-channel/utils/taskModeConversion.ts
@@ -0,0 +1,168 @@
+import type { TaskWithProperties } from './useTaskMode';
+import { propertyValueToApi } from '@core/component/Properties/api/converters';
+import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
+import { createTask } from '@core/util/create';
+import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
+import { err, ok, type Result } from 'neverthrow';
+
+export type TaskCreationSuccess = {
+ lineIndex: number;
+ documentId: string;
+ title: string;
+};
+
+export type TaskCreationError = {
+ lineIndex: number;
+ error: string;
+};
+
+export type TaskCreationResults = {
+ successes: TaskCreationSuccess[];
+ errors: TaskCreationError[];
+};
+
+export type TaskCreationOptions = {
+ currentUserId?: string;
+};
+
+function buildPropertyInputs(
+ task: TaskWithProperties,
+ options: TaskCreationOptions
+): PropertyInput[] {
+ const properties: PropertyInput[] = [];
+
+ for (const [propertyId, apiValue] of Object.entries(task.propertyValues)) {
+ // Only ASSIGNEES is multi-select; STATUS and PRIORITY are single-select
+ const isMultiSelect = propertyId === SYSTEM_PROPERTY_IDS.ASSIGNEES;
+
+ const value = propertyValueToApi(apiValue, isMultiSelect);
+ if (value !== null) {
+ properties.push({ propertyId, value });
+ }
+ }
+
+ if (
+ task.assigneeUserIds.length > 0 &&
+ !task.propertyValues[SYSTEM_PROPERTY_IDS.ASSIGNEES]
+ ) {
+ properties.push({
+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ value: {
+ type: 'multi_entity_reference',
+ references: task.assigneeUserIds.map((id) => ({
+ entity_id: id,
+ entity_type: 'USER' as const,
+ })),
+ },
+ });
+ } else if (
+ !task.propertyValues[SYSTEM_PROPERTY_IDS.ASSIGNEES] &&
+ options.currentUserId
+ ) {
+ properties.push({
+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ value: {
+ type: 'multi_entity_reference',
+ references: [
+ { entity_id: options.currentUserId, entity_type: 'USER' as const },
+ ],
+ },
+ });
+ }
+
+ if (task.dueDate && !task.propertyValues[SYSTEM_PROPERTY_IDS.DUE_DATE]) {
+ properties.push({
+ propertyId: SYSTEM_PROPERTY_IDS.DUE_DATE,
+ value: { type: 'date', value: task.dueDate },
+ });
+ }
+
+ return properties;
+}
+
+async function createSingleTask(
+ task: TaskWithProperties,
+ options: TaskCreationOptions
+): Promise<Result<TaskCreationSuccess, TaskCreationError>> {
+ if (!task.title.trim()) {
+ return err({ lineIndex: task.lineIndex, error: 'Empty task title' });
+ }
+
+ try {
+ const propertyValues = buildPropertyInputs(task, options);
+
+ const documentId = await createTask({
+ title: task.title,
+ content: '',
+ propertyValues: propertyValues.length > 0 ? propertyValues : undefined,
+ });
+
+ if (!documentId) {
+ return err({ lineIndex: task.lineIndex, error: 'Failed to create task' });
+ }
+
+ return ok({
+ lineIndex: task.lineIndex,
+ documentId,
+ title: task.title,
+ });
+ } catch (error) {
+ return err({
+ lineIndex: task.lineIndex,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ });
+ }
+}
+
+export async function createTasksFromPotential(
+ tasks: TaskWithProperties[],
+ options: TaskCreationOptions
+): Promise<TaskCreationResults> {
+ const results = await Promise.all(
+ tasks.map((task) => createSingleTask(task, options))
+ );
+
+ const successes: TaskCreationSuccess[] = [];
+ const errors: TaskCreationError[] = [];
+
+ for (const result of results) {
+ if (result.isOk()) {
+ successes.push(result.value);
+ } else {
+ errors.push(result.error);
+ }
+ }
+
+ return { successes, errors };
+}
+
+function createTaskMentionMarkdown(documentId: string, title: string): string {
+ const data = JSON.stringify({
+ documentId,
+ documentName: title,
+ blockName: 'task',
+ });
+ return `<m-document-mention>${data}</m-document-mention>`;
+}
+
+export function replaceCheckboxesWithMentions(
+ markdown: string,
+ createdTasks: TaskCreationSuccess[]
+): string {
+ const lines = markdown.split('\n');
+
+ const taskByLine = new Map<number, TaskCreationSuccess>();
+ for (const task of createdTasks) {
+ taskByLine.set(task.lineIndex, task);
+ }
+
+ const resultLines = lines.map((line, index) => {
+ const task = taskByLine.get(index);
+ if (task) {
+ return createTaskMentionMarkdown(task.documentId, task.title);
+ }
+ return line;
+ });
+
+ return resultLines.join('\n');
+}
diff --git a/js/app/packages/block-channel/utils/useTaskMode.ts b/js/app/packages/block-channel/utils/useTaskMode.ts
new file mode 100644
index 0000000000..53f90bf167
--- /dev/null
+++ b/js/app/packages/block-channel/utils/useTaskMode.ts
@@ -0,0 +1,117 @@
+import type { PropertyApiValues } from '@core/component/Properties/types';
+import {
+ extractCheckboxesFromMarkdown,
+ type PotentialTask,
+} from '@core/util/taskExtraction';
+import { debounce } from '@solid-primitives/scheduled';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+} from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+
+const DEBOUNCE_MS = 300;
+
+/** Extended task with property values in API format */
+export type TaskWithProperties = PotentialTask & {
+ propertyValues: Record<string, PropertyApiValues>;
+};
+
+type UseTaskModeReturn = {
+ /** Whether task mode is currently enabled */
+ taskModeEnabled: Accessor<boolean>;
+ /** Toggle task mode on/off */
+ toggleTaskMode: () => void;
+ /** Set task mode enabled state directly */
+ setTaskModeEnabled: (enabled: boolean) => void;
+ /** Potential tasks detected in current content (debounced) */
+ potentialTasks: Accessor<TaskWithProperties[]>;
+ /** Update a property value on a specific task */
+ updateTaskPropertyValue: (
+ lineIndex: number,
+ propertyDefinitionId: string,
+ value: PropertyApiValues
+ ) => void;
+};
+
+/**
+ * Hook for managing task mode state in the channel message input.
+ * When task mode is enabled, continuously parses checkboxes from the
+ * markdown content (debounced) to preview what tasks will be created on send.
+ *
+ * @param markdownState - Accessor for the current markdown content
+ * @returns Task mode state and controls
+ */
+export function useTaskMode(
+ markdownState: Accessor<string>
+): UseTaskModeReturn {
+ const [taskModeEnabled, setTaskModeEnabled] = createSignal(false);
+ const [debouncedMarkdown, setDebouncedMarkdown] = createSignal('');
+
+ // Store property values per task (keyed by lineIndex, then propertyDefinitionId)
+ const [taskPropertyValues, setTaskPropertyValues] = createStore<
+ Record<number, Record<string, PropertyApiValues>>
+ >({});
+
+ const updateDebouncedMarkdown = debounce(
+ (content: string) => setDebouncedMarkdown(content),
+ DEBOUNCE_MS
+ );
+
+ createEffect(
+ on(
+ () => (taskModeEnabled() ? markdownState() : null),
+ (markdown) => {
+ if (markdown !== null) {
+ updateDebouncedMarkdown(markdown);
+ }
+ },
+ { defer: true }
+ )
+ );
+
+ const potentialTasks = createMemo<TaskWithProperties[]>(() => {
+ if (!taskModeEnabled()) return [];
+ const markdown = debouncedMarkdown();
+ if (!markdown) return [];
+
+ const extracted = extractCheckboxesFromMarkdown(markdown);
+
+ return extracted.map((task) => ({
+ ...task,
+ propertyValues: taskPropertyValues[task.lineIndex] ?? {},
+ }));
+ });
+
+ const toggleTaskMode = () => {
+ const newState = !taskModeEnabled();
+ setTaskModeEnabled(newState);
+ if (newState) {
+ setDebouncedMarkdown(markdownState());
+ } else {
+ setTaskPropertyValues(reconcile({}));
+ }
+ };
+
+ const updateTaskPropertyValue = (
+ lineIndex: number,
+ propertyDefinitionId: string,
+ value: PropertyApiValues
+ ) => {
+ setTaskPropertyValues(lineIndex, (prev) => ({
+ ...prev,
+ [propertyDefinitionId]: value,
+ }));
+ };
+
+ return {
+ taskModeEnabled,
+ toggleTaskMode,
+ setTaskModeEnabled,
+ potentialTasks,
+ updateTaskPropertyValue,
+ };
+}
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.ts
index a91dc52281..10b6dc11db 100644
--- 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.ts
@@ -11,9 +11,7 @@ import {
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 { createTaskFromData } from '../../../../util/taskCreation';
import type {
ConvertCheckboxesOptions,
ConvertCheckboxesPluginOptions,
@@ -29,70 +27,6 @@ import { $parseCheckboxNodes } from './checkboxParsing';
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
*/
@@ -101,25 +35,14 @@ async function createTaskFromCheckbox(
currentUserId?: string,
parentTaskId?: string
): Promise<TaskCreationResult> {
- if (!checkbox.title.trim()) {
- return err({ tag: 'EmptyCheckbox', nodeKey: checkbox.nodeKey });
- }
-
try {
- const propertyValues = buildPropertyValues(
- checkbox,
+ const documentId = await createTaskFromData(checkbox, {
currentUserId,
- parentTaskId
- );
-
- const documentId = await createTask({
- title: checkbox.title,
- content: '',
- propertyValues,
+ parentTaskId,
});
if (!documentId) {
- return err({ tag: 'NoDocumentId', nodeKey: checkbox.nodeKey });
+ return err({ tag: 'EmptyCheckbox', nodeKey: checkbox.nodeKey });
}
return ok({
diff --git a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
index b64d7a1f20..51b01c84d1 100644
--- a/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/EditPropertyValueModal.tsx
@@ -1,23 +1,14 @@
+import { floatWithElement } from '@core/component/LexicalMarkdown/directive/floatWithElement';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
-import {
- constrainModalToViewport,
- MODAL_VIEWPORT_CLASSES,
-} from '@core/util/modalUtils';
import type { EntityReference } from '@service-properties/generated/schemas/entityReference';
import { mergeRefs } from '@solid-primitives/refs';
-import {
- createEffect,
- createMemo,
- createSignal,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
-import { MODAL_DIMENSIONS } from '../../constants';
+import { createSignal, onMount, Show } from 'solid-js';
import { usePropertiesContext } from '../../context/PropertiesContext';
import { usePropertyEditor } from '../../hooks/usePropertyEditor';
import type { PropertyApiValues, PropertyEditorProps } from '../../types';
+
+false && floatWithElement;
import {
entityReferencesToIdSet,
updateEntityReferences,
@@ -31,7 +22,7 @@ import {
// Common CSS classes
const MODAL_BASE =
- 'absolute bg-menu border border-edge-muted max-h-96 overflow-hidden flex flex-col w-full max-w-md';
+ 'absolute z-action-menu bg-menu border border-edge-muted max-h-96 overflow-hidden flex flex-col w-full max-w-md';
export function EditPropertyValueModal(props: PropertyEditorProps) {
const propertyOptionsQuery = usePropertyOptionsQuery(
@@ -40,7 +31,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
const addPropertyOptionMutation = useAddPropertyOptionMutation({});
- const propertyOptions = createMemo(() => {
+ const propertyOptions = () => {
if (
propertyOptionsQuery.isLoading ||
propertyOptionsQuery.isError ||
@@ -48,7 +39,7 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
)
return [];
return propertyOptionsQuery.data;
- });
+ };
const isLoading = () =>
propertyOptionsQuery.isLoading || addPropertyOptionMutation.isPending;
@@ -179,24 +170,6 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
});
});
- createEffect(() => {
- const handleResize = () => {
- if (modalRef && props.position) {
- const constrainedPosition = constrainModalToViewport(
- props.position,
- MODAL_DIMENSIONS.DEFAULT_WIDTH,
- MODAL_DIMENSIONS.DEFAULT_HEIGHT
- );
-
- modalRef.style.top = `${constrainedPosition.top}px`;
- modalRef.style.left = `${constrainedPosition.left}px`;
- }
- };
-
- window.addEventListener('resize', handleResize);
- onCleanup(() => window.removeEventListener('resize', handleResize));
- });
-
return (
<ScopedPortal scope="local">
<div class="fixed inset-0 z-modal" onClick={handleClose}>
@@ -204,28 +177,9 @@ export function EditPropertyValueModal(props: PropertyEditorProps) {
ref={mergeRefs((ref) => {
modalRef = ref;
})}
- class={`${MODAL_BASE} ${MODAL_VIEWPORT_CLASSES}`}
+ class={MODAL_BASE}
tabIndex={-1}
- style={createMemo(() => {
- if (!props.position) {
- return {
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- };
- }
-
- const constrainedPosition = constrainModalToViewport(
- props.position,
- MODAL_DIMENSIONS.DEFAULT_WIDTH,
- MODAL_DIMENSIONS.DEFAULT_HEIGHT
- );
-
- return {
- top: `${constrainedPosition.top}px`,
- left: `${constrainedPosition.left}px`,
- };
- })()}
+ use:floatWithElement={{ element: () => props.anchorRef }}
onClick={(e) => e.stopPropagation()}
>
<Show when={!isLoading()}>
diff --git a/js/app/packages/core/component/Properties/component/modal/Modals.tsx b/js/app/packages/core/component/Properties/component/modal/Modals.tsx
index 1e8cab7295..89f0e4bc96 100644
--- a/js/app/packages/core/component/Properties/component/modal/Modals.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/Modals.tsx
@@ -4,7 +4,6 @@ import { type Component, createMemo } from 'solid-js';
import { Show } from 'solid-js/web';
import { usePropertiesContext } from '../../context/PropertiesContext';
import type { Property } from '../../types';
-import { useModalPosition } from '../../utils/position';
import { CreatePropertyModal } from './CreatePropertyModal';
import { EditPropertyValueModal } from './EditPropertyValueModal';
import { SelectPropertyModal } from './SelectPropertyModal';
@@ -61,19 +60,15 @@ export const Modals: Component = () => {
</Show>
<Show when={propertyEditorModal()}>
- {(state) => {
- const position = useModalPosition(() => state().anchor);
-
- return (
- <EditPropertyValueModal
- property={state().property}
- onClose={closePropertyEditor}
- onSaved={handlePropertySaved}
- position={position()}
- entityType={entityType}
- />
- );
- }}
+ {(state) => (
+ <EditPropertyValueModal
+ property={state().property}
+ onClose={closePropertyEditor}
+ onSaved={handlePropertySaved}
+ anchorRef={state().anchor ?? undefined}
+ entityType={entityType}
+ />
+ )}
</Show>
<Show when={datePickerModal()}>
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx
index 33dde075e2..9618620194 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/CondensedPropertyValue.tsx
@@ -44,13 +44,6 @@ export const CondensedPropertyValue: Component<CondensedPropertyValueProps> = (
}
};
- const isUserProperty = () => {
- return (
- isEntityProperty(props.property) &&
- props.property.specificEntityType === 'USER'
- );
- };
-
return (
<Tooltip
unstyled
@@ -59,11 +52,10 @@ export const CondensedPropertyValue: Component<CondensedPropertyValueProps> = (
>
<div
class={cn(
- 'inline-flex items-center text-xs leading-none text-ink-muted shrink-0 py-1.5 h-6.5 transition-colors',
+ 'inline-flex items-center text-xs leading-none text-ink-muted shrink-0 py-1.5 h-6.5 transition-colors border border-edge-muted/50 px-1.5',
{
'cursor-pointer hover:border-edge-muted hover:bg-hover/50': canEdit,
'opacity-50': !validValue(),
- 'border border-edge-muted/50 px-1.5': !isUserProperty(),
}
)}
onClick={handleClick}
diff --git a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
index 925ed7a901..8a6860ced4 100644
--- a/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
+++ b/js/app/packages/core/component/Properties/component/propertyValue/DateValue.tsx
@@ -3,10 +3,10 @@ import { createSignal, Show } from 'solid-js';
import { usePropertiesContext } from '../../context/PropertiesContext';
import { formatDate } from '../../utils';
import {
- EmptyValue,
PropertyValueDeleteButton,
type PropertyValueProps,
} from './ValueComponents';
+import { cn } from '@ui/utils/classname';
/**
* Display component for date properties
@@ -56,12 +56,19 @@ export const DateValue: Component<PropertyValueProps> = (props) => {
>
<button
onClick={handleClick}
- class="text-left px-2 py-0.5 border border-edge-muted bg-transparent inline-block max-w-full break-words shrink-0"
- classList={{
- 'text-ink-muted cursor-default': true,
- }}
+ class={cn(
+ 'inline-flex items-center text-xs leading-none text-ink-muted shrink-0 py-1.5 h-6.5 transition-colors border border-edge-muted/50 px-1.5',
+ {
+ 'cursor-pointer hover:border-edge-muted hover:bg-hover/50':
+ props.canEdit,
+ 'opacity-50': !displayValue,
+ }
+ )}
>
- <Show when={displayValue} fallback={<EmptyValue />}>
+ <Show
+ when={displayValue}
+ fallback={<span class="opacity-20">Due Date</span>}
+ >
<span class="block truncate max-w-full">{displayValue}</span>
</Show>
</button>
diff --git a/js/app/packages/core/component/Properties/types.ts b/js/app/packages/core/component/Properties/types.ts
index 256db39b68..a54337e592 100644
--- a/js/app/packages/core/component/Properties/types.ts
+++ b/js/app/packages/core/component/Properties/types.ts
@@ -136,7 +136,7 @@ export type PropertyEditorProps = {
property: Property;
onClose: () => void;
onSaved: () => void;
- position?: { top: number; left: number };
+ anchorRef?: HTMLElement;
entityType: EntityType;
};
diff --git a/js/app/packages/core/util/taskCreation.ts b/js/app/packages/core/util/taskCreation.ts
new file mode 100644
index 0000000000..a386087200
--- /dev/null
+++ b/js/app/packages/core/util/taskCreation.ts
@@ -0,0 +1,80 @@
+import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
+import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
+import { createTask } from './create';
+
+export type TaskData = {
+ title: string;
+ assigneeUserIds: string[];
+ dueDate: string | null;
+};
+
+export type TaskCreationOptions = {
+ currentUserId?: string;
+ parentTaskId?: string;
+};
+
+function buildPropertyInputs(
+ task: TaskData,
+ options: TaskCreationOptions
+): PropertyInput[] {
+ const properties: PropertyInput[] = [];
+
+ const assigneeIds =
+ task.assigneeUserIds.length > 0
+ ? task.assigneeUserIds
+ : options.currentUserId
+ ? [options.currentUserId]
+ : [];
+
+ if (assigneeIds.length > 0) {
+ 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 (task.dueDate) {
+ properties.push({
+ propertyId: SYSTEM_PROPERTY_IDS.DUE_DATE,
+ value: { type: 'date', value: task.dueDate },
+ });
+ }
+
+ if (options.parentTaskId) {
+ properties.push({
+ propertyId: SYSTEM_PROPERTY_IDS.PARENT_TASK,
+ value: {
+ type: 'entity_reference',
+ reference: {
+ entity_id: options.parentTaskId,
+ entity_type: 'TASK' as const,
+ },
+ },
+ });
+ }
+
+ return properties;
+}
+
+export async function createTaskFromData(
+ task: TaskData,
+ options: TaskCreationOptions
+): Promise<string | null> {
+ if (!task.title.trim()) return null;
+
+ const propertyValues = buildPropertyInputs(task, options);
+
+ const documentId = await createTask({
+ title: task.title,
+ content: '',
+ propertyValues: propertyValues.length > 0 ? propertyValues : undefined,
+ });
+
+ return documentId ?? null;
+}
diff --git a/js/app/packages/core/util/taskExtraction.test.ts b/js/app/packages/core/util/taskExtraction.test.ts
new file mode 100644
index 0000000000..c02ba2c9fd
--- /dev/null
+++ b/js/app/packages/core/util/taskExtraction.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// Mock the Lexical utils to avoid JSX dependency chain
+vi.mock(
+ '@core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing',
+ async () => {
+ const actual = await vi.importActual<
+ typeof import('@core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing')
+ >(
+ '@core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing'
+ );
+ return {
+ extractUserMentions: actual.extractUserMentions,
+ extractDateMention: actual.extractDateMention,
+ extractTitleFromMarkdown: actual.extractTitleFromMarkdown,
+ };
+ }
+);
+
+vi.mock('@core/component/LexicalMarkdown/utils', () => ({
+ $elementNodeToMarkdown: vi.fn(),
+}));
+
+import { extractCheckboxesFromMarkdown } from './taskExtraction';
+
+describe('extractCheckboxesFromMarkdown', () => {
+ it('should extract single unchecked checkbox', () => {
+ const markdown = '- [ ] Buy groceries';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ lineIndex: 0,
+ title: 'Buy groceries',
+ rawLine: '- [ ] Buy groceries',
+ isChecked: false,
+ assigneeUserIds: [],
+ dueDate: null,
+ });
+ });
+
+ it('should extract single checked checkbox', () => {
+ const markdown = '- [x] Completed task';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ title: 'Completed task',
+ isChecked: true,
+ });
+ });
+
+ it('should handle uppercase X in checkbox', () => {
+ const markdown = '- [X] Task with uppercase X';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].isChecked).toBe(true);
+ });
+
+ it('should extract multiple checkboxes', () => {
+ const markdown = `- [ ] Task 1
+- [x] Task 2
+- [ ] Task 3`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(3);
+ expect(result[0]).toMatchObject({
+ lineIndex: 0,
+ title: 'Task 1',
+ isChecked: false,
+ });
+ expect(result[1]).toMatchObject({
+ lineIndex: 1,
+ title: 'Task 2',
+ isChecked: true,
+ });
+ expect(result[2]).toMatchObject({
+ lineIndex: 2,
+ title: 'Task 3',
+ isChecked: false,
+ });
+ });
+
+ it('should skip empty checkboxes', () => {
+ const markdown = `- [ ] Valid task
+- [ ]
+- [ ]
+- [ ] Another valid task`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(2);
+ expect(result[0].title).toBe('Valid task');
+ expect(result[1].title).toBe('Another valid task');
+ });
+
+ it('should ignore non-checkbox lines', () => {
+ const markdown = `Some intro text
+- [ ] A checkbox task
+Regular bullet point
+- Another bullet
+- [ ] Second checkbox`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toMatchObject({ lineIndex: 1, title: 'A checkbox task' });
+ expect(result[1]).toMatchObject({ lineIndex: 4, title: 'Second checkbox' });
+ });
+
+ it('should handle indented checkboxes', () => {
+ const markdown = `- [ ] Parent task
+ - [ ] Nested task
+ - [ ] Deeply nested`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(3);
+ expect(result[0].title).toBe('Parent task');
+ expect(result[1].title).toBe('Nested task');
+ expect(result[2].title).toBe('Deeply nested');
+ });
+
+ it('should extract user mentions as assignees', () => {
+ const markdown =
+ '- [ ] Fix bug <m-user-mention>{"userId":"user-123","email":"[email protected]"}</m-user-mention>';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].assigneeUserIds).toEqual(['user-123']);
+ expect(result[0].title).toBe('Fix bug');
+ });
+
+ it('should extract multiple user mentions', () => {
+ const markdown =
+ '- [ ] Review PR <m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention> and <m-user-mention>{"userId":"u2","email":"[email protected]"}</m-user-mention>';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].assigneeUserIds).toEqual(['u1', 'u2']);
+ });
+
+ it('should extract date mentions as due date', () => {
+ const markdown =
+ '- [ ] Submit report <m-date-mention>{"date":"2024-03-15T00:00:00Z","displayFormat":"March 15"}</m-date-mention>';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].dueDate).toBe('2024-03-15T00:00:00Z');
+ expect(result[0].title).toBe('Submit report');
+ });
+
+ it('should extract both user and date mentions', () => {
+ const markdown =
+ '- [ ] Complete task <m-user-mention>{"userId":"u1","email":"[email protected]"}</m-user-mention> by <m-date-mention>{"date":"2024-12-31","displayFormat":"Dec 31"}</m-date-mention>';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ title: 'Complete task by',
+ assigneeUserIds: ['u1'],
+ dueDate: '2024-12-31',
+ });
+ });
+
+ it('should return empty array for markdown without checkboxes', () => {
+ const markdown = `# Heading
+Regular paragraph text.
+- Bullet point
+1. Numbered item`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toEqual([]);
+ });
+
+ it('should return empty array for empty markdown', () => {
+ expect(extractCheckboxesFromMarkdown('')).toEqual([]);
+ });
+
+ it('should handle mixed content with checkboxes', () => {
+ const markdown = `# Shopping List
+
+Here are my tasks:
+
+- [ ] Buy milk
+- [ ] Get bread
+
+Some notes below.
+
+- [ ] Call mom`;
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(3);
+ expect(result[0]).toMatchObject({ lineIndex: 4, title: 'Buy milk' });
+ expect(result[1]).toMatchObject({ lineIndex: 5, title: 'Get bread' });
+ expect(result[2]).toMatchObject({ lineIndex: 9, title: 'Call mom' });
+ });
+
+ it('should preserve rawLine for replacement', () => {
+ const markdown = ' - [ ] Indented with spaces';
+ const result = extractCheckboxesFromMarkdown(markdown);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].rawLine).toBe(' - [ ] Indented with spaces');
+ });
+});
diff --git a/js/app/packages/core/util/taskExtraction.ts b/js/app/packages/core/util/taskExtraction.ts
new file mode 100644
index 0000000000..e88817407e
--- /dev/null
+++ b/js/app/packages/core/util/taskExtraction.ts
@@ -0,0 +1,79 @@
+/**
+ * Generalized utilities for extracting potential tasks from markdown content.
+ * Used by Task Mode in channel input to preview and create tasks from checkboxes.
+ */
+
+import {
+ extractUserMentions,
+ extractDateMention,
+ extractTitleFromMarkdown,
+} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task/checkboxParsing';
+
+export { extractUserMentions, extractDateMention, extractTitleFromMarkdown };
+
+/**
+ * Represents a potential task extracted from markdown text.
+ * Unlike ParsedCheckbox (which requires Lexical node context),
+ * this works with raw markdown strings.
+ */
+export type PotentialTask = {
+ /** Line index in the source markdown (0-based) */
+ lineIndex: number;
+ /** Cleaned title without mentions */
+ title: string;
+ /** Original line for replacement matching */
+ rawLine: string;
+ /** User IDs extracted from @mentions */
+ assigneeUserIds: string[];
+ /** ISO date string from date mention, or null */
+ dueDate: string | null;
+ /** Whether the checkbox is checked [x] or unchecked [ ] */
+ isChecked: boolean;
+};
+
+// Pattern to match checkbox lines: "- [ ] text" or "- [x] text"
+// Captures: (1) leading whitespace, (2) check state, (3) content after checkbox
+const CHECKBOX_LINE_PATTERN = /^(\s*)-\s*\[([ xX])\]\s*(.*)$/;
+
+/**
+ * Extract all checkbox items from a markdown string as potential tasks.
+ *
+ * @param markdown - Raw markdown content
+ * @returns Array of potential tasks with extracted metadata
+ */
+export function extractCheckboxesFromMarkdown(
+ markdown: string
+): PotentialTask[] {
+ const lines = markdown.split('\n');
+ const tasks: PotentialTask[] = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const match = CHECKBOX_LINE_PATTERN.exec(line);
+
+ if (match) {
+ const [, leadingWhitespace, checkState, content] = match;
+ const isChecked = checkState.toLowerCase() === 'x';
+
+ // Strip leading whitespace before passing to extractTitleFromMarkdown
+ // since it expects the line to start with "- [ ]"
+ const lineWithoutIndent = line.slice(leadingWhitespace.length);
+ const title = extractTitleFromMarkdown(lineWithoutIndent);
+
+ if (!title.trim()) {
+ continue;
+ }
+
+ tasks.push({
+ lineIndex: i,
+ title,
+ rawLine: line,
+ assigneeUserIds: extractUserMentions(content),
+ dueDate: extractDateMention(content),
+ isChecked,
+ });
+ }
+ }
+
+ return tasks;
+}