Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix(web): work item views stay fast with thousands of issues (#795)

Croff5a45d65e8cfc
diff --git a/apps/web/src/components/layout/DisplaySettingsSelect.tsx b/apps/web/src/components/layout/DisplaySettingsSelect.tsx
index 32e07aa2..20a872ef 100644
--- a/apps/web/src/components/layout/DisplaySettingsSelect.tsx
+++ b/apps/web/src/components/layout/DisplaySettingsSelect.tsx
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import {
Select,
SelectContent,
@@ -15,21 +16,30 @@ export default function DisplaySettingsSelect({
onChange: (value: string) => void;
options: { value: string; label: string }[];
}) {
+ // A closed Radix Select still renders all its items to find the selected label.
+ // The Display popover renders several of these on every open, so the label is
+ // passed in and the items render from the first focus or open. They stay mounted
+ // after that: a focused closed trigger picks an item by typed letters, and the
+ // list animates out on close.
+ const [used, setUsed] = useState(false);
return (
- <Select value={value} onValueChange={onChange}>
+ <Select value={value} onValueChange={onChange} onOpenChange={(open) => open && setUsed(true)}>
<SelectTrigger
size="sm"
className="gap-1 border-0 bg-transparent px-2 font-medium shadow-none hover:bg-accent data-[size=sm]:h-7 dark:bg-transparent dark:hover:bg-accent"
+ onFocus={() => setUsed(true)}
>
- <SelectValue />
+ <SelectValue>{options.find((o) => o.value === value)?.label}</SelectValue>
</SelectTrigger>
- <SelectContent>
- {options.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
+ {used && (
+ <SelectContent>
+ {options.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ )}
</Select>
);
}
diff --git a/apps/web/src/components/layout/Shell.tsx b/apps/web/src/components/layout/Shell.tsx
index d903b3d3..f9824bf1 100644
--- a/apps/web/src/components/layout/Shell.tsx
+++ b/apps/web/src/components/layout/Shell.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useMemo, useState, type ReactNode } from 'react';
+import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { useInitiativeOptionsQuery } from '@/services/initiatives.service';
import { useIssueBySeqQuery } from '@/services/issues.service';
@@ -19,7 +19,7 @@ import { useProjectRouteSync } from '@/hooks/useProjectRouteSync';
import { projectPath, issuePath } from '@/utils/paths';
import { defaultsFromFilters, type NewIssueDefaults } from '@/utils/project';
import { IssueRefsProvider } from '@/context/issueRefs';
-import { ShellCtx, type ShellContext } from '@/context/shellContext';
+import { IssueOpenerCtx, ShellCtx, type ShellContext } from '@/context/shellContext';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import AppSidebar from '@/components/layout/AppSidebar';
import AppHeader from '@/components/layout/AppHeader';
@@ -145,18 +145,24 @@ export default function Shell({
// while the URL addresses an issue by its project-scoped number, so the page route
// resolves the number first and falls back to the panel when the issue is not on
// the loaded board.
- const openIssue = (id: number, mode: IssueOpenMode = issueOpenMode) => {
- if (mode === 'page' && projectKey) {
- const seq = project?.issues.find((i) => i.id === id)?.sequenceNumber;
- if (seq != null) {
- router.push(issuePath(projectKey, seq));
- return;
+ // A stable callback: the views memoize their cards, and opening or closing the
+ // panel renders the Shell again.
+ const { setOpenIssueId } = overlays;
+ const openIssue = useCallback(
+ (id: number, mode: IssueOpenMode = issueOpenMode) => {
+ if (mode === 'page' && projectKey) {
+ const seq = project?.issues.find((i) => i.id === id)?.sequenceNumber;
+ if (seq != null) {
+ router.push(issuePath(projectKey, seq));
+ return;
+ }
}
- }
- // The issue the panel already shows closes it, so the card that opened the panel
- // is the one that puts it away.
- overlays.setOpenIssueId((current) => (current === id ? null : id));
- };
+ // The issue the panel already shows closes it, so the card that opened the
+ // panel is the one that puts it away.
+ setOpenIssueId((current) => (current === id ? null : id));
+ },
+ [issueOpenMode, projectKey, project, router, setOpenIssueId],
+ );
const context: ShellContext = {
project,
@@ -174,95 +180,97 @@ export default function Shell({
return (
<ShellCtx.Provider value={context}>
- <SidebarProvider defaultOpen={defaultSidebarOpen} className="h-svh overflow-hidden">
- <AppSidebar
- projects={projects}
- currentProjectKey={projectKey}
- onSelectProject={(key) => router.push(projectPath(key))}
- />
- <SidebarInset className="min-w-0">
- <AppHeader
- title={
- <ShellHeaderTitle
- route={route}
- projectName={projectName}
- issueIdentifier={issueQuery.data?.identifier ?? null}
- issueParent={issueQuery.data?.parent ?? null}
- />
- }
- hasProject={!!project}
- onOpenCommand={() => overlays.setShowCommand(true)}
- onNewIssue={openNewIssue}
- chatActive={chatPanel.open}
- onToggleChat={chatPanel.toggle}
+ <IssueOpenerCtx.Provider value={openIssue}>
+ <SidebarProvider defaultOpen={defaultSidebarOpen} className="h-svh overflow-hidden">
+ <AppSidebar
+ projects={projects}
+ currentProjectKey={projectKey}
+ onSelectProject={(key) => router.push(projectPath(key))}
/>
- <ShellNotice />
-
- {errorMsg && !forbidden && (
- <div className="border-b border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
- {errorMsg}
- </div>
- )}
+ <SidebarInset className="min-w-0">
+ <AppHeader
+ title={
+ <ShellHeaderTitle
+ route={route}
+ projectName={projectName}
+ issueIdentifier={issueQuery.data?.identifier ?? null}
+ issueParent={issueQuery.data?.parent ?? null}
+ />
+ }
+ hasProject={!!project}
+ onOpenCommand={() => overlays.setShowCommand(true)}
+ onNewIssue={openNewIssue}
+ chatActive={chatPanel.open}
+ onToggleChat={chatPanel.toggle}
+ />
+ <ShellNotice />
- <div className="relative flex min-h-0 flex-1 overflow-hidden">
- <div className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
- <ShellBody
- forbidden={forbidden}
- hasProject={!!project}
- hasError={!!errorMsg}
- projectsLoaded={projectsLoaded}
- projectCount={projects.length}
- >
- <IssueRefsProvider refs={issueRefs}>{children}</IssueRefsProvider>
- </ShellBody>
- </div>
-
- {chatAvailable && projectKey && (
- <ChatPanel
- projectKey={projectKey}
- open={chatPanel.open}
- mode={chatPanel.mode}
- fullscreen={chatPanel.fullscreen}
- onToggleMode={chatPanel.toggleMode}
- onToggleFullscreen={chatPanel.toggleFullscreen}
- onClose={chatPanel.toggle}
- newChatAgentId={chatAgentId}
- onNewChatHandled={() => setChatAgentId(null)}
- />
+ {errorMsg && !forbidden && (
+ <div className="border-b border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
+ {errorMsg}
+ </div>
)}
- </div>
- </SidebarInset>
- <CommandLayer
- open={overlays.showCommand}
- onOpenChange={overlays.setShowCommand}
- projects={projects}
- currentProjectKey={projectKey}
- onBoard={route.onBoard}
- view={editor.view}
- currentIssueId={currentIssueId}
- onViewChange={editor.changeView}
- onNewIssue={openNewIssue}
- // Handled by the kanban board's selection provider (mounted only on the
- // board); the constant matches BOARD_SELECT_ALL_EVENT in useSelection.
- onSelectAll={() => window.dispatchEvent(new Event('board:select-all'))}
- onNewInitiative={() => overlays.setShowNewInitiative(true)}
- onNewProject={openNewProject}
- onSelectProject={(key) => router.push(projectPath(key))}
- onOpenIssue={(seq) => projectKey && router.push(issuePath(projectKey, seq))}
- onIssueDeleted={onIssueDeleted}
- onToggleChat={chatPanel.toggle}
- />
+ <div className="relative flex min-h-0 flex-1 overflow-hidden">
+ <div className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ <ShellBody
+ forbidden={forbidden}
+ hasProject={!!project}
+ hasError={!!errorMsg}
+ projectsLoaded={projectsLoaded}
+ projectCount={projects.length}
+ >
+ <IssueRefsProvider refs={issueRefs}>{children}</IssueRefsProvider>
+ </ShellBody>
+ </div>
+
+ {chatAvailable && projectKey && (
+ <ChatPanel
+ projectKey={projectKey}
+ open={chatPanel.open}
+ mode={chatPanel.mode}
+ fullscreen={chatPanel.fullscreen}
+ onToggleMode={chatPanel.toggleMode}
+ onToggleFullscreen={chatPanel.toggleFullscreen}
+ onClose={chatPanel.toggle}
+ newChatAgentId={chatAgentId}
+ onNewChatHandled={() => setChatAgentId(null)}
+ />
+ )}
+ </div>
+ </SidebarInset>
- <IssueRefsProvider refs={issueRefs}>
- <ShellOverlays
- project={project}
- projectKey={projectKey}
- newProjectTeamId={newProjectTeamId}
- overlays={overlays}
+ <CommandLayer
+ open={overlays.showCommand}
+ onOpenChange={overlays.setShowCommand}
+ projects={projects}
+ currentProjectKey={projectKey}
+ onBoard={route.onBoard}
+ view={editor.view}
+ currentIssueId={currentIssueId}
+ onViewChange={editor.changeView}
+ onNewIssue={openNewIssue}
+ // Handled by the kanban board's selection provider (mounted only on the
+ // board); the constant matches BOARD_SELECT_ALL_EVENT in useSelection.
+ onSelectAll={() => window.dispatchEvent(new Event('board:select-all'))}
+ onNewInitiative={() => overlays.setShowNewInitiative(true)}
+ onNewProject={openNewProject}
+ onSelectProject={(key) => router.push(projectPath(key))}
+ onOpenIssue={(seq) => projectKey && router.push(issuePath(projectKey, seq))}
+ onIssueDeleted={onIssueDeleted}
+ onToggleChat={chatPanel.toggle}
/>
- </IssueRefsProvider>
- </SidebarProvider>
+
+ <IssueRefsProvider refs={issueRefs}>
+ <ShellOverlays
+ project={project}
+ projectKey={projectKey}
+ newProjectTeamId={newProjectTeamId}
+ overlays={overlays}
+ />
+ </IssueRefsProvider>
+ </SidebarProvider>
+ </IssueOpenerCtx.Provider>
</ShellCtx.Provider>
);
}
diff --git a/apps/web/src/context/shellContext.ts b/apps/web/src/context/shellContext.ts
index e2ac0f13..b3763ccc 100644
--- a/apps/web/src/context/shellContext.ts
+++ b/apps/web/src/context/shellContext.ts
@@ -26,6 +26,11 @@ export type ShellContext = {
export const ShellCtx = createContext<ShellContext | null>(null);
+// The Shell's onOpenIssue on its own. ShellCtx changes on every Shell render, while
+// this changes only with the project and the open-mode preference, so a component
+// that every card mounts reads this one.
+export const IssueOpenerCtx = createContext<ShellContext['onOpenIssue'] | null>(null);
+
export function useShell(): ShellContext {
const ctx = useContext(ShellCtx);
if (!ctx) throw new Error('useShell must be used within the project Shell');
diff --git a/apps/web/src/features/issue/components/actions/IssueContextMenu.tsx b/apps/web/src/features/issue/components/actions/IssueContextMenu.tsx
index ea7af8e2..fb10eec5 100644
--- a/apps/web/src/features/issue/components/actions/IssueContextMenu.tsx
+++ b/apps/web/src/features/issue/components/actions/IssueContextMenu.tsx
@@ -1,64 +1,9 @@
import { useContext, useState, type ReactNode } from 'react';
-import { toast } from 'sonner';
-import { useFormatter, useTranslations } from 'next-intl';
-import {
- Archive,
- ArchiveRestore,
- Bot,
- CalendarClock,
- Check,
- CircleDashed,
- ClipboardCopy,
- PanelRight,
- RefreshCw,
- SquareArrowOutUpRight,
- Tag,
- Target,
- Trash2,
- User,
- X,
-} from 'lucide-react';
-import type { ActionDef } from '@/lib/api/endpoints/actions';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
-import { getIssue, type Issue, type IssuePatch } from '@/lib/api/endpoints/issues';
-import { actionIcon } from '@/utils/actionIcons';
-import { useActionsQuery } from '@/services/actions.service';
-import { useRestoreIssue, useUpdateIssue } from '@/services/issues.service';
-import { useInitiativeOptionsQuery } from '@/services/initiatives.service';
-import { STATUS_META } from '@/utils/initiativeMeta';
-import { CYCLE_STATUS_META } from '@/utils/cycleMeta';
-import { usePermissions } from '@/hooks/usePermissions';
-import { usePriorityLabel } from '@/hooks/usePriorityLabel';
-import { ShellCtx } from '@/context/shellContext';
-import { useArchiveAction } from '../../hooks/useArchiveAction';
-import { ApplyActionDialog, DeleteIssueDialog, matchedActions } from './IssueActions';
-import { buildIssueBranchName, buildIssuePrompt } from '../../utils/issuePrompt';
-import { writeClipboardText } from '../../utils/clipboard';
-import { delegatableAgents } from '../../utils/delegates';
-import { useSession } from '@/lib/auth-client';
-import { toDateStr } from '@/utils/dates';
-import { colorDot } from '@/components/common/fields/colorDot';
-import { PRIORITY_FIELDS } from '@/components/common/fields/priorityFields';
-import { StateIcon } from '../shared/IssueIcons';
-import { dueDatePresets } from '../../utils/dueDatePresets';
-import { useDueDatePresetLabel } from '../../hooks/useDueDatePresetLabel';
-import { issuePath } from '@/utils/paths';
-import {
- ContextMenu,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuSeparator,
- ContextMenuShortcut,
- ContextMenuSub,
- ContextMenuSubContent,
- ContextMenuSubTrigger,
- ContextMenuTrigger,
-} from '@/components/ui/context-menu';
-
-// Trailing check on the currently-selected row in a single-select submenu.
-function SelectedCheck({ selected }: { selected: boolean }) {
- return selected ? <Check className="ml-auto size-4" /> : null;
-}
+import type { Issue } from '@/lib/api/endpoints/issues';
+import { IssueOpenerCtx } from '@/context/shellContext';
+import { ContextMenu, ContextMenuTrigger } from '@/components/ui/context-menu';
+import IssueMenu from './IssueMenu';
export default function IssueContextMenu({
project,
@@ -71,399 +16,34 @@ export default function IssueContextMenu({
onDeleted?: () => void;
children: ReactNode;
}) {
- const t = useTranslations('issue.menu');
- const format = useFormatter();
- const tCommon = useTranslations('common');
- const { can } = usePermissions();
- // Read the Shell directly (not useShell) so this can render outside it: on the
- // public read-only board there is no Shell, and the card is shown without a menu.
- const shell = useContext(ShellCtx);
- const { data: session } = useSession();
- const canEdit = can('work_items', 'edit');
- const canDelete = can('work_items', 'delete');
- const updateIssue = useUpdateIssue(project.project.ref);
- const { archive, dialog: archiveDialog } = useArchiveAction(project, onDeleted);
- const restoreIssue = useRestoreIssue(project.project.ref);
- const actionsQuery = useActionsQuery(shell ? project.project.ref : null);
- const priorityLabel = usePriorityLabel();
- const presetLabel = useDueDatePresetLabel();
+ // Null outside the Shell: on the public read-only board there is no Shell, and the
+ // card is shown without a menu.
+ const openIssue = useContext(IssueOpenerCtx);
const [open, setOpen] = useState(false);
- const [copyIssue, setCopyIssue] = useState<Issue | null>(null);
- const [confirmingDelete, setConfirmingDelete] = useState(false);
- const [confirmingAction, setConfirmingAction] = useState<ActionDef | null>(null);
- // Initiatives are not in the board scaffold, so they are fetched here — only
- // while this menu is open, as every card on the board mounts one.
- const initiativesQuery = useInitiativeOptionsQuery(
- open && project.project.initiativesEnabled ? project.project.ref : null,
- );
-
- // No Shell (public share): render the card as-is, without the right-click menu.
- if (!shell) return <>{children}</>;
- const onOpenIssue = shell.onOpenIssue;
-
- const actions = matchedActions(actionsQuery.data ?? [], project, issue);
-
- function patch(fields: IssuePatch) {
- updateIssue.mutate({ id: issue.id, patch: fields });
- }
-
- function toggleLabel(id: number) {
- const next = issue.labelIds.includes(id)
- ? issue.labelIds.filter((x) => x !== id)
- : [...issue.labelIds, id];
- patch({ labelIds: next });
- }
-
- async function copyText(value: string | Promise<string>) {
- try {
- await writeClipboardText(value);
- toast.success(tCommon('copied'));
- } catch {
- toast.error(t('copyFailed'));
- }
- }
-
- function openCopySubmenu(next: boolean) {
- if (!next) return;
- setCopyIssue(null);
- // Fetch while the submenu opens so the clipboard write stays in the selection gesture.
- void getIssue(issue.id)
- .then(setCopyIssue)
- .catch(() => toast.error(t('copyFailed')));
- }
+ // Every card on a board mounts a menu, and a scrolled board mounts cards all the
+ // time. The menu's queries, mutations and session are set up the first time it
+ // opens, and stay mounted so its dialogs outlive the menu.
+ const [everOpened, setEverOpened] = useState(false);
- const copyShortLink = () => copyText(`${window.location.origin}/${issue.identifier}`);
- const copyFullUrl = () =>
- copyText(`${window.location.origin}${issuePath(project.project.ref, issue.sequenceNumber)}`);
-
- const currentColumn = project.columns.find((c) => c.id === issue.columnId);
- const currentPriority =
- PRIORITY_FIELDS.find((p) => p.value === (issue.priority ?? '')) ?? PRIORITY_FIELDS[0];
- const members = project.assignees.filter((a) => a.kind === 'member');
- const agents = delegatableAgents(project.assignees, session?.user.id ?? null);
- const initiatives = initiativesQuery.data ?? [];
+ if (!openIssue) return <>{children}</>;
return (
- <>
- <ContextMenu onOpenChange={setOpen}>
- <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
- <ContextMenuContent className="w-56">
- {/* Both ways to open the issue, regardless of the account's default
- open mode. Reading an issue needs no permission. */}
- <ContextMenuItem onSelect={() => onOpenIssue(issue.id, 'panel')}>
- <PanelRight />
- {t('preview')}
- </ContextMenuItem>
- <ContextMenuItem onSelect={() => onOpenIssue(issue.id, 'page')}>
- <SquareArrowOutUpRight />
- {t('goToIssue')}
- </ContextMenuItem>
-
- <ContextMenuSeparator />
-
- {canEdit && (
- <>
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- {currentColumn ? (
- <StateIcon
- stateType={currentColumn.stateType}
- color={currentColumn.color}
- className="size-3.5"
- />
- ) : (
- <CircleDashed />
- )}
- {t('status')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- {project.columns.map((c) => (
- <ContextMenuItem key={c.id} onSelect={() => patch({ columnId: c.id })}>
- <StateIcon stateType={c.stateType} color={c.color} className="size-3.5" />
- <span className="truncate">{c.name}</span>
- <SelectedCheck selected={c.id === issue.columnId} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
-
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- {currentPriority.icon}
- {t('priority')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-52">
- {PRIORITY_FIELDS.map((p) => (
- <ContextMenuItem
- key={p.value || 'none'}
- onSelect={() => patch({ priority: p.value || null })}
- >
- {p.icon}
- <span className="flex-1">{priorityLabel(p.value)}</span>
- <SelectedCheck selected={p.value === (issue.priority ?? '')} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
-
- {members.length > 0 && (
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- <User />
- {t('assignee')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- <ContextMenuItem onSelect={() => patch({ assigneeUserId: null })}>
- <CircleDashed />
- <span className="flex-1">{t('noAssignee')}</span>
- <SelectedCheck selected={issue.assigneeUserId == null} />
- </ContextMenuItem>
- {members.map((a) => (
- <ContextMenuItem
- key={a.userId}
- onSelect={() => patch({ assigneeUserId: a.userId })}
- >
- <User />
- <span className="flex-1 truncate">{a.name}</span>
- <SelectedCheck selected={a.userId === issue.assigneeUserId} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- )}
-
- {agents.length > 0 && (
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- <Bot />
- {t('delegate')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- <ContextMenuItem onSelect={() => patch({ delegateUserId: null })}>
- <CircleDashed />
- <span className="flex-1">{t('noDelegate')}</span>
- <SelectedCheck selected={issue.delegateUserId == null} />
- </ContextMenuItem>
- {agents.map((a) => (
- <ContextMenuItem
- key={a.userId}
- onSelect={() => patch({ delegateUserId: a.userId })}
- >
- <Bot />
- <span className="flex-1 truncate">{a.name}</span>
- <SelectedCheck selected={a.userId === issue.delegateUserId} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- )}
-
- {project.project.initiativesEnabled && (
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- {issue.initiative ? <Target /> : <CircleDashed />}
- {t('initiative')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- <ContextMenuItem onSelect={() => patch({ initiativeId: null })}>
- <CircleDashed />
- <span className="flex-1">{t('noInitiative')}</span>
- <SelectedCheck selected={issue.initiative == null} />
- </ContextMenuItem>
- {initiatives.map((it) => (
- <ContextMenuItem key={it.id} onSelect={() => patch({ initiativeId: it.id })}>
- {colorDot(STATUS_META[it.status].color)}
- <span className="flex-1 truncate">{it.title}</span>
- <SelectedCheck selected={it.id === issue.initiative?.id} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- )}
-
- {project.project.cyclesEnabled && (
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- {issue.cycle ? <RefreshCw /> : <CircleDashed />}
- {t('cycle')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- <ContextMenuItem onSelect={() => patch({ cycleId: null })}>
- <CircleDashed />
- <span className="flex-1">{t('noCycle')}</span>
- <SelectedCheck selected={issue.cycle == null} />
- </ContextMenuItem>
- {project.plannedCycles.map((cycle) => (
- <ContextMenuItem key={cycle.id} onSelect={() => patch({ cycleId: cycle.id })}>
- {colorDot(CYCLE_STATUS_META[cycle.status].color)}
- <span className="flex-1 truncate">{cycle.name}</span>
- <SelectedCheck selected={cycle.id === issue.cycle?.id} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- )}
-
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- <CalendarClock />
- {t('dueDate')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-72">
- {dueDatePresets().map((p) => (
- <ContextMenuItem
- key={p.key}
- onSelect={() => patch({ dueDate: toDateStr(p.date) })}
- >
- <CalendarClock />
- <span className="whitespace-nowrap">{presetLabel(p.key)}</span>
- <ContextMenuShortcut className="whitespace-nowrap">
- {format.dateTime(p.date, {
- weekday: 'short',
- month: 'short',
- day: 'numeric',
- calendar: 'gregory',
- })}
- </ContextMenuShortcut>
- </ContextMenuItem>
- ))}
- {issue.dueDate && (
- <>
- <ContextMenuSeparator />
- <ContextMenuItem onSelect={() => patch({ dueDate: null })}>
- <X />
- {t('clearDueDate')}
- </ContextMenuItem>
- </>
- )}
- </ContextMenuSubContent>
- </ContextMenuSub>
-
- {project.labels.length > 0 && (
- <ContextMenuSub>
- <ContextMenuSubTrigger>
- <Tag />
- {t('labels')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-56">
- {project.labels.map((l) => (
- <ContextMenuItem
- key={l.id}
- // Keep the menu open so several labels can be toggled in one pass.
- onSelect={(e) => {
- e.preventDefault();
- toggleLabel(l.id);
- }}
- >
- {colorDot(l.color)}
- <span className="flex-1 truncate">{l.name}</span>
- <SelectedCheck selected={issue.labelIds.includes(l.id)} />
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- )}
-
- {actions.length > 0 && (
- <>
- <ContextMenuSeparator />
- {actions.map((a) => {
- const Icon = actionIcon(a.icon);
- return (
- <ContextMenuItem key={a.id} onSelect={() => setConfirmingAction(a)}>
- <Icon />
- <span className="truncate">{a.name}</span>
- </ContextMenuItem>
- );
- })}
- </>
- )}
- </>
- )}
-
- {canEdit && <ContextMenuSeparator />}
-
- <ContextMenuSub onOpenChange={openCopySubmenu}>
- <ContextMenuSubTrigger>
- <ClipboardCopy />
- {tCommon('copy')}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-52">
- <ContextMenuItem onSelect={() => copyText(issue.identifier)}>
- {t('copyId')}
- </ContextMenuItem>
- <ContextMenuItem onSelect={copyShortLink}>{t('copyShortLink')}</ContextMenuItem>
- <ContextMenuItem onSelect={copyFullUrl}>{t('copyFullUrl')}</ContextMenuItem>
- <ContextMenuItem onSelect={() => copyText(issue.title)}>
- {t('copyTitle')}
- </ContextMenuItem>
- <ContextMenuItem
- disabled={!copyIssue}
- onSelect={() => copyText(copyIssue!.description)}
- >
- {t('copyDescription')}
- </ContextMenuItem>
- <ContextMenuItem
- onSelect={() => copyText(buildIssueBranchName(issue, session?.user))}
- >
- {t('copyBranch')}
- </ContextMenuItem>
- <ContextMenuSeparator />
- <ContextMenuItem
- disabled={!copyIssue}
- onSelect={() => copyText(buildIssuePrompt(copyIssue!, project, session?.user))}
- >
- {t('copyPrompt')}
- </ContextMenuItem>
- </ContextMenuSubContent>
- </ContextMenuSub>
-
- {canEdit && <ContextMenuSeparator />}
-
- {/* Archiving hides the issue from the board but keeps it; restore brings it back. */}
- {canEdit &&
- (issue.archivedAt ? (
- <ContextMenuItem onSelect={() => restoreIssue.mutate(issue.id)}>
- <ArchiveRestore />
- {t('restore')}
- </ContextMenuItem>
- ) : (
- <ContextMenuItem onSelect={() => archive(issue)}>
- <Archive />
- {t('archive')}
- </ContextMenuItem>
- ))}
-
- {canDelete && <ContextMenuSeparator />}
-
- {canDelete && (
- <ContextMenuItem variant="destructive" onSelect={() => setConfirmingDelete(true)}>
- <Trash2 />
- {tCommon('delete')}
- </ContextMenuItem>
- )}
- </ContextMenuContent>
- </ContextMenu>
-
- {confirmingDelete && (
- <DeleteIssueDialog
+ <ContextMenu
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (next) setEverOpened(true);
+ }}
+ >
+ <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
+ {everOpened && (
+ <IssueMenu
project={project}
issue={issue}
- onClose={() => setConfirmingDelete(false)}
+ open={open}
onDeleted={onDeleted}
+ onOpenIssue={openIssue}
/>
)}
-
- {confirmingAction && (
- <ApplyActionDialog
- project={project}
- issue={issue}
- action={confirmingAction}
- onClose={() => setConfirmingAction(null)}
- />
- )}
-
- {archiveDialog}
- </>
+ </ContextMenu>
);
}
diff --git a/apps/web/src/features/issue/components/actions/IssueMenu.tsx b/apps/web/src/features/issue/components/actions/IssueMenu.tsx
new file mode 100644
index 00000000..50ee755c
--- /dev/null
+++ b/apps/web/src/features/issue/components/actions/IssueMenu.tsx
@@ -0,0 +1,452 @@
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { useFormatter, useTranslations } from 'next-intl';
+import {
+ Archive,
+ ArchiveRestore,
+ Bot,
+ CalendarClock,
+ CircleDashed,
+ ClipboardCopy,
+ PanelRight,
+ RefreshCw,
+ SquareArrowOutUpRight,
+ Tag,
+ Target,
+ Trash2,
+ User,
+ X,
+} from 'lucide-react';
+import type { ActionDef } from '@/lib/api/endpoints/actions';
+import type { ProjectDetail } from '@/lib/api/endpoints/projects';
+import { getIssue, type Issue, type IssuePatch } from '@/lib/api/endpoints/issues';
+import { actionIcon } from '@/utils/actionIcons';
+import { useActionsQuery } from '@/services/actions.service';
+import { useRestoreIssue, useUpdateIssue } from '@/services/issues.service';
+import { useInitiativeOptionsQuery } from '@/services/initiatives.service';
+import { STATUS_META } from '@/utils/initiativeMeta';
+import { CYCLE_STATUS_META } from '@/utils/cycleMeta';
+import { usePermissions } from '@/hooks/usePermissions';
+import { usePriorityLabel } from '@/hooks/usePriorityLabel';
+import type { ShellContext } from '@/context/shellContext';
+import { useArchiveAction } from '../../hooks/useArchiveAction';
+import { ApplyActionDialog, DeleteIssueDialog, matchedActions } from './IssueActions';
+import { buildIssueBranchName, buildIssuePrompt } from '../../utils/issuePrompt';
+import { writeClipboardText } from '../../utils/clipboard';
+import { delegatableAgents } from '../../utils/delegates';
+import { useSession } from '@/lib/auth-client';
+import { toDateStr } from '@/utils/dates';
+import { colorDot } from '@/components/common/fields/colorDot';
+import { PRIORITY_FIELDS } from '@/components/common/fields/priorityFields';
+import { StateIcon } from '../shared/IssueIcons';
+import { dueDatePresets } from '../../utils/dueDatePresets';
+import { useDueDatePresetLabel } from '../../hooks/useDueDatePresetLabel';
+import { issuePath } from '@/utils/paths';
+import {
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuShortcut,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+} from '@/components/ui/context-menu';
+import SelectedCheck from './SelectedCheck';
+
+// The right-click menu's content and the dialogs it opens.
+export default function IssueMenu({
+ project,
+ issue,
+ open,
+ onDeleted,
+ onOpenIssue,
+}: {
+ project: ProjectDetail;
+ issue: Issue;
+ open: boolean;
+ onDeleted?: () => void;
+ onOpenIssue: ShellContext['onOpenIssue'];
+}) {
+ const t = useTranslations('issue.menu');
+ const format = useFormatter();
+ const tCommon = useTranslations('common');
+ const { can } = usePermissions();
+ const { data: session } = useSession();
+ const canEdit = can('work_items', 'edit');
+ const canDelete = can('work_items', 'delete');
+ const updateIssue = useUpdateIssue(project.project.ref);
+ const { archive, dialog: archiveDialog } = useArchiveAction(project, onDeleted);
+ const restoreIssue = useRestoreIssue(project.project.ref);
+ const actionsQuery = useActionsQuery(project.project.ref);
+ const priorityLabel = usePriorityLabel();
+ const presetLabel = useDueDatePresetLabel();
+ const [copyIssue, setCopyIssue] = useState<Issue | null>(null);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+ const [confirmingAction, setConfirmingAction] = useState<ActionDef | null>(null);
+ // Initiatives are not in the board scaffold, so they are fetched only while the
+ // menu is open.
+ const initiativesQuery = useInitiativeOptionsQuery(
+ open && project.project.initiativesEnabled ? project.project.ref : null,
+ );
+
+ const actions = matchedActions(actionsQuery.data ?? [], project, issue);
+
+ function patch(fields: IssuePatch) {
+ updateIssue.mutate({ id: issue.id, patch: fields });
+ }
+
+ function toggleLabel(id: number) {
+ const next = issue.labelIds.includes(id)
+ ? issue.labelIds.filter((x) => x !== id)
+ : [...issue.labelIds, id];
+ patch({ labelIds: next });
+ }
+
+ async function copyText(value: string | Promise<string>) {
+ try {
+ await writeClipboardText(value);
+ toast.success(tCommon('copied'));
+ } catch {
+ toast.error(t('copyFailed'));
+ }
+ }
+
+ function openCopySubmenu(next: boolean) {
+ if (!next) return;
+ setCopyIssue(null);
+ // Fetch while the submenu opens so the clipboard write stays in the selection gesture.
+ void getIssue(issue.id)
+ .then(setCopyIssue)
+ .catch(() => toast.error(t('copyFailed')));
+ }
+
+ const copyShortLink = () => copyText(`${window.location.origin}/${issue.identifier}`);
+ const copyFullUrl = () =>
+ copyText(`${window.location.origin}${issuePath(project.project.ref, issue.sequenceNumber)}`);
+
+ const currentColumn = project.columns.find((c) => c.id === issue.columnId);
+ const currentPriority =
+ PRIORITY_FIELDS.find((p) => p.value === (issue.priority ?? '')) ?? PRIORITY_FIELDS[0];
+ const members = project.assignees.filter((a) => a.kind === 'member');
+ const agents = delegatableAgents(project.assignees, session?.user.id ?? null);
+ const initiatives = initiativesQuery.data ?? [];
+
+ return (
+ <>
+ <ContextMenuContent className="w-56">
+ {/* Both ways to open the issue, regardless of the account's default
+ open mode. Reading an issue needs no permission. */}
+ <ContextMenuItem onSelect={() => onOpenIssue(issue.id, 'panel')}>
+ <PanelRight />
+ {t('preview')}
+ </ContextMenuItem>
+ <ContextMenuItem onSelect={() => onOpenIssue(issue.id, 'page')}>
+ <SquareArrowOutUpRight />
+ {t('goToIssue')}
+ </ContextMenuItem>
+
+ <ContextMenuSeparator />
+
+ {canEdit && (
+ <>
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ {currentColumn ? (
+ <StateIcon
+ stateType={currentColumn.stateType}
+ color={currentColumn.color}
+ className="size-3.5"
+ />
+ ) : (
+ <CircleDashed />
+ )}
+ {t('status')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ {project.columns.map((c) => (
+ <ContextMenuItem key={c.id} onSelect={() => patch({ columnId: c.id })}>
+ <StateIcon stateType={c.stateType} color={c.color} className="size-3.5" />
+ <span className="truncate">{c.name}</span>
+ <SelectedCheck selected={c.id === issue.columnId} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ {currentPriority.icon}
+ {t('priority')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-52">
+ {PRIORITY_FIELDS.map((p) => (
+ <ContextMenuItem
+ key={p.value || 'none'}
+ onSelect={() => patch({ priority: p.value || null })}
+ >
+ {p.icon}
+ <span className="flex-1">{priorityLabel(p.value)}</span>
+ <SelectedCheck selected={p.value === (issue.priority ?? '')} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+
+ {members.length > 0 && (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <User />
+ {t('assignee')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ <ContextMenuItem onSelect={() => patch({ assigneeUserId: null })}>
+ <CircleDashed />
+ <span className="flex-1">{t('noAssignee')}</span>
+ <SelectedCheck selected={issue.assigneeUserId == null} />
+ </ContextMenuItem>
+ {members.map((a) => (
+ <ContextMenuItem
+ key={a.userId}
+ onSelect={() => patch({ assigneeUserId: a.userId })}
+ >
+ <User />
+ <span className="flex-1 truncate">{a.name}</span>
+ <SelectedCheck selected={a.userId === issue.assigneeUserId} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ )}
+
+ {agents.length > 0 && (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <Bot />
+ {t('delegate')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ <ContextMenuItem onSelect={() => patch({ delegateUserId: null })}>
+ <CircleDashed />
+ <span className="flex-1">{t('noDelegate')}</span>
+ <SelectedCheck selected={issue.delegateUserId == null} />
+ </ContextMenuItem>
+ {agents.map((a) => (
+ <ContextMenuItem
+ key={a.userId}
+ onSelect={() => patch({ delegateUserId: a.userId })}
+ >
+ <Bot />
+ <span className="flex-1 truncate">{a.name}</span>
+ <SelectedCheck selected={a.userId === issue.delegateUserId} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ )}
+
+ {project.project.initiativesEnabled && (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ {issue.initiative ? <Target /> : <CircleDashed />}
+ {t('initiative')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ <ContextMenuItem onSelect={() => patch({ initiativeId: null })}>
+ <CircleDashed />
+ <span className="flex-1">{t('noInitiative')}</span>
+ <SelectedCheck selected={issue.initiative == null} />
+ </ContextMenuItem>
+ {initiatives.map((it) => (
+ <ContextMenuItem key={it.id} onSelect={() => patch({ initiativeId: it.id })}>
+ {colorDot(STATUS_META[it.status].color)}
+ <span className="flex-1 truncate">{it.title}</span>
+ <SelectedCheck selected={it.id === issue.initiative?.id} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ )}
+
+ {project.project.cyclesEnabled && (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ {issue.cycle ? <RefreshCw /> : <CircleDashed />}
+ {t('cycle')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ <ContextMenuItem onSelect={() => patch({ cycleId: null })}>
+ <CircleDashed />
+ <span className="flex-1">{t('noCycle')}</span>
+ <SelectedCheck selected={issue.cycle == null} />
+ </ContextMenuItem>
+ {project.plannedCycles.map((cycle) => (
+ <ContextMenuItem key={cycle.id} onSelect={() => patch({ cycleId: cycle.id })}>
+ {colorDot(CYCLE_STATUS_META[cycle.status].color)}
+ <span className="flex-1 truncate">{cycle.name}</span>
+ <SelectedCheck selected={cycle.id === issue.cycle?.id} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ )}
+
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <CalendarClock />
+ {t('dueDate')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-72">
+ {dueDatePresets().map((p) => (
+ <ContextMenuItem
+ key={p.key}
+ onSelect={() => patch({ dueDate: toDateStr(p.date) })}
+ >
+ <CalendarClock />
+ <span className="whitespace-nowrap">{presetLabel(p.key)}</span>
+ <ContextMenuShortcut className="whitespace-nowrap">
+ {format.dateTime(p.date, {
+ weekday: 'short',
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ })}
+ </ContextMenuShortcut>
+ </ContextMenuItem>
+ ))}
+ {issue.dueDate && (
+ <>
+ <ContextMenuSeparator />
+ <ContextMenuItem onSelect={() => patch({ dueDate: null })}>
+ <X />
+ {t('clearDueDate')}
+ </ContextMenuItem>
+ </>
+ )}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+
+ {project.labels.length > 0 && (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <Tag />
+ {t('labels')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-56">
+ {project.labels.map((l) => (
+ <ContextMenuItem
+ key={l.id}
+ // Keep the menu open so several labels can be toggled in one pass.
+ onSelect={(e) => {
+ e.preventDefault();
+ toggleLabel(l.id);
+ }}
+ >
+ {colorDot(l.color)}
+ <span className="flex-1 truncate">{l.name}</span>
+ <SelectedCheck selected={issue.labelIds.includes(l.id)} />
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ )}
+
+ {actions.length > 0 && (
+ <>
+ <ContextMenuSeparator />
+ {actions.map((a) => {
+ const Icon = actionIcon(a.icon);
+ return (
+ <ContextMenuItem key={a.id} onSelect={() => setConfirmingAction(a)}>
+ <Icon />
+ <span className="truncate">{a.name}</span>
+ </ContextMenuItem>
+ );
+ })}
+ </>
+ )}
+ </>
+ )}
+
+ {canEdit && <ContextMenuSeparator />}
+
+ <ContextMenuSub onOpenChange={openCopySubmenu}>
+ <ContextMenuSubTrigger>
+ <ClipboardCopy />
+ {tCommon('copy')}
+ </ContextMenuSubTrigger>
+ <ContextMenuSubContent className="w-52">
+ <ContextMenuItem onSelect={() => copyText(issue.identifier)}>
+ {t('copyId')}
+ </ContextMenuItem>
+ <ContextMenuItem onSelect={copyShortLink}>{t('copyShortLink')}</ContextMenuItem>
+ <ContextMenuItem onSelect={copyFullUrl}>{t('copyFullUrl')}</ContextMenuItem>
+ <ContextMenuItem onSelect={() => copyText(issue.title)}>
+ {t('copyTitle')}
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!copyIssue}
+ onSelect={() => copyText(copyIssue!.description)}
+ >
+ {t('copyDescription')}
+ </ContextMenuItem>
+ <ContextMenuItem onSelect={() => copyText(buildIssueBranchName(issue, session?.user))}>
+ {t('copyBranch')}
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ disabled={!copyIssue}
+ onSelect={() => copyText(buildIssuePrompt(copyIssue!, project, session?.user))}
+ >
+ {t('copyPrompt')}
+ </ContextMenuItem>
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+
+ {canEdit && <ContextMenuSeparator />}
+
+ {/* Archiving hides the issue from the board but keeps it; restore brings it back. */}
+ {canEdit &&
+ (issue.archivedAt ? (
+ <ContextMenuItem onSelect={() => restoreIssue.mutate(issue.id)}>
+ <ArchiveRestore />
+ {t('restore')}
+ </ContextMenuItem>
+ ) : (
+ <ContextMenuItem onSelect={() => archive(issue)}>
+ <Archive />
+ {t('archive')}
+ </ContextMenuItem>
+ ))}
+
+ {canDelete && <ContextMenuSeparator />}
+
+ {canDelete && (
+ <ContextMenuItem variant="destructive" onSelect={() => setConfirmingDelete(true)}>
+ <Trash2 />
+ {tCommon('delete')}
+ </ContextMenuItem>
+ )}
+ </ContextMenuContent>
+
+ {confirmingDelete && (
+ <DeleteIssueDialog
+ project={project}
+ issue={issue}
+ onClose={() => setConfirmingDelete(false)}
+ onDeleted={onDeleted}
+ />
+ )}
+
+ {confirmingAction && (
+ <ApplyActionDialog
+ project={project}
+ issue={issue}
+ action={confirmingAction}
+ onClose={() => setConfirmingAction(null)}
+ />
+ )}
+
+ {archiveDialog}
+ </>
+ );
+}
diff --git a/apps/web/src/features/issue/components/actions/SelectedCheck.tsx b/apps/web/src/features/issue/components/actions/SelectedCheck.tsx
new file mode 100644
index 00000000..32355180
--- /dev/null
+++ b/apps/web/src/features/issue/components/actions/SelectedCheck.tsx
@@ -0,0 +1,6 @@
+import { Check } from 'lucide-react';
+
+// Trailing check on the currently-selected row in a single-select submenu.
+export default function SelectedCheck({ selected }: { selected: boolean }) {
+ return selected ? <Check className="ml-auto size-4" /> : null;
+}
diff --git a/apps/web/src/features/work-items/WorkItemsPage.tsx b/apps/web/src/features/work-items/WorkItemsPage.tsx
index 53093f4f..b8472615 100644
--- a/apps/web/src/features/work-items/WorkItemsPage.tsx
+++ b/apps/web/src/features/work-items/WorkItemsPage.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useState } from 'react';
+import { useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useShell } from '@/context/shellContext';
import { usePermissions } from '@/hooks/usePermissions';
@@ -62,6 +62,19 @@ export default function WorkItemsPage() {
targets: [qk.boardIssues(projectKey)],
});
+ // With an optional section off, its property and grouping are left out of what
+ // the layouts and the Display panel work with, and put back on the way out so the
+ // stored display keeps them for when the section is on again. Memoized: the
+ // layouts memoize their cards, and a new properties list renders every card again.
+ const settings = useMemo(
+ () => withoutHiddenSections(editor.settings, features),
+ [editor.settings, features],
+ );
+
+ // From the unfiltered project, so a column's WIP limit is measured against every
+ // issue in it rather than the ones the active filters leave on screen.
+ const columnCounts = useMemo(() => countIssuesByColumn(project?.issues ?? []), [project?.issues]);
+
if (!project || !filteredProject) return null;
// Saving persists the view: a project's view is a views edit, a private view is its
@@ -71,17 +84,9 @@ export default function WorkItemsPage() {
const canCreateProjectView = can('views', 'create');
const canSaveView = !editor.activeView || editor.activeView.isPrivate || can('views', 'edit');
- // With an optional section off, its property and grouping are left out of what
- // the layouts and the Display panel work with, and put back on the way out so the
- // stored display keeps them for when the section is on again.
- const settings = withoutHiddenSections(editor.settings, features);
const changeSettings = (next: ViewSettings) =>
editor.changeSettings(restoreHiddenSections(next, editor.settings, features));
- // From the unfiltered project, so a column's WIP limit is measured against every
- // issue in it rather than the ones the active filters leave on screen.
- const columnCounts = countIssuesByColumn(project.issues);
-
const timelineGroups = buildGroups(
filteredProject,
settings.group,
diff --git a/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledCard.tsx b/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledCard.tsx
index ac425f1c..c546128a 100644
--- a/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledCard.tsx
+++ b/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledCard.tsx
@@ -1,3 +1,4 @@
+import { memo } from 'react';
import { useDraggable } from '@dnd-kit/core';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { Issue } from '@/lib/api/endpoints/issues';
@@ -6,8 +7,9 @@ import { usePermissions } from '@/hooks/usePermissions';
import { cn } from '@/lib/utils';
import IssueContextMenu from '@/features/issue/components/actions/IssueContextMenu';
-// A draggable card in the unscheduled panel.
-export function CalendarUnscheduledCard({
+// A draggable card in the unscheduled panel. Memoized because the panel renders
+// again on every scroll step.
+export const CalendarUnscheduledCard = memo(function CalendarUnscheduledCard({
project,
issue,
color,
@@ -49,4 +51,4 @@ export function CalendarUnscheduledCard({
</div>
</IssueContextMenu>
);
-}
+});
diff --git a/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledPanel.tsx b/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledPanel.tsx
index 10b3c047..85eef239 100644
--- a/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledPanel.tsx
+++ b/apps/web/src/features/work-items/components/calendar/CalendarUnscheduledPanel.tsx
@@ -1,4 +1,6 @@
+import { useRef } from 'react';
import { useDroppable } from '@dnd-kit/core';
+import { useVirtualizer } from '@tanstack/react-virtual';
import { useTranslations } from 'next-intl';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { Issue } from '@/lib/api/endpoints/issues';
@@ -9,6 +11,9 @@ import { CalendarUnscheduledCard } from './CalendarUnscheduledCard';
// Droppable id for the unscheduled panel; day cells use `day:<YYYY-MM-DD>`.
export const UNSCHEDULED_ID = 'unscheduled';
+// A card plus the gap under it.
+const CARD_H = 38;
+
// The unscheduled panel — a drop target that clears an issue's date.
export function CalendarUnscheduledPanel({
project,
@@ -27,6 +32,19 @@ export function CalendarUnscheduledPanel({
const { setNodeRef, isOver } = useDroppable({ id: UNSCHEDULED_ID });
// A custom field placement has no wording of its own; it reads as a plain date.
const key = isCustomFieldKey(dateField) ? 'custom' : dateField;
+ // Only the cards in and near the viewport are rendered: without dates, most of a
+ // large project lands here, and the calendar renders the panel on every change.
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const virtualizer = useVirtualizer({
+ count: issues.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => CARD_H,
+ overscan: 10,
+ // A scroll step renders in a normal React update, not in flushSync inside the
+ // scroll event, which blocks every scroll event on a slow CPU.
+ useFlushSync: false,
+ getItemKey: (index) => issues[index].id,
+ });
return (
<div
ref={setNodeRef}
@@ -39,16 +57,28 @@ export function CalendarUnscheduledPanel({
{t(`noDate.${key}`)}
<span className="text-muted-foreground">{issues.length}</span>
</div>
- <div className="flex flex-col gap-1 overflow-y-auto">
- {issues.map((issue) => (
- <CalendarUnscheduledCard
- key={issue.id}
- project={project}
- issue={issue}
- color={dot(issue)}
- onOpen={onOpen}
- />
- ))}
+ <div ref={scrollRef} className="overflow-y-auto">
+ <div className="relative w-full" style={{ height: virtualizer.getTotalSize() }}>
+ {virtualizer.getVirtualItems().map((vi) => {
+ const issue = issues[vi.index];
+ return (
+ <div
+ key={vi.key}
+ data-index={vi.index}
+ ref={virtualizer.measureElement}
+ className="absolute start-0 top-0 w-full pb-1"
+ style={{ transform: `translateY(${vi.start}px)` }}
+ >
+ <CalendarUnscheduledCard
+ project={project}
+ issue={issue}
+ color={dot(issue)}
+ onOpen={onOpen}
+ />
+ </div>
+ );
+ })}
+ </div>
{issues.length === 0 && (
<span className="text-xs text-muted-foreground/50">{t(`allDated.${key}`)}</span>
)}
diff --git a/apps/web/src/features/work-items/components/kanban/BoardCard.tsx b/apps/web/src/features/work-items/components/kanban/BoardCard.tsx
index b2d135eb..1756ab6d 100644
--- a/apps/web/src/features/work-items/components/kanban/BoardCard.tsx
+++ b/apps/web/src/features/work-items/components/kanban/BoardCard.tsx
@@ -1,11 +1,10 @@
-import { useRef } from 'react';
-import { useDndContext, useDraggable } from '@dnd-kit/core';
+import { memo, useRef } from 'react';
+import { useDraggable } from '@dnd-kit/core';
import { DRAG_ACTIVATION_DISTANCE } from '@/lib/dnd';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { BoardIssue } from '@/lib/api/endpoints/issues';
import { type Maps } from '@/utils/project';
import { useIsPhone } from '@/hooks/useIsPhone';
-import { usePermissions } from '@/hooks/usePermissions';
import { cn } from '@/lib/utils';
import type { PropertyKey } from '@/utils/viewSettings';
import IssueContextMenu from '@/features/issue/components/actions/IssueContextMenu';
@@ -19,12 +18,14 @@ import { IssueCardBody } from './IssueCardBody';
// selection, so the drag carries those ids. A plain click opens it, but with a
// selection active (or a Shift/Cmd-click) the click toggles the card's selection
// instead — the board's multi-select for bulk actions.
-export function BoardCard({
+// Memoized because a column renders again on every scroll step.
+export const BoardCard = memo(function BoardCard({
project,
issue,
maps,
properties,
onOpen,
+ canEdit,
readOnly,
}: {
project: ProjectDetail;
@@ -32,22 +33,25 @@ export function BoardCard({
maps: Maps;
properties: PropertyKey[];
onOpen: (id: number) => void;
+ // Passed in rather than read with usePermissions: that reads the Shell context,
+ // which changes on every Shell render, and the card would render with it.
+ canEdit: boolean;
// In a read-only share a click always opens the issue; multi-select is off.
readOnly?: boolean;
}) {
- // Drag is disabled on phones, and without work_items edit (moving a card is an
- // issue edit).
- const { can } = usePermissions();
const selection = useSelection();
const selected = selection.isSelected(issue.id);
const blocked = useIsBlocked(issue);
- const { setNodeRef, attributes, listeners } = useDraggable({
+ // `active` comes from useDraggable, not useDndContext: the dnd-kit context changes
+ // each time a scrolled column mounts a card, and every card reading it renders again.
+ const { setNodeRef, attributes, listeners, active } = useDraggable({
id: issue.id,
data: { issueIds: selected ? [...selection.selected] : [issue.id] },
- disabled: useIsPhone() || !can('work_items', 'edit'),
+ // Drag is disabled on phones, and without work_items edit (moving a card is an
+ // issue edit).
+ disabled: useIsPhone() || !canEdit,
});
// Every card that moves with the drag dims, not just the grabbed one.
- const { active } = useDndContext();
const isDragging = draggedIds(active).includes(issue.id);
// The browser still fires a click after a drag ends, which would open the issue
@@ -105,4 +109,4 @@ export function BoardCard({
</div>
</IssueContextMenu>
);
-}
+});
diff --git a/apps/web/src/features/work-items/components/kanban/BoardColumn.tsx b/apps/web/src/features/work-items/components/kanban/BoardColumn.tsx
index 04ab51a8..0a06682d 100644
--- a/apps/web/src/features/work-items/components/kanban/BoardColumn.tsx
+++ b/apps/web/src/features/work-items/components/kanban/BoardColumn.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useRef } from 'react';
+import { memo, useCallback, useRef } from 'react';
import { useDroppable } from '@dnd-kit/core';
import { useVirtualizer } from '@tanstack/react-virtual';
import { ChevronsRightLeft, EyeOff, Pin, PinOff, Plus } from 'lucide-react';
@@ -8,7 +8,6 @@ import type { BoardIssue } from '@/lib/api/endpoints/issues';
import { type Maps, type IssueGroup } from '@/utils/project';
import { cn } from '@/lib/utils';
import type { PropertyKey } from '@/utils/viewSettings';
-import { usePermissions } from '@/hooks/usePermissions';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { GroupDot } from '../shared/GroupDot';
@@ -32,7 +31,9 @@ const ADD_BUTTON_HEIGHT = 36;
// list of its cards. The DOM holds only the cards in the viewport and near it, so
// a column with a large backlog stays fast. Card heights vary, so the virtualizer
// measures each rendered card instead of assuming a fixed size.
-export function BoardColumn({
+// Memoized: the board renders again whenever the page does, as when the issue panel
+// opens or closes, and a column whose props did not change is skipped.
+export const BoardColumn = memo(function BoardColumn({
project,
group,
issues,
@@ -49,6 +50,8 @@ export function BoardColumn({
wip,
filtered,
boardIssues,
+ canCreate,
+ canEdit,
readOnly,
}: {
project: ProjectDetail;
@@ -63,11 +66,11 @@ export function BoardColumn({
// into a position for each issue the drag carries.
onMoveIssue: (issueIds: number[], group: IssueGroup, index: number) => void;
onOpenIssue: (id: number) => void;
- onAddIssue: () => void;
- onHide: () => void;
- onCollapse: () => void;
+ onAddIssue: (group: IssueGroup) => void;
+ onHide: (group: IssueGroup) => void;
+ onCollapse: (group: IssueGroup) => void;
pinned: boolean;
- onTogglePin: () => void;
+ onTogglePin: (group: IssueGroup) => void;
// The column's WIP limit. It is null when the column has no limit, and null when
// the board is not grouped by status. `filtered` says whether the cards shown are
// only part of the column.
@@ -76,11 +79,14 @@ export function BoardColumn({
// Every issue that the board holds. It tells which of a drag's cards are already
// in this column when only some of them are on screen.
boardIssues: BoardIssue[];
+ // Passed in rather than read with usePermissions: that reads the Shell context,
+ // which changes on every Shell render, and the column would render with it.
+ canCreate: boolean;
+ canEdit: boolean;
readOnly?: boolean;
}) {
const t = useTranslations('workItems');
- const { can } = usePermissions();
- const canCreateIssue = can('work_items', 'create') && !readOnly;
+ const canCreateIssue = canCreate && !readOnly;
const scrollRef = useRef<HTMLDivElement>(null);
// A column with a full hard limit accepts no card from another column. It is not
// a drop target during such a drag. Cards already in the column still reorder
@@ -109,6 +115,9 @@ export function BoardColumn({
getScrollElement: () => scrollRef.current,
estimateSize: () => 130,
overscan: 8,
+ // A scroll step renders in a normal React update, not in flushSync inside the
+ // scroll event, which blocks every scroll event on a slow CPU.
+ useFlushSync: false,
getItemKey: (index) => issues[index].id,
});
const cardsHeight = virtualizer.getTotalSize();
@@ -138,7 +147,7 @@ export function BoardColumn({
variant="ghost"
size="icon"
className="hidden size-6 text-muted-foreground md:inline-flex"
- onClick={onTogglePin}
+ onClick={() => onTogglePin(group)}
aria-label={pinned ? t('unpin') : t('pin')}
>
{pinned ? <PinOff /> : <Pin />}
@@ -152,7 +161,7 @@ export function BoardColumn({
variant="ghost"
size="icon"
className="size-6 text-muted-foreground"
- onClick={onCollapse}
+ onClick={() => onCollapse(group)}
aria-label={t('collapse')}
>
<ChevronsRightLeft />
@@ -166,7 +175,7 @@ export function BoardColumn({
variant="ghost"
size="icon"
className="size-6 text-muted-foreground"
- onClick={onHide}
+ onClick={() => onHide(group)}
aria-label={t('hide')}
>
<EyeOff />
@@ -183,7 +192,7 @@ export function BoardColumn({
variant="ghost"
size="icon"
className="size-6 text-muted-foreground"
- onClick={onAddIssue}
+ onClick={() => onAddIssue(group)}
aria-label={t('newIssue')}
>
<Plus />
@@ -235,6 +244,7 @@ export function BoardColumn({
maps={maps}
properties={properties}
onOpen={onOpenIssue}
+ canEdit={canEdit}
readOnly={readOnly}
/>
</CardDropSlot>
@@ -251,7 +261,7 @@ export function BoardColumn({
variant="outline"
className="invisible absolute left-0 w-full text-muted-foreground opacity-0 group-focus-within/column:visible group-focus-within/column:opacity-100 group-hover/column:visible group-hover/column:opacity-100"
style={{ top: cardsHeight + ADD_BUTTON_GAP }}
- onClick={onAddIssue}
+ onClick={() => onAddIssue(group)}
aria-label={t('newIssue')}
>
<Plus />
@@ -264,4 +274,4 @@ export function BoardColumn({
</div>
</div>
);
-}
+});
diff --git a/apps/web/src/features/work-items/components/kanban/CardDropSlot.tsx b/apps/web/src/features/work-items/components/kanban/CardDropSlot.tsx
index c3e88a2a..a1b327b1 100644
--- a/apps/web/src/features/work-items/components/kanban/CardDropSlot.tsx
+++ b/apps/web/src/features/work-items/components/kanban/CardDropSlot.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
-import { useDndContext, useDroppable } from '@dnd-kit/core';
+import { useDroppable } from '@dnd-kit/core';
import { DropLine } from '../shared/DropLine';
import { draggedIds } from '../../utils/kanban';
@@ -22,13 +22,12 @@ export function CardDropSlot({
disabled?: boolean;
children: ReactNode;
}) {
- const { setNodeRef, isOver } = useDroppable({
+ const { setNodeRef, isOver, active } = useDroppable({
id: `card:${issueId}`,
disabled,
data: { onDrop: (ids: number[]) => !ids.includes(issueId) && onDrop(ids) },
});
// Dropping cards on one of themselves is a no-op, so it gets no marker.
- const { active } = useDndContext();
const showDropLine = isOver && !draggedIds(active).includes(issueId);
return (
diff --git a/apps/web/src/features/work-items/components/kanban/FlatBoard.tsx b/apps/web/src/features/work-items/components/kanban/FlatBoard.tsx
index e8ba7fd2..05f6d986 100644
--- a/apps/web/src/features/work-items/components/kanban/FlatBoard.tsx
+++ b/apps/web/src/features/work-items/components/kanban/FlatBoard.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from 'react';
import { DndContext } from '@dnd-kit/core';
import { toast } from 'sonner';
import { ChevronDown, Eye } from 'lucide-react';
@@ -12,12 +13,15 @@ import {
type WorkItemsViewProps,
type IssueGroup,
} from '@/utils/project';
+import type { BoardIssue } from '@/lib/api/endpoints/issues';
import { isActiveFilterSet } from '@/utils/filters';
import { useBoardDnd } from '../../hooks/useBoardDnd';
import { useSortedOrderMessage } from '../../hooks/useSortedOrderMessage';
import { useWipLimitMessage } from '../../hooks/useWipLimitMessage';
import { countEntering, wipAllows, wipStateFor } from '../../utils/wipLimit';
import { useGroupLabels } from '@/hooks/useGroupLabels';
+import { useStableCallback } from '@/hooks/useStableCallback';
+import { usePermissions } from '@/hooks/usePermissions';
import { useSelection } from '../../context/useSelection';
import { boardCollision, issuesToMove } from '../../utils/kanban';
import { Button } from '@/components/ui/button';
@@ -28,6 +32,9 @@ import { BoardColumn } from './BoardColumn';
import { CollapsedColumn } from './CollapsedColumn';
import { WipCount } from './WipCount';
+// A column with no issues gets the same empty list on every render.
+const NO_ISSUES: BoardIssue[] = [];
+
// Flat board: one vertically-virtualized column per group, in a horizontal row. A
// trailing "Hidden" panel holds the columns that the user hid.
export default function FlatBoard({
@@ -46,6 +53,7 @@ export default function FlatBoard({
const wipLimitMessage = useWipLimitMessage();
const dnd = useBoardDnd(project, readOnly);
const selection = useSelection();
+ const { can } = usePermissions();
const filtered = isActiveFilterSet(filters);
// Hidden columns are stored in the view's display (settings.hiddenGroups). A
@@ -78,10 +86,25 @@ export default function FlatBoard({
const togglePin = (key: string) =>
onSettingsChange({ ...settings, pinnedGroup: settings.pinnedGroup === key ? null : key });
- const groups = buildGroups(project, settings.group, groupLabels, filters);
- const sorted = sortIssues(project.issues, settings.sort, project);
- const issuesByGroup = groupIssues(groups, sorted, settings.group);
- const maps = buildMaps(project);
+ // The board's data is memoized on its inputs, so a render of the page that changes
+ // none of them hands the memoized columns and cards the same objects.
+ const groups = useMemo(
+ () => buildGroups(project, settings.group, groupLabels, filters),
+ [project, settings.group, groupLabels, filters],
+ );
+ const sorted = useMemo(
+ () => sortIssues(project.issues, settings.sort, project),
+ [project, settings.sort],
+ );
+ const issuesByGroup = useMemo(
+ () => groupIssues(groups, sorted, settings.group),
+ [groups, sorted, settings.group],
+ );
+ const maps = useMemo(() => buildMaps(project), [project]);
+ const wipByGroup = useMemo(
+ () => new Map(groups.map((g) => [g.key, wipStateFor(g, project.columns, columnCounts)])),
+ [groups, project.columns, columnCounts],
+ );
// Empty groups are removed when "Show empty columns" is off. A manual hide moves
// any of the remaining groups into the "Hidden" panel.
@@ -105,9 +128,9 @@ export default function FlatBoard({
// column is still moved, because that changes the grouping field, not the order.
const manualOrder = settings.sort.field === 'manual';
- const wipOf = (group: IssueGroup) => wipStateFor(group, project.columns, columnCounts);
+ const wipOf = (group: IssueGroup) => wipByGroup.get(group.key) ?? null;
- function moveIssue(issueIds: number[], group: IssueGroup, index: number) {
+ const moveIssue = useStableCallback((issueIds: number[], group: IssueGroup, index: number) => {
const assign = group.assign;
if (!assign) return;
const target = issuesByGroup.get(group.key) ?? [];
@@ -126,11 +149,14 @@ export default function FlatBoard({
}
const positions = positionsAt(target, index, ids.length);
ids.forEach((id, n) => dnd.move(id, assign, positions[n]));
- }
+ });
- function addIssueTo(group: IssueGroup) {
- onAddIssue(groupDefaults(group.assign));
- }
+ const addIssueTo = useStableCallback((group: IssueGroup) =>
+ onAddIssue(groupDefaults(group.assign)),
+ );
+ const hideGroup = useStableCallback((group: IssueGroup) => setHidden(group.key, true));
+ const collapseGroup = useStableCallback((group: IssueGroup) => setCollapsed(group.key, true));
+ const togglePinGroup = useStableCallback((group: IssueGroup) => togglePin(group.key));
return (
<DndContext
@@ -162,7 +188,7 @@ export default function FlatBoard({
key={group.key}
project={project}
group={group}
- issues={issuesByGroup.get(group.key) ?? []}
+ issues={issuesByGroup.get(group.key) ?? NO_ISSUES}
maps={maps}
properties={settings.properties}
manualOrder={manualOrder}
@@ -171,11 +197,13 @@ export default function FlatBoard({
boardIssues={sorted}
onMoveIssue={moveIssue}
onOpenIssue={onOpenIssue}
- onAddIssue={() => addIssueTo(group)}
- onHide={() => setHidden(group.key, true)}
- onCollapse={() => setCollapsed(group.key, true)}
+ onAddIssue={addIssueTo}
+ onHide={hideGroup}
+ onCollapse={collapseGroup}
pinned={group === pinnedGroup}
- onTogglePin={() => togglePin(group.key)}
+ onTogglePin={togglePinGroup}
+ canCreate={can('work_items', 'create')}
+ canEdit={can('work_items', 'edit')}
readOnly={readOnly}
/>
),
diff --git a/apps/web/src/features/work-items/components/kanban/SwimlaneBoard.tsx b/apps/web/src/features/work-items/components/kanban/SwimlaneBoard.tsx
index 8d45ffad..5a11f146 100644
--- a/apps/web/src/features/work-items/components/kanban/SwimlaneBoard.tsx
+++ b/apps/web/src/features/work-items/components/kanban/SwimlaneBoard.tsx
@@ -1,4 +1,4 @@
-import { useRef } from 'react';
+import { useMemo, useRef } from 'react';
import { DndContext } from '@dnd-kit/core';
import { toast } from 'sonner';
import { useVirtualizer } from '@tanstack/react-virtual';
@@ -64,7 +64,8 @@ export default function SwimlaneBoard({
const selection = useSelection();
const collapsed = usePersistedSet(collapsedSwimlanesKey(project.project.id, settings.subgroup));
- const maps = buildMaps(project);
+ // Memoized: every card takes the maps, and a new object renders every card again.
+ const maps = useMemo(() => buildMaps(project), [project]);
const columnGroups = buildGroups(project, settings.group, groupLabels, filters);
const swimlaneGroups = buildGroups(project, settings.subgroup, groupLabels, filters);
const sorted = sortIssues(project.issues, settings.sort, project);
@@ -119,6 +120,9 @@ export default function SwimlaneBoard({
getScrollElement: () => scrollRef.current,
estimateSize: () => 260,
overscan: 3,
+ // A scroll step renders in a normal React update, not in flushSync inside the
+ // scroll event, which blocks every scroll event on a slow CPU.
+ useFlushSync: false,
getItemKey: (index) => rows[index].swimlane.key,
});
diff --git a/apps/web/src/features/work-items/components/kanban/SwimlaneCell.tsx b/apps/web/src/features/work-items/components/kanban/SwimlaneCell.tsx
index 92adb42a..4919f016 100644
--- a/apps/web/src/features/work-items/components/kanban/SwimlaneCell.tsx
+++ b/apps/web/src/features/work-items/components/kanban/SwimlaneCell.tsx
@@ -3,6 +3,7 @@ import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { BoardIssue } from '@/lib/api/endpoints/issues';
import { type Maps } from '@/utils/project';
import { cn } from '@/lib/utils';
+import { usePermissions } from '@/hooks/usePermissions';
import type { PropertyKey } from '@/utils/viewSettings';
import { BoardCard } from './BoardCard';
import { CardDropSlot } from './CardDropSlot';
@@ -36,6 +37,7 @@ export function SwimlaneCell({
onOpenIssue: (id: number) => void;
onMoveIssue: (issueIds: number[], index: number) => void;
}) {
+ const { can } = usePermissions();
// Dropping on the empty cell area appends; dropping on a card inserts at it.
const cellId = `col:${cellKey}`;
const { setNodeRef, isOver } = useDroppable({
@@ -68,6 +70,7 @@ export function SwimlaneCell({
maps={maps}
properties={properties}
onOpen={onOpenIssue}
+ canEdit={can('work_items', 'edit')}
readOnly={readOnly}
/>
</CardDropSlot>
diff --git a/apps/web/src/features/work-items/components/table/TableRow.tsx b/apps/web/src/features/work-items/components/table/TableRow.tsx
index fee320b0..cb71906a 100644
--- a/apps/web/src/features/work-items/components/table/TableRow.tsx
+++ b/apps/web/src/features/work-items/components/table/TableRow.tsx
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { useDndContext, useDraggable, useDroppable } from '@dnd-kit/core';
+import { useDraggable, useDroppable } from '@dnd-kit/core';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { BoardIssue, IssuePatch } from '@/lib/api/endpoints/issues';
import { type Maps } from '@/utils/project';
@@ -73,14 +73,17 @@ export function TableRow({
listeners,
isDragging,
} = useDraggable({ id: issue.id, disabled: useIsPhone() || !can('work_items', 'edit') });
- const { setNodeRef: dropRef, isOver } = useDroppable({
+ const {
+ setNodeRef: dropRef,
+ isOver,
+ active,
+ } = useDroppable({
id: `row:${issue.id}`,
disabled: dropDisabled,
data: { onDrop: (draggedId: number) => draggedId !== issue.id && onDrop(draggedId) },
});
// The insertion marker sits at this row's top edge: a drop inserts before it.
// Dropping a row on itself is a no-op, so it gets no marker.
- const { active } = useDndContext();
const showDropLine = isOver && Number(active?.id) !== issue.id;
const mergedRef = useCallback(
(el: HTMLElement | null) => {
diff --git a/apps/web/src/features/work-items/components/table/TableView.tsx b/apps/web/src/features/work-items/components/table/TableView.tsx
index fa5f0dfd..c501f4f0 100644
--- a/apps/web/src/features/work-items/components/table/TableView.tsx
+++ b/apps/web/src/features/work-items/components/table/TableView.tsx
@@ -81,6 +81,9 @@ export default function TableView({
getScrollElement: () => scrollRef.current,
estimateSize: () => 40,
overscan: 12,
+ // A scroll step renders in a normal React update, not in flushSync inside the
+ // scroll event, which blocks every scroll event on a slow CPU.
+ useFlushSync: false,
getItemKey: (index) => {
const it = items[index];
if (it.kind === 'header') return `h${it.group.key}`;
diff --git a/apps/web/src/features/work-items/components/timeline/TimelineIssueBlock.tsx b/apps/web/src/features/work-items/components/timeline/TimelineIssueBlock.tsx
index 4a0e96a8..db7d9b1d 100644
--- a/apps/web/src/features/work-items/components/timeline/TimelineIssueBlock.tsx
+++ b/apps/web/src/features/work-items/components/timeline/TimelineIssueBlock.tsx
@@ -1,4 +1,4 @@
-import { useDndContext, useDroppable } from '@dnd-kit/core';
+import { useDroppable } from '@dnd-kit/core';
import { DropLine } from '../shared/DropLine';
import { SubtaskFoldProvider, useSubtaskFold } from '../../context/useSubtasks';
@@ -20,14 +20,13 @@ export function TimelineIssueBlock({
onDrop: (draggedId: number) => void;
children: React.ReactNode;
}) {
- // Dropping an issue on itself is a no-op: it neither moves nor gets a marker.
- const { active } = useDndContext();
- const self = Number(active?.id) === issueId;
- const { setNodeRef, isOver } = useDroppable({
+ const { setNodeRef, isOver, active } = useDroppable({
id: `row:${issueId}`,
disabled,
data: { onDrop: (draggedId: number) => draggedId !== issueId && onDrop(draggedId) },
});
+ // Dropping an issue on itself is a no-op: it neither moves nor gets a marker.
+ const self = Number(active?.id) === issueId;
// The subtask fold belongs to the block rather than to either row: the chevron is
// on the issue row and the rows it folds are its siblings.
const fold = useSubtaskFold();
diff --git a/apps/web/src/features/work-items/components/timeline/TimelineRowSlot.tsx b/apps/web/src/features/work-items/components/timeline/TimelineRowSlot.tsx
new file mode 100644
index 00000000..224d943c
--- /dev/null
+++ b/apps/web/src/features/work-items/components/timeline/TimelineRowSlot.tsx
@@ -0,0 +1,14 @@
+import { memo, type ReactNode } from 'react';
+import type { TimelineRow } from '../../utils/timeline';
+
+// Memoized so a scroll step, which renders TimelineRows again, skips the rows that
+// stay in view: their row and renderRow are the same as before.
+export const TimelineRowSlot = memo(function TimelineRowSlot({
+ row,
+ renderRow,
+}: {
+ row: TimelineRow;
+ renderRow: (row: TimelineRow) => ReactNode;
+}) {
+ return renderRow(row);
+});
diff --git a/apps/web/src/features/work-items/components/timeline/TimelineRows.tsx b/apps/web/src/features/work-items/components/timeline/TimelineRows.tsx
new file mode 100644
index 00000000..faef63c8
--- /dev/null
+++ b/apps/web/src/features/work-items/components/timeline/TimelineRows.tsx
@@ -0,0 +1,60 @@
+import { useRef, type ReactNode, type RefObject } from 'react';
+import { useVirtualizer } from '@tanstack/react-virtual';
+import { GROUP_H, ROW_H, SUBGROUP_H, type TimelineRow } from '../../utils/timeline';
+import { TimelineRowSlot } from './TimelineRowSlot';
+
+const ROW_HEIGHT: Record<TimelineRow['kind'], number> = {
+ group: GROUP_H,
+ subgroup: SUBGROUP_H,
+ issue: ROW_H,
+};
+
+function rowKey(row: TimelineRow): string {
+ if (row.kind === 'group') return `g-${row.group.key}`;
+ if (row.kind === 'subgroup') return `s-${row.groupKey}`;
+ return `i-${row.issue.id}`;
+}
+
+// Only the rows in and near the viewport are rendered: a project with thousands of
+// issues otherwise renders every row on each change. An issue's block grows with its
+// subtask and link rows, so each rendered row is measured.
+export function TimelineRows({
+ rows,
+ scrollRef,
+ renderRow,
+}: {
+ rows: TimelineRow[];
+ scrollRef: RefObject<HTMLDivElement | null>;
+ renderRow: (row: TimelineRow) => ReactNode;
+}) {
+ const listRef = useRef<HTMLDivElement>(null);
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: (index) => ROW_HEIGHT[rows[index].kind],
+ overscan: 10,
+ // A scroll step renders in a normal React update, not in flushSync inside the
+ // scroll event, which blocks every scroll event on a slow CPU.
+ useFlushSync: false,
+ getItemKey: (index) => rowKey(rows[index]),
+ // The rows start below the sticky header.
+ scrollMargin: listRef.current?.offsetTop ?? 0,
+ });
+ const scrollMargin = virtualizer.options.scrollMargin;
+
+ return (
+ <div ref={listRef} className="relative" style={{ height: virtualizer.getTotalSize() }}>
+ {virtualizer.getVirtualItems().map((vi) => (
+ <div
+ key={vi.key}
+ data-index={vi.index}
+ ref={virtualizer.measureElement}
+ className="absolute top-0 left-0 w-full"
+ style={{ transform: `translateY(${vi.start - scrollMargin}px)` }}
+ >
+ <TimelineRowSlot row={rows[vi.index]} renderRow={renderRow} />
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/work-items/components/timeline/TimelineView.tsx b/apps/web/src/features/work-items/components/timeline/TimelineView.tsx
index 2f0a77c3..e6176d60 100644
--- a/apps/web/src/features/work-items/components/timeline/TimelineView.tsx
+++ b/apps/web/src/features/work-items/components/timeline/TimelineView.tsx
@@ -10,7 +10,13 @@ import { TimelineHeader } from '@/components/common/timeline/TimelineHeader';
import { TimelineLabelResizer } from '@/components/common/timeline/TimelineLabelResizer';
import { useTimelineDrag } from '../../hooks/useTimelineDrag';
import { useIssueReorder } from '../../hooks/useIssueReorder';
-import { buildTimeline, labelWidthKey, SCALE_DAY_W, timelineColumns } from '../../utils/timeline';
+import {
+ buildTimeline,
+ labelWidthKey,
+ SCALE_DAY_W,
+ timelineColumns,
+ type TimelineRow,
+} from '../../utils/timeline';
import { IssueDragOverlay } from '../shared/IssueDragOverlay';
import { TimelineColumnHeader } from './TimelineColumnHeader';
import { TimelineGroupRow } from './TimelineGroupRow';
@@ -18,6 +24,7 @@ import { TimelineSubgroupRow } from './TimelineSubgroupRow';
import { TimelineIssueBlock } from './TimelineIssueBlock';
import { TimelineIssueRow } from './TimelineIssueRow';
import { TimelineLinkRows } from './TimelineLinkRows';
+import { TimelineRows } from './TimelineRows';
import { TimelineSubtaskRows } from './TimelineSubtaskRows';
interface TimelineViewProps extends WorkItemsViewProps {
@@ -92,6 +99,105 @@ export default function TimelineView({
dayW: DAY_W,
});
+ function renderRow(row: TimelineRow) {
+ if (row.kind === 'group') {
+ return (
+ <TimelineGroupRow
+ group={row.group}
+ count={row.count}
+ collapsed={row.collapsed}
+ aggregateRect={
+ row.aggregateSpan ? spanToRect(row.aggregateSpan.start, row.aggregateSpan.end) : null
+ }
+ labelW={labelW}
+ trackWidth={trackWidth}
+ disabled={subgrouped && !row.collapsed}
+ onDrop={(id) => reorder.moveIssue(id, row.assign, row.bucket, row.bucket.length)}
+ onToggle={() => toggleGroup(row.group.key)}
+ />
+ );
+ }
+
+ if (row.kind === 'subgroup') {
+ return (
+ <TimelineSubgroupRow
+ sub={row.sub}
+ groupKey={row.groupKey}
+ count={row.count}
+ collapsed={row.collapsed}
+ aggregateRect={
+ row.aggregateSpan ? spanToRect(row.aggregateSpan.start, row.aggregateSpan.end) : null
+ }
+ labelW={labelW}
+ trackWidth={trackWidth}
+ onDrop={(id) => reorder.moveIssue(id, row.assign, row.bucket, row.bucket.length)}
+ onToggle={() => toggleGroup(row.groupKey)}
+ />
+ );
+ }
+
+ const { issue, span } = row;
+ const active = preview?.issueId === issue.id;
+ const rect = spanToRect(active ? preview!.start : span.start, active ? preview!.end : span.end);
+ return (
+ <TimelineIssueBlock
+ issueId={issue.id}
+ disabled={!reorder.manualOrder}
+ onDrop={(draggedId) => reorder.moveIssue(draggedId, row.assign, row.bucket, row.index)}
+ >
+ <TimelineIssueRow
+ project={project}
+ issue={issue}
+ maps={maps}
+ span={span}
+ rect={rect}
+ color={issueColor(issue, maps)}
+ active={active}
+ indented={subgrouped}
+ labelW={labelW}
+ columns={columns}
+ trackWidth={trackWidth}
+ dayLines={dayLines}
+ todayInRange={todayInRange}
+ todayLeft={todayLeft}
+ readOnly={barsReadOnly}
+ onBeginDrag={beginDrag}
+ onOpen={onOpenIssue}
+ />
+ <TimelineSubtaskRows
+ project={project}
+ issueId={issue.id}
+ indented={subgrouped}
+ maps={maps}
+ labelW={labelW}
+ columns={columns}
+ readOnly={barsReadOnly}
+ trackWidth={trackWidth}
+ dayLines={dayLines}
+ todayInRange={todayInRange}
+ todayLeft={todayLeft}
+ spanToRect={spanToRect}
+ onOpen={onOpenIssue}
+ />
+ <TimelineLinkRows
+ project={project}
+ links={issue.links}
+ indented={subgrouped}
+ maps={maps}
+ labelW={labelW}
+ columns={columns}
+ readOnly={barsReadOnly}
+ trackWidth={trackWidth}
+ dayLines={dayLines}
+ todayInRange={todayInRange}
+ todayLeft={todayLeft}
+ spanToRect={spanToRect}
+ onOpen={onOpenIssue}
+ />
+ </TimelineIssueBlock>
+ );
+ }
+
return (
<DndContext
sensors={reorder.sensors}
@@ -115,116 +221,7 @@ export default function TimelineView({
/>
{!narrow && <TimelineLabelResizer labelW={titleW} onResize={setTitleWidth} />}
- {rows.map((row) => {
- if (row.kind === 'group') {
- return (
- <TimelineGroupRow
- key={`g-${row.group.key}`}
- group={row.group}
- count={row.count}
- collapsed={row.collapsed}
- aggregateRect={
- row.aggregateSpan
- ? spanToRect(row.aggregateSpan.start, row.aggregateSpan.end)
- : null
- }
- labelW={labelW}
- trackWidth={trackWidth}
- disabled={subgrouped && !row.collapsed}
- onDrop={(id) => reorder.moveIssue(id, row.assign, row.bucket, row.bucket.length)}
- onToggle={() => toggleGroup(row.group.key)}
- />
- );
- }
-
- if (row.kind === 'subgroup') {
- return (
- <TimelineSubgroupRow
- key={`s-${row.groupKey}`}
- sub={row.sub}
- groupKey={row.groupKey}
- count={row.count}
- collapsed={row.collapsed}
- aggregateRect={
- row.aggregateSpan
- ? spanToRect(row.aggregateSpan.start, row.aggregateSpan.end)
- : null
- }
- labelW={labelW}
- trackWidth={trackWidth}
- onDrop={(id) => reorder.moveIssue(id, row.assign, row.bucket, row.bucket.length)}
- onToggle={() => toggleGroup(row.groupKey)}
- />
- );
- }
-
- const { issue, span } = row;
- const active = preview?.issueId === issue.id;
- const rect = spanToRect(
- active ? preview!.start : span.start,
- active ? preview!.end : span.end,
- );
- return (
- <TimelineIssueBlock
- key={issue.id}
- issueId={issue.id}
- disabled={!reorder.manualOrder}
- onDrop={(draggedId) =>
- reorder.moveIssue(draggedId, row.assign, row.bucket, row.index)
- }
- >
- <TimelineIssueRow
- project={project}
- issue={issue}
- maps={maps}
- span={span}
- rect={rect}
- color={issueColor(issue, maps)}
- active={active}
- indented={subgrouped}
- labelW={labelW}
- columns={columns}
- trackWidth={trackWidth}
- dayLines={dayLines}
- todayInRange={todayInRange}
- todayLeft={todayLeft}
- readOnly={barsReadOnly}
- onBeginDrag={beginDrag}
- onOpen={onOpenIssue}
- />
- <TimelineSubtaskRows
- project={project}
- issueId={issue.id}
- indented={subgrouped}
- maps={maps}
- labelW={labelW}
- columns={columns}
- readOnly={barsReadOnly}
- trackWidth={trackWidth}
- dayLines={dayLines}
- todayInRange={todayInRange}
- todayLeft={todayLeft}
- spanToRect={spanToRect}
- onOpen={onOpenIssue}
- />
- <TimelineLinkRows
- project={project}
- links={issue.links}
- indented={subgrouped}
- maps={maps}
- labelW={labelW}
- columns={columns}
- readOnly={barsReadOnly}
- trackWidth={trackWidth}
- dayLines={dayLines}
- todayInRange={todayInRange}
- todayLeft={todayLeft}
- spanToRect={spanToRect}
- onOpen={onOpenIssue}
- />
- </TimelineIssueBlock>
- );
- })}
+ <TimelineRows rows={rows} scrollRef={scrollRef} renderRow={renderRow} />
</div>
</div>
diff --git a/apps/web/src/hooks/useGroupLabels.ts b/apps/web/src/hooks/useGroupLabels.ts
index 115d6443..ea050034 100644
--- a/apps/web/src/hooks/useGroupLabels.ts
+++ b/apps/web/src/hooks/useGroupLabels.ts
@@ -1,5 +1,6 @@
'use client';
+import { useMemo } from 'react';
import { useTranslations } from 'next-intl';
import type { GroupLabels } from '@/utils/project';
import { usePriorityLabel } from '@/hooks/usePriorityLabel';
@@ -9,14 +10,17 @@ import { usePriorityLabel } from '@/hooks/usePriorityLabel';
export function useGroupLabels(): GroupLabels {
const t = useTranslations('workItems.groups');
const priority = usePriorityLabel();
- return {
- noAssignee: t('noAssignee'),
- noDelegate: t('noDelegate'),
- noPriority: t('noPriority'),
- noType: t('noType'),
- noInitiative: t('noInitiative'),
- noCycle: t('noCycle'),
- noMember: t('noMember'),
- priority,
- };
+ return useMemo(
+ () => ({
+ noAssignee: t('noAssignee'),
+ noDelegate: t('noDelegate'),
+ noPriority: t('noPriority'),
+ noType: t('noType'),
+ noInitiative: t('noInitiative'),
+ noCycle: t('noCycle'),
+ noMember: t('noMember'),
+ priority,
+ }),
+ [t, priority],
+ );
}
diff --git a/apps/web/src/hooks/usePriorityLabel.ts b/apps/web/src/hooks/usePriorityLabel.ts
index 1c39fa38..5a7a6460 100644
--- a/apps/web/src/hooks/usePriorityLabel.ts
+++ b/apps/web/src/hooks/usePriorityLabel.ts
@@ -1,5 +1,6 @@
'use client';
+import { useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { PRIORITY_ORDER, type Priority } from '@/utils/fieldOptions';
@@ -8,8 +9,11 @@ import { PRIORITY_ORDER, type Priority } from '@/utils/fieldOptions';
// list is shown as it came instead of rendering a key path.
export function usePriorityLabel() {
const t = useTranslations('common.priority');
- return (value: string | null) => {
- if (!value) return t('none');
- return PRIORITY_ORDER.includes(value as Priority) ? t(value as Priority) : value;
- };
+ return useCallback(
+ (value: string | null) => {
+ if (!value) return t('none');
+ return PRIORITY_ORDER.includes(value as Priority) ? t(value as Priority) : value;
+ },
+ [t],
+ );
}
diff --git a/apps/web/src/hooks/useProjectFeatures.ts b/apps/web/src/hooks/useProjectFeatures.ts
index 94ebfcb0..4daa2bc3 100644
--- a/apps/web/src/hooks/useProjectFeatures.ts
+++ b/apps/web/src/hooks/useProjectFeatures.ts
@@ -1,4 +1,4 @@
-import { useContext } from 'react';
+import { useContext, useMemo } from 'react';
import { ShellCtx } from '@/context/shellContext';
import { projectFeatures, type ProjectFeatureSet } from '@/utils/projectFeatures';
@@ -10,5 +10,6 @@ import { projectFeatures, type ProjectFeatureSet } from '@/utils/projectFeatures
// again once it is turned back on. Without a project every section reads as off,
// the same way usePermissions grants nothing until the project is there.
export function useProjectFeatures(): ProjectFeatureSet {
- return projectFeatures(useContext(ShellCtx)?.project?.project ?? null);
+ const project = useContext(ShellCtx)?.project?.project ?? null;
+ return useMemo(() => projectFeatures(project), [project]);
}
diff --git a/apps/web/src/hooks/useStableCallback.ts b/apps/web/src/hooks/useStableCallback.ts
new file mode 100644
index 00000000..47577956
--- /dev/null
+++ b/apps/web/src/hooks/useStableCallback.ts
@@ -0,0 +1,15 @@
+import { useCallback, useLayoutEffect, useRef } from 'react';
+
+// A function with the same identity on every render that calls the latest `fn`. A
+// memoized child that takes it does not render again when only the parent's closure
+// changed. Call it from event handlers, not during render: until the commit it still
+// runs the `fn` of the previous render.
+export function useStableCallback<Args extends unknown[], Result>(
+ fn: (...args: Args) => Result,
+): (...args: Args) => Result {
+ const latest = useRef(fn);
+ useLayoutEffect(() => {
+ latest.current = fn;
+ });
+ return useCallback((...args: Args) => latest.current(...args), []);
+}
diff --git a/apps/web/src/lib/dnd.ts b/apps/web/src/lib/dnd.ts
index 49d6fb74..3bf83a3b 100644
--- a/apps/web/src/lib/dnd.ts
+++ b/apps/web/src/lib/dnd.ts
@@ -19,11 +19,18 @@ export const DRAG_ACTIVATION_DISTANCE = 4;
// share: the board keeps its DndContext (cards call useDraggable/useDroppable and
// need the ancestor), but nothing is draggable. `inert` is fixed per component
// instance, so the sensor-array length still never changes between its renders.
+// The options are module constants because useSensor memoizes on the options object.
+// A new object on each render gives the DndContext new sensors, and every draggable
+// and droppable of the board renders again.
+const MOUSE_OPTIONS = { activationConstraint: { distance: DRAG_ACTIVATION_DISTANCE } };
+const TOUCH_OPTIONS = { activationConstraint: { delay: 250, tolerance: 8 } };
+const KEYBOARD_OPTIONS = { coordinateGetter: sortableKeyboardCoordinates };
+
export function useDndSensors(inert = false) {
const sensors = useSensors(
- useSensor(MouseSensor, { activationConstraint: { distance: DRAG_ACTIVATION_DISTANCE } }),
- useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 8 } }),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ useSensor(MouseSensor, MOUSE_OPTIONS),
+ useSensor(TouchSensor, TOUCH_OPTIONS),
+ useSensor(KeyboardSensor, KEYBOARD_OPTIONS),
);
const inertSensors = useSensors();
return inert ? inertSensors : sensors;