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: add tabs, counts and order to the issue activity feed (#448)

Croffab78ffbbf11a
diff --git a/apps/api/src/modules/issues/__tests__/integration/activity.test.ts b/apps/api/src/modules/issues/__tests__/integration/activity.test.ts
index 8d89b2cb..686c9e55 100644
--- a/apps/api/src/modules/issues/__tests__/integration/activity.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/activity.test.ts
@@ -151,6 +151,62 @@ describe('issue activity', () => {
const res = await feed(asOwner, 999999);
expect(res.status).toBe(404);
});
+
+ it('serves the oldest entries first for order=asc, paging forward', async () => {
+ const { asOwner, columnId } = await setupProject();
+ const issue = (await createIssue(asOwner, columnId)).data!;
+ for (const body of ['a', 'b', 'c']) {
+ await asOwner.issues({ issueId: issue.id }).comments.post({ body });
+ }
+
+ const first = await feed(asOwner, issue.id, { order: 'asc', filter: 'comments', limit: '2' });
+ expect(first.data!.items.map((i) => i.body)).toEqual(['a', 'b']);
+ const second = await feed(asOwner, issue.id, {
+ order: 'asc',
+ filter: 'comments',
+ limit: '2',
+ cursor: JSON.stringify(first.data!.nextCursor),
+ });
+ expect(second.data!.items.map((i) => i.body)).toEqual(['c']);
+ expect(second.data!.nextCursor).toBeNull();
+ });
+
+ it('narrows the page to comments, the change log, or the work log', async () => {
+ const { asOwner, columnId } = await setupProject();
+ const issue = (await createIssue(asOwner, columnId)).data!;
+ const comment = (await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'hi' }))
+ .data!;
+ await asOwner
+ .issues({ issueId: issue.id })
+ .comments.post({ body: 'reply', replyToId: comment.id });
+ await asOwner
+ .issues({ issueId: issue.id })
+ .worklogs.post({ minutes: 30, spentOn: new Date().toISOString().slice(0, 10) });
+
+ const comments = await feed(asOwner, issue.id, { filter: 'comments' });
+ expect(comments.data!.items.map((i) => i.body)).toEqual(['hi', 'reply']);
+ const history = await feed(asOwner, issue.id, { filter: 'history' });
+ expect(history.data!.items.map((i) => i.action)).toEqual(['created']);
+ const worklog = await feed(asOwner, issue.id, { filter: 'worklog' });
+ expect(worklog.data!.items.map((i) => i.action)).toEqual(['worklog']);
+ });
+
+ it('counts the entries behind each filter, replies included', async () => {
+ const { asOwner, columnId } = await setupProject();
+ const issue = (await createIssue(asOwner, columnId)).data!;
+ const comment = (await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'hi' }))
+ .data!;
+ await asOwner
+ .issues({ issueId: issue.id })
+ .comments.post({ body: 'reply', replyToId: comment.id });
+ await asOwner
+ .issues({ issueId: issue.id })
+ .worklogs.post({ minutes: 30, spentOn: new Date().toISOString().slice(0, 10) });
+
+ const res = await asOwner.issues({ issueId: issue.id }).feed.counts.get();
+ expect(res.status).toBe(200);
+ expect(res.data).toEqual({ all: 4, comments: 2, history: 1, worklog: 1 });
+ });
});
// A reply is a comment carrying replyToId. The feed pages over the top-level
@@ -541,6 +597,26 @@ describe('issue activity', () => {
expect(bodies).toEqual([['after the move'], ['before the move']]);
});
+ it('runs the stretches oldest first for order=asc', async () => {
+ const { asOwner, columnId, columnIds } = await setupProject();
+ const view = await asOwner.projects({ projectKey: 'MKT' }).get();
+ const names = new Map(view.data!.columns.map((c) => [c.id, c.name]));
+ const issue = (await createIssue(asOwner, columnId)).data!;
+ await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'before the move' });
+ await asOwner.issues({ issueId: issue.id }).patch({ columnId: columnIds[1] });
+ await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'after the move' });
+
+ const res = await grouped(asOwner, issue.id, { order: 'asc', filter: 'comments' });
+ expect(res.data!.groups.map((g) => g.status)).toEqual([
+ names.get(columnId)!,
+ names.get(columnIds[1])!,
+ ]);
+ expect(res.data!.groups.map((g) => g.items.map((i) => i.body))).toEqual([
+ ['before the move'],
+ ['after the move'],
+ ]);
+ });
+
it('marks a status the issue had already been in as a repeat', async () => {
const { asOwner, columnId, columnIds } = await setupProject();
const issue = (await createIssue(asOwner, columnId)).data!;
diff --git a/apps/api/src/modules/issues/activity.ts b/apps/api/src/modules/issues/activity.ts
index f0b01204..b7b907eb 100644
--- a/apps/api/src/modules/issues/activity.ts
+++ b/apps/api/src/modules/issues/activity.ts
@@ -11,7 +11,7 @@ import {
type ActivityPayload,
type ActivitySide,
} from '@repo/db';
-import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, gte, inArray, isNull, lt, ne, sql } from 'drizzle-orm';
import { HttpError, iso } from '#shared/lib';
import { emitCommentEvent } from './webhook-payload';
import { addedMentionHandles, parseMentionHandles, resolveMentionHandles } from '#shared/mentions';
@@ -92,17 +92,44 @@ function mapFeedItem(row: {
};
}
-// One page of an issue's feed, newest first. The page is a window over the
-// top-level entries; the replies of the comments in it follow at the end of items,
-// however deep they are nested, so a thread is never split across pages. cursor_ts
-// is created_at as full-precision text so the returned nextCursor round-trips
-// without the millisecond truncation iso() would apply. limit is clamped to 1..100.
-export async function listFeed(
- issueId: number,
- opts: { before?: FeedCursor | null; limit?: number } = {},
-): Promise<FeedPage> {
+export type FeedFilter = 'comments' | 'history' | 'worklog';
+export type FeedOrder = 'asc' | 'desc';
+
+export interface FeedPageOptions {
+ cursor?: FeedCursor | null;
+ limit?: number;
+ // Narrows the page to one tab of the activity log; absent serves every entry.
+ filter?: FeedFilter;
+ order?: FeedOrder;
+}
+
+// The change log is split into the time spent on the issue (its work log) and the
+// rest of its history.
+function feedFilterCondition(filter?: FeedFilter) {
+ switch (filter) {
+ case 'comments':
+ return eq(issueActivity.kind, 'comment');
+ case 'worklog':
+ return and(eq(issueActivity.kind, 'activity'), eq(issueActivity.action, 'worklog'));
+ case 'history':
+ return and(eq(issueActivity.kind, 'activity'), ne(issueActivity.action, 'worklog'));
+ default:
+ return undefined;
+ }
+}
+
+// One page of an issue's feed, newest first unless `order` is 'asc'. The page is a
+// window over the top-level entries; the replies of the comments in it follow at the
+// end of items, however deep they are nested, so a thread is never split across
+// pages. cursor_ts is created_at as full-precision text so the returned nextCursor
+// round-trips without the millisecond truncation iso() would apply. limit is clamped
+// to 1..100.
+export async function listFeed(issueId: number, opts: FeedPageOptions = {}): Promise<FeedPage> {
const limit = Math.min(Math.max(opts.limit ?? 25, 1), 100);
- const before = opts.before ?? null;
+ const cursor = opts.cursor ?? null;
+ const ascending = opts.order === 'asc';
+ const direction = ascending ? asc : desc;
+ const pastCursor = sql.raw(ascending ? '>' : '<');
const rows = await db
.select({
id: issueActivity.id,
@@ -123,12 +150,13 @@ export async function listFeed(
and(
eq(issueActivity.issueId, issueId),
isNull(issueActivity.replyToId),
- before
- ? sql`(${issueActivity.createdAt}, ${issueActivity.id}) < (${before.ts}::timestamptz, ${before.id}::integer)`
+ feedFilterCondition(opts.filter),
+ cursor
+ ? sql`(${issueActivity.createdAt}, ${issueActivity.id}) ${pastCursor} (${cursor.ts}::timestamptz, ${cursor.id}::integer)`
: undefined,
),
)
- .orderBy(desc(issueActivity.createdAt), desc(issueActivity.id))
+ .orderBy(direction(issueActivity.createdAt), direction(issueActivity.id))
.limit(limit + 1);
const hasMore = rows.length > limit;
@@ -142,6 +170,36 @@ export async function listFeed(
};
}
+// How many entries each tab of the activity log holds. A reply is a comment and
+// counts as one.
+export interface FeedCounts {
+ all: number;
+ comments: number;
+ history: number;
+ worklog: number;
+}
+
+export async function countFeed(issueId: number): Promise<FeedCounts> {
+ const [counts] = await db
+ .select({
+ comments: sql<number>`count(*) FILTER (WHERE ${issueActivity.kind} = 'comment')`.mapWith(
+ Number,
+ ),
+ worklog:
+ sql<number>`count(*) FILTER (WHERE ${issueActivity.kind} = 'activity' AND ${issueActivity.action} = 'worklog')`.mapWith(
+ Number,
+ ),
+ history:
+ sql<number>`count(*) FILTER (WHERE ${issueActivity.kind} = 'activity' AND ${issueActivity.action} <> 'worklog')`.mapWith(
+ Number,
+ ),
+ })
+ .from(issueActivity)
+ .where(eq(issueActivity.issueId, issueId));
+ const { comments, worklog, history } = counts;
+ return { all: comments + worklog + history, comments, history, worklog };
+}
+
// Every reply under the given entries, oldest first, read one level at a time until
// a level has none. A thread is a handful of comments deep, so the loop is short and
// each level is one query.
@@ -207,14 +265,14 @@ export interface GroupedFeedPage {
nextCursor: FeedCursor | null;
}
-// The feed split into the stretches the issue spent in one column, newest first. The
-// page is the window of entries listFeed serves, under the same keyset cursor, so a
-// long history is read page by page rather than whole; a stretch that spans a page
-// boundary is served in both, each time with the entries of that page. A stretch in
-// which nothing was written carries no entries and so gets no group.
+// The feed split into the stretches the issue spent in one column, in the order the
+// page runs. The page is the window of entries listFeed serves, under the same keyset
+// cursor, so a long history is read page by page rather than whole; a stretch that
+// spans a page boundary is served in both, each time with the entries of that page. A
+// stretch in which nothing was written carries no entries and so gets no group.
export async function listGroupedFeed(
issueId: number,
- opts: { before?: FeedCursor | null; limit?: number } = {},
+ opts: FeedPageOptions = {},
): Promise<GroupedFeedPage> {
const page = await listFeed(issueId, opts);
const timeline = page.items.length ? await listStatusTimeline(issueId) : [];
@@ -231,9 +289,10 @@ export async function listGroupedFeed(
// A reply joins the group of the thread it hangs under, wherever the issue stood
// when it was written, so the thread stays whole.
const groupByItemId = new Map<number, FeedGroup>();
- // The entries run newest first and the segments oldest first, so the segment the
- // walk sits on only ever moves back towards the start.
- let index = segments.length - 1;
+ // The segments run oldest first. Newest-first entries move the walk back towards
+ // the start, oldest-first ones forward towards the end, never both.
+ const ascending = opts.order === 'asc';
+ let index = ascending ? 0 : segments.length - 1;
for (const item of page.items) {
if (item.replyToId != null) {
const group = groupByItemId.get(item.replyToId);
@@ -243,7 +302,11 @@ export async function listGroupedFeed(
continue;
}
const at = Date.parse(item.createdAt);
- while (index > 0 && Date.parse(segments[index].from) > at) index--;
+ if (ascending) {
+ while (index < segments.length - 1 && Date.parse(segments[index + 1].from) <= at) index++;
+ } else {
+ while (index > 0 && Date.parse(segments[index].from) > at) index--;
+ }
const segment = segments[index];
const open = groups[groups.length - 1];
if (open && open.from === segment.from) {
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index 072c3d4d..8ea3fc6b 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -29,6 +29,7 @@ import {
} from './service';
import {
listFeed,
+ countFeed,
listFeedRange,
listGroupedFeed,
createComment,
@@ -111,6 +112,7 @@ import {
FeedPageResponse,
GroupedFeedPageResponse,
feedPageQuery,
+ FeedCountsResponse,
TimelineSegmentResponse,
IssueCycleResponse,
projectKeyParams,
@@ -1212,15 +1214,15 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // One page of an issue's timeline, newest first: comments and change-log
- // activity merged in issue_activity. `limit` (default 25) and an opaque
- // `cursor` (the JSON-encoded nextCursor from the previous page) drive keyset
- // pagination. The response is { items, nextCursor }, and nextCursor is null on the
- // last page.
+ // One page of an issue's timeline: comments and change-log activity merged in
+ // issue_activity, newest first unless `order` is 'asc', narrowed by `filter`.
+ // `limit` (default 25) and an opaque `cursor` (the JSON-encoded nextCursor from the
+ // previous page) drive keyset pagination. The response is { items, nextCursor }, and
+ // nextCursor is null on the last page.
.get(
'/issues/:issueId/feed',
async ({ params, query }) =>
- listFeed(params.issueId, { before: feedCursor(query.cursor), limit: query.limit }),
+ listFeed(params.issueId, { ...query, cursor: feedCursor(query.cursor) }),
{
params: issueParams,
query: feedPageQuery,
@@ -1230,7 +1232,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
summary: 'Get an issue feed',
description:
"Get an issue's activity feed by its numeric id: comments and change-log " +
- 'entries, newest first. The page holds the top-level entries; the replies of ' +
+ 'entries, newest first by default. The page holds the top-level entries; the replies of ' +
"its comments come with them, each carrying its parent's id in replyToId.",
...mcpTool('list_issue_activity'),
},
@@ -1242,7 +1244,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
.get(
'/issues/:issueId/feed/grouped',
async ({ params, query }) =>
- listGroupedFeed(params.issueId, { before: feedCursor(query.cursor), limit: query.limit }),
+ listGroupedFeed(params.issueId, { ...query, cursor: feedCursor(query.cursor) }),
{
params: issueParams,
query: feedPageQuery,
@@ -1256,6 +1258,17 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
+ // The number of entries behind each feed filter, for the tabs of the activity log.
+ .get('/issues/:issueId/feed/counts', async ({ params }) => countFeed(params.issueId), {
+ params: issueParams,
+ workItem: 'read',
+ response: { 200: FeedCountsResponse, ...commonErrors },
+ detail: {
+ summary: 'Count an issue feed',
+ description: "Count an issue's comments, change-log entries and time entries.",
+ },
+ })
+
// The stretches the issue spent in one column, oldest first, with the duration of
// each. Entry-free and unpaged: the change log holds a handful of status entries,
// and a client reads the entries of one stretch separately when it opens that
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
index e118aac9..6dda6eb6 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -370,10 +370,30 @@ export const GroupedFeedPageResponse = t.Object({
nextCursor: FeedCursorResponse,
});
-// Both feed routes page the same way: a limit and the previous page's cursor.
+// Both feed routes page the same way: a limit and the previous page's cursor, over
+// the entries the filter keeps, in the order asked for.
export const feedPageQuery = t.Object({
limit: t.Optional(t.Numeric({ description: 'Max items per page (1-100). Default 25.' })),
cursor: t.Optional(t.String({ description: 'nextCursor from the previous page, for paging.' })),
+ filter: t.Optional(
+ t.Union([t.Literal('comments'), t.Literal('history'), t.Literal('worklog')], {
+ description:
+ 'Only comments, only the change log without time entries, or only time entries. Omit for every entry.',
+ }),
+ ),
+ order: t.Optional(
+ t.Union([t.Literal('desc'), t.Literal('asc')], {
+ description: "'desc' (default) serves the newest entries first, 'asc' the oldest.",
+ }),
+ ),
+});
+
+// FeedCounts from activity.ts: how many entries each feed filter keeps.
+export const FeedCountsResponse = t.Object({
+ all: t.Number(),
+ comments: t.Number(),
+ history: t.Number(),
+ worklog: t.Number(),
});
// TimelineSegment from status-history.ts: one stretch the issue spent in a column.
diff --git a/apps/web/messages/ar/issue.json b/apps/web/messages/ar/issue.json
index 7d34c821..49bccc88 100644
--- a/apps/web/messages/ar/issue.json
+++ b/apps/web/messages/ar/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "فتح كصفحة",
"titlePlaceholder": "عنوان المهمة",
"noActivity": "لا يوجد نشاط بعد.",
+ "noComments": "لا توجد تعليقات بعد.",
+ "noHistory": "لا توجد تغييرات بعد.",
+ "noWorklog": "لم يُسجَّل وقت بعد.",
"noActivityInStretch": "لا يوجد نشاط في هذه الفترة.",
"activityLoadFailed": "تعذّر تحميل النشاط.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "مؤرشفة",
"activityHeading": "النشاط",
- "feedFlat": "مسطّح",
- "feedGrouped": "مجمّع",
+ "feedTabAll": "الكل",
+ "feedTabComments": "التعليقات",
+ "feedTabHistory": "السجل",
+ "feedTabWorklog": "سجل الوقت",
+ "feedStatus": "الحالات",
+ "feedGroupByStatus": "التجميع حسب الحالة",
+ "feedNewest": "الأحدث أولاً",
+ "feedOldest": "الأقدم أولاً",
+ "feedChangeOrder": "تغيير الترتيب",
+ "feedRunToggle": "عرض التغييرات المشابهة",
"shareUnavailable": "المهمة المشاركة دي مش متاحة. يمكن الرابط اتلغى.",
"fieldSelects": {
"changeState": "تغيير الحالة…",
diff --git a/apps/web/messages/en/issue.json b/apps/web/messages/en/issue.json
index 6a421597..2265077d 100644
--- a/apps/web/messages/en/issue.json
+++ b/apps/web/messages/en/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Open as page",
"titlePlaceholder": "Issue title",
"noActivity": "No activity yet.",
+ "noComments": "No comments yet.",
+ "noHistory": "No changes yet.",
+ "noWorklog": "No time logged yet.",
"noActivityInStretch": "No activity in this stretch.",
"activityLoadFailed": "Could not load the activity.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Archived",
"activityHeading": "Activity",
- "feedFlat": "Flat",
- "feedGrouped": "Grouped",
+ "feedTabAll": "All",
+ "feedTabComments": "Comments",
+ "feedTabHistory": "History",
+ "feedTabWorklog": "Work log",
+ "feedStatus": "Status",
+ "feedGroupByStatus": "Group by status",
+ "feedNewest": "Newest",
+ "feedOldest": "Oldest",
+ "feedChangeOrder": "Change order",
+ "feedRunToggle": "Show similar changes",
"shareUnavailable": "This shared issue is not available. The link may have been revoked.",
"fieldSelects": {
"changeState": "Change state…",
diff --git a/apps/web/messages/es-ES/issue.json b/apps/web/messages/es-ES/issue.json
index 9bd6089f..7057fc6d 100644
--- a/apps/web/messages/es-ES/issue.json
+++ b/apps/web/messages/es-ES/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Abrir como página",
"titlePlaceholder": "Título del ticket",
"noActivity": "Todavía no hay actividad.",
+ "noComments": "Todavía no hay comentarios.",
+ "noHistory": "Todavía no hay cambios.",
+ "noWorklog": "Todavía no se ha registrado tiempo.",
"noActivityInStretch": "No hay actividad en este tramo.",
"activityLoadFailed": "No se ha podido cargar la actividad.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Archivada",
"activityHeading": "Actividad",
- "feedFlat": "Plana",
- "feedGrouped": "Agrupada",
+ "feedTabAll": "Todo",
+ "feedTabComments": "Comentarios",
+ "feedTabHistory": "Historial",
+ "feedTabWorklog": "Registro de tiempo",
+ "feedStatus": "Estados",
+ "feedGroupByStatus": "Agrupar por estado",
+ "feedNewest": "Más recientes",
+ "feedOldest": "Más antiguos",
+ "feedChangeOrder": "Cambiar orden",
+ "feedRunToggle": "Mostrar cambios similares",
"shareUnavailable": "Este ticket compartida no está disponible. Puede que el enlace haya sido revocado.",
"fieldSelects": {
"changeState": "Cambiar el estado…",
diff --git a/apps/web/messages/fr/issue.json b/apps/web/messages/fr/issue.json
index 7e11a911..246406de 100644
--- a/apps/web/messages/fr/issue.json
+++ b/apps/web/messages/fr/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Ouvrir en pleine page",
"titlePlaceholder": "Titre du ticket",
"noActivity": "Aucune activité pour l'instant.",
+ "noComments": "Aucun commentaire pour l'instant.",
+ "noHistory": "Aucune modification pour l'instant.",
+ "noWorklog": "Aucun temps enregistré pour l'instant.",
"noActivityInStretch": "Aucune activité sur cette période.",
"activityLoadFailed": "Impossible de charger l'activité.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Archivé",
"activityHeading": "Activité",
- "feedFlat": "À plat",
- "feedGrouped": "Groupée",
+ "feedTabAll": "Tout",
+ "feedTabComments": "Commentaires",
+ "feedTabHistory": "Historique",
+ "feedTabWorklog": "Temps passé",
+ "feedStatus": "Statuts",
+ "feedGroupByStatus": "Grouper par statut",
+ "feedNewest": "Plus récents",
+ "feedOldest": "Plus anciens",
+ "feedChangeOrder": "Changer l'ordre",
+ "feedRunToggle": "Afficher les changements similaires",
"shareUnavailable": "Ce ticket partagé n'est pas disponible. Le lien a peut-être été révoqué.",
"fieldSelects": {
"changeState": "Changer l'état…",
diff --git a/apps/web/messages/id/issue.json b/apps/web/messages/id/issue.json
index c79927b8..6a670d4d 100644
--- a/apps/web/messages/id/issue.json
+++ b/apps/web/messages/id/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Buka sebagai halaman",
"titlePlaceholder": "Judul issue",
"noActivity": "Belum ada aktivitas.",
+ "noComments": "Belum ada komentar.",
+ "noHistory": "Belum ada perubahan.",
+ "noWorklog": "Belum ada waktu yang dicatat.",
"noActivityInStretch": "Tidak ada aktivitas pada rentang ini.",
"activityLoadFailed": "Tidak dapat memuat aktivitas.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Diarsipkan",
"activityHeading": "Aktivitas",
- "feedFlat": "Datar",
- "feedGrouped": "Dikelompokkan",
+ "feedTabAll": "Semua",
+ "feedTabComments": "Komentar",
+ "feedTabHistory": "Riwayat",
+ "feedTabWorklog": "Catatan waktu",
+ "feedStatus": "Status",
+ "feedGroupByStatus": "Kelompokkan menurut status",
+ "feedNewest": "Terbaru",
+ "feedOldest": "Terlama",
+ "feedChangeOrder": "Ubah urutan",
+ "feedRunToggle": "Tampilkan perubahan serupa",
"shareUnavailable": "Issue yang dibagikan ini tidak tersedia. Tautan mungkin telah dicabut.",
"fieldSelects": {
"changeState": "Ubah status…",
diff --git a/apps/web/messages/pt-BR/issue.json b/apps/web/messages/pt-BR/issue.json
index 3629c140..5b4c0cd5 100644
--- a/apps/web/messages/pt-BR/issue.json
+++ b/apps/web/messages/pt-BR/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Abrir como página",
"titlePlaceholder": "Título da issue",
"noActivity": "Nenhuma atividade ainda.",
+ "noComments": "Nenhum comentário ainda.",
+ "noHistory": "Nenhuma alteração ainda.",
+ "noWorklog": "Nenhum tempo registrado ainda.",
"noActivityInStretch": "Nenhuma atividade neste trecho.",
"activityLoadFailed": "Não foi possível carregar a atividade.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Arquivado",
"activityHeading": "Atividade",
- "feedFlat": "Plana",
- "feedGrouped": "Agrupada",
+ "feedTabAll": "Tudo",
+ "feedTabComments": "Comentários",
+ "feedTabHistory": "Histórico",
+ "feedTabWorklog": "Registro de tempo",
+ "feedStatus": "Status",
+ "feedGroupByStatus": "Agrupar por status",
+ "feedNewest": "Mais recentes",
+ "feedOldest": "Mais antigos",
+ "feedChangeOrder": "Alterar ordem",
+ "feedRunToggle": "Mostrar alterações semelhantes",
"shareUnavailable": "Esta issue compartilhada não está disponível. O link pode ter sido revogado.",
"fieldSelects": {
"changeState": "Alterar estado…",
diff --git a/apps/web/messages/ru/issue.json b/apps/web/messages/ru/issue.json
index 13148107..e158f7d5 100644
--- a/apps/web/messages/ru/issue.json
+++ b/apps/web/messages/ru/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Открыть как страницу",
"titlePlaceholder": "Название задачи",
"noActivity": "Активности пока нет.",
+ "noComments": "Комментариев пока нет.",
+ "noHistory": "Изменений пока нет.",
+ "noWorklog": "Время пока не списано.",
"noActivityInStretch": "Нет активности за этот период.",
"activityLoadFailed": "Не удалось загрузить активность.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "В архиве",
"activityHeading": "Активность",
- "feedFlat": "Списком",
- "feedGrouped": "По статусам",
+ "feedTabAll": "Все",
+ "feedTabComments": "Комментарии",
+ "feedTabHistory": "История",
+ "feedTabWorklog": "Учёт времени",
+ "feedStatus": "Статусы",
+ "feedGroupByStatus": "Группировать по статусам",
+ "feedNewest": "Сначала новые",
+ "feedOldest": "Сначала старые",
+ "feedChangeOrder": "Изменить порядок",
+ "feedRunToggle": "Показать похожие изменения",
"shareUnavailable": "Эта общая задача недоступна. Возможно, ссылку отозвали.",
"fieldSelects": {
"changeState": "Изменить статус…",
diff --git a/apps/web/messages/uk/issue.json b/apps/web/messages/uk/issue.json
index 342ec2d6..1dc197ec 100644
--- a/apps/web/messages/uk/issue.json
+++ b/apps/web/messages/uk/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "Відкрити як сторінку",
"titlePlaceholder": "Назва задачі",
"noActivity": "Активності ще немає.",
+ "noComments": "Коментарів ще немає.",
+ "noHistory": "Змін ще немає.",
+ "noWorklog": "Час ще не списано.",
"noActivityInStretch": "Немає активності за цей період.",
"activityLoadFailed": "Не вдалося завантажити активність.",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "Архівовано",
"activityHeading": "Активність",
- "feedFlat": "Списком",
- "feedGrouped": "За статусами",
+ "feedTabAll": "Усі",
+ "feedTabComments": "Коментарі",
+ "feedTabHistory": "Історія",
+ "feedTabWorklog": "Облік часу",
+ "feedStatus": "Статуси",
+ "feedGroupByStatus": "Групувати за статусами",
+ "feedNewest": "Спочатку нові",
+ "feedOldest": "Спочатку старі",
+ "feedChangeOrder": "Змінити порядок",
+ "feedRunToggle": "Показати схожі зміни",
"shareUnavailable": "Ця спільна задача недоступна. Можливо, посилання відкликали.",
"fieldSelects": {
"changeState": "Змінити статус…",
diff --git a/apps/web/messages/zh-CN/issue.json b/apps/web/messages/zh-CN/issue.json
index 5bafc756..22d0086d 100644
--- a/apps/web/messages/zh-CN/issue.json
+++ b/apps/web/messages/zh-CN/issue.json
@@ -5,6 +5,9 @@
"openAsPage": "在完整页面中打开",
"titlePlaceholder": "工作项标题",
"noActivity": "暂无活动记录。",
+ "noComments": "暂无评论。",
+ "noHistory": "暂无变更。",
+ "noWorklog": "暂无工时记录。",
"noActivityInStretch": "此时间段内没有活动。",
"activityLoadFailed": "无法加载活动。",
"fields": {
@@ -402,8 +405,16 @@
},
"archived": "已归档",
"activityHeading": "活动记录",
- "feedFlat": "平铺",
- "feedGrouped": "分组",
+ "feedTabAll": "全部",
+ "feedTabComments": "评论",
+ "feedTabHistory": "历史",
+ "feedTabWorklog": "工时记录",
+ "feedStatus": "状态",
+ "feedGroupByStatus": "按状态分组",
+ "feedNewest": "最新优先",
+ "feedOldest": "最早优先",
+ "feedChangeOrder": "切换顺序",
+ "feedRunToggle": "显示类似的变更",
"shareUnavailable": "此共享工作项不可用,链接可能已撤销。",
"fieldSelects": {
"changeState": "更改状态…",
diff --git a/apps/web/src/features/issue/components/detail/ActivityItemList.tsx b/apps/web/src/features/issue/components/detail/ActivityItemList.tsx
index 2db6e7ca..3f9dcaf3 100644
--- a/apps/web/src/features/issue/components/detail/ActivityItemList.tsx
+++ b/apps/web/src/features/issue/components/detail/ActivityItemList.tsx
@@ -1,11 +1,15 @@
import type { FeedItem } from '@/lib/api/endpoints/activity';
-import ActivityLine from './ActivityLine';
+import ActivityRun from './ActivityRun';
import CommentThread from './CommentThread';
import { type ComposerContext } from './CommentComposer';
-// A list of feed entries in the order given: a comment and its replies render as one
-// thread card, change-log entries as a one-line sentence between the cards. Shared by
-// the live feed, the shared read-only feed, and the timeline's per-status popover.
+// A list of feed entries in the order given, on one vertical line: a comment and its
+// replies render as one thread, change-log entries as a one-line sentence. Changes of
+// the same kind by the same person in a row collapse into their first line, which
+// opens the rest. Shared by the live feed, the shared read-only feed, and the
+// timeline's per-status popover.
+
+type Row = { comment: FeedItem } | { run: FeedItem[] };
export default function ActivityItemList({
items,
@@ -24,32 +28,40 @@ export default function ActivityItemList({
// the feed by time) opens a thread of its own rather than dropping out of the list.
const present = new Set(items.map((item) => item.id));
const repliesByParent = new Map<number, FeedItem[]>();
- const roots: FeedItem[] = [];
+ const rows: Row[] = [];
for (const item of items) {
if (item.replyToId != null && present.has(item.replyToId)) {
const siblings = repliesByParent.get(item.replyToId) ?? [];
siblings.push(item);
repliesByParent.set(item.replyToId, siblings);
+ } else if (item.kind === 'comment') {
+ rows.push({ comment: item });
} else {
- roots.push(item);
+ const last = rows[rows.length - 1];
+ if (last && 'run' in last && sameChange(last.run[0], item)) last.run.push(item);
+ else rows.push({ run: [item] });
}
}
return (
- <ul className="flex flex-col gap-2.5">
- {roots.map((item) =>
- item.kind === 'comment' ? (
+ <ul className="relative flex flex-col gap-1 before:absolute before:inset-y-3 before:start-3 before:w-px before:bg-border">
+ {rows.map((row) =>
+ 'comment' in row ? (
<CommentThread
- key={item.id}
- root={item}
+ key={row.comment.id}
+ root={row.comment}
repliesByParent={repliesByParent}
imageByUserId={imageByUserId}
composer={composer}
/>
) : (
- <ActivityLine key={item.id} item={item} />
+ <ActivityRun key={row.run[0].id} run={row.run} />
),
)}
</ul>
);
}
+
+function sameChange(a: FeedItem, b: FeedItem): boolean {
+ return a.action === b.action && a.actorUserId === b.actorUserId && a.actorName === b.actorName;
+}
diff --git a/apps/web/src/features/issue/components/detail/ActivityLine.tsx b/apps/web/src/features/issue/components/detail/ActivityLine.tsx
index eebae561..65ca261e 100644
--- a/apps/web/src/features/issue/components/detail/ActivityLine.tsx
+++ b/apps/web/src/features/issue/components/detail/ActivityLine.tsx
@@ -1,18 +1,30 @@
+import { type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { CircleDot } from 'lucide-react';
import type { FeedItem } from '@/lib/api/endpoints/activity';
import { useRelativeTime } from '@/context/relativeTimeContext';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { formatDateTime } from '@/utils/dates';
import { ACTION_ICON } from '../../utils/activityIcons';
import { useActivityText } from '../../hooks/useActivityText';
import MarkdownEditor from '@/components/common/editor/MarkdownEditor';
// One change-log entry in an activity list: icon, actor, the sentence describing
// the change, and how long ago it happened. A change with a long value (a new
-// description) puts it behind a "view" popover instead of inlining it. Used by the
-// live feed, the shared read-only feed, and the timeline's per-status popover.
+// description) puts it behind a "view" popover instead of inlining it. A `nested`
+// line is one of a collapsed run opened under its first line, so it leaves the icon
+// out. Used by the live feed, the shared read-only feed, and the timeline's
+// per-status popover.
-export default function ActivityLine({ item }: { item: FeedItem }) {
+export default function ActivityLine({
+ item,
+ trailing,
+ nested,
+}: {
+ item: FeedItem;
+ trailing?: ReactNode;
+ nested?: boolean;
+}) {
const t = useTranslations('issue');
const relativeTime = useRelativeTime();
const describeActivity = useActivityText();
@@ -20,18 +32,22 @@ export default function ActivityLine({ item }: { item: FeedItem }) {
const { line, popover } = describeActivity(item);
const actor = item.actorName ?? t('system');
return (
- <li className="flex items-center gap-2.5 text-xs">
- <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
- <Icon className="size-3" />
- </span>
- <span className="min-w-0 text-muted-foreground">
- <span className="font-medium text-muted-foreground">{actor}</span> {line}
+ <li className="flex items-start gap-2.5 py-1 text-[13px]">
+ {nested ? (
+ <span className="w-6 shrink-0" />
+ ) : (
+ <span className="relative flex size-6 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
+ <Icon className="size-3.5" />
+ </span>
+ )}
+ <span className="min-w-0 flex-1 pt-0.5 text-muted-foreground">
+ <span className="font-medium text-foreground/85">{actor}</span> {line}
{popover && (
<Popover>
<PopoverTrigger asChild>
<button
type="button"
- className="ml-1.5 text-foreground/70 underline underline-offset-2 hover:text-foreground"
+ className="ms-1.5 text-foreground/70 underline underline-offset-2 hover:text-foreground"
>
{t('viewValue')}
</button>
@@ -41,7 +57,13 @@ export default function ActivityLine({ item }: { item: FeedItem }) {
</PopoverContent>
</Popover>
)}
- <span className="ml-1.5 text-xs">· {relativeTime(item.createdAt)}</span>
+ {trailing}
+ </span>
+ <span
+ className="shrink-0 pt-0.5 text-xs text-muted-foreground/80 tabular-nums"
+ title={formatDateTime(item.createdAt)}
+ >
+ {relativeTime(item.createdAt)}
</span>
</li>
);
diff --git a/apps/web/src/features/issue/components/detail/ActivityRun.tsx b/apps/web/src/features/issue/components/detail/ActivityRun.tsx
new file mode 100644
index 00000000..e882d5d3
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/ActivityRun.tsx
@@ -0,0 +1,37 @@
+import { useState } from 'react';
+import { ChevronDown } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { FeedItem } from '@/lib/api/endpoints/activity';
+import { cn } from '@/lib/utils';
+import ActivityLine from './ActivityLine';
+
+// Changes of the same kind by the same person in a row: the first line, with a
+// button that opens the rest under it.
+
+export default function ActivityRun({ run }: { run: FeedItem[] }) {
+ const t = useTranslations('issue');
+ const [open, setOpen] = useState(false);
+ const [first, ...rest] = run;
+ if (rest.length === 0) return <ActivityLine item={first} />;
+
+ return (
+ <>
+ <ActivityLine
+ item={first}
+ trailing={
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-label={t('feedRunToggle')}
+ onClick={() => setOpen((prev) => !prev)}
+ className="ms-1.5 inline-flex items-center gap-0.5 rounded px-1 text-xs text-muted-foreground tabular-nums hover:bg-accent hover:text-foreground"
+ >
+ +{rest.length}
+ <ChevronDown className={cn('size-3 transition-transform', open && 'rotate-180')} />
+ </button>
+ }
+ />
+ {open && rest.map((item) => <ActivityLine key={item.id} item={item} nested />)}
+ </>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/CommentComposer.tsx b/apps/web/src/features/issue/components/detail/CommentComposer.tsx
index 287d34fe..e5f9ac25 100644
--- a/apps/web/src/features/issue/components/detail/CommentComposer.tsx
+++ b/apps/web/src/features/issue/components/detail/CommentComposer.tsx
@@ -61,6 +61,7 @@ export default function CommentComposer({
const [menu, setMenu] = useState<MentionQuery | null>(null);
const [active, setActive] = useState(0);
const [pendingCaret, setPendingCaret] = useState<number | null>(null);
+ const [focused, setFocused] = useState(false);
const taRef = useRef<HTMLTextAreaElement | null>(null);
const isReply = replyToId != null;
@@ -181,9 +182,12 @@ export default function CommentComposer({
if (isEdit) submitLabel = tCommon('save');
if (posting) submitLabel = isEdit ? tCommon('saving') : t('posting');
- // The reply and edit boxes sit inside a thread card, so they render compact and
+ // The reply and edit boxes open inside a thread, so they render compact and
// without the bottom gap the standalone composer keeps.
const compact = isReply || isEdit;
+ // The standalone box stays one line until it is used, so it weighs no more than
+ // the feed under it; it grows its footer once focused or holding a draft.
+ const expanded = compact || focused || body.length > 0;
return (
<div className={cn(!compact && 'mb-5')}>
@@ -191,7 +195,7 @@ export default function CommentComposer({
<Avatar
name={authorName}
image={authorImage}
- className={cn('mt-0.5 shrink-0 text-[11px]', compact ? 'size-6' : 'size-7')}
+ className={cn('shrink-0 text-[11px]', compact ? 'mt-0.5 size-6' : 'mt-1.5 size-7')}
title={t('commentAs', { name: authorName })}
/>
<div className="relative min-w-0 flex-1">
@@ -206,36 +210,42 @@ export default function CommentComposer({
onChange={(e) =>
onChange(e.target.value, e.target.selectionStart ?? e.target.value.length)
}
- onBlur={() => setMenu(null)}
+ onFocus={() => setFocused(true)}
+ onBlur={() => {
+ setMenu(null);
+ setFocused(false);
+ }}
placeholder={placeholder}
className={cn(
'resize-none rounded-none border-0 bg-transparent px-3 py-2.5 shadow-none focus-visible:ring-0',
- compact ? 'min-h-[52px]' : 'min-h-[64px]',
+ !expanded ? 'min-h-10' : compact ? 'min-h-[52px]' : 'min-h-[64px]',
)}
onKeyDown={onKeyDown}
/>
- <div className="flex items-center justify-between gap-2 border-t px-2.5 py-2">
- {isEdit ? (
- <span />
- ) : (
- <span className="text-[11px] text-muted-foreground/70">
- <kbd className="rounded bg-muted px-1.5 py-0.5 font-sans text-[10px] font-medium">
- {cmdKey} ↵
- </kbd>
- <span className="ml-1.5">{t('toSend')}</span>
- </span>
- )}
- <div className="flex items-center gap-1.5">
- {onClose && (
- <Button size="sm" variant="ghost" onClick={onClose}>
- {t('cancel')}
- </Button>
+ {expanded && (
+ <div className="flex items-center justify-between gap-2 border-t px-2.5 py-2">
+ {isEdit ? (
+ <span />
+ ) : (
+ <span className="text-[11px] text-muted-foreground/70">
+ <kbd className="rounded bg-muted px-1.5 py-0.5 font-sans text-[10px] font-medium">
+ {cmdKey} ↵
+ </kbd>
+ <span className="ml-1.5">{t('toSend')}</span>
+ </span>
)}
- <Button size="sm" disabled={!body.trim() || posting} onClick={() => void post()}>
- {submitLabel}
- </Button>
+ <div className="flex items-center gap-1.5">
+ {onClose && (
+ <Button size="sm" variant="ghost" onClick={onClose}>
+ {t('cancel')}
+ </Button>
+ )}
+ <Button size="sm" disabled={!body.trim() || posting} onClick={() => void post()}>
+ {submitLabel}
+ </Button>
+ </div>
</div>
- </div>
+ )}
</div>
{menu && matches.length > 0 && (
diff --git a/apps/web/src/features/issue/components/detail/CommentItem.tsx b/apps/web/src/features/issue/components/detail/CommentItem.tsx
index 3b398dde..8b394664 100644
--- a/apps/web/src/features/issue/components/detail/CommentItem.tsx
+++ b/apps/web/src/features/issue/components/detail/CommentItem.tsx
@@ -10,10 +10,10 @@ import CommentComposer, { type ComposerContext } from './CommentComposer';
import { useDeleteComment } from '../../services/comments.service';
import { useTranslations } from 'next-intl';
-// One comment inside a thread card: a line of author, age and the reply button over
-// the rendered markdown body. A feed entry stores the author's name, not their
-// picture, so the uploaded avatar comes in as a prop (null falls back to the initials
-// circle). The card and the indent of a reply belong to CommentThread.
+// One comment inside a thread: a line of author, age and the reply button over the
+// rendered markdown body. A feed entry stores the author's name, not their picture,
+// so the uploaded avatar comes in as a prop (null falls back to the initials circle).
+// The indent of a reply belongs to CommentThread.
export default function CommentItem({
item,
@@ -45,9 +45,9 @@ export default function CommentItem({
return (
// The id is the scroll target of the last-comment bubble.
<div id={`feed-item-${item.id}`} className="group/comment">
- <div className="flex items-center gap-2">
- <Avatar name={author} image={image} className="size-5 shrink-0 text-[10px]" />
- <span className="truncate text-sm font-medium">{author}</span>
+ <div className="flex items-center gap-2.5">
+ <Avatar name={author} image={image} className="size-6 shrink-0 text-[10px]" />
+ <span className="truncate text-[13px] font-semibold">{author}</span>
<span className="shrink-0 text-xs text-muted-foreground">
· {relativeTime(item.createdAt)}
{item.editedAt && ` · ${t('edited')}`}
@@ -91,7 +91,7 @@ export default function CommentItem({
)}
</div>
{editing && composer ? (
- <div className="mt-1 ps-7">
+ <div className="mt-1 ps-8.5">
<CommentComposer
{...composer}
commentId={item.id}
@@ -100,11 +100,15 @@ export default function CommentItem({
/>
</div>
) : (
- <MarkdownEditor
- className="mt-1 ps-7 text-sm text-foreground/85 [&_a.issue-ref]:mx-1 [&_a.issue-ref]:text-[0.9em]"
- defaultValue={item.body ?? ''}
- editable={false}
- />
+ <div className="mt-1 ps-8.5">
+ <div className="w-fit max-w-full rounded-xl rounded-ss-sm bg-muted/60 px-3 py-2">
+ <MarkdownEditor
+ className="text-sm text-foreground/90 [&_a.issue-ref]:mx-1 [&_a.issue-ref]:text-[0.9em]"
+ defaultValue={item.body ?? ''}
+ editable={false}
+ />
+ </div>
+ </div>
)}
{confirmingDelete && (
diff --git a/apps/web/src/features/issue/components/detail/CommentThread.tsx b/apps/web/src/features/issue/components/detail/CommentThread.tsx
index 3c151261..f45779c6 100644
--- a/apps/web/src/features/issue/components/detail/CommentThread.tsx
+++ b/apps/web/src/features/issue/components/detail/CommentThread.tsx
@@ -2,16 +2,11 @@ import { useState } from 'react';
import type { FeedItem } from '@/lib/api/endpoints/activity';
import { useSession } from '@/lib/auth-client';
import { usePermissions } from '@/hooks/usePermissions';
-import { cn } from '@/lib/utils';
import CommentItem from './CommentItem';
import CommentComposer, { type ComposerContext } from './CommentComposer';
-// A comment and everything written under it, as one card: the comments are its rows,
-// split by a hairline, each reply a step further in than what it answers, and the
-// reply box opens at the bottom. Read as one exchange rather than a stack of boxes.
-// The issue panel is itself a `card` surface, so the thread stands off it by a
-// darker fill and a soft shadow; an outline at this size would pull more attention
-// than the comments do.
+// A comment and everything written under it: each reply a step further in than what
+// it answers, and the reply box opens at the bottom.
// How deep a reply keeps stepping in. Past it the thread still nests, but on the same
// indent, so a long exchange does not squeeze the text off the screen.
@@ -54,16 +49,9 @@ export default function CommentThread({
collect(root, 0);
return (
- <li className="overflow-hidden rounded-lg border border-black/4 bg-muted/40 shadow-xs dark:border-white/8 dark:bg-background/60">
- {rows.map((row, index) => (
- <div
- key={row.item.id}
- className={cn(
- 'px-3 py-2.5',
- index > 0 && 'border-t border-border/50',
- indentClass(row.depth),
- )}
- >
+ <li className="flex flex-col gap-2 py-1.5">
+ {rows.map((row) => (
+ <div key={row.item.id} className={indentClass(row.depth)}>
<CommentItem
item={row.item}
image={(row.item.actorUserId && imageByUserId.get(row.item.actorUserId)) ?? null}
@@ -75,9 +63,7 @@ export default function CommentThread({
</div>
))}
{replyTo && composer && (
- <div
- className={cn('border-t border-border/50 px-3 py-2.5', indentClass(replyTo.depth + 1))}
- >
+ <div className={indentClass(replyTo.depth + 1)}>
<CommentComposer
{...composer}
replyToId={replyTo.item.id}
@@ -94,5 +80,5 @@ export default function CommentThread({
// the source.
function indentClass(depth: number): string {
const step = Math.min(depth, MAX_INDENT_DEPTH);
- return ['', 'ps-7', 'ps-11', 'ps-15'][step];
+ return ['', 'ps-8.5', 'ps-12.5', 'ps-16.5'][step];
}
diff --git a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx
index a68c4b7b..7160c14b 100644
--- a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx
@@ -1,40 +1,41 @@
-import { useState } from 'react';
-import type { IssueActivityView } from '@/lib/api/endpoints/userPreferences';
+import { useTranslations } from 'next-intl';
import type { Column } from '@/lib/api/endpoints/columns';
import type { Assignee } from '@/lib/api/endpoints/projects';
import { useSession } from '@/lib/auth-client';
-import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import { useAccountPreferencesQuery } from '@/services/preferences.service';
+import { Tabs, TabsContent } from '@/components/ui/tabs';
+import { type ActivityFeedView, type ActivityTab } from '../../hooks/useActivityFeedView';
import CommentComposer, { type ComposerContext } from './CommentComposer';
+import IssueActivityToolbar from './IssueActivityToolbar';
import IssueFeedList from './IssueFeedList';
import IssueGroupedFeed from './IssueGroupedFeed';
-import { useTranslations } from 'next-intl';
-// The issue's activity log: a comment composer over the entries, in one of two shapes
-// picked by the tabs between them. Both run newest first and page 25 at a time; the
-// grouped one splits the entries by the status the issue was in when each was written.
+// The issue's activity log: a comment composer over the entries, which the tabs narrow
+// to comments, the change log or the work log. Grouping by status and the order apply
+// to every tab. Both shapes page 25 at a time.
+
+const EMPTY_TEXT = {
+ all: 'noActivity',
+ comments: 'noComments',
+ history: 'noHistory',
+ worklog: 'noWorklog',
+} as const satisfies Record<ActivityTab, string>;
export default function IssueActivityFeed({
issueId,
assignees,
columns,
imageByUserId,
+ view,
}: {
issueId: number;
assignees: Assignee[];
columns: Column[];
imageByUserId: Map<string, string | null>;
+ view: ActivityFeedView;
}) {
const tIssue = useTranslations('issue');
const t = useTranslations('issue.comments');
const { data: session } = useSession();
- const { data: preferences } = useAccountPreferencesQuery();
- // Null until the person picks a shape on this issue, and then it wins over the
- // preference for as long as the issue stays open. Undefined while the preferences
- // are still loading: the entries wait for the saved shape rather than opening in
- // the default one and switching under the reader.
- const [viewHere, setViewHere] = useState<IssueActivityView | null>(null);
- const view = viewHere ?? preferences?.issueActivityView;
const user = session?.user ?? null;
const composer: ComposerContext = {
@@ -43,6 +44,7 @@ export default function IssueActivityFeed({
authorName: user?.name || user?.email || t('you'),
authorImage: (user as { image?: string | null } | null)?.image ?? null,
};
+ const emptyText = tIssue(EMPTY_TEXT[view.tab]);
return (
<div className="mt-6 border-t pt-5">
@@ -52,30 +54,32 @@ export default function IssueActivityFeed({
<CommentComposer {...composer} />
- {view && (
+ {view.ready && (
<Tabs
- value={view}
- onValueChange={(value) => setViewHere(value as IssueActivityView)}
- className="gap-4"
+ value={view.tab}
+ onValueChange={(value) => view.setTab(value as ActivityTab)}
+ className="mt-5 gap-3"
>
- <TabsList className="ml-auto h-7 p-[2px]">
- <TabsTrigger value="flat" className="px-2 text-xs">
- {tIssue('feedFlat')}
- </TabsTrigger>
- <TabsTrigger value="grouped" className="px-2 text-xs">
- {tIssue('feedGrouped')}
- </TabsTrigger>
- </TabsList>
- <TabsContent value="flat">
- <IssueFeedList issueId={issueId} imageByUserId={imageByUserId} composer={composer} />
- </TabsContent>
- <TabsContent value="grouped">
- <IssueGroupedFeed
- issueId={issueId}
- columns={columns}
- imageByUserId={imageByUserId}
- composer={composer}
- />
+ <IssueActivityToolbar issueId={issueId} view={view} />
+ <TabsContent value={view.tab}>
+ {view.grouped ? (
+ <IssueGroupedFeed
+ issueId={issueId}
+ slice={view.slice}
+ columns={columns}
+ imageByUserId={imageByUserId}
+ composer={composer}
+ emptyText={emptyText}
+ />
+ ) : (
+ <IssueFeedList
+ issueId={issueId}
+ slice={view.slice}
+ imageByUserId={imageByUserId}
+ composer={composer}
+ emptyText={emptyText}
+ />
+ )}
</TabsContent>
</Tabs>
)}
diff --git a/apps/web/src/features/issue/components/detail/IssueActivityToolbar.tsx b/apps/web/src/features/issue/components/detail/IssueActivityToolbar.tsx
new file mode 100644
index 00000000..9f785fcd
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/IssueActivityToolbar.tsx
@@ -0,0 +1,65 @@
+import { ArrowDownUp, Layers } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { useFeedCountsQuery } from '../../services/comments.service';
+import type { ActivityFeedView, ActivityTab } from '../../hooks/useActivityFeedView';
+
+// The row over the activity log: its tabs with how many entries each holds, and the
+// switches for grouping by status and for the order.
+
+const TABS = [
+ { tab: 'all', label: 'feedTabAll' },
+ { tab: 'comments', label: 'feedTabComments' },
+ { tab: 'history', label: 'feedTabHistory' },
+ { tab: 'worklog', label: 'feedTabWorklog' },
+] as const satisfies { tab: ActivityTab; label: string }[];
+
+export default function IssueActivityToolbar({
+ issueId,
+ view,
+}: {
+ issueId: number;
+ view: ActivityFeedView;
+}) {
+ const t = useTranslations('issue');
+ const counts = useFeedCountsQuery(issueId).data;
+
+ return (
+ <div className="flex items-center gap-2">
+ <TabsList variant="line" className="h-8 min-w-0 flex-1 overflow-x-auto">
+ {TABS.map(({ tab, label }) => (
+ <TabsTrigger key={tab} value={tab} className="text-[13px]">
+ {t(label)}
+ {counts && (
+ <span className="text-[11px] font-normal text-muted-foreground tabular-nums">
+ {counts[tab]}
+ </span>
+ )}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-pressed={view.grouped}
+ title={t('feedGroupByStatus')}
+ onClick={() => view.setGrouped(!view.grouped)}
+ className="h-7 gap-1.5 px-2 text-xs text-muted-foreground aria-pressed:bg-accent aria-pressed:text-foreground"
+ >
+ <Layers className="size-3.5" />
+ {t('feedStatus')}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ title={t('feedChangeOrder')}
+ onClick={() => view.setOrder(view.order === 'desc' ? 'asc' : 'desc')}
+ className="h-7 gap-1.5 px-2 text-xs text-muted-foreground"
+ >
+ <ArrowDownUp className="size-3.5" />
+ {t(view.order === 'desc' ? 'feedNewest' : 'feedOldest')}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
index dbdc8194..49874494 100644
--- a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
@@ -73,6 +73,7 @@ export default function IssueDetailContent({
uploadFile,
imageAttachments,
setDescEditor,
+ activityView,
} = useIssueDetail(project, issueId, onIssueLoaded);
const permissions = usePermissions(project);
const canEdit = permissions.can('work_items', 'edit');
@@ -270,6 +271,7 @@ export default function IssueDetailContent({
assignees={project.assignees}
columns={project.columns}
imageByUserId={imageByUserId}
+ view={activityView}
/>
</div>
<LastCommentBubble
@@ -277,6 +279,7 @@ export default function IssueDetailContent({
issueId={issue.id}
feedRef={feedRef}
imageByUserId={imageByUserId}
+ view={activityView}
/>
</>
);
diff --git a/apps/web/src/features/issue/components/detail/IssueFeedList.tsx b/apps/web/src/features/issue/components/detail/IssueFeedList.tsx
index 9d131e7e..42433fe3 100644
--- a/apps/web/src/features/issue/components/detail/IssueFeedList.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueFeedList.tsx
@@ -1,31 +1,33 @@
-import { useTranslations } from 'next-intl';
import type { FeedItem } from '@/lib/api/endpoints/activity';
-import { useFeedQuery } from '../../services/comments.service';
+import { type FeedSlice, useFeedQuery } from '../../services/comments.service';
import ShowMoreButton from '@/components/common/ShowMoreButton';
import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
import ActivityItemList from './ActivityItemList';
import { type ComposerContext } from './CommentComposer';
-// The flat activity list, newest first, paged 25 at a time by "Show more". The feed
-// query refetches on its own when an issue edit invalidates it (see useUpdateIssue /
-// useSetFieldValue), so it reflects edits without the parent signaling it.
+// The flat activity list in the order the slice asks for, paged 25 at a time by
+// "Show more". The feed query refetches on its own when an issue edit invalidates it
+// (see useUpdateIssue / useSetFieldValue), so it reflects edits without the parent
+// signaling it.
export default function IssueFeedList({
issueId,
+ slice,
imageByUserId,
composer,
+ emptyText,
}: {
issueId: number;
+ slice: FeedSlice;
imageByUserId: Map<string, string | null>;
composer: ComposerContext;
+ emptyText: string;
}) {
- const t = useTranslations('issue');
- const feedQuery = useFeedQuery(issueId);
+ const feedQuery = useFeedQuery(issueId, slice);
- // The pages come back newest first. Dedupe by id so a boundary item that shifts
- // between pages after a refetch (an edit adds new entries at the top) never
- // renders with a duplicate key. The first copy wins: it comes from the newer
- // page, so an edited comment keeps its latest body.
+ // Dedupe by id so a boundary item that shifts between pages after a refetch (an
+ // edit adds new entries at the top of a newest-first feed) never renders with a
+ // duplicate key. The first copy wins.
const byId = new Map<number, FeedItem>();
for (const item of (feedQuery.data?.pages ?? []).flatMap((p) => p.items)) {
if (!byId.has(item.id)) byId.set(item.id, item);
@@ -35,7 +37,7 @@ export default function IssueFeedList({
if (feedQuery.isLoading) return <ListSkeleton rows={3} rowClassName="h-12" />;
if (items.length === 0) {
- return <p className="text-sm text-muted-foreground">{t('noActivity')}</p>;
+ return <p className="text-sm text-muted-foreground">{emptyText}</p>;
}
return (
diff --git a/apps/web/src/features/issue/components/detail/IssueGroupedFeed.tsx b/apps/web/src/features/issue/components/detail/IssueGroupedFeed.tsx
index 06e10e51..c3294987 100644
--- a/apps/web/src/features/issue/components/detail/IssueGroupedFeed.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueGroupedFeed.tsx
@@ -1,37 +1,39 @@
-import { useTranslations } from 'next-intl';
import type { Column } from '@/lib/api/endpoints/columns';
import type { FeedGroup, GroupedFeedPage } from '@/lib/api/endpoints/activity';
import ShowMoreButton from '@/components/common/ShowMoreButton';
import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
-import { useGroupedFeedQuery } from '../../services/comments.service';
+import { type FeedSlice, useGroupedFeedQuery } from '../../services/comments.service';
import { statusColor } from '../../utils/timeline';
import IssueActivityGroup from './IssueActivityGroup';
import { type ComposerContext } from './CommentComposer';
// The activity log split by the status the issue was in when each entry was written,
-// newest first and paged 25 at a time like the flat one. The server does the
+// in the slice's order and paged 25 at a time like the flat one. The server does the
// splitting; this only joins a stretch whose entries fell into two pages.
export default function IssueGroupedFeed({
issueId,
+ slice,
columns,
imageByUserId,
composer,
+ emptyText,
}: {
issueId: number;
+ slice: FeedSlice;
// The project's columns, for the status colors.
columns: Column[];
imageByUserId: Map<string, string | null>;
composer: ComposerContext;
+ emptyText: string;
}) {
- const t = useTranslations('issue');
- const feedQuery = useGroupedFeedQuery(issueId);
+ const feedQuery = useGroupedFeedQuery(issueId, slice);
const groups = joinGroups(feedQuery.data?.pages ?? []);
if (feedQuery.isLoading) return <ListSkeleton rows={3} rowClassName="h-12" />;
if (groups.length === 0) {
- return <p className="text-sm text-muted-foreground">{t('noActivity')}</p>;
+ return <p className="text-sm text-muted-foreground">{emptyText}</p>;
}
return (
diff --git a/apps/web/src/features/issue/components/detail/LastCommentBubble.tsx b/apps/web/src/features/issue/components/detail/LastCommentBubble.tsx
index 0a0b6bab..735b3561 100644
--- a/apps/web/src/features/issue/components/detail/LastCommentBubble.tsx
+++ b/apps/web/src/features/issue/components/detail/LastCommentBubble.tsx
@@ -5,6 +5,7 @@ import Avatar from '@/components/common/Avatar';
import { useRelativeTime } from '@/context/relativeTimeContext';
import { cn } from '@/lib/utils';
import { useLastComment } from '../../hooks/useLastComment';
+import type { ActivityFeedView } from '../../hooks/useActivityFeedView';
import { commentPreview } from '../../utils/commentPreview';
const SHOW_MS = 5000;
@@ -17,16 +18,18 @@ export default function LastCommentBubble({
issueId,
feedRef,
imageByUserId,
+ view,
}: {
issueId: number;
// The feed section to watch: the bubble stands in for it only while it is off screen.
feedRef: RefObject<HTMLDivElement | null>;
imageByUserId: Map<string, string | null>;
+ view: ActivityFeedView;
}) {
const t = useTranslations('issue.comments');
const tCommon = useTranslations('common');
const relativeTime = useRelativeTime();
- const comment = useLastComment(issueId);
+ const comment = useLastComment(issueId, view);
const preview = commentPreview(comment?.body ?? '');
// One turn per mounted issue: it waits for the feed to leave the screen, runs its few
// seconds, and is then done for good. Starting in 'waiting' keeps the bubble off an
diff --git a/apps/web/src/features/issue/hooks/useActivityFeedView.ts b/apps/web/src/features/issue/hooks/useActivityFeedView.ts
new file mode 100644
index 00000000..6ba06193
--- /dev/null
+++ b/apps/web/src/features/issue/hooks/useActivityFeedView.ts
@@ -0,0 +1,82 @@
+import { useCallback, useEffect, useState } from 'react';
+import type { FeedFilter, FeedOrder } from '@/lib/api/endpoints/activity';
+import {
+ useAccountPreferencesQuery,
+ useUpdateAccountPreferences,
+} from '@/services/preferences.service';
+import type { FeedSlice } from '../services/comments.service';
+
+export type ActivityTab = 'all' | FeedFilter;
+
+const TABS: ActivityTab[] = ['all', 'comments', 'history', 'worklog'];
+const TAB_KEY = 'issue-activity-tab';
+const ORDER_KEY = 'issue-activity-order';
+
+// How the activity log of every issue is shown: the tab and the order are the last
+// ones picked in this browser, and grouping by status is the account preference, so
+// switching it here changes it on the preferences page too.
+//
+// The stored values are read in an effect, not in the state initializer: the
+// initializer also runs during the server render, where there is no localStorage.
+// `ready` stays false until they and the preferences are read, so the feed never
+// fetches a default page it then throws away.
+export function useActivityFeedView() {
+ const [stored, setStored] = useState<{ tab: ActivityTab; order: FeedOrder } | null>(null);
+ const preference = useAccountPreferencesQuery().data?.issueActivityView;
+ const { mutate } = useUpdateAccountPreferences();
+
+ useEffect(() => {
+ const tab = read(TAB_KEY);
+ setStored({
+ tab: TABS.includes(tab as ActivityTab) ? (tab as ActivityTab) : 'all',
+ order: read(ORDER_KEY) === 'asc' ? 'asc' : 'desc',
+ });
+ }, []);
+
+ const setTab = useCallback((tab: ActivityTab) => {
+ write(TAB_KEY, tab);
+ setStored((prev) => prev && { ...prev, tab });
+ }, []);
+
+ const setOrder = useCallback((order: FeedOrder) => {
+ write(ORDER_KEY, order);
+ setStored((prev) => prev && { ...prev, order });
+ }, []);
+
+ const setGrouped = useCallback(
+ (grouped: boolean) => mutate({ issueActivityView: grouped ? 'grouped' : 'flat' }),
+ [mutate],
+ );
+
+ const tab = stored?.tab ?? 'all';
+ const order = stored?.order ?? 'desc';
+ const slice: FeedSlice = { filter: tab === 'all' ? null : tab, order };
+ return {
+ ready: stored != null && preference != null,
+ tab,
+ order,
+ slice,
+ grouped: preference === 'grouped',
+ setTab,
+ setOrder,
+ setGrouped,
+ };
+}
+
+export type ActivityFeedView = ReturnType<typeof useActivityFeedView>;
+
+function read(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function write(key: string, value: string) {
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ // Ignore write failures (private mode / quota); the view still switches.
+ }
+}
diff --git a/apps/web/src/features/issue/hooks/useIssueDetail.ts b/apps/web/src/features/issue/hooks/useIssueDetail.ts
index b32cfbd8..a1efc6e2 100644
--- a/apps/web/src/features/issue/hooks/useIssueDetail.ts
+++ b/apps/web/src/features/issue/hooks/useIssueDetail.ts
@@ -13,9 +13,14 @@ import { useIssueQuery, useSetFieldValue, useUpdateIssue } from '@/services/issu
import { useLiveRefresh } from '@/hooks/useLiveRefresh';
import { revScope } from '@/utils/revScopes';
import { qk } from '@/services/queryKeys';
-import { useAccountPreferencesQuery } from '@/services/preferences.service';
import { useAttachmentsQuery, useUploadAttachment } from '../services/attachments.service';
-import { useFeedQuery, useGroupedFeedQuery, useTimelineQuery } from '../services/comments.service';
+import {
+ useFeedCountsQuery,
+ useFeedQuery,
+ useGroupedFeedQuery,
+ useTimelineQuery,
+} from '../services/comments.service';
+import { useActivityFeedView } from './useActivityFeedView';
import { attachmentMarkdown, isImage } from '@/components/common/editor/attachmentEmbed';
import { fieldDefsForType } from '../utils/fieldDefs';
@@ -33,14 +38,14 @@ export function useIssueDetail(
// Started here, not in the components that read them: those mount only after the
// issue arrives, which would put these reads in a second wave after it. Only the
- // activity shape the preference opens with is read; the other one waits for a switch.
+ // activity view the log opens with is read; the others wait for a switch, and none
+ // is read before the saved view is known.
const attachmentsQuery = useAttachmentsQuery(issueId);
- // Undefined until the preferences arrive — the saved shape is read, never the
- // default standing in for it, so neither feed is fetched to be thrown away.
- const activityView = useAccountPreferencesQuery().data?.issueActivityView;
+ const activityView = useActivityFeedView();
useTimelineQuery(issueId);
- useFeedQuery(issueId, activityView === 'flat');
- useGroupedFeedQuery(issueId, activityView === 'grouped');
+ useFeedCountsQuery(issueId);
+ useFeedQuery(issueId, activityView.slice, activityView.ready && !activityView.grouped);
+ useGroupedFeedQuery(issueId, activityView.slice, activityView.ready && activityView.grouped);
// What the markdown editors' image picker offers.
const imageAttachments = (attachmentsQuery.data ?? []).filter(isImage);
@@ -129,5 +134,6 @@ export function useIssueDetail(
uploadFile,
imageAttachments,
setDescEditor,
+ activityView,
};
}
diff --git a/apps/web/src/features/issue/hooks/useLastComment.ts b/apps/web/src/features/issue/hooks/useLastComment.ts
index 6391d781..be6e887c 100644
--- a/apps/web/src/features/issue/hooks/useLastComment.ts
+++ b/apps/web/src/features/issue/hooks/useLastComment.ts
@@ -1,20 +1,21 @@
import type { FeedItem } from '@/lib/api/endpoints/activity';
import { useFeedQuery, useGroupedFeedQuery } from '../services/comments.service';
+import { type ActivityFeedView } from './useActivityFeedView';
-// The last comment written on the issue, read from whatever the activity section has
-// already loaded: both queries run with fetching off, so this asks for no page of its
-// own. Both feed shapes are taken together because only one of them is on screen and
-// the other can still hold a page loaded earlier in the session.
-export function useLastComment(issueId: number): FeedItem | undefined {
- const flatFeed = useFeedQuery(issueId, false);
- const groupedFeed = useGroupedFeedQuery(issueId, false);
+// The newest comment the activity log shows, read from the pages it has already
+// loaded: the query runs with fetching off, so this asks for no page of its own. Only
+// the view on screen is read, so the comment the bubble scrolls to is always rendered.
+// An oldest-first log loads its oldest pages, which need not hold the newest comment,
+// so it gets none.
+export function useLastComment(issueId: number, view: ActivityFeedView): FeedItem | undefined {
+ const flatFeed = useFeedQuery(issueId, view.slice, false);
+ const groupedFeed = useGroupedFeedQuery(issueId, view.slice, false);
- return [
- ...(flatFeed.data?.pages ?? []).flatMap((page) => page.items),
- ...(groupedFeed.data?.pages ?? []).flatMap((page) =>
- page.groups.flatMap((group) => group.items),
- ),
- ]
+ if (view.order === 'asc') return undefined;
+ const items = view.grouped
+ ? (groupedFeed.data?.pages ?? []).flatMap((page) => page.groups.flatMap((g) => g.items))
+ : (flatFeed.data?.pages ?? []).flatMap((page) => page.items);
+ return items
.filter((item) => item.kind === 'comment')
.reduce<FeedItem | undefined>(
(newest, item) => (!newest || item.createdAt > newest.createdAt ? item : newest),
diff --git a/apps/web/src/features/issue/services/comments.service.ts b/apps/web/src/features/issue/services/comments.service.ts
index 2bf1b974..12c5916a 100644
--- a/apps/web/src/features/issue/services/comments.service.ts
+++ b/apps/web/src/features/issue/services/comments.service.ts
@@ -10,6 +10,9 @@ import {
} from '@tanstack/react-query';
import {
type FeedCursor,
+ type FeedFilter,
+ type FeedOrder,
+ getFeedCounts,
listFeed,
listGroupedFeed,
listTimeline,
@@ -20,12 +23,20 @@ import {
} from '@/lib/api/endpoints/activity';
import { qk } from '@/services/queryKeys';
-// The issue's timeline (comments + activity), paged newest first. Each page is
-// 25 items; getNextPageParam yields the server's cursor until it returns null.
-export function useFeedQuery(id: number, enabled = true) {
+// Which slice of the feed a query reads and in what order: the tab the activity log
+// is on and the direction it runs.
+export interface FeedSlice {
+ filter: FeedFilter | null;
+ order: FeedOrder;
+}
+
+// The issue's timeline (comments + activity), 25 items a page; getNextPageParam
+// yields the server's cursor until it returns null.
+export function useFeedQuery(id: number, { filter, order }: FeedSlice, enabled = true) {
return useInfiniteQuery({
- queryKey: qk.feed(id),
- queryFn: ({ pageParam }) => listFeed(id, { cursor: pageParam, limit: 25 }),
+ queryKey: qk.flatFeed(id, filter, order),
+ queryFn: ({ pageParam }) =>
+ listFeed(id, { cursor: pageParam, limit: 25, filter: filter ?? undefined, order }),
initialPageParam: null as FeedCursor | null,
getNextPageParam: (last) => last.nextCursor,
enabled,
@@ -35,16 +46,22 @@ export function useFeedQuery(id: number, enabled = true) {
// The same entries as useFeedQuery, split by the status the issue was in when each
// was written. Paged the same way, and by the same cursor: a stretch that spans a page
// boundary comes back in both pages, and the feed joins the halves.
-export function useGroupedFeedQuery(id: number, enabled = true) {
+export function useGroupedFeedQuery(id: number, { filter, order }: FeedSlice, enabled = true) {
return useInfiniteQuery({
- queryKey: qk.groupedFeed(id),
- queryFn: ({ pageParam }) => listGroupedFeed(id, { cursor: pageParam, limit: 25 }),
+ queryKey: qk.groupedFeed(id, filter, order),
+ queryFn: ({ pageParam }) =>
+ listGroupedFeed(id, { cursor: pageParam, limit: 25, filter: filter ?? undefined, order }),
initialPageParam: null as FeedCursor | null,
getNextPageParam: (last) => last.nextCursor,
enabled,
});
}
+// The number of entries behind each tab of the activity log.
+export function useFeedCountsQuery(id: number) {
+ return useQuery({ queryKey: qk.feedCounts(id), queryFn: () => getFeedCounts(id) });
+}
+
// The stretches the issue spent in one status, oldest first. Carries no entries,
// so it stays small however long the issue's history is.
export function useTimelineQuery(id: number) {
diff --git a/apps/web/src/lib/api/endpoints/activity.ts b/apps/web/src/lib/api/endpoints/activity.ts
index 60a0aaf0..2bbb37a4 100644
--- a/apps/web/src/lib/api/endpoints/activity.ts
+++ b/apps/web/src/lib/api/endpoints/activity.ts
@@ -1,10 +1,24 @@
import { request } from '@/lib/api/core/client';
-// The query string both feed reads take, empty for the first page.
-function feedPageQuery(params: { cursor?: FeedCursor | null; limit?: number }): string {
+// Which entries a feed page holds: only comments, only the change log without time
+// entries, or only time entries. Absent serves every entry.
+export type FeedFilter = 'comments' | 'history' | 'worklog';
+export type FeedOrder = 'desc' | 'asc';
+
+export interface FeedPageParams {
+ cursor?: FeedCursor | null;
+ limit?: number;
+ filter?: FeedFilter;
+ order?: FeedOrder;
+}
+
+// The query string both feed reads take, empty for the first page of every entry.
+function feedPageQuery(params: FeedPageParams): string {
const q = new URLSearchParams();
if (params.limit) q.set('limit', String(params.limit));
if (params.cursor) q.set('cursor', JSON.stringify(params.cursor));
+ if (params.filter) q.set('filter', params.filter);
+ if (params.order) q.set('order', params.order);
const qs = q.toString();
return qs ? `?${qs}` : '';
}
@@ -154,16 +168,23 @@ export interface TimelineSegment {
durationMs: number;
}
-export const listFeed = (
- issueId: number,
- params: { cursor?: FeedCursor | null; limit?: number } = {},
-) => request<FeedPage>(`/issues/${issueId}/feed${feedPageQuery(params)}`);
+export const listFeed = (issueId: number, params: FeedPageParams = {}) =>
+ request<FeedPage>(`/issues/${issueId}/feed${feedPageQuery(params)}`);
// The same page, split into the stretches the issue spent in one status.
-export const listGroupedFeed = (
- issueId: number,
- params: { cursor?: FeedCursor | null; limit?: number } = {},
-) => request<GroupedFeedPage>(`/issues/${issueId}/feed/grouped${feedPageQuery(params)}`);
+export const listGroupedFeed = (issueId: number, params: FeedPageParams = {}) =>
+ request<GroupedFeedPage>(`/issues/${issueId}/feed/grouped${feedPageQuery(params)}`);
+
+// How many entries each filter keeps; `all` is every entry. A reply counts as a comment.
+export interface FeedCounts {
+ all: number;
+ comments: number;
+ history: number;
+ worklog: number;
+}
+
+export const getFeedCounts = (issueId: number) =>
+ request<FeedCounts>(`/issues/${issueId}/feed/counts`);
export const listTimeline = (issueId: number) =>
request<TimelineSegment[]>(`/issues/${issueId}/timeline`);
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 84b16e6c..19c22760 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -1,3 +1,5 @@
+import type { FeedFilter, FeedOrder } from '@/lib/api/endpoints/activity';
+
// Query keys shared by every service. Each is a stable tuple; a project/issue id
// or key scopes its entry. Kept in one registry so a mutation in one service can
// invalidate another service's queries by the same key.
@@ -195,9 +197,15 @@ export const qk = {
anyIssue: ['issue'] as const,
// Resolving an issue by its project-scoped number (the identifier-based URL).
issueBySeq: (projectKey: string, seq: number) => ['issueBySeq', projectKey, seq] as const,
+ // Every read of one issue's feed sits under this key, so invalidating it refreshes
+ // them all.
feed: (id: number) => ['feed', id] as const,
+ flatFeed: (id: number, filter: FeedFilter | null, order: FeedOrder) =>
+ ['feed', id, 'flat', filter, order] as const,
// The same feed split by status, paged on its own.
- groupedFeed: (id: number) => ['feed', id, 'grouped'] as const,
+ groupedFeed: (id: number, filter: FeedFilter | null, order: FeedOrder) =>
+ ['feed', id, 'grouped', filter, order] as const,
+ feedCounts: (id: number) => ['feed', id, 'counts'] as const,
// The status stretches of the timeline view, and the entries of one stretch read
// when it is opened. Both keyed under the feed, so every existing feed
// invalidation refreshes them too.