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): add a context menu to project rows (#7182)

teo04d8eaa21f05
diff --git a/apps/web/src/components/ui/components/DeleteDialog.tsx b/apps/web/src/components/ui/components/DeleteDialog.tsx
index 87d26a6938..e5cd62b05f 100644
--- a/apps/web/src/components/ui/components/DeleteDialog.tsx
+++ b/apps/web/src/components/ui/components/DeleteDialog.tsx
@@ -21,6 +21,8 @@ export type DeleteDialogProps = ManagedDialogProps & {
pending?: boolean;
position?: DialogProps['position'];
class?: string;
+ /** Where focus lands on close, e.g. when the opener no longer exists. */
+ onCloseAutoFocus?: DialogProps['onCloseAutoFocus'];
onDelete: () => void;
};
@@ -49,6 +51,7 @@ export function DeleteDialog(props: DeleteDialogProps) {
onOpenChange={(open) => {
if (!open) close();
}}
+ onCloseAutoFocus={props.onCloseAutoFocus}
position={props.position ?? 'center'}
class={cn('w-110', props.class)}
visibleScrim
diff --git a/apps/web/src/features/projects/components/delete-projects-dialog.tsx b/apps/web/src/features/projects/components/delete-projects-dialog.tsx
new file mode 100644
index 0000000000..c5c485878c
--- /dev/null
+++ b/apps/web/src/features/projects/components/delete-projects-dialog.tsx
@@ -0,0 +1,41 @@
+import { DeleteDialog } from '@ui';
+import { Show } from 'solid-js';
+
+/** Confirms deleting projects; their tasks stay in the workspace. */
+export function DeleteProjectsDialog(props: {
+ count: number;
+ pending: boolean;
+ error?: string;
+ onOpenChange(open: boolean): void;
+ onDelete(): void;
+ onCloseAutoFocus?(event: Event): void;
+}) {
+ const many = () => props.count > 1;
+ return (
+ <DeleteDialog
+ open
+ onOpenChange={props.onOpenChange}
+ title={many() ? `Delete ${props.count} projects?` : 'Delete project?'}
+ body={
+ <>
+ <p>
+ {many()
+ ? 'These projects and their activity will be deleted. Their tasks will remain in your workspace.'
+ : 'The project and its activity will be deleted. Its tasks will remain in your workspace.'}
+ </p>
+ <Show when={props.error}>
+ {(message) => (
+ <p role="alert" class="mt-2 text-failure">
+ {message()}
+ </p>
+ )}
+ </Show>
+ </>
+ }
+ deleteLabel={many() ? `Delete ${props.count} projects` : 'Delete project'}
+ pending={props.pending}
+ onDelete={props.onDelete}
+ onCloseAutoFocus={props.onCloseAutoFocus}
+ />
+ );
+}
diff --git a/apps/web/src/features/projects/components/project-row-menu.tsx b/apps/web/src/features/projects/components/project-row-menu.tsx
new file mode 100644
index 0000000000..2d92cc6740
--- /dev/null
+++ b/apps/web/src/features/projects/components/project-row-menu.tsx
@@ -0,0 +1,305 @@
+import {
+ SoupEntityActionDrawer,
+ type SoupEntityDrawerActionGroup,
+} from '@app/features/soup/SoupEntityActionDrawer';
+import {
+ ContextMenuContent,
+ ContextMenuTrigger,
+ MenuItem,
+ MenuSeparator,
+ SubTrigger,
+} from '@core/component/ContextMenu';
+import { touchHandler } from '@core/directive/touchHandler';
+import { isMobile } from '@core/mobile/isMobile';
+import type { InitiativeEntity } from '@entity';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import { PropertyValueIcon } from '@property/component/propertyValue';
+import type { Property } from '@property/types';
+import { formatOptionValue } from '@property/utils/formatting';
+import {
+ createSignal,
+ For,
+ Match,
+ type ParentProps,
+ Show,
+ Switch,
+} from 'solid-js';
+import { match } from 'ts-pattern';
+import type { ProjectRow } from '../context/projects-context';
+import { type ProjectMenuItem, projectMenuGroups } from '../core/project-menu';
+
+type ProjectRowMenuProps = {
+ /** The projects the menu acts on, read each time it opens. */
+ targets(): readonly ProjectRow[];
+ /** Definitions offering the choices; their entries wait until they load. */
+ status?: Property;
+ priority?: Property;
+ canOpenInNewSplit: boolean;
+ onOpenInNewSplit(row: ProjectRow): void;
+ onRename(row: ProjectRow): void;
+ onSetOption(
+ rows: readonly ProjectRow[],
+ property: Property,
+ optionId: string
+ ): void;
+ onCopyLink(row: ProjectRow): void;
+ onCopyId(row: ProjectRow): void;
+ /** Omit where the host cannot show the Share menu. */
+ onShare?(row: ProjectRow): void;
+ onDelete(rows: readonly ProjectRow[]): void;
+};
+
+/** One entry, shown as a menu item on desktop and a drawer row on mobile. */
+type ProjectMenuEntry =
+ | {
+ kind: 'action';
+ id: ProjectMenuItem;
+ label: string;
+ shortcut?: string;
+ disabled?: boolean;
+ destructive?: boolean;
+ run(): void;
+ }
+ | {
+ kind: 'options';
+ id: ProjectMenuItem;
+ label: string;
+ property: Property;
+ options: { id: string; label: string }[];
+ choose(optionId: string): void;
+ };
+
+function projectMenuEntries(
+ props: ProjectRowMenuProps,
+ rows: readonly ProjectRow[]
+): ProjectMenuEntry[][] {
+ const single = (callback?: (row: ProjectRow) => void) => () => {
+ const row = rows[0];
+ if (row) callback?.(row);
+ };
+ const action = (
+ id: ProjectMenuItem,
+ label: string,
+ run: () => void,
+ extra: { shortcut?: string; disabled?: boolean; destructive?: boolean } = {}
+ ): ProjectMenuEntry[] => [{ kind: 'action', id, label, run, ...extra }];
+ const options = (
+ id: ProjectMenuItem,
+ label: string,
+ property: Property | undefined
+ ): ProjectMenuEntry[] =>
+ property
+ ? [
+ {
+ kind: 'options',
+ id,
+ label,
+ property,
+ options: (property.options ?? []).map((option) => ({
+ id: option.id,
+ label: formatOptionValue(option),
+ })),
+ choose: (optionId) => props.onSetOption(rows, property, optionId),
+ },
+ ]
+ : [];
+ return projectMenuGroups(
+ rows.map((row) => row.project),
+ {
+ splits: !isMobile(),
+ share: Boolean(props.onShare),
+ status: Boolean(props.status),
+ priority: Boolean(props.priority),
+ }
+ ).map((group) =>
+ group.flatMap((item) =>
+ match(item)
+ .with('open-in-split', (id) =>
+ action(id, 'Open in new split', single(props.onOpenInNewSplit), {
+ shortcut: 'shift+enter',
+ // Without room for another split the open would replace this one.
+ disabled: !props.canOpenInNewSplit,
+ })
+ )
+ .with('rename', (id) => action(id, 'Rename', single(props.onRename)))
+ .with('status', (id) => options(id, 'Set status', props.status))
+ .with('priority', (id) => options(id, 'Set priority', props.priority))
+ .with('copy-link', (id) =>
+ action(id, 'Copy Link', single(props.onCopyLink))
+ )
+ .with('copy-id', (id) => action(id, 'Copy ID', single(props.onCopyId)))
+ .with('share', (id) => action(id, 'Share', single(props.onShare)))
+ .with('delete', (id) =>
+ action(id, 'Delete', () => props.onDelete(rows), {
+ destructive: true,
+ })
+ )
+ .exhaustive()
+ )
+ );
+}
+
+/** A drawer has no submenus, so each option becomes its own row. */
+function drawerGroups(
+ entries: ProjectMenuEntry[][]
+): SoupEntityDrawerActionGroup[] {
+ return entries.flatMap((group) => {
+ const actions = group.flatMap((entry) =>
+ entry.kind === 'action'
+ ? [
+ {
+ id: entry.id,
+ label: entry.label,
+ disabled: entry.disabled,
+ destructive: entry.destructive,
+ onClick: entry.run,
+ },
+ ]
+ : []
+ );
+ const options = group.flatMap((entry) =>
+ entry.kind === 'options'
+ ? [
+ {
+ items: entry.options.map((option) => ({
+ id: `${entry.id}:${option.id}`,
+ label: `${entry.property.displayName}: ${option.label}`,
+ onClick: () => entry.choose(option.id),
+ })),
+ },
+ ]
+ : []
+ );
+ return actions.length > 0 ? [{ items: actions }, ...options] : options;
+ });
+}
+
+/** The drawer header shows the project like any other entity. */
+const initiativeEntity = (row: ProjectRow): InitiativeEntity => ({
+ type: 'initiative',
+ id: row.project.id,
+ name: row.project.name,
+ ownerId: '',
+ descriptionDocumentId: row.project.descriptionDocumentId,
+});
+
+/**
+ * A project row's actions: a right-click menu on desktop and, as for task
+ * rows, a long-press drawer on mobile.
+ */
+export function ProjectRowMenu(
+ props: ParentProps<
+ ProjectRowMenuProps & {
+ onOpenChange(open: boolean): void;
+ onCloseAutoFocus?(event: Event): void;
+ }
+ >
+) {
+ const [drawerRows, setDrawerRows] = createSignal<readonly ProjectRow[]>();
+ return (
+ <Switch>
+ <Match when={isMobile()}>
+ <div
+ class="w-full"
+ ref={(element) =>
+ touchHandler(element, () => ({
+ onLongPress: () => {
+ props.onOpenChange(true);
+ setDrawerRows(props.targets());
+ },
+ }))
+ }
+ >
+ {props.children}
+ </div>
+ <Show when={drawerRows()}>
+ {(rows) => {
+ const [row, ...rest] = rows();
+ return (
+ <SoupEntityActionDrawer
+ entity={
+ row && rest.length === 0 ? initiativeEntity(row) : undefined
+ }
+ groups={drawerGroups(projectMenuEntries(props, rows()))}
+ open
+ onOpenChange={(open) => {
+ if (!open) setDrawerRows(undefined);
+ }}
+ />
+ );
+ }}
+ </Show>
+ </Match>
+ <Match when={true}>
+ <ContextMenu onOpenChange={props.onOpenChange}>
+ <ContextMenuTrigger class="w-full">
+ {props.children}
+ </ContextMenuTrigger>
+ <ContextMenu.Portal>
+ <ContextMenuContent
+ class="w-56 text-xs text-ink-muted"
+ onCloseAutoFocus={props.onCloseAutoFocus}
+ >
+ <ProjectMenuItems {...props} />
+ </ContextMenuContent>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ </Match>
+ </Switch>
+ );
+}
+
+function ProjectMenuItems(props: ProjectRowMenuProps) {
+ // Mounted per opening, so the entries match the rows they act on.
+ const entries = projectMenuEntries(props, props.targets());
+ return (
+ <For each={entries}>
+ {(group, index) => (
+ <>
+ <Show when={index() > 0}>
+ <MenuSeparator />
+ </Show>
+ <For each={group}>
+ {(entry) =>
+ match(entry)
+ .with({ kind: 'action' }, (action) => (
+ <MenuItem
+ text={action.label}
+ shortcut={action.shortcut}
+ disabled={action.disabled}
+ class={action.destructive ? 'text-failure-ink' : undefined}
+ onClick={action.run}
+ />
+ ))
+ .with({ kind: 'options' }, (entry) => (
+ <ContextMenu.Sub>
+ <SubTrigger text={entry.label} />
+ <ContextMenuContent
+ submenu
+ class="w-48 text-xs text-ink-muted"
+ >
+ <For each={entry.options}>
+ {(option) => (
+ <MenuItem
+ text={option.label}
+ icon={(icon) => (
+ <PropertyValueIcon
+ optionId={option.id}
+ class={icon.class}
+ />
+ )}
+ onClick={() => entry.choose(option.id)}
+ />
+ )}
+ </For>
+ </ContextMenuContent>
+ </ContextMenu.Sub>
+ ))
+ .exhaustive()
+ }
+ </For>
+ </>
+ )}
+ </For>
+ );
+}
diff --git a/apps/web/src/features/projects/components/project-row.tsx b/apps/web/src/features/projects/components/project-row.tsx
index 6112823cf8..0e5efab4bb 100644
--- a/apps/web/src/features/projects/components/project-row.tsx
+++ b/apps/web/src/features/projects/components/project-row.tsx
@@ -13,6 +13,7 @@ import type { Property, PropertyApiValues } from '@property/types';
import { cn } from '@ui';
import { For, Show, Suspense } from 'solid-js';
import type { ProjectRow as ProjectRowData } from '../context/projects-context';
+import { canEditProject } from '../core/project';
// Projects reuse the task grid; its project column holds the due date.
const gridStyle = taskGridTemplate({ indicator: true, project: true });
@@ -65,8 +66,7 @@ export function ProjectRow(props: {
onChecked(selected: boolean, shiftKey: boolean): void;
onSave(property: Property, value: PropertyApiValues): Promise<void>;
}) {
- const canEdit = () =>
- props.row.project.access === 'edit' || props.row.project.access === 'owner';
+ const canEdit = () => canEditProject(props.row.project);
const properties = () => [...props.row.properties];
const propertyFor = (id: string) =>
props.row.properties.find(
diff --git a/apps/web/src/features/projects/components/rename-project-dialog.tsx b/apps/web/src/features/projects/components/rename-project-dialog.tsx
new file mode 100644
index 0000000000..71c56efa58
--- /dev/null
+++ b/apps/web/src/features/projects/components/rename-project-dialog.tsx
@@ -0,0 +1,92 @@
+import { ActionDialogShell, Button, Dialog, TextField } from '@ui';
+import { createSignal, Show } from 'solid-js';
+
+/** Renames one project; stays open with the error when the save fails. */
+export function RenameProjectDialog(props: {
+ name: string;
+ onOpenChange(open: boolean): void;
+ onRename(name: string): Promise<void>;
+ onCloseAutoFocus?(event: Event): void;
+}) {
+ const [value, setValue] = createSignal(props.name);
+ const [pending, setPending] = createSignal(false);
+ const [failed, setFailed] = createSignal(false);
+ const name = () => value().trim();
+ const canSubmit = () =>
+ !pending() && name().length > 0 && name() !== props.name.trim();
+
+ const submit = async (event: SubmitEvent) => {
+ event.preventDefault();
+ if (!canSubmit()) return;
+ setPending(true);
+ setFailed(false);
+ try {
+ await props.onRename(name());
+ props.onOpenChange(false);
+ } catch (error) {
+ console.error('Failed to rename project', error);
+ setFailed(true);
+ } finally {
+ setPending(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!pending()) props.onOpenChange(open);
+ }}
+ onCloseAutoFocus={props.onCloseAutoFocus}
+ position="center"
+ class="w-110"
+ visibleScrim
+ >
+ <ActionDialogShell>
+ <form
+ class="flex min-h-0 flex-col"
+ aria-busy={pending()}
+ onSubmit={(event) => void submit(event)}
+ >
+ <ActionDialogShell.Body>
+ <ActionDialogShell.Header>
+ <ActionDialogShell.Title>Rename project</ActionDialogShell.Title>
+ </ActionDialogShell.Header>
+ <TextField value={value()} onChange={setValue}>
+ <TextField.Label>Name</TextField.Label>
+ <TextField.Input
+ placeholder="Project name"
+ readOnly={pending()}
+ onFocus={(event) => event.currentTarget.select()}
+ />
+ </TextField>
+ <Show when={failed()}>
+ <p role="alert" class="text-sm text-failure">
+ Could not rename project. Please try again.
+ </p>
+ </Show>
+ </ActionDialogShell.Body>
+ <ActionDialogShell.Footer>
+ <Button
+ type="button"
+ variant="ghost"
+ depth={2}
+ disabled={pending()}
+ onClick={() => props.onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="strong"
+ depth={2}
+ disabled={!canSubmit()}
+ >
+ {pending() ? 'Saving…' : 'Save name'}
+ </Button>
+ </ActionDialogShell.Footer>
+ </form>
+ </ActionDialogShell>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/projects/context/projects-context.tsx b/apps/web/src/features/projects/context/projects-context.tsx
index 149dae124d..5e7f1d66f3 100644
--- a/apps/web/src/features/projects/context/projects-context.tsx
+++ b/apps/web/src/features/projects/context/projects-context.tsx
@@ -73,11 +73,17 @@ export type ProjectsContext = {
taskIds: readonly string[]
): Promise<ProjectAssignmentResult[]>;
delete(id: string): Promise<void>;
+ /** Deletes each project and refreshes once; resolves with the ids that failed. */
+ deleteMany(ids: readonly string[]): Promise<string[]>;
saveProperty(
id: string,
property: Property,
value: PropertyApiValues
): Promise<void>;
+ /** Saves every value as one batch; rejects when any of them fails. */
+ saveProperties(
+ updates: readonly (ProjectPropertyDraft & { id: string })[]
+ ): Promise<void>;
};
};
diff --git a/apps/web/src/features/projects/core/project-menu.test.ts b/apps/web/src/features/projects/core/project-menu.test.ts
new file mode 100644
index 0000000000..d57f8a2090
--- /dev/null
+++ b/apps/web/src/features/projects/core/project-menu.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { projectMenuGroups } from './project-menu';
+
+const surface = { splits: true, share: true, status: true, priority: true };
+
+describe('projectMenuGroups', () => {
+ it('offers every action to a single owned project', () => {
+ expect(projectMenuGroups([{ access: 'owner' }], surface)).toEqual([
+ ['open-in-split'],
+ ['rename', 'status', 'priority'],
+ ['copy-link', 'copy-id', 'share'],
+ ['delete'],
+ ]);
+ });
+
+ it('lets editors change but not delete a project', () => {
+ expect(projectMenuGroups([{ access: 'edit' }], surface)).toEqual([
+ ['open-in-split'],
+ ['rename', 'status', 'priority'],
+ ['copy-link', 'copy-id', 'share'],
+ ]);
+ });
+
+ it.each(['view', 'comment', undefined] as const)(
+ 'keeps %s access to navigation and links',
+ (access) => {
+ expect(projectMenuGroups([{ access }], surface)).toEqual([
+ ['open-in-split'],
+ ['copy-link', 'copy-id', 'share'],
+ ]);
+ }
+ );
+
+ it('limits a selection to actions every project allows', () => {
+ expect(
+ projectMenuGroups([{ access: 'owner' }, { access: 'owner' }], surface)
+ ).toEqual([['status', 'priority'], ['delete']]);
+ expect(
+ projectMenuGroups([{ access: 'owner' }, { access: 'edit' }], surface)
+ ).toEqual([['status', 'priority']]);
+ expect(
+ projectMenuGroups([{ access: 'owner' }, { access: 'view' }], surface)
+ ).toEqual([]);
+ });
+
+ it('omits entries the surface cannot offer without leaving empty groups', () => {
+ const limited = {
+ splits: false,
+ share: false,
+ status: false,
+ priority: false,
+ };
+ expect(projectMenuGroups([{ access: 'view' }], limited)).toEqual([
+ ['copy-link', 'copy-id'],
+ ]);
+ expect(
+ projectMenuGroups([{ access: 'owner' }, { access: 'owner' }], limited)
+ ).toEqual([['delete']]);
+ expect(
+ projectMenuGroups([{ access: 'edit' }], { ...limited, priority: true })
+ ).toEqual([
+ ['rename', 'priority'],
+ ['copy-link', 'copy-id'],
+ ]);
+ });
+});
diff --git a/apps/web/src/features/projects/core/project-menu.ts b/apps/web/src/features/projects/core/project-menu.ts
new file mode 100644
index 0000000000..4f83966892
--- /dev/null
+++ b/apps/web/src/features/projects/core/project-menu.ts
@@ -0,0 +1,46 @@
+import { canDeleteProject, canEditProject, type Project } from './project';
+
+/** Entries of a project row's context menu. */
+export type ProjectMenuItem =
+ | 'open-in-split'
+ | 'rename'
+ | 'status'
+ | 'priority'
+ | 'copy-link'
+ | 'copy-id'
+ | 'share'
+ | 'delete';
+
+/**
+ * The entries every target allows, in separator-delimited groups. Actions on
+ * one project's identity drop out of a multi-project menu, and `surface`
+ * removes entries the host cannot offer yet, such as unloaded properties.
+ */
+export function projectMenuGroups(
+ projects: readonly Pick<Project, 'access'>[],
+ surface: {
+ splits: boolean;
+ share: boolean;
+ status: boolean;
+ priority: boolean;
+ }
+): ProjectMenuItem[][] {
+ if (projects.length === 0) return [];
+ const single = projects.length === 1;
+ const editable = projects.every(canEditProject);
+ const groups: ProjectMenuItem[][] = [
+ single && surface.splits ? ['open-in-split'] : [],
+ editable
+ ? [
+ ...(single ? (['rename'] as const) : []),
+ ...(surface.status ? (['status'] as const) : []),
+ ...(surface.priority ? (['priority'] as const) : []),
+ ]
+ : [],
+ single
+ ? ['copy-link', 'copy-id', ...(surface.share ? (['share'] as const) : [])]
+ : [],
+ projects.every(canDeleteProject) ? ['delete'] : [],
+ ];
+ return groups.filter((group) => group.length > 0);
+}
diff --git a/apps/web/src/features/projects/core/project.ts b/apps/web/src/features/projects/core/project.ts
index 7bb289a3fc..70693adf43 100644
--- a/apps/web/src/features/projects/core/project.ts
+++ b/apps/web/src/features/projects/core/project.ts
@@ -35,9 +35,12 @@ export type TaskProjectReference =
| { state: 'unavailable' }
| { state: 'visible'; id: string; name: string };
-export const canEditProject = (project: ProjectDetail) =>
+export const canEditProject = (project: Pick<Project, 'access'>) =>
project.access === 'edit' || project.access === 'owner';
+export const canDeleteProject = (project: Pick<Project, 'access'>) =>
+ project.access === 'owner';
+
export const canDiscussProject = (project: ProjectDetail) =>
project.access !== 'view';
diff --git a/apps/web/src/features/projects/primitives/create-project.test.ts b/apps/web/src/features/projects/primitives/create-project.test.ts
index cc63a05baf..9d077f4727 100644
--- a/apps/web/src/features/projects/primitives/create-project.test.ts
+++ b/apps/web/src/features/projects/primitives/create-project.test.ts
@@ -24,6 +24,8 @@ function commands() {
setMembers: vi.fn(async () => {}),
assignTasks: vi.fn(async () => []),
delete: vi.fn(async () => {}),
+ deleteMany: vi.fn(async (): Promise<string[]> => []),
+ saveProperties: vi.fn(async () => {}),
saveProperty: vi.fn(async () => {}),
} satisfies ReturnType<ProjectsContext['createCommands']>;
}
diff --git a/apps/web/src/features/projects/project-detail.tsx b/apps/web/src/features/projects/project-detail.tsx
index fc36eab8f7..ff155b82c9 100644
--- a/apps/web/src/features/projects/project-detail.tsx
+++ b/apps/web/src/features/projects/project-detail.tsx
@@ -12,17 +12,12 @@ import {
useSplitDisplayName,
useSplitPanelOrThrow,
} from '@components/app/split-layout/layoutUtils';
-import { getPermissions } from '@core/component/SharePermissions';
import { TabsInset } from '@core/component/TabsInset';
-import { toast } from '@core/component/Toast/Toast';
import { ShareTrigger } from '@core/component/TopBar/ShareButton';
-import { useShareModal } from '@core/component/TopBar/shareModal';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { getDisplayName, tryMacroId } from '@core/user';
import StackIcon from '@phosphor/stack.svg';
import { Button } from '@ui';
import { Match, Show, Switch } from 'solid-js';
-import { ProjectCollaborators } from './components/project-collaborators';
import {
type ProjectsContext,
useProjectsContext,
@@ -36,6 +31,7 @@ import {
import type { ProjectRoute } from './core/route';
import { ProjectDiscussion } from './project-collaboration';
import { ProjectDescription } from './project-description';
+import { useProjectShareModal } from './project-share';
import { Projects } from './projects';
import { ProjectWorkspace } from './views/project-workspace';
@@ -88,45 +84,12 @@ type ProjectDetailProps = {
onDelete?(): void;
};
-const userName = (id: string) => getDisplayName(tryMacroId(id));
-
-/** The standard Share menu; collaborators are the project's direct grants. */
function ProjectShareTrigger(props: {
project: ProjectDetailData;
commands: ReturnType<ProjectsContext['createCommands']>;
}) {
const panel = useSplitPanelOrThrow();
- const setMembers = async (ids: string[]) => {
- try {
- await props.commands.setMembers(props.project.id, ids);
- } catch (error) {
- toast.failure('Could not update collaborators', {
- subtext: 'Please try again',
- });
- throw error;
- }
- };
- // Stable, so the open dialog keeps the picker's draft across refreshes.
- const Collaborators = () => (
- <ProjectCollaborators
- project={props.project}
- getUserName={userName}
- pending={props.commands.pending()}
- onMembers={setMembers}
- />
- );
- const openShare = useShareModal(() => ({
- id: props.project.id,
- blockAlias: 'initiative',
- itemType: 'initiative',
- name: props.project.name,
- owner: props.project.ownerId,
- userPermissions: getPermissions(props.project.access),
- people: Collaborators,
- hasDirectShares: props.project.memberIds.some(
- (id) => id !== props.project.ownerId
- ),
- }));
+ const openShare = useProjectShareModal(() => props.project, props.commands);
return (
<ShareTrigger
onClick={openShare}
diff --git a/apps/web/src/features/projects/project-share.test.tsx b/apps/web/src/features/projects/project-share.test.tsx
new file mode 100644
index 0000000000..c27e1b060e
--- /dev/null
+++ b/apps/web/src/features/projects/project-share.test.tsx
@@ -0,0 +1,139 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { ImperativeDialogHost } from '@ui';
+import { type Accessor, createSignal, Show } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ type ProjectsContext,
+ ProjectsProvider,
+} from './context/projects-context';
+import type { ProjectDetail } from './core/project';
+import { ProjectShareLauncher } from './project-share';
+
+const toast = vi.hoisted(() => ({ failure: vi.fn() }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast }));
+vi.mock('@core/component/TopBar/ShareButton', () => ({
+ ShareModal: (props: {
+ name: string;
+ itemType: string;
+ userPermissions: string;
+ hasDirectShares?: boolean;
+ onOpenChange: (open: boolean) => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="share-modal"
+ data-item-type={props.itemType}
+ data-permissions={props.userPermissions}
+ data-direct-shares={String(props.hasDirectShares)}
+ onClick={() => props.onOpenChange(false)}
+ >
+ {props.name}
+ </button>
+ ),
+}));
+vi.mock('@core/user', () => ({
+ getDisplayName: (id: string) => id,
+ tryMacroId: (id: string) => id,
+}));
+vi.mock('./components/project-collaborators', () => ({
+ ProjectCollaborators: () => null,
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+const detail: ProjectDetail = {
+ id: 'launch',
+ name: 'Launch',
+ descriptionDocumentId: 'description',
+ updatedAt: '',
+ ownerId: 'owner',
+ memberIds: ['owner', 'collaborator'],
+ taskIds: [],
+ access: 'owner',
+ createdAt: '',
+};
+
+function launch(source: {
+ project: Accessor<ProjectDetail | undefined>;
+ loading: Accessor<boolean>;
+}) {
+ const [sharing, setSharing] = createSignal(true);
+ const requested: string[] = [];
+ const unused = (): never => {
+ throw new Error('Unused capability');
+ };
+ const context: ProjectsContext = {
+ userId: () => 'owner',
+ createCollectionSource: unused,
+ createPropertyDefinitionsSource: unused,
+ createReferencesSource: unused,
+ createProjectSource: (id) => {
+ requested.push(id());
+ return {
+ ...source,
+ properties: () => [],
+ error: () => undefined,
+ refresh: async () => {},
+ };
+ },
+ createCommands: () => ({
+ createTask: vi.fn(),
+ pending: () => false,
+ create: vi.fn(),
+ rename: vi.fn(),
+ setMembers: vi.fn(),
+ assignTasks: vi.fn(),
+ delete: vi.fn(),
+ deleteMany: vi.fn(),
+ saveProperty: vi.fn(),
+ saveProperties: vi.fn(),
+ }),
+ };
+ render(() => (
+ <ProjectsProvider context={context}>
+ <Show when={sharing()}>
+ <ProjectShareLauncher
+ projectId="launch"
+ onClose={() => setSharing(false)}
+ />
+ </Show>
+ <ImperativeDialogHost />
+ </ProjectsProvider>
+ ));
+ return { sharing, requested };
+}
+
+it('opens a listed project’s Share menu once its detail loads', async () => {
+ const [project, setProject] = createSignal<ProjectDetail>();
+ const view = launch({ project, loading: () => !project() });
+
+ expect(view.requested).toEqual(['launch']);
+ expect(screen.queryByTestId('share-modal')).toBeNull();
+ setProject(detail);
+ const modal = await screen.findByTestId('share-modal');
+ expect(modal.textContent).toBe('Launch');
+ expect(modal.dataset).toMatchObject({
+ itemType: 'initiative',
+ permissions: 'Owner',
+ directShares: 'true',
+ });
+
+ fireEvent.click(modal);
+ await vi.waitFor(() => expect(view.sharing()).toBe(false));
+ expect(screen.queryByTestId('share-modal')).toBeNull();
+ expect(toast.failure).not.toHaveBeenCalled();
+});
+
+it('reports and closes when the project cannot load', async () => {
+ const [loading, setLoading] = createSignal(true);
+ const view = launch({ project: () => undefined, loading });
+
+ expect(view.sharing()).toBe(true);
+ setLoading(false);
+ await vi.waitFor(() => expect(view.sharing()).toBe(false));
+ expect(toast.failure).toHaveBeenCalledOnce();
+ expect(screen.queryByTestId('share-modal')).toBeNull();
+});
diff --git a/apps/web/src/features/projects/project-share.tsx b/apps/web/src/features/projects/project-share.tsx
new file mode 100644
index 0000000000..5d65f021ea
--- /dev/null
+++ b/apps/web/src/features/projects/project-share.tsx
@@ -0,0 +1,90 @@
+import { getPermissions } from '@core/component/SharePermissions';
+import { toast } from '@core/component/Toast/Toast';
+import { useShareModal } from '@core/component/TopBar/shareModal';
+import { getDisplayName, tryMacroId } from '@core/user';
+import { type Accessor, createEffect, on, onMount, Show } from 'solid-js';
+import { ProjectCollaborators } from './components/project-collaborators';
+import {
+ type ProjectsContext,
+ useProjectsContext,
+} from './context/projects-context';
+import type { ProjectDetail } from './core/project';
+
+const userName = (id: string) => getDisplayName(tryMacroId(id));
+
+/** The standard Share menu; collaborators are the project's direct grants. */
+export function useProjectShareModal(
+ project: Accessor<ProjectDetail | undefined>,
+ commands: ReturnType<ProjectsContext['createCommands']>,
+ options: { onClose?: () => void } = {}
+) {
+ const setMembers = async (id: string, memberIds: string[]) => {
+ try {
+ await commands.setMembers(id, memberIds);
+ } catch (error) {
+ toast.failure('Could not update collaborators', {
+ subtext: 'Please try again',
+ });
+ throw error;
+ }
+ };
+ // Stable, so the open dialog keeps the picker's draft across refreshes.
+ const Collaborators = () => (
+ <Show when={project()}>
+ {(current) => (
+ <ProjectCollaborators
+ project={current()}
+ getUserName={userName}
+ pending={commands.pending()}
+ onMembers={(ids) => setMembers(current().id, ids)}
+ />
+ )}
+ </Show>
+ );
+ return useShareModal(() => {
+ const current = project();
+ if (!current) return;
+ return {
+ id: current.id,
+ blockAlias: 'initiative',
+ itemType: 'initiative',
+ name: current.name,
+ owner: current.ownerId,
+ userPermissions: getPermissions(current.access),
+ people: Collaborators,
+ hasDirectShares: current.memberIds.some((id) => id !== current.ownerId),
+ };
+ }, options);
+}
+
+/**
+ * Opens a listed project's Share menu once its detail has loaded, or reports
+ * and closes when the project cannot load, e.g. after losing access.
+ */
+export function ProjectShareLauncher(props: {
+ projectId: string;
+ onClose(): void;
+}) {
+ const context = useProjectsContext();
+ const source = context.createProjectSource(() => props.projectId);
+ const openShare = useProjectShareModal(
+ source.project,
+ context.createCommands(),
+ { onClose: props.onClose }
+ );
+ onMount(openShare);
+ // The source only reports the outcome; the toast and close are imperative.
+ createEffect(
+ on(
+ () => !source.loading() && !source.project(),
+ (unavailable) => {
+ if (!unavailable) return;
+ toast.failure('Could not open sharing for this project', {
+ subtext: 'Please try again',
+ });
+ props.onClose();
+ }
+ )
+ );
+ return null;
+}
diff --git a/apps/web/src/features/projects/projects.test.tsx b/apps/web/src/features/projects/projects.test.tsx
index 09e2610873..7621aa7c6b 100644
--- a/apps/web/src/features/projects/projects.test.tsx
+++ b/apps/web/src/features/projects/projects.test.tsx
@@ -29,6 +29,8 @@ vi.mock('@app/lib/analytics/posthog', () => ({
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));
// The list and assignment hosts are outside this provider/query lifecycle test.
vi.mock('@app/components/list/owned-slots', () => ({}));
+vi.mock('@app/features/next-soup/actions', () => ({}));
+vi.mock('@app/signal/splitLayout', () => ({}));
vi.mock('@components/app/split-layout/layout', () => ({}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({}));
vi.mock('@ui', () => ({
@@ -36,6 +38,7 @@ vi.mock('@ui', () => ({
}));
vi.mock('./primitives/project-collection', () => ({}));
vi.mock('./project-collection-persistence', () => ({}));
+vi.mock('./project-share', () => ({}));
vi.mock('./views/project-assignment', () => ({}));
vi.mock('./views/projects-collection', () => ({}));
vi.mock('@queries/activity/push-registry', () => ({
diff --git a/apps/web/src/features/projects/projects.tsx b/apps/web/src/features/projects/projects.tsx
index 364c48492d..1df291da4f 100644
--- a/apps/web/src/features/projects/projects.tsx
+++ b/apps/web/src/features/projects/projects.tsx
@@ -1,5 +1,10 @@
import { listOwnedSlotName } from '@app/components/list/owned-slots';
+import {
+ makeCopyEntityIdAction,
+ makeCopyLinkAction,
+} from '@app/features/next-soup/actions';
import { ShowFeatureFlag, useFeatureFlag } from '@app/lib/analytics/posthog';
+import { globalSplitManager } from '@app/signal/splitLayout';
import { useSplitLayout } from '@components/app/split-layout/layout';
import {
useSplitPanelOrThrow,
@@ -16,16 +21,25 @@ import {
import { initiativeClient } from '@service-storage/initiative';
import { Button } from '@ui';
import type { Accessor } from 'solid-js';
-import { ErrorBoundary, onCleanup, type ParentProps, Suspense } from 'solid-js';
+import {
+ createSignal,
+ ErrorBoundary,
+ onCleanup,
+ type ParentProps,
+ Show,
+ Suspense,
+} from 'solid-js';
import {
ProjectsProvider,
useProjectsContext,
} from './context/projects-context';
+import { projectRouteId } from './core/route';
import {
createProjectCollection,
type ProjectListActivation,
} from './primitives/project-collection';
import { createProjectCollectionPersistence } from './project-collection-persistence';
+import { ProjectShareLauncher } from './project-share';
import { projectKeys } from './queries/keys';
import { createProjectSources } from './queries/project-sources';
import { ProjectAssignment } from './views/project-assignment';
@@ -130,16 +144,40 @@ function ProjectsCollectionHost(props: {
onOpen: (id, metadata) => activation.current?.(id, metadata),
})
);
+ const copyLink = makeCopyLinkAction();
+ const copyId = makeCopyEntityIdAction();
+ const [sharing, setSharing] = createSignal<string>();
return (
- <ProjectsCollection
- onOpen={open}
- collection={collection}
- onCreate={() =>
- layout.popoverSplit({ type: 'component', id: 'project-compose' })
- }
- scopeId={panel.splitHotkeyScope}
- isActive={panel.isPanelActive}
- />
+ <>
+ <ProjectsCollection
+ onOpen={open}
+ collection={collection}
+ onCreate={() =>
+ layout.popoverSplit({ type: 'component', id: 'project-compose' })
+ }
+ scopeId={panel.splitHotkeyScope}
+ isActive={panel.isPanelActive}
+ canOpenInNewSplit={() =>
+ globalSplitManager()?.canAppendSplit() ?? false
+ }
+ onCopyLink={(id) =>
+ void copyLink.executeByBlock(
+ projectRouteId({ id, section: 'overview' }),
+ 'component'
+ )
+ }
+ onCopyId={(id) => void copyId.executeById(id)}
+ onShare={(projectId) => setSharing(projectId)}
+ />
+ <Show when={sharing()} keyed>
+ {(projectId) => (
+ <ProjectShareLauncher
+ projectId={projectId}
+ onClose={() => setSharing(undefined)}
+ />
+ )}
+ </Show>
+ </>
);
}
diff --git a/apps/web/src/features/projects/queries/project-sources.ts b/apps/web/src/features/projects/queries/project-sources.ts
index 12c726c164..26fdffe219 100644
--- a/apps/web/src/features/projects/queries/project-sources.ts
+++ b/apps/web/src/features/projects/queries/project-sources.ts
@@ -27,6 +27,8 @@ import { toProjectDetail } from './project-model';
import { projectDefinitionProperties } from './project-properties';
import { createProjectSoupSource } from './project-soup';
+type ProjectCommands = ReturnType<ProjectsContext['createCommands']>;
+
const accessLost = (error: unknown) =>
['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'].some((code) =>
thrownResultErrorHasCode(error, code)
@@ -220,10 +222,25 @@ export function createProjectSources(
}),
() => cache
);
+ // Deletes resolve with their failures so a batch refreshes the list once.
const remove = useMutation(
() => ({
- mutationFn: (id: string) => throwOnErr(() => client.delete(id)),
- onSuccess: refresh,
+ mutationFn: async (ids: readonly string[]) => {
+ const failures: { id: string; error: unknown }[] = [];
+ await Promise.all(
+ ids.map(async (id) => {
+ try {
+ await throwOnErr(() => client.delete(id));
+ } catch (error) {
+ failures.push({ id, error });
+ }
+ })
+ );
+ return failures;
+ },
+ onSuccess: async (failures, ids) => {
+ if (failures.length < ids.length) await refresh();
+ },
}),
() => cache
);
@@ -289,6 +306,19 @@ export function createProjectSources(
}),
() => cache
);
+ const saveProperties: ProjectCommands['saveProperties'] = async (
+ updates
+ ) => {
+ const result = await property.mutateAsync({
+ properties: updates.map(({ id, property, value }) => ({
+ entityType: 'INITIATIVE',
+ entityId: id,
+ property,
+ apiValues: value,
+ })),
+ });
+ if (result.error) throw result.error;
+ };
return {
createTask,
pending: () =>
@@ -305,21 +335,14 @@ export function createProjectSources(
await update.mutateAsync({ id, memberIds });
},
delete: async (id) => {
- await remove.mutateAsync(id);
- },
- saveProperty: async (id, input, value) => {
- const result = await property.mutateAsync({
- properties: [
- {
- entityType: 'INITIATIVE',
- entityId: id,
- property: input,
- apiValues: value,
- },
- ],
- });
- if (result.error) throw result.error;
+ const [failure] = await remove.mutateAsync([id]);
+ if (failure) throw failure.error;
},
+ deleteMany: async (ids) =>
+ (await remove.mutateAsync(ids)).map(({ id }) => id),
+ saveProperty: (id, property, value) =>
+ saveProperties([{ id, property, value }]),
+ saveProperties,
assignTasks: (projectId, taskIds) =>
assign.mutateAsync({ projectId, taskIds }),
};
diff --git a/apps/web/src/features/projects/views/create-project.test.tsx b/apps/web/src/features/projects/views/create-project.test.tsx
index d021a923e1..2a0355851d 100644
--- a/apps/web/src/features/projects/views/create-project.test.tsx
+++ b/apps/web/src/features/projects/views/create-project.test.tsx
@@ -88,6 +88,8 @@ function commands() {
setMembers: vi.fn(async () => {}),
assignTasks: vi.fn(async () => []),
delete: vi.fn(async () => {}),
+ deleteMany: vi.fn(async (): Promise<string[]> => []),
+ saveProperties: vi.fn(async () => {}),
} satisfies ReturnType<ProjectsContext['createCommands']>;
}
function setup(
diff --git a/apps/web/src/features/projects/views/project-assignment.tsx b/apps/web/src/features/projects/views/project-assignment.tsx
index dde88733f5..2a40c5dea2 100644
--- a/apps/web/src/features/projects/views/project-assignment.tsx
+++ b/apps/web/src/features/projects/views/project-assignment.tsx
@@ -4,6 +4,7 @@ import StackIcon from '@phosphor/stack.svg';
import { Button, Dialog } from '@ui';
import { createSignal, For, Show } from 'solid-js';
import { useProjectsContext } from '../context/projects-context';
+import { canEditProject } from '../core/project';
export function ProjectAssignment(props: {
taskIds: readonly string[];
@@ -76,21 +77,12 @@ export function ProjectAssignment(props: {
{(row) => (
<Button
class="w-full justify-start"
- disabled={
- commands.pending() ||
- (row.project.access !== 'edit' &&
- row.project.access !== 'owner')
- }
+ disabled={commands.pending() || !canEditProject(row.project)}
onClick={() => void assign(row.project.id)}
>
<StackIcon class="size-4 shrink-0" />
<span class="truncate">{row.project.name}</span>
- <Show
- when={
- row.project.access !== 'edit' &&
- row.project.access !== 'owner'
- }
- >
+ <Show when={!canEditProject(row.project)}>
<span class="ml-auto text-xs text-ink-muted">Read only</span>
</Show>
</Button>
diff --git a/apps/web/src/features/projects/views/project-picker.tsx b/apps/web/src/features/projects/views/project-picker.tsx
index d9dd6c8aa1..871efa00fb 100644
--- a/apps/web/src/features/projects/views/project-picker.tsx
+++ b/apps/web/src/features/projects/views/project-picker.tsx
@@ -21,6 +21,7 @@ import {
Switch,
} from 'solid-js';
import { useProjectsContext } from '../context/projects-context';
+import { canEditProject } from '../core/project';
type PickerItem =
| { type: 'clear' }
@@ -74,9 +75,7 @@ export function ProjectPicker(props: {
const items = createMemo<PickerItem[]>(() => {
const projects: PickerItem[] = (source.rows() ?? [])
- .filter(
- (row) => row.project.access === 'edit' || row.project.access === 'owner'
- )
+ .filter((row) => canEditProject(row.project))
.map((row) => ({
type: 'project',
id: row.project.id,
diff --git a/apps/web/src/features/projects/views/project-workspace.tsx b/apps/web/src/features/projects/views/project-workspace.tsx
index a2d0830a51..f6837ad759 100644
--- a/apps/web/src/features/projects/views/project-workspace.tsx
+++ b/apps/web/src/features/projects/views/project-workspace.tsx
@@ -4,14 +4,16 @@ import { InlineTitleEditor } from '@core/component/InlineTitleEditor';
import { PropertyValuePill } from '@property/component/PropertyValuePill';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
import { EntityPropertiesSection } from '@property/side-panel/properties/EntityPropertiesSection';
-import { Button, Dialog } from '@ui';
+import { Button } from '@ui';
import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';
+import { DeleteProjectsDialog } from '../components/delete-projects-dialog';
import {
type ProjectSource,
type ProjectsContext,
useProjectsContext,
} from '../context/projects-context';
import {
+ canDeleteProject,
canEditProject,
type ProjectDetail,
type ProjectSection,
@@ -86,7 +88,7 @@ export function ProjectWorkspace(props: {
)}
</Show>
</SidePanel.Section>
- <Show when={props.project.access === 'owner'}>
+ <Show when={canDeleteProject(props.project)}>
<SidePanel.Section id="actions" title="Actions" order={3}>
<Button
size="sm"
@@ -180,47 +182,20 @@ export function ProjectWorkspace(props: {
</div>
</div>
<Show when={deleting()}>
- <Dialog
- open
+ <DeleteProjectsDialog
+ count={1}
+ pending={props.commands.pending()}
+ error={error()}
onOpenChange={(open) => {
- if (!open && !props.commands.pending()) setDeleting(false);
+ if (!open) setDeleting(false);
}}
- class="max-w-md"
- >
- <div class="flex flex-col gap-4 p-5">
- <Dialog.Title>Delete project?</Dialog.Title>
- <p class="text-sm text-ink-muted">
- The project and its activity will be deleted. Its tasks will
- remain in your workspace.
- </p>
- <Show when={error()}>
- {(message) => (
- <p role="alert" class="text-sm text-failure">
- {message()}
- </p>
- )}
- </Show>
- <div class="flex justify-end gap-2">
- <Button
- disabled={props.commands.pending()}
- onClick={() => setDeleting(false)}
- >
- Cancel
- </Button>
- <Button
- disabled={props.commands.pending()}
- onClick={() =>
- void run(async () => {
- await props.commands.delete(props.project.id);
- props.onDelete();
- })
- }
- >
- Delete project
- </Button>
- </div>
- </div>
- </Dialog>
+ onDelete={() =>
+ void run(async () => {
+ await props.commands.delete(props.project.id);
+ props.onDelete();
+ })
+ }
+ />
</Show>
</SidePanel.Layout>
);
diff --git a/apps/web/src/features/projects/views/projects-collection.test.tsx b/apps/web/src/features/projects/views/projects-collection.test.tsx
new file mode 100644
index 0000000000..790b6b22da
--- /dev/null
+++ b/apps/web/src/features/projects/views/projects-collection.test.tsx
@@ -0,0 +1,499 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@property/identifiers';
+import type { Property } from '@property/types';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { For, type JSX, type ParentProps } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ type ProjectRow,
+ type ProjectsContext,
+ ProjectsProvider,
+} from '../context/projects-context';
+import type { ProjectAccess } from '../core/project';
+import { createProjectCollection } from '../primitives/project-collection';
+import { ProjectsCollection } from './projects-collection';
+
+const toast = vi.hoisted(() => ({ success: vi.fn(), failure: vi.fn() }));
+const device = vi.hoisted(() => ({ mobile: false }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast }));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => device.mobile }));
+// Touch timing is covered by the directive; a test event stands in for it.
+vi.mock('@core/directive/touchHandler', () => ({
+ touchHandler: (
+ element: HTMLElement,
+ options: () => { onLongPress?: () => void }
+ ) =>
+ element.addEventListener('test-long-press', () =>
+ options().onLongPress?.()
+ ),
+}));
+vi.mock('@app/components/ui/components/Tooltip', () => ({
+ Tooltip: (props: ParentProps) => props.children,
+}));
+// The shell, list engine, and row cells have their own coverage; this suite
+// exercises what a row's context menu does to the list.
+vi.mock('@app/components/view-shell', () => ({
+ ViewShell: {
+ Header: (props: ParentProps) => props.children,
+ Content: (props: ParentProps) => props.children,
+ },
+ SearchBar: () => null,
+ ListSortDropdown: () => null,
+ ListGroupDropdown: () => null,
+ ListFilterDropdown: () => null,
+ useViewControlHotkeys: () => {},
+}));
+vi.mock('@app/components/view-shell/SidebarCreateButton', () => ({
+ SidebarCreateButton: () => null,
+}));
+vi.mock('@app/components/list/ListViewport', () => ({
+ ListViewport: <T,>(props: {
+ items: readonly T[];
+ children: (item: T) => JSX.Element;
+ }) => <For each={props.items}>{(item) => props.children(item)}</For>,
+}));
+vi.mock('@app/components/list', () => ({
+ useListInteractions: () => ({
+ selection: { set: vi.fn(), toggle: vi.fn(), clear: vi.fn() },
+ }),
+}));
+vi.mock(
+ '@app/features/tasks-view/components/task-list/TaskGroupHeader',
+ () => ({ TaskGroupHeader: () => null })
+);
+vi.mock('@entity/EntitySelectionToolbarModal', () => ({
+ EntitySelectionToolbarModal: () => null,
+}));
+vi.mock('@entity', () => ({
+ InlineEntity: (props: { entity: { name: string } }) => props.entity.name,
+}));
+// Rows portal their property editors, as the real cells do.
+vi.mock('../components/project-row', async () => {
+ const { Portal } = await import('solid-js/web');
+ return {
+ ProjectListHeader: () => null,
+ ProjectRow: (props: {
+ rowId: string;
+ row: ProjectRow;
+ highlighted: boolean;
+ }) => (
+ <div role="row" id={props.rowId} data-highlighted={props.highlighted}>
+ {props.row.project.name}
+ <Portal>
+ <button type="button">Edit {props.row.project.name}</button>
+ </Portal>
+ </div>
+ ),
+ };
+});
+
+let animationStyle: HTMLStyleElement;
+beforeEach(() => {
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: vi.fn(),
+ });
+ animationStyle = document.createElement('style');
+ animationStyle.textContent = '* { animation-name: none !important; }';
+ document.head.append(animationStyle);
+});
+afterEach(() => {
+ cleanup();
+ device.mobile = false;
+ vi.unstubAllGlobals();
+ animationStyle.remove();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+function selectProperty(
+ id: string,
+ displayName: string,
+ options: [string, string][],
+ value: string[] | null = null
+): Property {
+ return {
+ propertyId: `${id}-value`,
+ propertyDefinitionId: id,
+ displayName,
+ isMultiSelect: false,
+ owner: { scope: 'system' },
+ createdAt: '',
+ updatedAt: '',
+ valueType: 'SELECT_STRING',
+ value,
+ options: options.map(([optionId, label], index) => ({
+ id: optionId,
+ value: { type: 'string', value: label },
+ display_order: index,
+ property_definition_id: id,
+ created_at: '',
+ updated_at: '',
+ })),
+ };
+}
+
+const statusOptions: [string, string][] = [
+ [PROPERTY_OPTION_IDS.STATUS.NOT_STARTED, 'Not Started'],
+ [PROPERTY_OPTION_IDS.STATUS.COMPLETED, 'Completed'],
+];
+const status = selectProperty(
+ SYSTEM_PROPERTY_IDS.STATUS,
+ 'Status',
+ statusOptions
+);
+const priority = selectProperty(SYSTEM_PROPERTY_IDS.PRIORITY, 'Priority', [
+ [PROPERTY_OPTION_IDS.PRIORITY.HIGH, 'High'],
+]);
+
+function project(
+ id: string,
+ name: string,
+ access: ProjectAccess | undefined,
+ properties: Property[] = []
+): ProjectRow {
+ return {
+ project: {
+ id,
+ name,
+ descriptionDocumentId: `${id}-description`,
+ updatedAt: '',
+ access,
+ },
+ properties,
+ };
+}
+
+function commands() {
+ return {
+ createTask: vi.fn(async () => null),
+ pending: () => false,
+ create: vi.fn(),
+ rename: vi.fn(async (_id: string, _name: string) => {}),
+ setMembers: vi.fn(async () => {}),
+ assignTasks: vi.fn(async () => []),
+ delete: vi.fn(async (_id: string) => {}),
+ deleteMany: vi.fn(async (_ids: readonly string[]): Promise<string[]> => []),
+ saveProperty: vi.fn(async () => {}),
+ saveProperties: vi.fn(async () => {}),
+ } satisfies ReturnType<ProjectsContext['createCommands']>;
+}
+
+function setup(
+ rows: readonly ProjectRow[],
+ options: { canOpenInNewSplit?: boolean; properties?: Property[] } = {}
+) {
+ const service = commands();
+ const unused = (): never => {
+ throw new Error('Unused capability');
+ };
+ const context: ProjectsContext = {
+ userId: () => 'viewer',
+ createCollectionSource: () => ({
+ rows: () => rows,
+ loading: () => false,
+ error: () => undefined,
+ hasMore: () => false,
+ loadingMore: () => false,
+ loadMore: async () => {},
+ refresh: async () => {},
+ }),
+ createProjectSource: unused,
+ createReferencesSource: unused,
+ createPropertyDefinitionsSource: () => ({
+ properties: () => options.properties ?? [status, priority],
+ loading: () => false,
+ error: () => undefined,
+ }),
+ createCommands: () => service,
+ };
+ const host = {
+ onOpen: vi.fn(),
+ onCopyLink: vi.fn(),
+ onCopyId: vi.fn(),
+ onShare: vi.fn(),
+ };
+ let collection!: ReturnType<typeof createProjectCollection>;
+ const view = render(() => {
+ collection = createProjectCollection({
+ createSource: context.createCollectionSource,
+ userId: context.userId,
+ initialState: {
+ search: '',
+ status: '',
+ priority: '',
+ dueBefore: '',
+ dueAfter: '',
+ mine: false,
+ sort: 'updated',
+ groupBy: 'none',
+ scrollOffset: 0,
+ collapsedGroupIds: [],
+ },
+ });
+ return (
+ <ProjectsProvider context={context}>
+ <ProjectsCollection
+ {...host}
+ onCreate={vi.fn()}
+ scopeId="projects"
+ isActive={() => true}
+ collection={collection}
+ canOpenInNewSplit={() => options.canOpenInNewSplit ?? true}
+ />
+ </ProjectsProvider>
+ );
+ });
+ const rowKey = (id: string) => {
+ const item = collection
+ .items()
+ .find((row) => row.kind === 'entity' && row.entity.id === id);
+ if (!item) throw new Error(`No row for ${id}`);
+ return item.id;
+ };
+ return { ...view, service, host, collection, rowKey };
+}
+
+async function openMenu(name: string) {
+ expect(
+ fireEvent.contextMenu(screen.getByText(name), { clientX: 20, clientY: 20 })
+ ).toBe(false);
+ await screen.findByRole('menu');
+}
+
+const entries = () =>
+ screen
+ .getAllByRole('menuitem')
+ .map((item) => item.firstChild?.textContent ?? '');
+
+function choose(name: string | RegExp) {
+ fireEvent.keyDown(screen.getByRole('menuitem', { name }), { key: 'Enter' });
+}
+
+describe('project row context menu', () => {
+ it('focuses the row and offers an owner every project action', async () => {
+ const view = setup([project('launch', 'Launch', 'owner')]);
+ await openMenu('Launch');
+ expect(
+ screen.getByText('Launch').closest<HTMLElement>('[role="row"]')?.dataset
+ .highlighted
+ ).toBe('true');
+ expect(view.collection.list.focus.key()).toBe(view.rowKey('launch'));
+ expect(entries()).toEqual([
+ 'Open in new split',
+ 'Rename',
+ 'Set status',
+ 'Set priority',
+ 'Copy Link',
+ 'Copy ID',
+ 'Share',
+ 'Delete',
+ ]);
+ });
+
+ it('keeps view access to navigation and links', async () => {
+ setup([project('launch', 'Launch', 'view')]);
+ await openMenu('Launch');
+ expect(entries()).toEqual([
+ 'Open in new split',
+ 'Copy Link',
+ 'Copy ID',
+ 'Share',
+ ]);
+ });
+
+ it('hands navigation, links, and sharing to the host', async () => {
+ const view = setup([project('launch', 'Launch', 'edit')]);
+ for (const [entry, callback] of [
+ ['Copy Link', view.host.onCopyLink],
+ ['Copy ID', view.host.onCopyId],
+ ['Share', view.host.onShare],
+ ] as const) {
+ await openMenu('Launch');
+ choose(entry);
+ await waitFor(() => expect(callback).toHaveBeenCalledWith('launch'));
+ }
+ await openMenu('Launch');
+ choose(/Open in new split/);
+ await waitFor(() =>
+ expect(view.host.onOpen).toHaveBeenCalledWith('launch', {
+ newSplit: true,
+ })
+ );
+ });
+
+ it('disables opening beside the list when no split fits', async () => {
+ setup([project('launch', 'Launch', 'owner')], {
+ canOpenInNewSplit: false,
+ });
+ await openMenu('Launch');
+ expect(
+ screen
+ .getByRole('menuitem', { name: /Open in new split/ })
+ .getAttribute('aria-disabled')
+ ).toBe('true');
+ });
+
+ it('renames through a dialog that keeps a failed name for retry', async () => {
+ const view = setup([project('launch', 'Launch', 'edit')]);
+ view.service.rename.mockRejectedValueOnce(new Error('Name taken'));
+ await openMenu('Launch');
+ choose('Rename');
+ const input = await screen.findByRole('textbox', { name: 'Name' });
+ expect((input as HTMLInputElement).value).toBe('Launch');
+ const save = screen.getByRole('button', { name: 'Save name' });
+ expect(save.hasAttribute('disabled')).toBe(true);
+ fireEvent.input(input, { target: { value: ' Launch v2 ' } });
+ fireEvent.click(save);
+ expect(await screen.findByRole('alert')).toHaveProperty(
+ 'textContent',
+ 'Could not rename project. Please try again.'
+ );
+ fireEvent.click(save);
+ await waitFor(() =>
+ expect(screen.queryByRole('textbox', { name: 'Name' })).toBeNull()
+ );
+ expect(view.service.rename).toHaveBeenCalledTimes(2);
+ expect(view.service.rename).toHaveBeenLastCalledWith('launch', 'Launch v2');
+ });
+
+ it('deletes a project after confirmation', async () => {
+ const view = setup([project('launch', 'Launch', 'owner')]);
+ await openMenu('Launch');
+ choose('Delete');
+ expect(await screen.findByText('Delete project?')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Delete project' }));
+ await waitFor(() =>
+ expect(screen.queryByText('Delete project?')).toBeNull()
+ );
+ expect(view.service.deleteMany).toHaveBeenCalledWith(['launch']);
+ expect(toast.success).toHaveBeenCalledWith('Project deleted');
+ });
+
+ it('leaves right-clicks in a row’s portaled editors to them', () => {
+ setup([project('launch', 'Launch', 'owner')]);
+ expect(fireEvent.contextMenu(screen.getByText('Edit Launch'))).toBe(true);
+ expect(screen.queryByRole('menu')).toBeNull();
+ });
+
+ it('adds the property submenus once their definitions load', async () => {
+ const view = setup(
+ [
+ project('launch', 'Launch', 'owner'),
+ project('roadmap', 'Roadmap', 'owner'),
+ ],
+ { properties: [] }
+ );
+ view.collection.list.selection.select(view.rowKey('launch'));
+ view.collection.list.selection.select(view.rowKey('roadmap'));
+ await openMenu('Launch');
+ expect(entries()).toEqual(['Delete']);
+ expect(screen.queryByRole('separator')).toBeNull();
+ });
+
+ it('opens the same actions in a long-press drawer on mobile', async () => {
+ device.mobile = true;
+ const view = setup([project('launch', 'Launch', 'owner')]);
+ screen
+ .getByText('Launch')
+ .closest('[role="row"]')
+ ?.parentElement?.dispatchEvent(new Event('test-long-press'));
+ expect(view.collection.list.focus.key()).toBe(view.rowKey('launch'));
+ const drawer = await screen.findByRole('dialog', {
+ name: 'Entity actions',
+ });
+ expect(
+ [...drawer.querySelectorAll('button')].map((item) => item.textContent)
+ ).toEqual([
+ 'Rename',
+ 'Status: Not Started',
+ 'Status: Completed',
+ 'Priority: High',
+ 'Copy Link',
+ 'Copy ID',
+ 'Share',
+ 'Delete',
+ ]);
+ fireEvent.click(screen.getByRole('button', { name: 'Copy ID' }));
+ await waitFor(() =>
+ expect(view.host.onCopyId).toHaveBeenCalledWith('launch')
+ );
+ });
+
+ it('acts on the selection and keeps failed deletions for retry', async () => {
+ const launchStatus: Property = {
+ ...selectProperty(SYSTEM_PROPERTY_IDS.STATUS, 'Status', statusOptions, [
+ PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,
+ ]),
+ propertyId: 'launch-status',
+ };
+ const view = setup([
+ project('launch', 'Launch', 'owner', [launchStatus]),
+ project('roadmap', 'Roadmap', 'owner'),
+ project('hiring', 'Hiring', 'owner'),
+ ]);
+ view.collection.list.selection.select(view.rowKey('launch'));
+ view.collection.list.selection.select(view.rowKey('roadmap'));
+
+ await openMenu('Hiring');
+ expect(entries()).toContain('Rename');
+
+ await openMenu('Roadmap');
+ expect(entries()).toEqual(['Set status', 'Set priority', 'Delete']);
+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Set status' }), {
+ key: 'ArrowRight',
+ });
+ await screen.findByRole('menuitem', { name: 'Completed' });
+ choose('Completed');
+ await waitFor(() =>
+ expect(view.service.saveProperties).toHaveBeenCalledOnce()
+ );
+ const value = {
+ valueType: 'SELECT_STRING',
+ values: [PROPERTY_OPTION_IDS.STATUS.COMPLETED],
+ };
+ // A row's own value saves like its cell; a missing one uses the definition.
+ expect(view.service.saveProperties).toHaveBeenCalledWith([
+ { id: 'launch', property: launchStatus, value },
+ { id: 'roadmap', property: status, value },
+ ]);
+
+ view.service.deleteMany.mockResolvedValueOnce(['roadmap']);
+ await openMenu('Launch');
+ choose('Delete');
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Delete 2 projects' })
+ );
+ expect(await screen.findByRole('alert')).toHaveProperty(
+ 'textContent',
+ 'Deleted 1 of 2. The rest could not be deleted.'
+ );
+ expect(screen.getByText('Delete project?')).toBeTruthy();
+ expect(view.collection.list.selection.isKeySelected('launch')).toBe(false);
+ expect(view.collection.list.selection.isKeySelected('roadmap')).toBe(true);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete project' }));
+ await waitFor(() =>
+ expect(screen.queryByText('Delete project?')).toBeNull()
+ );
+ expect(view.service.deleteMany).toHaveBeenCalledTimes(2);
+ expect(view.service.deleteMany).toHaveBeenLastCalledWith(['roadmap']);
+ });
+});
diff --git a/apps/web/src/features/projects/views/projects-collection.tsx b/apps/web/src/features/projects/views/projects-collection.tsx
index 62d5c27f75..3fea0d68fb 100644
--- a/apps/web/src/features/projects/views/projects-collection.tsx
+++ b/apps/web/src/features/projects/views/projects-collection.tsx
@@ -10,21 +10,41 @@ import {
ViewShell,
} from '@app/components/view-shell';
import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';
+import {
+ getSoupMenuEntities,
+ getSoupRowEntities,
+} from '@app/features/soup/collection/rows';
import { TaskGroupHeader } from '@app/features/tasks-view/components/task-list/TaskGroupHeader';
import { taskGridColumnCount } from '@app/features/tasks-view/components/task-list/task-grid-template';
+import { toast } from '@core/component/Toast/Toast';
import { EntitySelectionToolbarModal } from '@entity/EntitySelectionToolbarModal';
import CalendarIcon from '@phosphor/calendar.svg';
import SpinnerIcon from '@phosphor/spinner.svg';
import { PropertyValueIcon } from '@property/component/propertyValue';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { Property, PropertyApiValues } from '@property/types';
import { Button, Dropdown, Input } from '@ui';
-import { type Accessor, createSignal, Match, Show, Switch } from 'solid-js';
+import {
+ type Accessor,
+ batch,
+ createSignal,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
import type { VirtualizerHandle } from 'virtua/solid';
+import { DeleteProjectsDialog } from '../components/delete-projects-dialog';
import { ProjectListHeader, ProjectRow } from '../components/project-row';
-import { useProjectsContext } from '../context/projects-context';
+import { ProjectRowMenu } from '../components/project-row-menu';
+import { RenameProjectDialog } from '../components/rename-project-dialog';
+import {
+ type ProjectRow as ProjectRowData,
+ useProjectsContext,
+} from '../context/projects-context';
import type {
createProjectCollection,
ProjectListActivation,
+ ProjectListEntity,
} from '../primitives/project-collection';
type FilterGroup = 'status' | 'priority' | 'assignee';
@@ -35,6 +55,12 @@ export function ProjectsCollection(props: {
scopeId: string;
isActive: Accessor<boolean>;
collection: ReturnType<typeof createProjectCollection>;
+ /** Whether the layout has room to open a project beside the list. */
+ canOpenInNewSplit: Accessor<boolean>;
+ onCopyLink(id: string): void;
+ onCopyId(id: string): void;
+ /** Omit where the host cannot show the project's Share menu. */
+ onShare?(id: string): void;
}) {
const context = useProjectsContext();
const collection = props.collection;
@@ -44,37 +70,33 @@ export function ProjectsCollection(props: {
let grid: HTMLDivElement | undefined;
let searchInput: HTMLInputElement | undefined;
const [openMenu, setOpenMenu] = createSignal<'filters' | 'sort'>();
+ const definition = (id: string) =>
+ definitions
+ .properties()
+ .find((property) => property.propertyDefinitionId === id);
const filters = (): ListFilterGroup<FilterGroup, string>[] => [
...(['status', 'priority'] as const).map((id) => ({
id,
label: id === 'status' ? 'Status' : 'Priority',
selectionMode: 'single' as const,
options:
- definitions
- .properties()
- .find(
- (property) =>
- property.propertyDefinitionId ===
- (id === 'status'
- ? SYSTEM_PROPERTY_IDS.STATUS
- : SYSTEM_PROPERTY_IDS.PRIORITY)
- )
- ?.options?.flatMap((option) =>
- option.value.type === 'string'
- ? [
- {
- id: option.id,
- label: option.value.value,
- icon: () => (
- <PropertyValueIcon
- optionId={option.id}
- class="size-3.5"
- />
- ),
- },
- ]
- : []
- ) ?? [],
+ definition(
+ id === 'status'
+ ? SYSTEM_PROPERTY_IDS.STATUS
+ : SYSTEM_PROPERTY_IDS.PRIORITY
+ )?.options?.flatMap((option) =>
+ option.value.type === 'string'
+ ? [
+ {
+ id: option.id,
+ label: option.value.value,
+ icon: () => (
+ <PropertyValueIcon optionId={option.id} class="size-3.5" />
+ ),
+ },
+ ]
+ : []
+ ) ?? [],
})),
{
id: 'assignee',
@@ -130,6 +152,83 @@ export function ProjectsCollection(props: {
},
},
});
+ const [renaming, setRenaming] = createSignal<ProjectRowData>();
+ const [deleting, setDeleting] = createSignal<{
+ rows: readonly ProjectRowData[];
+ error?: string;
+ }>();
+ const [deletePending, setDeletePending] = createSignal(false);
+ // The menu entry that opened a dialog no longer exists when it closes.
+ const returnFocusToList = (event: Event) => {
+ event.preventDefault();
+ grid?.focus();
+ };
+ const menuTargets = (entity: ProjectListEntity) =>
+ getSoupMenuEntities(entity, getSoupRowEntities(list.selection.items()));
+ const setOption = async (
+ rows: readonly ProjectRowData[],
+ property: Property,
+ optionId: string
+ ) => {
+ const value: PropertyApiValues = {
+ valueType: 'SELECT_STRING',
+ values: [optionId],
+ };
+ try {
+ await commands.saveProperties(
+ rows.map((row) => ({
+ id: row.project.id,
+ // A row's own value saves exactly like editing its cell.
+ property:
+ row.properties.find(
+ (current) =>
+ current.propertyDefinitionId === property.propertyDefinitionId
+ ) ?? property,
+ value,
+ }))
+ );
+ } catch (error) {
+ console.error('Failed to update projects', error);
+ const name = property.displayName.toLowerCase();
+ toast.failure(
+ rows.length === 1
+ ? `Could not update ${name}`
+ : `Could not update ${name} for every project`
+ );
+ }
+ };
+ const deleteProjects = async (rows: readonly ProjectRowData[]) => {
+ setDeletePending(true);
+ let failedIds: readonly string[];
+ try {
+ failedIds = await commands.deleteMany(rows.map((row) => row.project.id));
+ } catch (error) {
+ console.error('Failed to delete projects', error);
+ failedIds = rows.map((row) => row.project.id);
+ } finally {
+ setDeletePending(false);
+ }
+ const failed = rows.filter((row) => failedIds.includes(row.project.id));
+ batch(() => {
+ for (const row of rows)
+ if (!failed.includes(row)) list.selection.deselectKey(row.project.id);
+ });
+ if (failed.length === 0) {
+ setDeleting(undefined);
+ toast.success(
+ rows.length > 1 ? `Deleted ${rows.length} projects` : 'Project deleted'
+ );
+ return;
+ }
+ // Only the failures remain for a retry.
+ setDeleting({
+ rows: failed,
+ error:
+ failed.length === rows.length
+ ? 'Could not delete. Please try again.'
+ : `Deleted ${rows.length - failed.length} of ${rows.length}. The rest could not be deleted.`,
+ });
+ };
useViewControlHotkeys({
scopeId: props.scopeId,
enabled: props.isActive,
@@ -381,36 +480,70 @@ export function ProjectsCollection(props: {
</Match>
<Match when={row.kind === 'entity' ? row : undefined}>
{(item) => (
- <ProjectRow
- rowId={item().id}
- row={item().entity}
- highlighted={list.focus.key() === item().id}
- checked={list.selection.isSelected(item().id)}
- onFocus={() =>
- list.focus.set(item().id, { reason: 'hover' })
+ <ProjectRowMenu
+ targets={() => menuTargets(item().entity)}
+ status={definition(SYSTEM_PROPERTY_IDS.STATUS)}
+ priority={definition(SYSTEM_PROPERTY_IDS.PRIORITY)}
+ canOpenInNewSplit={props.canOpenInNewSplit()}
+ onOpenInNewSplit={(row) =>
+ props.onOpen(row.project.id, { newSplit: true })
}
- onChecked={(selected, range) =>
- interaction.selection.set(item().id, selected, {
- range,
- })
+ onRename={(row) => setRenaming(row)}
+ onSetOption={(rows, property, optionId) =>
+ void setOption(rows, property, optionId)
}
- onOpen={(event) => {
- if (event.ctrlKey || event.metaKey)
- interaction.selection.toggle(item().id);
- else
- list.activate.key(item().id, {
- reason: 'pointer',
- metadata: { event, newSplit: event.shiftKey },
- });
- }}
- onSave={(property, value) =>
- commands.saveProperty(
- item().entity.id,
- property,
- value
- )
+ onCopyLink={(row) => props.onCopyLink(row.project.id)}
+ onCopyId={(row) => props.onCopyId(row.project.id)}
+ onShare={
+ props.onShare &&
+ ((row) => props.onShare?.(row.project.id))
}
- />
+ onDelete={(rows) => setDeleting({ rows })}
+ onOpenChange={(open) => {
+ if (!open) return;
+ list.focus.set(item().id, {
+ reason: 'pointer',
+ force: true,
+ });
+ list.selection.setAnchor(item().id);
+ }}
+ onCloseAutoFocus={(event) => {
+ // Leave focus with a dialog the entry just opened.
+ if (renaming() || deleting())
+ event.preventDefault();
+ }}
+ >
+ <ProjectRow
+ rowId={item().id}
+ row={item().entity}
+ highlighted={list.focus.key() === item().id}
+ checked={list.selection.isSelected(item().id)}
+ onFocus={() =>
+ list.focus.set(item().id, { reason: 'hover' })
+ }
+ onChecked={(selected, range) =>
+ interaction.selection.set(item().id, selected, {
+ range,
+ })
+ }
+ onOpen={(event) => {
+ if (event.ctrlKey || event.metaKey)
+ interaction.selection.toggle(item().id);
+ else
+ list.activate.key(item().id, {
+ reason: 'pointer',
+ metadata: { event, newSplit: event.shiftKey },
+ });
+ }}
+ onSave={(property, value) =>
+ commands.saveProperty(
+ item().entity.id,
+ property,
+ value
+ )
+ }
+ />
+ </ProjectRowMenu>
)}
</Match>
<Match when={row.kind === 'load-more' ? row : undefined}>
@@ -448,6 +581,32 @@ export function ProjectsCollection(props: {
onClose={interaction.selection.clear}
/>
</Show>
+ <Show when={renaming()} keyed>
+ {(row) => (
+ <RenameProjectDialog
+ name={row.project.name}
+ onOpenChange={(open) => {
+ if (!open) setRenaming(undefined);
+ }}
+ onRename={(name) => commands.rename(row.project.id, name)}
+ onCloseAutoFocus={returnFocusToList}
+ />
+ )}
+ </Show>
+ <Show when={deleting()}>
+ {(request) => (
+ <DeleteProjectsDialog
+ count={request().rows.length}
+ pending={deletePending()}
+ error={request().error}
+ onOpenChange={(open) => {
+ if (!open) setDeleting(undefined);
+ }}
+ onDelete={() => void deleteProjects(request().rows)}
+ onCloseAutoFocus={returnFocusToList}
+ />
+ )}
+ </Show>
</div>
</ViewShell.Content>
</>
diff --git a/apps/web/src/features/soup/SoupEntityContextMenu.tsx b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
index e88e7f5b9e..de848d3294 100644
--- a/apps/web/src/features/soup/SoupEntityContextMenu.tsx
+++ b/apps/web/src/features/soup/SoupEntityContextMenu.tsx
@@ -4,7 +4,11 @@ import {
makeAddTagAction,
} from '@app/features/next-soup/actions';
import { ProjectPickerPopover } from '@app/features/projects/project-property';
-import { ContextMenuContent, MenuSeparator } from '@core/component/ContextMenu';
+import {
+ ContextMenuContent,
+ ContextMenuTrigger,
+ MenuSeparator,
+} from '@core/component/ContextMenu';
import { touchHandler } from '@core/directive/touchHandler';
import { isMobile } from '@core/mobile/isMobile';
import type { EntityData } from '@entity';
@@ -26,6 +30,7 @@ import {
Show,
Switch,
} from 'solid-js';
+import { getSoupMenuEntities } from './collection/rows';
import { useSoupEntityActionDrawer } from './SoupEntityActionDrawerContext';
import { SoupEntityActionsMenu } from './SoupEntityActionsMenu';
@@ -83,16 +88,8 @@ export const SoupEntityContextMenu: FlowComponent<
y: number;
}>();
- const menuEntities = () => {
- const selected = props.selectedEntities();
- if (
- selected.length > 1 &&
- selected.some((entity) => entity.id === props.entity.id)
- ) {
- return selected;
- }
- return [props.entity];
- };
+ const menuEntities = () =>
+ getSoupMenuEntities(props.entity, props.selectedEntities());
const canEditTags = () => addTagAction.canExecute(props.entity);
@@ -120,7 +117,7 @@ export const SoupEntityContextMenu: FlowComponent<
</Match>
<Match when={true}>
<ContextMenu onOpenChange={props.onOpenChange}>
- <ContextMenu.Trigger
+ <ContextMenuTrigger
as={props.as}
class={cn('h-full w-full group/cm-trigger', props.class)}
on:contextmenu={(event: MouseEvent) =>
@@ -128,7 +125,7 @@ export const SoupEntityContextMenu: FlowComponent<
}
>
{props.children}
- </ContextMenu.Trigger>
+ </ContextMenuTrigger>
<ContextMenu.Portal>
<Show when={props.entity}>
<ContextMenuContent class="w-64 text-xs text-ink-muted">
diff --git a/apps/web/src/features/soup/collection/rows.test.ts b/apps/web/src/features/soup/collection/rows.test.ts
new file mode 100644
index 0000000000..9449460600
--- /dev/null
+++ b/apps/web/src/features/soup/collection/rows.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { getSoupMenuEntities } from './rows';
+
+describe('getSoupMenuEntities', () => {
+ const rows = [
+ { id: 'a', type: 'initiative' },
+ { id: 'b', type: 'initiative' },
+ { id: 'c', type: 'initiative' },
+ ];
+
+ it('acts on the selection when the clicked row is part of it', () => {
+ expect(getSoupMenuEntities(rows[1], rows.slice(0, 2))).toEqual(
+ rows.slice(0, 2)
+ );
+ });
+
+ it('acts on the clicked row outside a selection or with one selected', () => {
+ expect(getSoupMenuEntities(rows[2], rows.slice(0, 2))).toEqual([rows[2]]);
+ expect(getSoupMenuEntities(rows[0], [rows[0]])).toEqual([rows[0]]);
+ expect(getSoupMenuEntities(rows[0], [])).toEqual([rows[0]]);
+ });
+});
diff --git a/apps/web/src/features/soup/collection/rows.ts b/apps/web/src/features/soup/collection/rows.ts
index 8a83a264e0..a7fd349c61 100644
--- a/apps/web/src/features/soup/collection/rows.ts
+++ b/apps/web/src/features/soup/collection/rows.ts
@@ -182,6 +182,17 @@ export function getUniqueSoupRowEntities<TEntity extends SoupEntityIdentity>(
return deduplicateSoupEntities(getSoupRowEntities(rows));
}
+/** A row's menu acts on the selection that includes it, else on the row alone. */
+export function getSoupMenuEntities<TEntity extends SoupEntityIdentity>(
+ entity: TEntity,
+ selected: TEntity[]
+): TEntity[] {
+ return selected.length > 1 &&
+ selected.some((candidate) => candidate.id === entity.id)
+ ? selected
+ : [entity];
+}
+
export const isSoupRowVisible = <TEntity extends SoupEntityIdentity>(
row: SoupRow<TEntity>,
isGroupExpanded: (groupId: string) => boolean
diff --git a/apps/web/src/lib/core/component/ContextMenu.test.tsx b/apps/web/src/lib/core/component/ContextMenu.test.tsx
new file mode 100644
index 0000000000..e853c583e0
--- /dev/null
+++ b/apps/web/src/lib/core/component/ContextMenu.test.tsx
@@ -0,0 +1,36 @@
+import { ContextMenu } from '@kobalte/core/context-menu';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { Portal } from 'solid-js/web';
+import { afterEach, expect, it } from 'vitest';
+import {
+ ContextMenuContent,
+ ContextMenuTrigger,
+ MenuItem,
+} from './ContextMenu';
+
+afterEach(cleanup);
+
+it('opens for the trigger’s own content but not for portaled descendants', async () => {
+ render(() => (
+ <ContextMenu>
+ <ContextMenuTrigger>
+ <span>Row</span>
+ <Portal>
+ <button type="button">Editor</button>
+ </Portal>
+ </ContextMenuTrigger>
+ <ContextMenu.Portal>
+ <ContextMenuContent>
+ <MenuItem text="Rename" />
+ </ContextMenuContent>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ ));
+
+ // A portaled editor keeps the browser's own menu.
+ expect(fireEvent.contextMenu(screen.getByText('Editor'))).toBe(true);
+ expect(screen.queryByRole('menu')).toBeNull();
+
+ expect(fireEvent.contextMenu(screen.getByText('Row'))).toBe(false);
+ expect(await screen.findByRole('menuitem', { name: 'Rename' })).toBeTruthy();
+});
diff --git a/apps/web/src/lib/core/component/ContextMenu.tsx b/apps/web/src/lib/core/component/ContextMenu.tsx
index 1223a2b453..dafe9916d8 100644
--- a/apps/web/src/lib/core/component/ContextMenu.tsx
+++ b/apps/web/src/lib/core/component/ContextMenu.tsx
@@ -12,6 +12,7 @@ import {
import { Hotkey } from '@ui/components/Hotkey';
import {
type Component,
+ type ComponentProps,
createEffect,
type JSX,
Match,
@@ -19,6 +20,7 @@ import {
type ParentProps,
Show,
Switch,
+ splitProps,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
@@ -274,6 +276,39 @@ export function MenuGroup(props: { children: JSX.Element; class?: string }) {
);
}
+/**
+ * Solid delegates a portal's events to where it sits in the component tree,
+ * so an editor portaled out of a trigger would open the trigger's menu and
+ * lose its native one.
+ */
+const ignorePortaledEvents = (
+ event: Event & { currentTarget: HTMLElement }
+) => {
+ if (
+ !(event.target instanceof Node) ||
+ !event.currentTarget.contains(event.target)
+ )
+ event.stopPropagation();
+};
+
+/** Kobalte's context-menu trigger, ignoring events from portaled content. */
+export function ContextMenuTrigger(
+ props: ComponentProps<typeof ContextMenu.Trigger>
+) {
+ const [local, others] = splitProps(props, ['children']);
+ return (
+ <ContextMenu.Trigger {...others}>
+ <div
+ class="contents"
+ onContextMenu={ignorePortaledEvents}
+ onPointerDown={ignorePortaledEvents}
+ >
+ {local.children}
+ </div>
+ </ContextMenu.Trigger>
+ );
+}
+
export function MenuSeparator() {
return (
<ContextMenu.Separator class="my-1.5 -mx-1.5 w-[calc(100%+0.75rem)] border-t border-edge-divider" />
diff --git a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
index 9581e763b0..48663a6b14 100644
--- a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
@@ -1,13 +1,22 @@
import { render, screen } from '@solidjs/testing-library';
import { ImperativeDialogHost } from '@ui';
-import { createSignal } from 'solid-js';
+import { createSignal, Show } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
import { Permissions } from '../SharePermissions';
import { useShareModal } from './shareModal';
vi.mock('./ShareButton', () => ({
- ShareModal: (props: { name: string }) => (
- <div data-testid="share-modal">{props.name}</div>
+ ShareModal: (props: {
+ name: string;
+ onOpenChange: (open: boolean) => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="share-modal"
+ onClick={() => props.onOpenChange(false)}
+ >
+ {props.name}
+ </button>
),
}));
vi.mock('@queries/storage/document-metadata', () => ({
@@ -40,4 +49,46 @@ describe('useShareModal', () => {
setReady(true);
expect((await screen.findByTestId('share-modal')).textContent).toBe('Plan');
});
+
+ it('reports when the person closes an opened modal', async () => {
+ const onClose = vi.fn();
+ const [owned, setOwned] = createSignal(true);
+ let openShare!: () => void;
+ function Opener() {
+ openShare = useShareModal(
+ () => ({
+ id: 'doc-1',
+ blockAlias: 'md',
+ itemType: 'document',
+ name: 'Plan',
+ userPermissions: Permissions.OWNER,
+ }),
+ { onClose }
+ );
+ return null;
+ }
+ render(() => (
+ <>
+ <Show when={owned()}>
+ <Opener />
+ </Show>
+ <ImperativeDialogHost />
+ </>
+ ));
+
+ openShare();
+ (await screen.findByTestId('share-modal')).click();
+ await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(screen.queryByTestId('share-modal')).toBeNull();
+
+ // Unmounting the owner closes the modal without reporting it.
+ openShare();
+ await screen.findByTestId('share-modal');
+ setOwned(false);
+ await vi.waitFor(() =>
+ expect(screen.queryByTestId('share-modal')).toBeNull()
+ );
+ await Promise.resolve();
+ expect(onClose).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/web/src/lib/core/component/TopBar/shareModal.tsx b/apps/web/src/lib/core/component/TopBar/shareModal.tsx
index c58500bb9f..f47be6d88b 100644
--- a/apps/web/src/lib/core/component/TopBar/shareModal.tsx
+++ b/apps/web/src/lib/core/component/TopBar/shareModal.tsx
@@ -43,16 +43,25 @@ export function openShareModal(props: ShareModalInput): DialogHandle {
* modal follows `props` while open and closes when the component unmounts.
* Return `undefined` from `props` until the share data has loaded; opening
* before then waits for it, so the modal never shows placeholder permissions.
+ * `onClose` runs when the person closes an opened modal, not when a newer
+ * one replaces it or its owner unmounts.
*/
export function useShareModal(
- props: Accessor<ShareModalInput | undefined>
+ props: Accessor<ShareModalInput | undefined>,
+ options: { onClose?: () => void } = {}
): () => void {
const dialog = useImperativeDialog(SuspendedShareModal);
const [pending, setPending] = createSignal(false);
+ const notifyClosed = async (handle: DialogHandle) => {
+ const { reason } = await handle.closed;
+ if (reason === 'dismissed' || reason === 'programmatic')
+ options.onClose?.();
+ };
+
const openWith = (initial: ShareModalInput) => {
setPending(false);
- dialog.open(() => props() ?? initial);
+ void notifyClosed(dialog.open(() => props() ?? initial));
};
createEffect(() => {
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index 00f9c71204..ab39371a63 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -127,6 +127,20 @@ end loads more projects; `Load more projects` also continues the list.
Keyboard movement changes focus; Enter opens the focused project and
Shift-selection opens it in a new split. Folders remain separate in Files.
+Right-click a project row for its context menu; the row takes focus, as in
+Tasks. Every project offers `Open in new split` (disabled when no split fits),
+`Copy Link` (the Overview link), `Copy ID`, and `Share`, which opens the same
+Share menu as the project's top bar. Edit access adds `Rename`, which opens a
+name dialog, and the `Set status` and `Set priority` submenus; owners also get
+`Delete`, which confirms first and leaves the project's tasks in place.
+Right-clicking one of several checked rows acts on the whole selection and
+offers only `Set status`, `Set priority`, and, when you own every project,
+`Delete`. A partially failed delete keeps only the failed projects in the
+dialog for retry. On phones, long-press a row for the same actions in the
+bottom action drawer, without `Open in new split` and with each Status and
+Priority choice as its own row. Use disposable projects: these actions change
+hosted data.
+
`New project` and the global Create menu's `Project` action (C, then P) open
the same native composer host and layout as task creation,
with a project name and the shared property pills for Status, Priority,