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(projects): set a task's project like any other property (#7160)

teo9ce0a2fdb144
diff --git a/apps/web/src/features/projects/project-property.tsx b/apps/web/src/features/projects/project-property.tsx
new file mode 100644
index 0000000000..8cf29390ac
--- /dev/null
+++ b/apps/web/src/features/projects/project-property.tsx
@@ -0,0 +1,132 @@
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';
+import StackIcon from '@phosphor/stack.svg';
+import { Property } from '@property';
+import { Dropdown, HoverCard, Layer } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import type { TaskProjectReference } from './core/project';
+import { Projects } from './projects';
+import { ProjectPicker } from './views/project-picker';
+
+type AnchorRect = { x: number; y: number; width?: number; height?: number };
+
+/** The project picker in the same popover shell as the property editors. */
+export function ProjectPickerPopover(props: {
+ taskIds: readonly string[];
+ open: boolean;
+ onOpenChange(open: boolean): void;
+ getAnchorRect(): AnchorRect | undefined;
+}) {
+ let openedAt = 0;
+ // A context menu hands focus back to its row just after this opens; 100ms
+ // (as in TagPickerPopover) keeps that focus-out from dismissing it.
+ const close = () => {
+ if (performance.now() - openedAt > 100) props.onOpenChange(false);
+ };
+ return (
+ <Dropdown
+ open={props.open}
+ onOpenChange={(open) => (open ? props.onOpenChange(true) : close())}
+ getAnchorRect={props.getAnchorRect}
+ placement="bottom-start"
+ >
+ <Show when={props.open}>
+ {(_) => {
+ openedAt = performance.now();
+ return (
+ <Property.EditorPopover onClose={close}>
+ <Projects>
+ <ProjectPicker
+ taskIds={props.taskIds}
+ onClose={() => props.onOpenChange(false)}
+ />
+ </Projects>
+ </Property.EditorPopover>
+ );
+ }}
+ </Show>
+ </Dropdown>
+ );
+}
+
+/** Task list cell for a task's project, matching the other property cells. */
+export function ProjectPropertyCell(props: {
+ taskId: string;
+ reference?: TaskProjectReference;
+}) {
+ const [anchor, setAnchor] = createSignal<HTMLElement>();
+ const project = () =>
+ props.reference?.state === 'visible' ? props.reference : undefined;
+ const emptyLabel = () =>
+ props.reference?.state === 'unavailable'
+ ? 'Unavailable project'
+ : 'Project';
+ return (
+ <>
+ <HoverCard
+ content={
+ <div class="flex flex-row gap-2 items-center">
+ <div class="flex items-center gap-2 text-ink-muted">
+ <StackIcon class="size-3.5 text-ink-muted" />
+ <span class="text-xs">Project</span>
+ </div>
+ <div class="inline-flex min-w-0 items-center gap-1.5 px-2 py-0.5 text-xs leading-5 text-ink-muted w-fit rounded-sm">
+ <span class="truncate max-w-37.5">
+ {project()?.name ?? `No project set`}
+ </span>
+ </div>
+ </div>
+ }
+ disabled={anchor() !== undefined}
+ contentClass="rounded-xl p-1.5 px-3 glass bg-menu-glass"
+ // The trigger is a flex item; min-w-0 lets long names truncate in the column.
+ triggerClass="w-full min-w-0"
+ >
+ <Layer depth={2}>
+ <button
+ type="button"
+ class="list-property-cell cursor-default inline-flex w-full max-w-full min-w-0 items-center gap-1 overflow-hidden rounded-full px-2 py-1.5 text-left leading-tight hover:bg-surface/50 @max-[840px]/u-list:px-1"
+ onClick={(event) => {
+ event.stopPropagation();
+ setAnchor(event.currentTarget);
+ }}
+ >
+ <Show
+ when={project()}
+ fallback={
+ <>
+ <CircleDashedEmpty class="size-3 shrink-0 opacity-50 @max-[840px]/u-list:size-4" />
+ <span class="min-w-0 flex-1 truncate opacity-50 @max-[840px]/u-list:hidden">
+ {emptyLabel()}
+ </span>
+ </>
+ }
+ >
+ {(project) => (
+ <>
+ <StackIcon class="size-3 shrink-0 @max-[840px]/u-list:size-4" />
+ <span class="min-w-0 max-w-full flex-1 truncate @max-[840px]/u-list:hidden">
+ {project().name}
+ </span>
+ </>
+ )}
+ </Show>
+ <CaretDownIcon class="size-3 shrink-0 @max-[840px]/u-list:hidden" />
+ </button>
+ </Layer>
+ </HoverCard>
+ <ProjectPickerPopover
+ taskIds={[props.taskId]}
+ open={anchor() !== undefined}
+ onOpenChange={(open) => {
+ if (open) return;
+ const trigger = anchor();
+ setAnchor(undefined);
+ // No Kobalte trigger to return focus to, so hand it back ourselves.
+ setTimeout(() => trigger?.isConnected && trigger.focus(), 0);
+ }}
+ getAnchorRect={() => anchor()?.getBoundingClientRect()}
+ />
+ </>
+ );
+}
diff --git a/apps/web/src/features/projects/views/project-picker.test.tsx b/apps/web/src/features/projects/views/project-picker.test.tsx
new file mode 100644
index 0000000000..c1b86d827c
--- /dev/null
+++ b/apps/web/src/features/projects/views/project-picker.test.tsx
@@ -0,0 +1,74 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { ProjectPicker } from './project-picker';
+
+const mock = vi.hoisted(() => ({
+ assignTasks: vi.fn(),
+ failure: vi.fn(),
+}));
+
+vi.mock('@ui', async () => ({
+ ...(await import('@app/components/ui/utils/classname')),
+ Hotkey: () => null,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mock.failure },
+}));
+// Cut the selector's property-utils import graph, which reaches the editor.
+vi.mock('@property/utils', () => ({ useSearchInputFocus: () => {} }));
+vi.mock('@property/utils/errorHandling', () => ({ ERROR_MESSAGES: {} }));
+vi.mock('@property/component/propertyValue', () => ({
+ PropertyValueIcon: () => null,
+}));
+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
+vi.mock('../context/projects-context', () => ({
+ useProjectsContext: () => ({
+ createCollectionSource: () => ({
+ rows: () => [
+ { project: { id: 'editable', name: 'Editable', access: 'edit' } },
+ { project: { id: 'readonly', name: 'Read only', access: 'view' } },
+ ],
+ loading: () => false,
+ error: () => undefined,
+ hasMore: () => false,
+ loadingMore: () => false,
+ }),
+ createCommands: () => ({ assignTasks: mock.assignTasks }),
+ }),
+}));
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+it('lists only projects the user can add tasks to', () => {
+ render(() => <ProjectPicker taskIds={['task']} onClose={() => {}} />);
+ expect(screen.getByText('No project')).toBeTruthy();
+ expect(screen.getByText('Editable')).toBeTruthy();
+ expect(screen.queryByText('Read only')).toBeNull();
+});
+
+it('closes, then assigns only the given tasks', async () => {
+ mock.assignTasks.mockResolvedValue([{ taskId: 'task' }]);
+ const close = vi.fn();
+ render(() => <ProjectPicker taskIds={['task']} onClose={close} />);
+ fireEvent.click(screen.getByText('Editable'));
+ expect(close).toHaveBeenCalledOnce();
+ expect(mock.assignTasks).toHaveBeenCalledWith('editable', ['task']);
+ await Promise.resolve();
+ expect(mock.failure).not.toHaveBeenCalled();
+});
+
+it('clears the project and reports per-task failures', async () => {
+ mock.assignTasks.mockResolvedValue([
+ { taskId: 'task', error: 'You need edit access to this task.' },
+ ]);
+ render(() => <ProjectPicker taskIds={['task']} onClose={() => {}} />);
+ fireEvent.click(screen.getByText('No project'));
+ expect(mock.assignTasks).toHaveBeenCalledWith(undefined, ['task']);
+ await vi.waitFor(() =>
+ expect(mock.failure).toHaveBeenCalledWith('Could not set project', {
+ subtext: 'You need edit access to this task.',
+ })
+ );
+});
diff --git a/apps/web/src/features/projects/views/project-picker.tsx b/apps/web/src/features/projects/views/project-picker.tsx
new file mode 100644
index 0000000000..d9dd6c8aa1
--- /dev/null
+++ b/apps/web/src/features/projects/views/project-picker.tsx
@@ -0,0 +1,205 @@
+import { toast } from '@core/component/Toast/Toast';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { debouncedDependent } from '@core/util/debounce';
+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';
+import LoadingSpinner from '@phosphor/spinner.svg';
+import StackIcon from '@phosphor/stack.svg';
+import {
+ DropdownSearchInput,
+ DropdownSelectableRow,
+ useDropdownSearch,
+} from '@property/editors/selectors/PropertyOptionSelector';
+import { useSearchInputFocus } from '@property/utils';
+import {
+ createEffect,
+ createMemo,
+ For,
+ Match,
+ onCleanup,
+ onMount,
+ Show,
+ Switch,
+} from 'solid-js';
+import { useProjectsContext } from '../context/projects-context';
+
+type PickerItem =
+ | { type: 'clear' }
+ | { type: 'project'; id: string; name: string };
+
+/** Project list for the property popover, laid out like the select editor. */
+export function ProjectPicker(props: {
+ taskIds: readonly string[];
+ onClose(): void;
+}) {
+ const context = useProjectsContext();
+ const commands = context.createCommands();
+ let searchInputRef: HTMLInputElement | undefined;
+ let listRef: HTMLDivElement | undefined;
+
+ const assign = async (projectId?: string) => {
+ // Close first like the other property editors; the save settles after.
+ props.onClose();
+ try {
+ const results = await commands.assignTasks(projectId, props.taskIds);
+ const failed = results.filter((item) => item.error);
+ if (!failed.length) return;
+ toast.failure(
+ failed.length === 1
+ ? 'Could not set project'
+ : `${failed.length} tasks could not be updated`,
+ { subtext: failed[0].error }
+ );
+ } catch (error) {
+ toast.failure('Could not set project', {
+ subtext: error instanceof Error ? error.message : undefined,
+ });
+ }
+ };
+
+ const dropdown = useDropdownSearch({
+ itemCount: () => items().length,
+ onSelect: (index) => {
+ const item = items()[index];
+ if (item) void assign(item.type === 'project' ? item.id : undefined);
+ },
+ onClose: props.onClose,
+ });
+
+ const query = debouncedDependent(dropdown.searchQuery, 150);
+ const source = context.createCollectionSource(() => ({
+ query: query().trim() || undefined,
+ sort: 'updated',
+ descending: true,
+ }));
+
+ const items = createMemo<PickerItem[]>(() => {
+ const projects: PickerItem[] = (source.rows() ?? [])
+ .filter(
+ (row) => row.project.access === 'edit' || row.project.access === 'owner'
+ )
+ .map((row) => ({
+ type: 'project',
+ id: row.project.id,
+ name: row.project.name,
+ }));
+ // Matches the select editor: the "no value" row only shows unsearched.
+ return dropdown.searchQuery().trim()
+ ? projects
+ : [{ type: 'clear' }, ...projects];
+ });
+
+ createEffect(() => {
+ const index = dropdown.selectedIndex();
+ if (!dropdown.keyboardMode() || !listRef) return;
+ listRef
+ .querySelector(`[data-project-index="${index}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ });
+
+ const loadMoreNearEnd = (element: HTMLElement) => {
+ if (!source.hasMore() || source.loadingMore()) return;
+ // One row of slack so the next page lands before the list bottoms out.
+ if (element.scrollTop + element.clientHeight >= element.scrollHeight - 32)
+ void source.loadMore();
+ };
+
+ onMount(() => document.addEventListener('keydown', dropdown.handleKeyDown));
+ onCleanup(() =>
+ document.removeEventListener('keydown', dropdown.handleKeyDown)
+ );
+
+ useSearchInputFocus(() => searchInputRef);
+
+ return (
+ <div>
+ <Show when={!isTouchDevice()}>
+ <DropdownSearchInput
+ value={dropdown.searchQuery()}
+ inputRef={(element) => {
+ searchInputRef = element;
+ }}
+ onInput={dropdown.setSearchQuery}
+ placeholder="Add to project..."
+ />
+ </Show>
+ <div class="p-1.5">
+ <Switch>
+ <Match when={source.error()}>
+ <div role="alert" class="text-center py-4 text-ink-muted">
+ Could not load projects
+ </div>
+ </Match>
+ <Match when={source.loading() && !source.rows()?.length}>
+ <div class="flex items-center justify-center py-8">
+ <div class="w-5 h-5 animate-spin">
+ <LoadingSpinner />
+ </div>
+ <span class="ml-2 text-ink-muted">Loading projects...</span>
+ </div>
+ </Match>
+ <Match when={true}>
+ <div
+ ref={listRef}
+ class="max-h-50 overflow-y-auto overflow-x-hidden scrollbar-hidden"
+ onScroll={(event) => loadMoreNearEnd(event.currentTarget)}
+ >
+ <For each={items()}>
+ {(item, index) => (
+ <div data-project-index={index()}>
+ <DropdownSelectableRow
+ isSelected={index() === dropdown.selectedIndex()}
+ onClick={() =>
+ void assign(
+ item.type === 'project' ? item.id : undefined
+ )
+ }
+ onMouseEnter={() => {
+ if (!dropdown.keyboardMode())
+ dropdown.setSelectedIndex(index());
+ }}
+ showHotkey={dropdown.shouldShowHotkeys() && index() <= 9}
+ hotkeyShortcut={`${index()}`}
+ >
+ <Show
+ when={item.type === 'project' && item}
+ fallback={
+ <>
+ <CircleDashedEmpty class="size-3 shrink-0 text-ink-extra-muted" />
+ <p class="flex-1 min-w-0 truncate text-ink-muted">
+ No project
+ </p>
+ </>
+ }
+ >
+ {(project) => (
+ <>
+ <StackIcon class="size-3 shrink-0" />
+ <p class="flex-1 min-w-0 truncate">
+ {project().name}
+ </p>
+ </>
+ )}
+ </Show>
+ </DropdownSelectableRow>
+ </div>
+ )}
+ </For>
+ <Show
+ when={
+ !source.loading() &&
+ !items().some((item) => item.type === 'project')
+ }
+ >
+ <div class="text-center py-4 text-ink-muted">
+ {dropdown.searchQuery().trim()
+ ? 'No projects match your search'
+ : 'No projects available'}
+ </div>
+ </Show>
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/property/editors/popover/EditorPopover.tsx b/apps/web/src/features/property/editors/popover/EditorPopover.tsx
index 95f4da4975..db4a0eda4d 100644
--- a/apps/web/src/features/property/editors/popover/EditorPopover.tsx
+++ b/apps/web/src/features/property/editors/popover/EditorPopover.tsx
@@ -1,14 +1,14 @@
import { useIsInsideHoverCard } from '@core/component/HoverCard';
import { cn, Dropdown } from '@ui';
-import { type JSX, onCleanup, onMount } from 'solid-js';
-import { useProperty } from '../../core/context';
+import { type JSX, onCleanup, onMount, useContext } from 'solid-js';
+import { PropertyRootContext } from '../../core/context';
type EditorPopoverProps = {
children: JSX.Element;
class?: string;
/**
* Called on ESC or outside-interaction. Default: <Property.Root>'s closeEditor.
- * Override to save-on-close.
+ * Override to save-on-close, or to host the popover outside a Property.Root.
*/
onClose?: () => void;
/**
@@ -22,18 +22,18 @@ type EditorPopoverProps = {
/**
* Floating shell for popover-style editors (date / select / entity). The
- * surrounding <Property.Root> hosts a Kobalte DropdownMenu — this component
+ * surrounding <Property.Root> (or any <Dropdown>) hosts a Kobalte DropdownMenu — this component
* just renders the Content. Kobalte handles ESC, click-outside, focus
* trap, and focus return. `onClose` is invoked on dismissal so consumers can
* save-on-close.
*/
export function EditorPopover(props: EditorPopoverProps) {
- const ctx = useProperty();
+ const ctx = useContext(PropertyRootContext);
const isInsideHoverCard = useIsInsideHoverCard();
const close = () => {
if (props.onClose) props.onClose();
- else ctx.closeEditor();
+ else ctx?.closeEditor();
};
const handleEscapeKeyDown = (event: KeyboardEvent) => {
diff --git a/apps/web/src/features/soup/SoupEntityContextMenu.tsx b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
index 2ec9886c90..e88e7f5b9e 100644
--- a/apps/web/src/features/soup/SoupEntityContextMenu.tsx
+++ b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
@@ -3,7 +3,7 @@ import {
type EntityActionViewContext,
makeAddTagAction,
} from '@app/features/next-soup/actions';
-import { ProjectAssignmentDialog } from '@app/features/projects/projects';
+import { ProjectPickerPopover } from '@app/features/projects/project-property';
import { ContextMenuContent, MenuSeparator } from '@core/component/ContextMenu';
import { touchHandler } from '@core/directive/touchHandler';
import { isMobile } from '@core/mobile/isMobile';
@@ -156,9 +156,13 @@ export const SoupEntityContextMenu: FlowComponent<
</ContextMenu>
<Show when={projectTasks()}>
{(ids) => (
- <ProjectAssignmentDialog
+ <ProjectPickerPopover
taskIds={ids()}
- onClose={() => setProjectTasks(undefined)}
+ open
+ onOpenChange={(open) => {
+ if (!open) setProjectTasks(undefined);
+ }}
+ getAnchorRect={() => menuPosition()}
/>
)}
</Show>
diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.ts
index 64fb7d570e..52e8884d54 100644
--- a/apps/web/src/features/soup/createSoupEntityActions.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.ts
@@ -43,7 +43,6 @@ import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import type { EntityData } from '@entity';
import { isTaskEntity } from '@entity';
-import StackIcon from '@phosphor/stack.svg';
import { useSetCompanyHiddenMutation } from '@queries/crm/companies';
import type { Component, JSX } from 'solid-js';
@@ -396,8 +395,7 @@ export function createSoupEntityActions(): {
) {
middleItems.push({
id: 'set-initiative',
- label: 'Set project…',
- icon: StackIcon,
+ label: 'Set project',
onClick: () => {
if (isFeatureEnabled(enableProjects)) openProjectPicker();
},
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
index d35f95aae9..c445443712 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
@@ -212,7 +212,10 @@ export function TaskGridLayout(props: TaskGridLayoutProps) {
</For>
<Show when={props.projectSlot !== undefined}>
- <Entity.Slot placement="initiative" class="min-w-0 truncate text-xs">
+ <Entity.Slot
+ placement="initiative"
+ class="flex items-center min-w-0 text-xs ph-no-capture @container/slot @max-[840px]/u-list:justify-center"
+ >
{props.projectSlot}
</Entity.Slot>
</Show>
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
index 87fc6ec5a0..6f27e7857d 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
@@ -61,13 +61,11 @@ import { TaskListEntity } from './TaskListEntity';
import { TaskListHeader } from './TaskListHeader';
import { taskGridColumnCount } from './task-grid-template';
import './task-list.css';
-import { ProjectChip } from '@app/features/projects/components/project-chip';
-import { openProject } from '@app/features/projects/open-project';
import {
- ProjectAssignmentDialog,
- useTaskProjectReferences,
-} from '@app/features/projects/projects';
-import { useSplitLayout } from '@components/app/split-layout/layout';
+ ProjectPickerPopover,
+ ProjectPropertyCell,
+} from '@app/features/projects/project-property';
+import { useTaskProjectReferences } from '@app/features/projects/projects';
function ResponsiveTaskListHeader() {
const layout = useListLayout();
@@ -228,10 +226,11 @@ export function TaskList(props: TaskListProps) {
row.kind === 'entity' ? [row.entity.id] : []
)
);
- const projectLayout = useSplitLayout();
const columnCount = () => taskGridColumnCount(projectsEnabled());
- const [assigningProjectTasks, setAssigningProjectTasks] =
- createSignal<string[]>();
+ const [assigningProjectTasks, setAssigningProjectTasks] = createSignal<{
+ ids: string[];
+ anchor: HTMLElement;
+ }>();
const tasksById = createMemo(() => {
const tasks = new Map<string, TaskEntityWithProperties>();
for (const row of visibleRows()) {
@@ -513,15 +512,11 @@ export function TaskList(props: TaskListProps) {
<TaskListEntity
projectSlot={
projectsEnabled() ? (
- <ProjectChip
+ <ProjectPropertyCell
+ taskId={entityRow().entity.id}
reference={projectReferences
.references()
.get(entityRow().entity.id)}
- onOpen={(id, event) =>
- openProject(projectLayout, id, {
- newSplit: event.shiftKey,
- })
- }
/>
) : undefined
}
@@ -675,10 +670,11 @@ export function TaskList(props: TaskListProps) {
<Button
size="sm"
class="whitespace-nowrap"
- onClick={() =>
- setAssigningProjectTasks(
- selectedTasks().map((task) => task.id)
- )
+ onClick={(event) =>
+ setAssigningProjectTasks({
+ ids: selectedTasks().map((task) => task.id),
+ anchor: event.currentTarget,
+ })
}
>
Set project
@@ -687,10 +683,14 @@ export function TaskList(props: TaskListProps) {
</EntitySelectionToolbar>
</Show>
<Show when={projectsEnabled() && assigningProjectTasks()}>
- {(ids) => (
- <ProjectAssignmentDialog
- taskIds={ids()}
- onClose={() => setAssigningProjectTasks(undefined)}
+ {(assigning) => (
+ <ProjectPickerPopover
+ taskIds={assigning().ids}
+ open
+ onOpenChange={(open) => {
+ if (!open) setAssigningProjectTasks(undefined);
+ }}
+ getAnchorRect={() => assigning().anchor.getBoundingClientRect()}
/>
)}
</Show>