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.

feat(initiatives): server-side search, pagination and sorting (#20)

Croffd2ac91d1c265
diff --git a/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts b/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts
index fb1c2a90..42d8a8be 100644
--- a/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts
+++ b/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts
@@ -46,7 +46,8 @@ describe('initiatives', () => {
expect(typeof created.data?.id).toBe('number');
const list = await initiatives(asOwner).get();
- expect(list.data!.map((i) => i.title)).toEqual(['Q3 Launch']);
+ expect(list.data!.items.map((i) => i.title)).toEqual(['Q3 Launch']);
+ expect(list.data!.total).toBe(1);
});
it('stores the provided fields and labels', async () => {
@@ -103,7 +104,7 @@ describe('initiatives', () => {
expect(badOwner.status).toBe(400);
expect(badLabel.status).toBe(400);
- expect((await initiatives(asOwner).get()).data).toHaveLength(0);
+ expect((await initiatives(asOwner).get()).data!.items).toHaveLength(0);
});
});
@@ -115,10 +116,83 @@ describe('initiatives', () => {
await createInitiative(asOwner, { title: 'Pr', status: 'proposed' });
const active = await initiatives(asOwner).get({ query: { status: 'active' } });
- expect(active.data!.map((i) => i.title)).toEqual(['A']);
+ expect(active.data!.items.map((i) => i.title)).toEqual(['A']);
const planned = await initiatives(asOwner).get({ query: { status: 'proposed,planned' } });
- expect(planned.data!.map((i) => i.title).sort()).toEqual(['P', 'Pr']);
+ expect(planned.data!.items.map((i) => i.title).sort()).toEqual(['P', 'Pr']);
+ });
+
+ it('matches the title case-insensitively with search', async () => {
+ const { asOwner } = await setup();
+ await createInitiative(asOwner, { title: 'Growth loops' });
+ await createInitiative(asOwner, { title: 'Retention' });
+
+ const res = await initiatives(asOwner).get({ query: { search: 'GROWTH' } });
+ expect(res.data!.items.map((i) => i.title)).toEqual(['Growth loops']);
+ expect(res.data!.total).toBe(1);
+ });
+ });
+
+ describe('list sort and paging', () => {
+ it('sorts by title and reverses with dir', async () => {
+ const { asOwner } = await setup();
+ await createInitiative(asOwner, { title: 'B' });
+ await createInitiative(asOwner, { title: 'A' });
+ await createInitiative(asOwner, { title: 'C' });
+
+ const asc = await initiatives(asOwner).get({ query: { sort: 'title' } });
+ expect(asc.data!.items.map((i) => i.title)).toEqual(['A', 'B', 'C']);
+
+ const desc = await initiatives(asOwner).get({ query: { sort: 'title', dir: 'desc' } });
+ expect(desc.data!.items.map((i) => i.title)).toEqual(['C', 'B', 'A']);
+ });
+
+ it('sorts by priority severity, unset last', async () => {
+ const { asOwner } = await setup();
+ await createInitiative(asOwner, { title: 'none' });
+ await createInitiative(asOwner, { title: 'low', priority: 'low' });
+ await createInitiative(asOwner, { title: 'urgent', priority: 'urgent' });
+
+ const res = await initiatives(asOwner).get({ query: { sort: 'priority' } });
+ expect(res.data!.items.map((i) => i.title)).toEqual(['urgent', 'low', 'none']);
+ });
+
+ it('pages with page and pageSize and reports the full total', async () => {
+ const { asOwner } = await setup();
+ for (const title of ['A', 'B', 'C']) await createInitiative(asOwner, { title });
+
+ const first = await initiatives(asOwner).get({
+ query: { sort: 'title', page: 1, pageSize: 2 },
+ });
+ expect(first.data!.items.map((i) => i.title)).toEqual(['A', 'B']);
+ expect(first.data!.total).toBe(3);
+
+ const second = await initiatives(asOwner).get({
+ query: { sort: 'title', page: 2, pageSize: 2 },
+ });
+ expect(second.data!.items.map((i) => i.title)).toEqual(['C']);
+ expect(second.data!.total).toBe(3);
+ });
+ });
+
+ describe('counts', () => {
+ it('returns per-status counts for the tabs', async () => {
+ const { asOwner } = await setup();
+ await createInitiative(asOwner, { title: 'a1', status: 'active' });
+ await createInitiative(asOwner, { title: 'a2', status: 'active' });
+ await createInitiative(asOwner, { title: 'p', status: 'planned' });
+ await createInitiative(asOwner, { title: 'c', status: 'completed' });
+
+ const res = await initiatives(asOwner).counts.get();
+ expect(res.status).toBe(200);
+ expect(res.data).toMatchObject({
+ total: 4,
+ proposed: 0,
+ planned: 1,
+ active: 2,
+ completed: 1,
+ canceled: 0,
+ });
});
});
diff --git a/apps/api/src/initiatives/routes.ts b/apps/api/src/initiatives/routes.ts
index c8364812..db838adf 100644
--- a/apps/api/src/initiatives/routes.ts
+++ b/apps/api/src/initiatives/routes.ts
@@ -8,6 +8,7 @@ import { HttpError } from '../shared/lib';
import { ErrorResponse } from '../shared/responses';
import {
listInitiatives,
+ initiativeStatusCounts,
getInitiative,
getInitiativeProjectId,
createInitiative,
@@ -96,7 +97,17 @@ export const initiativeRoutes = new Elysia({
.map((s) => s.trim())
.filter(Boolean)
: undefined;
- return listInitiatives(project.id, { statuses });
+ const page = query.page ?? 1;
+ const pageSize = query.pageSize ?? 25;
+ const { items, total } = await listInitiatives(project.id, {
+ statuses,
+ search: query.search,
+ sort: query.sort,
+ dir: query.dir,
+ limit: pageSize,
+ offset: (page - 1) * pageSize,
+ });
+ return { items, total, page, pageSize };
},
{
params: t.Object({ projectKey: t.String() }),
@@ -107,10 +118,40 @@ export const initiativeRoutes = new Elysia({
'Filter by status: a comma-separated subset of proposed,planned,active,completed,canceled. Omit for all.',
}),
),
+ search: t.Optional(t.String({ description: 'Case-insensitive match on the title.' })),
+ sort: t.Optional(
+ t.Union(
+ [
+ t.Literal('title'),
+ t.Literal('priority'),
+ t.Literal('targetDate'),
+ t.Literal('owner'),
+ ],
+ { description: 'Sort column. Omit for the manual position order.' },
+ ),
+ ),
+ dir: t.Optional(
+ t.Union([t.Literal('asc'), t.Literal('desc')], {
+ description: 'Sort direction. Default asc.',
+ }),
+ ),
+ page: t.Optional(t.Numeric({ minimum: 1, description: '1-based page. Default 1.' })),
+ pageSize: t.Optional(
+ t.Numeric({
+ minimum: 1,
+ maximum: 100,
+ description: 'Items per page (1-100). Default 25.',
+ }),
+ ),
}),
permission: ['initiatives', 'read'],
response: {
- 200: t.Array(InitiativeResponse),
+ 200: t.Object({
+ items: t.Array(InitiativeResponse),
+ total: t.Number(),
+ page: t.Number(),
+ pageSize: t.Number(),
+ }),
400: ErrorResponse,
401: ErrorResponse,
403: ErrorResponse,
@@ -118,12 +159,39 @@ export const initiativeRoutes = new Elysia({
},
detail: {
summary: 'List initiatives',
- description: "List a project's initiatives.",
+ description: "List a project's initiatives, filtered, sorted and paged.",
...mcpTool('list_initiatives'),
},
},
)
+ .get(
+ '/projects/:projectKey/initiatives/counts',
+ async ({ project }) => initiativeStatusCounts(project.id),
+ {
+ params: t.Object({ projectKey: t.String() }),
+ permission: ['initiatives', 'read'],
+ response: {
+ 200: t.Object({
+ total: t.Number(),
+ proposed: t.Number(),
+ planned: t.Number(),
+ active: t.Number(),
+ completed: t.Number(),
+ canceled: t.Number(),
+ }),
+ 400: ErrorResponse,
+ 401: ErrorResponse,
+ 403: ErrorResponse,
+ 404: ErrorResponse,
+ },
+ detail: {
+ summary: 'Initiative status counts',
+ description: "Per-status initiative counts for a project, for the list's tabs.",
+ },
+ },
+ )
+
.post(
'/projects/:projectKey/initiatives',
async ({ project, body, user, set }) => {
diff --git a/apps/api/src/initiatives/store.ts b/apps/api/src/initiatives/store.ts
index f055d4c9..61576c61 100644
--- a/apps/api/src/initiatives/store.ts
+++ b/apps/api/src/initiatives/store.ts
@@ -1,5 +1,5 @@
-import { db, initiative, initiativeLabel, issue, label, projectColumn } from '@repo/db';
-import { and, desc, eq, inArray, sql } from 'drizzle-orm';
+import { db, initiative, initiativeLabel, issue, label, projectColumn, user } from '@repo/db';
+import { and, asc, desc, eq, ilike, inArray, sql } from 'drizzle-orm';
import { labelNames } from '../issues/activity';
import { getMembership } from '../members/store';
import { HttpError, iso, num } from '../shared/lib';
@@ -109,24 +109,123 @@ function mapInitiative(
const EMPTY_PROGRESS: InitiativeProgress = { completed: 0, canceled: 0, total: 0 };
+// Sortable columns. progress and health are derived per row after the query, so
+// they are not sortable at the database level.
+export type InitiativeSort = 'title' | 'priority' | 'targetDate' | 'owner';
+
+export interface ListInitiativesOpts {
+ statuses?: string[];
+ search?: string;
+ sort?: InitiativeSort;
+ dir?: 'asc' | 'desc';
+ limit?: number;
+ offset?: number;
+}
+
+export interface InitiativeListPage {
+ items: InitiativeRow[];
+ total: number;
+}
+
+// Priority is a text column with no natural sort order; rank it by severity so a
+// priority sort reads urgent → low, with unset last.
+const PRIORITY_ORDER = sql`case ${initiative.priority}
+ when 'urgent' then 0 when 'high' then 1 when 'medium' then 2 when 'low' then 3 else 4 end`;
+
+function orderExpr(sort: InitiativeSort) {
+ switch (sort) {
+ case 'title':
+ return initiative.title;
+ case 'priority':
+ return PRIORITY_ORDER;
+ case 'targetDate':
+ return initiative.targetDate;
+ case 'owner':
+ // Sort by the owner's display name, not the opaque user id.
+ return sql`(select ${user.name} from ${user} where ${user.id} = ${initiative.ownerUserId})`;
+ }
+}
+
export async function listInitiatives(
projectId: number,
- opts: { statuses?: string[] } = {},
-): Promise<InitiativeRow[]> {
- const where =
- opts.statuses && opts.statuses.length
- ? and(eq(initiative.projectId, projectId), inArray(initiative.status, opts.statuses))
- : eq(initiative.projectId, projectId);
- const rows = await db
+ opts: ListInitiativesOpts = {},
+): Promise<InitiativeListPage> {
+ const conds = [eq(initiative.projectId, projectId)];
+ if (opts.statuses && opts.statuses.length) {
+ conds.push(inArray(initiative.status, opts.statuses));
+ }
+ if (opts.search && opts.search.trim()) {
+ conds.push(ilike(initiative.title, `%${opts.search.trim()}%`));
+ }
+ const where = and(...conds);
+
+ // A chosen sort orders by that column (nulls last); the default is the manual
+ // position. desc(id) breaks ties for a stable page order.
+ const orderBy = opts.sort
+ ? [
+ sql`${orderExpr(opts.sort)} ${opts.dir === 'desc' ? sql`desc` : sql`asc`} nulls last`,
+ desc(initiative.id),
+ ]
+ : [asc(initiative.position), desc(initiative.id)];
+
+ const q = db
.select()
.from(initiative)
.where(where)
- .orderBy(initiative.position, desc(initiative.id));
+ .orderBy(...orderBy);
+ const rows =
+ opts.limit !== undefined ? await q.limit(opts.limit).offset(opts.offset ?? 0) : await q;
+
+ const [{ total }] = await db
+ .select({ total: sql<number>`count(*)` })
+ .from(initiative)
+ .where(where);
+
const ids = rows.map((r) => r.id);
const [counts, labels] = await Promise.all([countsFor(ids), labelsFor(ids)]);
- return rows.map((row) =>
- mapInitiative(row, labels.get(row.id) ?? [], counts.get(row.id) ?? EMPTY_PROGRESS),
- );
+ return {
+ items: rows.map((row) =>
+ mapInitiative(row, labels.get(row.id) ?? [], counts.get(row.id) ?? EMPTY_PROGRESS),
+ ),
+ total: Number(total),
+ };
+}
+
+export interface InitiativeStatusCounts {
+ total: number;
+ proposed: number;
+ planned: number;
+ active: number;
+ completed: number;
+ canceled: number;
+}
+
+// Per-status row counts for the whole project, for the list's status tabs. Kept
+// separate from listInitiatives so the tab counts stay correct under paging.
+export async function initiativeStatusCounts(projectId: number): Promise<InitiativeStatusCounts> {
+ const rows = await db
+ .select({ status: initiative.status, c: sql<number>`count(*)` })
+ .from(initiative)
+ .where(eq(initiative.projectId, projectId))
+ .groupBy(initiative.status);
+ const out: InitiativeStatusCounts = {
+ total: 0,
+ proposed: 0,
+ planned: 0,
+ active: 0,
+ completed: 0,
+ canceled: 0,
+ };
+ for (const r of rows) {
+ const n = Number(r.c);
+ out.total += n;
+ if (r.status === 'proposed') out.proposed = n;
+ else if (r.status === 'planned') out.planned = n;
+ else if (r.status === 'active') out.active = n;
+ else if (r.status === 'completed') out.completed = n;
+ else if (r.status === 'canceled') out.canceled = n;
+ }
+ return out;
}
export async function getInitiative(id: number): Promise<InitiativeRow | null> {
diff --git a/apps/web/src/features/initiatives/InitiativesPage.tsx b/apps/web/src/features/initiatives/InitiativesPage.tsx
index 48d07f62..b9696474 100644
--- a/apps/web/src/features/initiatives/InitiativesPage.tsx
+++ b/apps/web/src/features/initiatives/InitiativesPage.tsx
@@ -4,14 +4,17 @@ import { useState } from 'react';
import { Plus } from 'lucide-react';
import { useShell } from '@/context/shellContext';
import { usePermissions } from '@/hooks/usePermissions';
-import { useInitiativesQuery } from '@/services/initiatives.service';
-import type { Initiative, InitiativeStatus } from '@/lib/api';
+import { useInitiativeCountsQuery, useInitiativesQuery } from '@/services/initiatives.service';
+import type { InitiativeCounts, InitiativeSort, InitiativeStatus } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import InitiativesList from './components/list/InitiativesList';
+import InitiativesPagination from './components/list/InitiativesPagination';
import CreateInitiativeDialog from './components/list/CreateInitiativeDialog';
import InitiativeTabCount from './components/list/InitiativeTabCount';
+const PAGE_SIZE = 25;
+
type Tab = 'all' | 'proposed' | 'planned' | 'active' | 'completed';
// One tab per lifecycle status, except the terminal statuses share a "Completed"
@@ -24,27 +27,64 @@ const TABS: { value: Tab; label: string; statuses: InitiativeStatus[] | undefine
{ value: 'completed', label: 'Completed', statuses: ['completed', 'canceled'] },
];
-function filterByTab(initiatives: Initiative[], tab: Tab): Initiative[] {
- const { statuses } = TABS.find((t) => t.value === tab)!;
- return statuses ? initiatives.filter((i) => statuses.includes(i.status)) : initiatives;
+// The "Completed" tab groups the two terminal statuses, so its count sums them.
+function tabCount(counts: InitiativeCounts | undefined, tab: Tab): number | undefined {
+ if (!counts) return undefined;
+ switch (tab) {
+ case 'all':
+ return counts.total;
+ case 'proposed':
+ return counts.proposed;
+ case 'planned':
+ return counts.planned;
+ case 'active':
+ return counts.active;
+ case 'completed':
+ return counts.completed + counts.canceled;
+ }
}
-// The list of a project's initiatives, filtered by a status tab. Rows link to the
-// detail page. All initiatives are fetched once and filtered client-side so each
-// tab can show its count.
+// A project's initiatives, one status tab at a time. Each tab loads its own page
+// from the server, sorted and paged there; the tab counts come from a separate
+// aggregate so they stay correct regardless of the current page.
export default function InitiativesPage() {
const { project } = useShell();
const { can } = usePermissions();
const [tab, setTab] = useState<Tab>('all');
+ const [page, setPage] = useState(1);
+ const [sort, setSort] = useState<{ key: InitiativeSort; dir: 'asc' | 'desc' } | null>(null);
const [creating, setCreating] = useState(false);
const projectKey = project?.project.key ?? null;
- const query = useInitiativesQuery(projectKey);
+ const statuses = TABS.find((t) => t.value === tab)!.statuses;
- const all = query.data ?? [];
+ const query = useInitiativesQuery(projectKey, {
+ statuses,
+ sort: sort?.key,
+ dir: sort?.dir,
+ page,
+ pageSize: PAGE_SIZE,
+ });
+ const counts = useInitiativeCountsQuery(projectKey).data;
if (!project) return null;
+ const items = query.data?.items ?? [];
+ const total = query.data?.total ?? 0;
+
+ const changeTab = (next: Tab) => {
+ setTab(next);
+ setPage(1);
+ };
+
+ // Re-selecting the sorted column flips its direction; a new column sorts ascending.
+ const changeSort = (key: InitiativeSort) => {
+ setSort((prev) =>
+ prev?.key === key ? { key, dir: prev.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: 'asc' },
+ );
+ setPage(1);
+ };
+
return (
<div className="flex-1 overflow-y-auto">
<div className="flex items-center justify-between px-4 py-3">
@@ -58,12 +98,12 @@ export default function InitiativesPage() {
</div>
<div className="px-4 pb-2">
- <Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}>
+ <Tabs value={tab} onValueChange={(v) => changeTab(v as Tab)}>
<TabsList variant="line">
{TABS.map((t) => (
<TabsTrigger key={t.value} value={t.value}>
{t.label}
- <InitiativeTabCount value={filterByTab(all, t.value).length} />
+ <InitiativeTabCount value={tabCount(counts, t.value)} />
</TabsTrigger>
))}
</TabsList>
@@ -71,13 +111,18 @@ export default function InitiativesPage() {
</div>
<InitiativesList
- initiatives={filterByTab(all, tab)}
+ initiatives={items}
project={project}
isLoading={query.isLoading}
canCreate={can('initiatives', 'create')}
onCreate={() => setCreating(true)}
+ sort={sort?.key}
+ dir={sort?.dir}
+ onSort={changeSort}
/>
+ <InitiativesPagination page={page} pageSize={PAGE_SIZE} total={total} onPage={setPage} />
+
{creating && projectKey && (
<CreateInitiativeDialog projectKey={projectKey} onClose={() => setCreating(false)} />
)}
diff --git a/apps/web/src/features/initiatives/components/detail/InitiativeFeedRow.tsx b/apps/web/src/features/initiatives/components/detail/InitiativeFeedRow.tsx
index e4887cfa..6200b7b5 100644
--- a/apps/web/src/features/initiatives/components/detail/InitiativeFeedRow.tsx
+++ b/apps/web/src/features/initiatives/components/detail/InitiativeFeedRow.tsx
@@ -17,7 +17,7 @@ import type { InitiativeFeedItem } from '@/lib/api';
import { formatDate } from '@/utils/dates';
import { issuePath } from '@/utils/paths';
import { priorityLabel } from '@/utils/fieldOptions';
-import { STATUS_META } from '../shared/initiativeMeta';
+import { STATUS_META } from '@/utils/initiativeMeta';
const ICON: Record<string, typeof CircleDot> = {
created: CirclePlus,
diff --git a/apps/web/src/features/initiatives/components/list/InitiativeRow.tsx b/apps/web/src/features/initiatives/components/list/InitiativeRow.tsx
index 38a9e3a2..cc60d632 100644
--- a/apps/web/src/features/initiatives/components/list/InitiativeRow.tsx
+++ b/apps/web/src/features/initiatives/components/list/InitiativeRow.tsx
@@ -8,7 +8,7 @@ import { AssigneeAvatar } from '@/features/issue/components/shared/IssueBadges';
import { PriorityIcon } from '@/features/issue/components/shared/IssueIcons';
import { colorDot } from '@/components/common/fields/colorDot';
import { TableCell, TableRow } from '@/components/ui/table';
-import { STATUS_META } from '../shared/initiativeMeta';
+import { STATUS_META } from '@/utils/initiativeMeta';
import HealthBadge from '../shared/HealthBadge';
import ProgressBar from '../shared/ProgressBar';
diff --git a/apps/web/src/features/initiatives/components/list/InitiativeTabCount.tsx b/apps/web/src/features/initiatives/components/list/InitiativeTabCount.tsx
index 46b1ee27..9a2c0f52 100644
--- a/apps/web/src/features/initiatives/components/list/InitiativeTabCount.tsx
+++ b/apps/web/src/features/initiatives/components/list/InitiativeTabCount.tsx
@@ -1,5 +1,7 @@
-// Tab counts cap at 99+ so a long label never widens the tab bar.
-export default function InitiativeTabCount({ value }: { value: number }) {
+// A tab's initiative count, capped at 99+ so a long label never widens the tab
+// bar. Renders nothing until the count has loaded.
+export default function InitiativeTabCount({ value }: { value: number | undefined }) {
+ if (value == null) return null;
return (
<span className="rounded bg-muted px-1.5 py-0.5 text-xs font-normal text-muted-foreground tabular-nums">
{value > 99 ? '99+' : value}
diff --git a/apps/web/src/features/initiatives/components/list/InitiativesList.tsx b/apps/web/src/features/initiatives/components/list/InitiativesList.tsx
index ecee6d2b..7921ecfe 100644
--- a/apps/web/src/features/initiatives/components/list/InitiativesList.tsx
+++ b/apps/web/src/features/initiatives/components/list/InitiativesList.tsx
@@ -1,20 +1,38 @@
-import type { Initiative, ProjectDetail } from '@/lib/api';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import type { Initiative, InitiativeSort, ProjectDetail } from '@/lib/api';
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import InitiativeRow from './InitiativeRow';
import InitiativesEmpty from './InitiativesEmpty';
+// Columns in table order. A `sort` key marks the column as sortable; progress and
+// health are derived per row and cannot be sorted server-side.
+const COLUMNS: { label: string; sort?: InitiativeSort }[] = [
+ { label: 'Name', sort: 'title' },
+ { label: 'Priority', sort: 'priority' },
+ { label: 'Owner', sort: 'owner' },
+ { label: 'Target', sort: 'targetDate' },
+ { label: 'Progress' },
+ { label: 'Health' },
+];
+
export default function InitiativesList({
initiatives,
project,
isLoading,
canCreate,
onCreate,
+ sort,
+ dir,
+ onSort,
}: {
initiatives: Initiative[];
project: ProjectDetail;
isLoading: boolean;
canCreate: boolean;
onCreate: () => void;
+ sort: InitiativeSort | undefined;
+ dir: 'asc' | 'desc' | undefined;
+ onSort: (key: InitiativeSort) => void;
}) {
const ownerById = new Map(project.assignees.map((a) => [a.userId, a]));
@@ -23,7 +41,7 @@ export default function InitiativesList({
return <InitiativesEmpty canCreate={canCreate} onCreate={onCreate} />;
return (
- <div className="px-4 pb-6">
+ <div className="px-4 pb-2">
<Table className="min-w-[880px] table-fixed">
<colgroup>
<col className="w-[34%]" />
@@ -35,16 +53,27 @@ export default function InitiativesList({
</colgroup>
<TableHeader>
<TableRow className="hover:bg-transparent">
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">Name</TableHead>
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">
- Priority
- </TableHead>
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">Owner</TableHead>
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">Target</TableHead>
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">
- Progress
- </TableHead>
- <TableHead className="px-3 text-xs font-medium text-muted-foreground">Health</TableHead>
+ {COLUMNS.map((col) => (
+ <TableHead key={col.label} className="px-3 text-xs font-medium text-muted-foreground">
+ {col.sort ? (
+ <button
+ type="button"
+ onClick={() => onSort(col.sort!)}
+ className="inline-flex items-center gap-1 hover:text-foreground"
+ >
+ {col.label}
+ {sort === col.sort &&
+ (dir === 'desc' ? (
+ <ChevronDown className="size-3.5" />
+ ) : (
+ <ChevronUp className="size-3.5" />
+ ))}
+ </button>
+ ) : (
+ col.label
+ )}
+ </TableHead>
+ ))}
</TableRow>
</TableHeader>
<TableBody>
diff --git a/apps/web/src/features/initiatives/components/list/InitiativesPagination.tsx b/apps/web/src/features/initiatives/components/list/InitiativesPagination.tsx
new file mode 100644
index 00000000..4c88f967
--- /dev/null
+++ b/apps/web/src/features/initiatives/components/list/InitiativesPagination.tsx
@@ -0,0 +1,81 @@
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+
+// The page numbers to show: always the first and last page, the current page and
+// its immediate neighbors; every other run collapses to a single 'gap'.
+function pageItems(page: number, pageCount: number): (number | 'gap')[] {
+ const items: (number | 'gap')[] = [];
+ for (let p = 1; p <= pageCount; p++) {
+ if (p === 1 || p === pageCount || Math.abs(p - page) <= 1) {
+ items.push(p);
+ } else if (items[items.length - 1] !== 'gap') {
+ items.push('gap');
+ }
+ }
+ return items;
+}
+
+// Offset pagination for the initiatives list. Hidden when everything fits on one
+// page.
+export default function InitiativesPagination({
+ page,
+ pageSize,
+ total,
+ onPage,
+}: {
+ page: number;
+ pageSize: number;
+ total: number;
+ onPage: (page: number) => void;
+}) {
+ const pageCount = Math.max(1, Math.ceil(total / pageSize));
+ if (pageCount <= 1) return null;
+
+ const from = (page - 1) * pageSize + 1;
+ const to = Math.min(page * pageSize, total);
+
+ return (
+ <div className="flex items-center justify-between px-4 pt-2 pb-6">
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {from}–{to} of {total}
+ </span>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={page <= 1}
+ onClick={() => onPage(page - 1)}
+ aria-label="Previous page"
+ >
+ <ChevronLeft className="size-4" />
+ </Button>
+ {pageItems(page, pageCount).map((it, i) =>
+ it === 'gap' ? (
+ <span key={`gap-${i}`} className="px-1 text-xs text-muted-foreground">
+ …
+ </span>
+ ) : (
+ <Button
+ key={it}
+ variant={it === page ? 'secondary' : 'ghost'}
+ size="icon-sm"
+ className="text-xs tabular-nums"
+ onClick={() => onPage(it)}
+ >
+ {it}
+ </Button>
+ ),
+ )}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={page >= pageCount}
+ onClick={() => onPage(page + 1)}
+ aria-label="Next page"
+ >
+ <ChevronRight className="size-4" />
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/initiatives/components/shared/HealthBadge.tsx b/apps/web/src/features/initiatives/components/shared/HealthBadge.tsx
index 3a78a827..6f66bba5 100644
--- a/apps/web/src/features/initiatives/components/shared/HealthBadge.tsx
+++ b/apps/web/src/features/initiatives/components/shared/HealthBadge.tsx
@@ -1,5 +1,5 @@
import type { InitiativeHealth } from '@/lib/api';
-import { healthMeta } from './initiativeMeta';
+import { healthMeta } from '@/utils/initiativeMeta';
// A small health signal: a colored dot plus its label. null renders a muted
// "No update". Used in the list column and the detail header.
diff --git a/apps/web/src/features/initiatives/components/shared/HealthInfoPopover.tsx b/apps/web/src/features/initiatives/components/shared/HealthInfoPopover.tsx
index 73de7509..66ad2e92 100644
--- a/apps/web/src/features/initiatives/components/shared/HealthInfoPopover.tsx
+++ b/apps/web/src/features/initiatives/components/shared/HealthInfoPopover.tsx
@@ -3,7 +3,7 @@ import { ChevronRight, HelpCircle } from 'lucide-react';
import type { InitiativeHealth } from '@/lib/api';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
-import { healthMeta } from './initiativeMeta';
+import { healthMeta } from '@/utils/initiativeMeta';
// The health values explained in the info popover, in severity order.
const HEALTH_LEGEND: { health: InitiativeHealth | null; desc: string }[] = [
diff --git a/apps/web/src/features/initiatives/components/shared/InitiativeStatusSelect.tsx b/apps/web/src/features/initiatives/components/shared/InitiativeStatusSelect.tsx
index 557b1c1c..fdbc2337 100644
--- a/apps/web/src/features/initiatives/components/shared/InitiativeStatusSelect.tsx
+++ b/apps/web/src/features/initiatives/components/shared/InitiativeStatusSelect.tsx
@@ -5,7 +5,7 @@ import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { colorDot } from '@/components/common/fields/colorDot';
import { Pill } from '@/components/common/fields/Pill';
-import { STATUS_META, STATUS_ORDER } from './initiativeMeta';
+import { STATUS_META, STATUS_ORDER } from '@/utils/initiativeMeta';
// A Pill trigger opening the fixed initiative status lifecycle. Mirrors the issue
// field selects (Pill + Popover + Command) but over a static enum.
diff --git a/apps/web/src/features/issue/components/fields/InitiativeSelect.tsx b/apps/web/src/features/issue/components/fields/InitiativeSelect.tsx
index e1d3e2da..11ba9385 100644
--- a/apps/web/src/features/issue/components/fields/InitiativeSelect.tsx
+++ b/apps/web/src/features/issue/components/fields/InitiativeSelect.tsx
@@ -1,6 +1,11 @@
import { useState } from 'react';
import { Check, CircleDashed, Target } from 'lucide-react';
-import { useInitiativesQuery } from '@/services/initiatives.service';
+import { useQueryClient } from '@tanstack/react-query';
+import { useInitiativeQuery, useInitiativesQuery } from '@/services/initiatives.service';
+import type { Initiative } from '@/lib/api';
+import { qk } from '@/services/queryKeys';
+import { colorDot } from '@/components/common/fields/colorDot';
+import { LINKABLE_STATUSES, STATUS_META } from '@/utils/initiativeMeta';
import {
Command,
CommandEmpty,
@@ -12,6 +17,10 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Pill } from '@/components/common/fields/Pill';
+// The dropdown shows at most this many initiatives at once; the rest are reached by
+// typing, which the server matches by title.
+const PAGE_SIZE = 15;
+
// A Pill trigger opening the project's initiatives, for linking an issue to one.
// Lives in the shared layer so the issue detail can use it without depending on
// the initiatives feature. Value is the initiative id or null.
@@ -25,44 +34,57 @@ export default function InitiativeSelect({
onChange: (id: number | null) => void;
}) {
const [open, setOpen] = useState(false);
- const { data: initiatives = [] } = useInitiativesQuery(projectKey);
- const current = initiatives.find((i) => i.id === value);
+ const [query, setQuery] = useState('');
+ const qc = useQueryClient();
+
+ // The linked initiative may fall outside the first page, so fetch it directly to
+ // label the trigger. The list query only runs while the dropdown is open.
+ const current = useInitiativeQuery(value).data;
+ const { data } = useInitiativesQuery(open ? projectKey : null, {
+ statuses: LINKABLE_STATUSES,
+ search: query.trim() || undefined,
+ pageSize: PAGE_SIZE,
+ });
+ const options = data?.items ?? [];
+
+ // Seed the single-initiative cache on pick so the trigger labels immediately,
+ // without waiting for its own fetch.
+ const select = (initiative: Initiative | null) => {
+ if (initiative) qc.setQueryData(qk.initiative(initiative.id), initiative);
+ onChange(initiative?.id ?? null);
+ setOpen(false);
+ };
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setQuery('');
+ }}
+ >
<PopoverTrigger asChild>
- <Pill active={!!current}>
- {current ? <Target /> : <CircleDashed />}
+ <Pill active={value != null}>
+ {value != null ? <Target /> : <CircleDashed />}
{current?.title ?? 'Initiative'}
</Pill>
</PopoverTrigger>
<PopoverContent className="w-56 p-0" align="start">
- <Command>
- <CommandInput placeholder="Link to initiative…" />
+ <Command shouldFilter={false}>
+ <CommandInput placeholder="Link to initiative…" value={query} onValueChange={setQuery} />
<CommandList>
<CommandEmpty>No initiatives.</CommandEmpty>
<CommandGroup>
- <CommandItem
- value="No initiative"
- onSelect={() => {
- onChange(null);
- setOpen(false);
- }}
- >
- <CircleDashed />
- <span className="flex-1">No initiative</span>
- {value == null && <Check className="ml-auto" />}
- </CommandItem>
- {initiatives.map((it) => (
- <CommandItem
- key={it.id}
- value={it.title}
- onSelect={() => {
- onChange(it.id);
- setOpen(false);
- }}
- >
- <Target />
+ {!query && (
+ <CommandItem value="No initiative" onSelect={() => select(null)}>
+ <CircleDashed />
+ <span className="flex-1">No initiative</span>
+ {value == null && <Check className="ml-auto" />}
+ </CommandItem>
+ )}
+ {options.map((it) => (
+ <CommandItem key={it.id} value={it.title} onSelect={() => select(it)}>
+ {colorDot(STATUS_META[it.status].color)}
<span className="flex-1 truncate">{it.title}</span>
{it.id === value && <Check className="ml-auto" />}
</CommandItem>
diff --git a/apps/web/src/features/work-items/components/kanban/BulkActionBar.tsx b/apps/web/src/features/work-items/components/kanban/BulkActionBar.tsx
index 17821d41..f6da1f49 100644
--- a/apps/web/src/features/work-items/components/kanban/BulkActionBar.tsx
+++ b/apps/web/src/features/work-items/components/kanban/BulkActionBar.tsx
@@ -5,6 +5,7 @@ import { Archive, Bot, CircleDashed, Tag, Target, Trash2, User, X } from 'lucide
import { type ProjectDetail } from '@/lib/api';
import { usePermissions } from '@/hooks/usePermissions';
import { useInitiativesQuery } from '@/services/initiatives.service';
+import { LINKABLE_STATUSES } from '@/utils/initiativeMeta';
import { cn } from '@/lib/utils';
import { colorDot } from '@/components/common/fields/colorDot';
import { PRIORITY_FIELDS } from '@/components/common/fields/priorityFields';
@@ -26,11 +27,13 @@ export function BulkActionBar({ project }: { project: ProjectDetail }) {
const { can } = usePermissions();
const bulk = useBulkActions(project);
const [confirmingDelete, setConfirmingDelete] = useState(false);
- // Initiatives are an unbounded list, so they are not in the board scaffold. The
- // bulk picker fetches them only while selection is active.
- const { data: initiatives = [] } = useInitiativesQuery(
- selection.isSelecting ? project.project.key : null,
- );
+ // Initiatives are not in the board scaffold. The bulk picker fetches the first
+ // page of linkable (open) initiatives only while selection is active.
+ const { data } = useInitiativesQuery(selection.isSelecting ? project.project.key : null, {
+ statuses: LINKABLE_STATUSES,
+ pageSize: 50,
+ });
+ const initiatives = data?.items ?? [];
if (!selection.isSelecting) return null;
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 5d9f59c2..a038a72f 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1375,6 +1375,36 @@ export interface Initiative {
health: InitiativeHealth | null;
}
+// Columns the initiative list can be sorted by, server-side. progress and health
+// are derived and not sortable.
+export type InitiativeSort = 'title' | 'priority' | 'targetDate' | 'owner';
+
+export interface InitiativeListParams {
+ statuses?: string[];
+ search?: string;
+ sort?: InitiativeSort;
+ dir?: 'asc' | 'desc';
+ page?: number;
+ pageSize?: number;
+}
+
+export interface InitiativePage {
+ items: Initiative[];
+ total: number;
+ page: number;
+ pageSize: number;
+}
+
+// Per-status initiative counts for the list's status tabs.
+export interface InitiativeCounts {
+ total: number;
+ proposed: number;
+ planned: number;
+ active: number;
+ completed: number;
+ canceled: number;
+}
+
export interface NewInitiativeInput {
title: string;
description?: string;
@@ -1815,11 +1845,19 @@ export const api = {
// Initiatives — collection ops take projectKey; ops on one initiative take its
// own id and hit /initiatives/:id (like issues).
- listInitiatives: (projectKey: string, statuses?: string[]) => {
- const q =
- statuses && statuses.length ? `?status=${encodeURIComponent(statuses.join(','))}` : '';
- return request<Initiative[]>(`/projects/${projectKey}/initiatives${q}`);
+ listInitiatives: (projectKey: string, params: InitiativeListParams = {}) => {
+ const q = new URLSearchParams();
+ if (params.statuses && params.statuses.length) q.set('status', params.statuses.join(','));
+ if (params.search) q.set('search', params.search);
+ if (params.sort) q.set('sort', params.sort);
+ if (params.dir) q.set('dir', params.dir);
+ if (params.page) q.set('page', String(params.page));
+ if (params.pageSize) q.set('pageSize', String(params.pageSize));
+ const qs = q.toString();
+ return request<InitiativePage>(`/projects/${projectKey}/initiatives${qs ? `?${qs}` : ''}`);
},
+ initiativeCounts: (projectKey: string) =>
+ request<InitiativeCounts>(`/projects/${projectKey}/initiatives/counts`),
getInitiative: (id: number) => request<Initiative>(`/initiatives/${id}`),
createInitiative: (projectKey: string, input: NewInitiativeInput) =>
request<Initiative>(`/projects/${projectKey}/initiatives`, {
diff --git a/apps/web/src/services/initiatives.service.ts b/apps/web/src/services/initiatives.service.ts
index e16278ed..46fe9b5d 100644
--- a/apps/web/src/services/initiatives.service.ts
+++ b/apps/web/src/services/initiatives.service.ts
@@ -1,14 +1,36 @@
-import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { api, type FeedCursor, type InitiativePatch, type NewInitiativeInput } from '@/lib/api';
+import {
+ keepPreviousData,
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query';
+import {
+ api,
+ type FeedCursor,
+ type InitiativeListParams,
+ type InitiativePatch,
+ type NewInitiativeInput,
+} from '@/lib/api';
import { qk } from '@/services/queryKeys';
-// A status filter for the list. Omit (or 'all') to load every initiative; a value
-// maps to a comma-separated status set the server filters by.
-export function useInitiativesQuery(projectKey: string | null, statuses?: string[]) {
- const status = statuses && statuses.length ? statuses.join(',') : undefined;
+// A page of the project's initiatives. params filter (status/search), sort and
+// page it server-side; keepPreviousData holds the current page on screen while the
+// next one loads. Omit params to load the default first page.
+export function useInitiativesQuery(projectKey: string | null, params: InitiativeListParams = {}) {
return useQuery({
- queryKey: qk.initiatives(projectKey ?? '', status),
- queryFn: () => api.listInitiatives(projectKey!, statuses),
+ queryKey: qk.initiatives(projectKey ?? '', params as Record<string, unknown>),
+ queryFn: () => api.listInitiatives(projectKey!, params),
+ enabled: projectKey != null,
+ placeholderData: keepPreviousData,
+ });
+}
+
+// Per-status counts for the list's status tabs, independent of the current page.
+export function useInitiativeCountsQuery(projectKey: string | null) {
+ return useQuery({
+ queryKey: qk.initiativeCounts(projectKey ?? ''),
+ queryFn: () => api.initiativeCounts(projectKey!),
enabled: projectKey != null,
});
}
@@ -27,6 +49,7 @@ export function useCreateInitiative(projectKey: string) {
mutationFn: (input: NewInitiativeInput) => api.createInitiative(projectKey, input),
onSuccess: () => {
qc.invalidateQueries({ queryKey: qk.initiativesForProject(projectKey) });
+ qc.invalidateQueries({ queryKey: qk.initiativeCounts(projectKey) });
qc.invalidateQueries({ queryKey: qk.project(projectKey) });
},
});
@@ -39,6 +62,7 @@ export function useUpdateInitiative(projectKey: string) {
api.updateInitiative(id, patch),
onSuccess: (_data, { id }) => {
qc.invalidateQueries({ queryKey: qk.initiativesForProject(projectKey) });
+ qc.invalidateQueries({ queryKey: qk.initiativeCounts(projectKey) });
qc.invalidateQueries({ queryKey: qk.project(projectKey) });
qc.invalidateQueries({ queryKey: qk.initiative(id) });
qc.invalidateQueries({ queryKey: qk.initiativeFeed(id) });
@@ -52,6 +76,7 @@ export function useDeleteInitiative(projectKey: string) {
mutationFn: (id: number) => api.deleteInitiative(id),
onSuccess: (_data, id) => {
qc.invalidateQueries({ queryKey: qk.initiativesForProject(projectKey) });
+ qc.invalidateQueries({ queryKey: qk.initiativeCounts(projectKey) });
qc.invalidateQueries({ queryKey: qk.project(projectKey) });
// Deleting an initiative unlinks its issues (initiativeId -> null), so the
// board issues change too.
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 1e603a93..58bb62e1 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -83,11 +83,12 @@ export const qk = {
// Resolving an issue by its project-scoped number (the identifier-based URL).
issueBySeq: (projectKey: string, seq: number) => ['issueBySeq', projectKey, seq] as const,
feed: (id: number) => ['feed', id] as const,
- // Initiatives: a project's list (status narrows it), one initiative, and one
- // initiative's activity feed.
- initiatives: (projectKey: string, status?: string) =>
- ['initiatives', projectKey, status ?? 'all'] as const,
+ // Initiatives: a project's list (params narrow, sort and page it), the per-status
+ // tab counts, one initiative, and one initiative's activity feed.
+ initiatives: (projectKey: string, params?: Record<string, unknown>) =>
+ ['initiatives', projectKey, params ?? {}] as const,
initiativesForProject: (projectKey: string) => ['initiatives', projectKey] as const,
+ initiativeCounts: (projectKey: string) => ['initiativeCounts', projectKey] as const,
initiative: (id: number) => ['initiative', id] as const,
initiativeFeed: (id: number) => ['initiativeFeed', id] as const,
// Prefix keys: issue mutations invalidate every initiative query without
diff --git a/apps/web/src/features/initiatives/components/shared/initiativeMeta.ts b/apps/web/src/utils/initiativeMeta.ts
similarity index 84%
rename from apps/web/src/features/initiatives/components/shared/initiativeMeta.ts
rename to apps/web/src/utils/initiativeMeta.ts
index 211dabfd..4b509d02 100644
--- a/apps/web/src/features/initiatives/components/shared/initiativeMeta.ts
+++ b/apps/web/src/utils/initiativeMeta.ts
@@ -20,6 +20,10 @@ export const STATUS_ORDER: InitiativeStatus[] = [
'canceled',
];
+// The open statuses an issue can be linked to: the lifecycle without the terminal
+// completed and canceled, which are not offered in the link pickers.
+export const LINKABLE_STATUSES: InitiativeStatus[] = ['proposed', 'planned', 'active'];
+
// Health (computed server-side). null means there is nothing to judge yet.
export const HEALTH_META: Record<InitiativeHealth, { label: string; color: string }> = {
on_track: { label: 'On track', color: '#22c55e' },