diff --git a/.changeset/39085-list-comments-column.md b/.changeset/39085-list-comments-column.md new file mode 100644 index 00000000000..51a82644e86 --- /dev/null +++ b/.changeset/39085-list-comments-column.md @@ -0,0 +1,18 @@ +--- +'@object-ui/types': patch +'@object-ui/data-objectstack': patch +'@object-ui/plugin-list': patch +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +feat(console): a comments column on the list page, with the threads of the records the view shows + +Clause-②: yes (widening) — new optional members and exports only: `DataSource.queryCommentThreads` and the `CommentThreadsQueryRequest` / `CommentThreadsQueryResponse` types on `@object-ui/types`; `ListView`'s `onEffectiveFilterChange` host prop and the `ListEffectiveFilter` type on `@object-ui/plugin-list`; `ViewCommentsPanel`, `splitCommentMentions` and their types on `@object-ui/plugin-detail`; nothing removed or renamed +Metadata-protocol: none + +An object's list page now has a comments icon in its header, on a grid and on a board, where the object's discussion is on (`enable.feeds` not `false`). A press opens a 380 px column at the page's right and the list narrows to make room; ✕ or Esc closes it, and the browser remembers whether it was left open. + +The column lists the comment threads on the records the view shows, newest first: the view's saved filter together with the filters the reader has set on the list and not saved. The search box does not narrow it. The server runs the filter as the reader's own read, so someone who may read fewer records sees fewer threads. Each card names the record (which opens it the way a row does), who wrote the first comment and when, its text with mentions highlighted, and 「N 条回复」 with the latest repliers' faces; 「加载更多」 reads the next page. A card opens its thread in place, with reply, resolve and reopen, reactions, edit and delete as the record page offers them; there is no box for a new thread. The filter menu holds 「显示已解决」 (off) and 「只看我参与的」. The column reads again when the view, its filter or a toggle changes and when a comment is written, and reads nothing while closed. It says so when the reader may not read the comments, when the read failed (with a retry), when the list's filter cannot be sent, and when the server does not answer the threads read (`POST /api/v1/comments/threads/query`). + +For React hosts: `ObjectStackAdapter.queryCommentThreads(request)` calls that read; `ListView`'s `onEffectiveFilterChange` reports the filter the list applies, on every layout (`{ kind: 'filter', filter }`, or `{ kind: 'unlowerable' }` for a filter it cannot lower); `ViewCommentsPanel` draws the column from threads its host reads. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 621b8b34866..c0be9b3efc0 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -351,6 +351,42 @@ The components are exported from `@object-ui/plugin-detail` (`CommentsPanel`, `CommentComposer`, `useRecordComments`); each reads the discussion off the host's `DiscussionContext`, as the feed blocks do. +## The list page's comments column + +An object's list page carries the same comments icon, without a number, in its +header's button group, on a grid and on a board (objectstack#39085). It is +there only on the desktop, on an object whose discussion is on +(`enable.feeds` not `false`), against a server that answers the threads read +(`POST /api/v1/comments/threads/query`). A press opens a 380 px column at the +page's right and the list narrows to make room; the icon shows it pressed. ✕ +or Esc closes it, and the browser remembers whether it was left open. The +record drawer still shows no comments. + +- **Which threads.** The comment threads on the records the list shows: the + view's saved filter together with the filters you have set on the list and + not saved. The search box does not narrow them. The server runs that filter + as your own read of the object, so someone who may read fewer records sees + fewer threads. Where the list's filter cannot be sent, the column says so + instead of listing every record's threads. +- **The cards** are newest first, one per thread: the object's icon and the + record's name, who wrote the first comment and when, its text with the + people it mentions highlighted, and 「N 条回复」 with the faces of the latest + repliers. 「加载更多」 reads the next page. The record's name opens the + record the way a row of the list does. +- **A thread in place.** The card, or its 「N 条回复」, opens the thread where + it is, with reply, ✓ resolve and reopen, reactions, Edit and Delete, each + offered exactly as on the record page. There is no box for a new thread: + a new thread starts on the record. +- **The filter menu** holds 「显示已解决」 (off) and 「只看我参与的」, as on the + record page. With nothing left to show it offers 「显示全部」. +- **It stays current.** The column reads again when the view, its filter or a + toggle changes, and when a comment is written: a reply raises the count, a + thread resolved while 「显示已解决」 is off leaves the column, and the row's + comment dot goes with it. Closed, it reads nothing. +- **When it cannot read**, it says which: you may not read this object's + comments, the read failed (with a retry), or the server does not list a + view's comments. + ## The `record:activity` block `RecordActivityTimeline` is a presenter: you hand it `items`. The SDUI block diff --git a/ui/e2e/list-frame-geometry-35548.spec.ts b/ui/e2e/list-frame-geometry-35548.spec.ts index 789132a9f9e..d55edbd14c9 100644 --- a/ui/e2e/list-frame-geometry-35548.spec.ts +++ b/ui/e2e/list-frame-geometry-35548.spec.ts @@ -310,7 +310,8 @@ test.describe('the list page frame (objectstack#35548)', () => { // The page bar names the object as the page's heading, and the view bar // does not (objectstack#36113, which split objectstack#35878's one row). expect(SRC.pageBar.includes('data-testid="list-view-bar-object-name"'), `${FILES.pageBar} names the object in the view bar again`).toBe(false); - expect(//.test(read('packages/app-shell/src/views/ObjectView.tsx')), 'the list page no longer draws its page bar above the view bar').toBe(true); + // objectstack#39085 — the bar also carries the comments icon (`comments=`). + expect(//.test(read('packages/app-shell/src/views/ObjectView.tsx')), 'the list page no longer draws its page bar above the view bar').toBe(true); // One trigger: type icon → name → count → caret, in that source order. const at = SWITCHER_PARTS.map((p) => switcherBody.indexOf(`data-testid="list-view-switcher-${p}"`)); expect(at.every((i) => i > 0), `a switcher part is missing: ${JSON.stringify(at)}`).toBe(true); diff --git a/ui/packages/app-shell/src/layout/PageHeader.tsx b/ui/packages/app-shell/src/layout/PageHeader.tsx index f2590ddddd3..db818d6dfab 100644 --- a/ui/packages/app-shell/src/layout/PageHeader.tsx +++ b/ui/packages/app-shell/src/layout/PageHeader.tsx @@ -182,6 +182,12 @@ export interface ConsolePageHeaderProps { * nothing keeps today's header at every width. */ compactBelow?: number; + /** + * objectstack#39085 — the page's comments entry (the list page's comments + * icon): the first button of the shell's group where the shell draws one, + * else after the page's own actions. + */ + comments?: React.ReactNode; /** * CSS color used to tint the top hairline, icon chip background, and * icon stroke. Defaults to the Shadcn `--primary` token so the header @@ -233,6 +239,7 @@ export function PageHeader({ actions, foldedActions, compactBelow, + comments, accentColor, sticky = false, posture, @@ -283,7 +290,8 @@ export function PageHeader({ const renderSidebarExpand = useShellSidebarExpandSlot(); const leading = renderSidebarExpand?.(); const pageActions = refreshButton || drawnActions; - const trailing = (pageActions || renderShellGroup) && ( + const ownComments = renderShellGroup ? null : comments ?? null; + const trailing = (pageActions || renderShellGroup || ownComments) && ( ); diff --git a/ui/packages/app-shell/src/layout/shellPageActionsSlot.ts b/ui/packages/app-shell/src/layout/shellPageActionsSlot.ts index 2eebc3f019e..cfa32b4eef5 100644 --- a/ui/packages/app-shell/src/layout/shellPageActionsSlot.ts +++ b/ui/packages/app-shell/src/layout/shellPageActionsSlot.ts @@ -23,8 +23,9 @@ import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; export interface ShellPageActionsSlotProps { /** - * The comments entry, first in the group: handed by the list and record - * pages only, nothing until the comments work puts its icon here. + * The comments entry, first in the group: handed by the record page + * (objectstack#36112) and the list page (objectstack#39085, through + * `PageHeader`'s `comments`) only. */ comments?: React.ReactNode; /** diff --git a/ui/packages/app-shell/src/views/ObjectView.commentsColumn-39085.test.tsx b/ui/packages/app-shell/src/views/ObjectView.commentsColumn-39085.test.tsx new file mode 100644 index 00000000000..b6df64ce606 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.commentsColumn-39085.test.tsx @@ -0,0 +1,276 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#39085 (U3 of epic #39077) — the list page's comments column. + * Through the real `ObjectView` and the real `ListView`; the data source + * answers the threads read (`queryCommentThreads`) as the server would. + * + * Pinned: the comments icon in the header on a grid and a board of an object + * whose discussion is on, and none where feeds are off or the data source + * reads no threads; nothing read while the column is closed; pressed, it + * opens a 380px column beside the list (in the content row, not over it) and + * reads ONE page with the view's filter; the record name opens the record the + * way a row click does; ✕ closes it and the closed state is remembered, as is + * the open one; a comment write announced re-reads the page once. + */ + +// Paid at collection, not inside a case's clock (check:test-source-alias): +// ObjectView reaches `import('@objectstack/lint')` through the CEL editor. +import '@objectstack/lint'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, cleanup, screen, waitFor, act, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; +import { createI18n, I18nProvider } from '@object-ui/i18n'; +import { notifyDataChanged } from '@object-ui/react'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + // Stable identities — `ListView` names `perms` in its fetch dependencies. + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRealtimeSubscription: () => ({ lastMessage: null }), + useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }), +})); + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); + +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => ({ save: vi.fn(async () => ({})), get: vi.fn(async () => null) }), +})); + +import { ObjectView } from './ObjectView'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; +import { VIEW_COMMENTS_OPEN_KEY } from './objectViewComments'; + +const FIELDS = { + id: { type: 'text', label: 'Id' }, + title: { type: 'text', label: 'Title' }, + status: { type: 'select', label: 'Status', options: [{ value: 'open', label: 'Open' }, { value: 'done', label: 'Done' }] }, +}; + +function taskObject(enable?: Record) { + return { + name: 'tracker_task', + label: 'Task', + pluralLabel: 'Tasks', + ...(enable ? { enable } : {}), + fields: FIELDS, + listViews: { + all: { name: 'all', label: 'All', type: 'grid', columns: ['title'], filter: [['status', '=', 'open']] }, + board: { name: 'board', label: 'Board', type: 'kanban', columns: ['title'], kanban: { groupByField: 'status' } }, + }, + }; +} + +const ROWS = [ + { id: 't1', title: 'Write the spec', status: 'open' }, + { id: 't2', title: 'Review the plan', status: 'open' }, +]; + +const THREADS = { + threads: [{ + comment: { id: 'c1', body: 'Looks good @Ada', author_id: 'u2', author_name: 'Grace', created_at: '2026-12-02T09:00:00Z', is_resolved: false }, + record: { id: 't1', name: 'Write the spec' }, + replyCount: 2, + repliers: [{ id: 'u3', name: 'Linus', avatarUrl: null }], + }], + nextCursor: null, +}; + +function LocationProbe() { + const location = useLocation(); + return
; +} + +beforeEach(() => { + try { window.localStorage.removeItem(VIEW_COMMENTS_OPEN_KEY); } catch { /* none */ } +}); + +afterEach(() => { + cleanup(); + try { window.localStorage.removeItem(VIEW_COMMENTS_OPEN_KEY); } catch { /* none */ } +}); + +function mount(opts: { enable?: Record; door?: boolean; view?: string } = {}) { + const object = taskObject(opts.enable); + const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + const queryCommentThreads = vi.fn(async () => THREADS); + const dataSource = { + find: vi.fn(async (resource: string) => (resource === 'tracker_task' ? { data: ROWS, total: ROWS.length } : { data: [] })), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => ({ name: 'tracker_task', label: 'Task', fields: FIELDS })), + queryGroupHeaders: vi.fn(async () => []), + ...(opts.door === false ? {} : { queryCommentThreads }), + } as never; + render( + + + + + + {}} />} + /> + } /> + + + + , + ); + return { queryCommentThreads }; +} + +const settle = () => act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); +}); + +const commentsButton = () => document.querySelector('[data-comments-button]') as HTMLElement | null; +const column = () => document.querySelector('[data-view-comments-column]') as HTMLElement | null; + +describe('objectstack#39085 — the list page comments column', () => { + it('offers the icon on a grid and reads nothing while the column is closed', async () => { + const { queryCommentThreads } = mount(); + + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + await settle(); + expect(commentsButton()).not.toBeNull(); + expect(commentsButton()!.getAttribute('aria-pressed')).toBe('false'); + expect(column()).toBeNull(); + expect(queryCommentThreads).not.toHaveBeenCalled(); + }); + + it("opens a column beside the list that reads one page with the view's filter", async () => { + const { queryCommentThreads } = mount(); + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + + fireEvent.click(commentsButton()!); + await waitFor(() => expect(document.querySelector('[data-view-comment-card="c1"]')).not.toBeNull(), { timeout: 5000 }); + await settle(); + + expect(commentsButton()!.getAttribute('aria-pressed')).toBe('true'); + // Beside the list in the content row, narrowing it — not laid over it. + const col = column()!; + expect(col.className).toContain('w-[380px]'); + expect(col.className).toContain('shrink-0'); + expect(col.className).not.toContain('absolute'); + expect(col.parentElement!.className).toContain('flex-row'); + expect(col.parentElement!.textContent).toContain('Review the plan'); + // One threads request for the page, scoped by the view's filter. + expect(queryCommentThreads).toHaveBeenCalledTimes(1); + const request = (queryCommentThreads.mock.calls[0] as unknown[])[0] as Record; + expect(request).toMatchObject({ object: 'tracker_task', limit: 25 }); + expect(JSON.stringify(request.filter)).toContain('open'); + expect(request.showResolved).toBeUndefined(); + expect(request.onlyMine).toBeUndefined(); + expect(window.localStorage.getItem(VIEW_COMMENTS_OPEN_KEY)).toBe('open'); + }); + + it('opens the record from the card the way a row click does', async () => { + mount(); + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + fireEvent.click(commentsButton()!); + const open = await waitFor(() => { + const el = document.querySelector('[data-view-comment-open-record="t1"]') as HTMLElement | null; + expect(el).not.toBeNull(); + return el!; + }, { timeout: 5000 }); + const before = screen.getByTestId('location').getAttribute('data-href'); + + fireEvent.click(open); + await waitFor(() => expect(screen.getByTestId('location').getAttribute('data-href')).not.toBe(before)); + expect(screen.getByTestId('location').getAttribute('data-href')).toContain('t1'); + }); + + it('closes on ✕, remembers it, and reads nothing more', async () => { + const { queryCommentThreads } = mount(); + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + fireEvent.click(commentsButton()!); + await waitFor(() => expect(queryCommentThreads).toHaveBeenCalledTimes(1), { timeout: 5000 }); + + fireEvent.click(document.querySelector('[data-comments-panel-close]') as HTMLElement); + await settle(); + expect(column()).toBeNull(); + expect(commentsButton()!.getAttribute('aria-pressed')).toBe('false'); + expect(window.localStorage.getItem(VIEW_COMMENTS_OPEN_KEY)).toBeNull(); + + act(() => notifyDataChanged({ objectName: 'sys_comment' })); + await settle(); + expect(queryCommentThreads).toHaveBeenCalledTimes(1); + }); + + it('opens as it was left, and re-reads the page once when a comment write is announced', async () => { + window.localStorage.setItem(VIEW_COMMENTS_OPEN_KEY, 'open'); + const { queryCommentThreads } = mount(); + + await waitFor(() => expect(document.querySelector('[data-view-comment-card="c1"]')).not.toBeNull(), { timeout: 5000 }); + await settle(); + expect(queryCommentThreads).toHaveBeenCalledTimes(1); + + act(() => notifyDataChanged({ objectName: 'sys_comment', recordId: 'c1' })); + await waitFor(() => expect(queryCommentThreads).toHaveBeenCalledTimes(2), { timeout: 5000 }); + await settle(); + expect(queryCommentThreads).toHaveBeenCalledTimes(2); + }); + + it('offers the icon on a board too', async () => { + mount({ view: 'board' }); + await waitFor(() => expect(commentsButton()).not.toBeNull(), { timeout: 5000 }); + }); + + it.each([ + ['feeds are off', { enable: { feeds: false } }], + ['the data source reads no threads', { door: false }], + ] as const)('offers no icon where %s', async (_case, opts) => { + const { queryCommentThreads } = mount(opts); + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + await settle(); + expect(commentsButton()).toBeNull(); + expect(queryCommentThreads).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index b8c2f1f58e5..4aaff1ce7e4 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -40,6 +40,7 @@ import { useServedViewItems } from '../hooks/useServedViewItems.js'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; import type { DataSource } from '@object-ui/types'; import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; +import { useObjectViewComments } from './objectViewComments.js'; // objectstack#33293: the view config panel loads with the first list, not with // the console. Statically, it held the view-variant inspector, `SchemaForm` and // the Studio form widgets in the EAGER closure, so a dashboard route downloaded @@ -1299,6 +1300,22 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // bar above it is not drawn (`ListViewBarHostContext`). const [listBarHosted, setListBarHosted] = useState(false); + // objectstack#39085 — the comments icon in the header's button group and + // the column it opens at the page's right (`./objectViewComments.tsx`): + // the threads on the records the list's filter selects. + const viewComments = useObjectViewComments({ + dataSource, + objectName, + objectDef: objectDef as any, + objects, + layout: listLayoutType, + phone, + user, + confirmHandler, + t, + onOpenRecord: (recordId: string) => handleRowClick({ id: recordId }), + }); + // objectstack#25992 slice 11a: the column-declaration flags, the held list refs and // `renderListView` moved to `./objectViewListRenderer.tsx`. const { renderListView } = useObjectViewListRenderer({ @@ -1381,6 +1398,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }, onBulkChangeOwner: bulkChangeOwnerReachable ? openBulkChangeOwner : undefined, bulkChangeOwnerOffered, + onEffectiveFilterChange: viewComments.onEffectiveFilterChange, }); // objectstack#25992 slice 9: the merged views and the plugin's `ObjectViewSchema` @@ -1545,7 +1563,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co {/* objectstack#36113 — the page's first row: while the list's view bar carries the page's acts it draws the object's icon and name alone, ended by the shell's button group. */} - + {/* Floating "+" action button — phone-only counterpart to the PageHeader's primary create action we just hid. Positioned @@ -1701,6 +1719,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
+ {/* objectstack#39085 — the comments column narrows the list. */} + {viewComments.column} {/* Metadata panel only shows for admin users */} + import('./objectViewCommentsColumn.js').then((m) => ({ default: m.ObjectViewCommentsColumn })), +); + +/** Where the list page keeps its comments column open or closed. */ +export const VIEW_COMMENTS_OPEN_KEY = 'os:list-comments-column'; + +/** The layouts the column is offered on: a grid and a board. */ +const COMMENTS_COLUMN_LAYOUTS: ReadonlySet = new Set(['grid', 'kanban']); + +export interface ObjectViewCommentsInput { + dataSource: DataSource | null | undefined; + objectName: string | undefined; + objectDef: { name?: string; icon?: string; color?: string; enable?: { feeds?: boolean } } | null | undefined; + objects: readonly unknown[] | undefined; + /** The layout the list draws now (the reader's unsaved layout first). */ + layout: string; + phone: boolean; + user: { id: string; name?: string | null; image?: string | null } | null | undefined; + confirmHandler: ConfirmationHandler; + t: TranslateFn; + /** Opens a record the way a row click opens it. */ + onOpenRecord: (recordId: string) => void; +} + +export interface ObjectViewComments { + /** The header's comments icon; `null` where the column is not offered. */ + button: ReactNode; + /** The column, for the page's content row; `null` while closed. */ + column: ReactNode; + /** The list's effective-filter report, wired only while the column is open. */ + onEffectiveFilterChange: ((report: ListEffectiveFilter) => void) | undefined; +} + +export function useObjectViewComments({ + dataSource, + objectName, + objectDef, + objects, + layout, + phone, + user, + confirmHandler, + t, + onOpenRecord, +}: ObjectViewCommentsInput): ObjectViewComments { + const offered = + !phone && + !!objectName && + !!dataSource && + !!user?.id && + objectDef?.enable?.feeds !== false && + COMMENTS_COLUMN_LAYOUTS.has(layout) && + typeof dataSource.queryCommentThreads === 'function'; + const [kept, setKept] = useCommentsPanelOpen(VIEW_COMMENTS_OPEN_KEY); + const open = offered && kept; + // The list's scope, for the object it was reported on: forgotten on close, + // so a column opened again reads only once the list has told it afresh. + const [scope, setScope] = useState<{ objectName: string; report: ListEffectiveFilter } | null>(null); + if (!open && scope !== null) setScope(null); + const report = (next: ListEffectiveFilter) => { + if (objectName) setScope({ objectName, report: next }); + }; + + const button = offered ? ( + + ) : null; + const column = open && dataSource && objectName && user ? ( + + setKept(false)} + onOpenRecord={onOpenRecord} + /> + + ) : null; + return { button, column, onEffectiveFilterChange: open ? report : undefined }; +} diff --git a/ui/packages/app-shell/src/views/objectViewCommentsColumn.tsx b/ui/packages/app-shell/src/views/objectViewCommentsColumn.tsx new file mode 100644 index 00000000000..62645bf9abf --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewCommentsColumn.tsx @@ -0,0 +1,340 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The list page's comments column (objectstack#39085): a 380px column at the + * page's right that narrows the list, holding the comment threads on the + * records the list's filter selects (`useViewCommentThreads`), newest first, + * one card each (`ViewCommentsPanel`). + * + * Loaded on its own (`ObjectView` imports it lazily) and mounted only while + * the column is open: a closed column costs the list page no code and no + * request. + * + * A card expanded in place is the record's live discussion: the record page's + * own unit (`useRecordDiscussion`), read for that record, drawn as the record + * page's comment panel draws a thread, with the same reply, resolve and + * reopen, react, edit and delete, each offered exactly where the record page + * offers it. Its writes announce themselves on the data bus as the record + * page's do, so the column re-reads its threads and the grid its comment dots. + */ + +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { Loader2 } from 'lucide-react'; +import { Button, ObjectIconTile } from '@object-ui/components'; +import { createAuthenticatedFetch } from '@object-ui/auth'; +import { DiscussionContextProvider, type DiscussionContextValue } from '@object-ui/react'; +import { + CommentHoverActions, + CommentThread, + DEFAULT_COMMENT_THREAD_FILTER, + ViewCommentsPanel, + useRecordComments, + type CommentThreadFilter, + type ViewCommentThreadItem, +} from '@object-ui/plugin-detail'; +import type { ListEffectiveFilter } from '@object-ui/plugin-list'; +import type { ConfirmationHandler } from '@object-ui/core'; +import type { TranslateFn } from '@object-ui/i18n'; +import type { DataSource } from '@object-ui/types'; +import { useRecordDiscussion, type MentionSuggestion } from './useRecordDiscussion.js'; +import { useViewCommentThreads } from './useViewCommentThreads.js'; + +/** The signed-in user, as the page knows them. */ +export interface ViewCommentsUser { + id: string; + name: string; + avatar?: string; +} + +export interface ObjectViewCommentsColumnProps { + dataSource: DataSource; + /** The list's object. */ + objectName: string; + /** The object's definition: its name, icon and colour. */ + objectDef: { name?: string; icon?: string; color?: string } | null | undefined; + /** The served object definitions the write gates read each object's policy from. */ + objects: readonly unknown[] | undefined; + /** The list's effective filter, or `null` until the list has reported it. */ + scope: ListEffectiveFilter | null; + currentUser: ViewCommentsUser; + confirmHandler: ConfirmationHandler; + t: TranslateFn; + /** Closes the column (its ✕, and Esc inside it). */ + onClose: () => void; + /** Opens a record the way the list opens it. */ + onOpenRecord: (recordId: string) => void; +} + +/** + * The people a comment can mention: the signed-in user first, then up to 50 + * of the directory, read once per column and only when a comment write wants + * it, as the record page reads it. + */ +function useMentionRoster(dataSource: DataSource, currentUser: ViewCommentsUser) { + const [suggestions, setSuggestions] = useState([]); + const readRef = useRef | null>(null); + const self: MentionSuggestion = { id: currentUser.id, label: currentUser.name || currentUser.id, avatarUrl: currentUser.avatar }; + const selfRef = useRef(self); + selfRef.current = self; + const read = (): Promise => { + if (readRef.current) return readRef.current; + const me = selfRef.current; + readRef.current = (async () => { + try { + type UserRow = { id?: unknown; name?: string | null; email?: string | null; image?: string | null }; + const res: unknown = await dataSource.find('sys_user', { $top: 50, $select: ['id', 'name', 'email', 'image'] }); + const rows: UserRow[] = Array.isArray(res) ? res : ((res as { data?: UserRow[] } | null)?.data ?? []); + const fetched = rows + .map((u) => ({ id: String(u.id), label: u.name || u.email || String(u.id), avatarUrl: u.image || undefined })) + .filter((s) => s.label && s.id !== me.id); + return [me, ...fetched]; + } catch { + return [me]; + } + })(); + return readRef.current; + }; + const [wanted, setWanted] = useState(false); + useEffect(() => { + if (!wanted) return undefined; + let live = true; + void read().then((roster) => { + if (live) setSuggestions(roster); + }); + return () => { + live = false; + }; + // `read` holds its one read in a ref. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [wanted]); + const rosterFor = async (text: string): Promise => { + if (suggestions.length > 0 || !text.includes('@')) return suggestions; + setWanted(true); + return read(); + }; + return { suggestions, want: () => setWanted(true), rosterFor }; +} + +type MentionRoster = ReturnType; + +export function ObjectViewCommentsColumn({ + dataSource, + objectName, + objectDef, + objects, + scope, + currentUser, + confirmHandler, + t, + onClose, + onOpenRecord, +}: ObjectViewCommentsColumnProps) { + // The filter menu: resolved threads hidden, 「只看我参与的」 off, held while + // the column is open. + const [filter, setFilter] = useState(DEFAULT_COMMENT_THREAD_FILTER); + const unknownName = t('detail.unknownUser', { defaultValue: 'Unknown' }); + const read = useViewCommentThreads({ dataSource, objectName, scope, filter, viewerId: currentUser.id, unknownName }); + const [expanded, setExpanded] = useState>(() => new Set()); + const roster = useMentionRoster(dataSource, currentUser); + const authFetch = useMemo(() => createAuthenticatedFetch(), []); + // The names a card highlights as one `@` mention: the people the column + // draws, and the viewer. + const mentionLabels = [ + currentUser.name, + ...read.threads.flatMap((thread) => [thread.comment.actor, ...thread.repliers.map((replier) => replier.name)]), + ...roster.suggestions.map((suggestion) => suggestion.label), + ]; + // Closed from inside (✕, Esc), the focus goes back to the comments icon + // that opened the column, the nearest one round it (the page's header). + const columnRef = useRef(null); + const close = () => { + const el = columnRef.current; + const hadFocus = !!el && el.contains(document.activeElement); + let button: HTMLElement | null = null; + for (let node = el?.parentElement; node && !button; node = node.parentElement) { + button = node.querySelector('[data-comments-button]'); + } + onClose(); + if (hadFocus) button?.focus(); + }; + return ( +
+ } + onOpenRecord={onOpenRecord} + expandedIds={expanded} + onExpand={(id) => setExpanded((prev) => (prev.has(id) ? prev : new Set(prev).add(id)))} + mentionLabels={mentionLabels} + renderExpanded={(thread) => ( + + )} + /> +
+ ); +} + +/** + * An expanded card: the record's discussion, read for this record, and the + * card's thread drawn from it with the record page's actions. + */ +function ViewCommentThreadLive({ + thread, + dataSource, + objectName, + verdictObjectName, + objects, + currentUser, + confirmHandler, + authFetch, + roster, + t, +}: { + thread: ViewCommentThreadItem; + dataSource: DataSource; + objectName: string; + verdictObjectName: string; + objects: readonly unknown[] | undefined; + currentUser: ViewCommentsUser; + confirmHandler: ConfirmationHandler; + authFetch: typeof fetch; + roster: MentionRoster; + t: TranslateFn; +}) { + const discussion = useRecordDiscussion({ + dataSource, + objectName, + recordId: thread.recordId, + verdictObjectName, + currentUser, + // The column is offered only where the object's discussion is on. + feedsEnabled: true, + objects, + t, + confirmHandler, + authFetch, + mentionRosterFor: roster.rosterFor, + verdictsWanted: true, + }); + const { reactionStore, readComments } = discussion; + // The comments and their reactions are read as one answer, once the + // deployment's reaction store is known. + const [reading, setReading] = useState(true); + const [reads, setReads] = useState(0); + const readRef = useRef(readComments); + readRef.current = readComments; + useEffect(() => { + if (reactionStore === null) return undefined; + let live = true; + setReading(true); + const settled = readRef.current(null); + if (!settled) { + setReading(false); + return undefined; + } + void settled.then(() => { + if (live) setReading(false); + }); + return () => { + live = false; + }; + }, [reactionStore, reads, thread.recordId]); + const verdict = discussion.commentsVerdict; + return ( +
+ setReads((n) => n + 1) : undefined} + onAddReply={discussion.onAddReply as DiscussionContextValue['onAddReply']} + onEditComment={discussion.onEditComment} + onDeleteComment={discussion.onDeleteComment} + ownCommentDeletesOnly={discussion.ownCommentDeletesOnly} + onResolveComment={discussion.onResolveComment} + moderatesComments={discussion.moderatesComments} + updatesOthersComments={discussion.updatesOthersComments} + onToggleReaction={discussion.onToggleReaction as DiscussionContextValue['onToggleReaction']} + mentionSuggestions={roster.suggestions} + onMentionSuggestionsWanted={roster.want} + > + + +
+ ); +} + +/** The card's thread out of the record's discussion, with its read's states. */ +function LiveThread({ rootId, t }: { rootId: string; t: TranslateFn }) { + const comments = useRecordComments(); + const live = comments.threads.find((candidate) => String(candidate.root.id) === rootId); + let note: ReactNode = null; + if (comments.denied) { + note = t('detail.viewCommentsDenied'); + } else if (comments.failed) { + note = ( + <> + {t('detail.viewCommentsLoadFailed')} + {comments.onRetry && ( + + )} + + ); + } + if (note) { + return

{note}

; + } + if (!live) { + // Still reading, or gone (deleted since the column read it): the + // column's own re-read drops a gone thread's card. + return comments.loading ? ( +
+
+ ) : null; + } + return ( + ( + + )} + /> + ); +} + +export default ObjectViewCommentsColumn; diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index fb46b554df9..098efd3c442 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -18,7 +18,7 @@ import type { ListViewPreference } from './listDraftStore.js'; const ObjectChart = lazy(() => import('@object-ui/plugin-charts').then((m) => ({ default: m.ObjectChart })), ); -import { ListView, type ListToolbarTrailingState } from '@object-ui/plugin-list'; +import { ListView, type ListEffectiveFilter, type ListToolbarTrailingState } from '@object-ui/plugin-list'; import type { ListColumn, ListViewSchema, TreeViewConfig } from '@object-ui/types'; import type { FilterBuilderRowGroup } from '@object-ui/components'; import type { useAuth } from '@object-ui/auth'; @@ -118,6 +118,7 @@ export function useObjectViewListRenderer({ listViewActions, onBulkChangeOwner, bulkChangeOwnerOffered, + onEffectiveFilterChange, }: { objectName: string | undefined; t: ReturnType['t']; @@ -215,6 +216,13 @@ export function useObjectViewListRenderer({ * a selection is open. */ bulkChangeOwnerOffered?: boolean; + /** + * objectstack#39085 — the list's effective filter (`ListView`'s + * `onEffectiveFilterChange`), for the page's comments column, which reads + * the threads of the records the view scopes. Given only while the column + * is open: a closed column has the list build nothing for it. + */ + onEffectiveFilterChange?: (report: ListEffectiveFilter) => void; }) { // objectstack#35551 — the host hands fresh closures every render; the list // reads the latest through a ref, and re-renders only when one appears or goes. @@ -225,6 +233,11 @@ export function useObjectViewListRenderer({ const bulkChangeOwnerRef = useRef(onBulkChangeOwner); bulkChangeOwnerRef.current = onBulkChangeOwner; const offersBulkChangeOwner = !!onBulkChangeOwner; + // objectstack#39085 — read through a ref too: the list re-renders only + // when the column opens or closes. + const effectiveFilterRef = useRef(onEffectiveFilterChange); + effectiveFilterRef.current = onEffectiveFilterChange; + const reportsEffectiveFilter = !!onEffectiveFilterChange; const offersRename = !!listViewActions?.rename; const offersSave = !!listViewActions?.save; const offersReset = !!listViewActions?.reset; @@ -1187,6 +1200,9 @@ export function useObjectViewListRenderer({ }} onRowsChange={dots.onRowsChange} onTotalChange={handleListTotalChange} + // objectstack#39085 — the filter the list applies, for the + // comments column while it is open. + onEffectiveFilterChange={reportsEffectiveFilter ? (report: ListEffectiveFilter) => effectiveFilterRef.current?.(report) : undefined} // objectstack#30850 — the page lives in the address (`uf__page`, // replace): the list reads it and reports every move back. page={listPage} @@ -1288,7 +1304,7 @@ export function useObjectViewListRenderer({ {drawList} ); - }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listLayout.layout, listLayout.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, openReferencedRecord, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, offersBulkChangeOwner, bulkChangeOwnerOffered, previewDrafts, previewDataSource, unpublishedObjects]); + }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listLayout.layout, listLayout.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, openReferencedRecord, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, offersBulkChangeOwner, bulkChangeOwnerOffered, reportsEffectiveFilter, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx index 72ac6512eb5..3ae8222c81e 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -485,13 +485,19 @@ export function ObjectViewImportExportMenu({ ); } -export function ObjectViewPageHeader({ hosted = false, ...props }: ObjectViewPageBarProps & { +export function ObjectViewPageHeader({ hosted = false, comments, ...props }: ObjectViewPageBarProps & { /** * objectstack#36113 — the list's view bar carries the page's acts * (`ListViewBarHostContext`): this bar is the page's first row, the * object's icon and name, and draws none of them. */ hosted?: boolean; + /** + * objectstack#39085 — the comments icon that opens the page's comments + * column, first in the shell's button group; drawn whether or not the + * view bar hosts the page's acts. + */ + comments?: ReactNode; }) { const { objectDef, objectPluralLabel, foldedHeaderActions } = props; const actionProps = props; @@ -521,6 +527,7 @@ export function ObjectViewPageHeader({ hosted = false, ...props }: ObjectViewPag actions={hosted ? undefined : } foldedActions={hosted ? undefined : foldedHeaderActions} compactBelow={hosted ? undefined : LIST_HEADER_COMPACT_WIDTH} + comments={comments} /> ); diff --git a/ui/packages/app-shell/src/views/recordCommentsPanel.tsx b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx index a6c72699f84..f7c1d5e7a98 100644 --- a/ui/packages/app-shell/src/views/recordCommentsPanel.tsx +++ b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx @@ -40,10 +40,11 @@ export const COMMENTS_PANEL_OPEN_KEY = 'os:record-comments-panel:page'; /** * Whether the reader keeps the record page's comment panel open * (objectstack#36075, item 2): a preference, kept in this browser, so a - * record opened later opens with the panel as it was left. + * record opened later opens with the panel as it was left. `key` names the + * preference: the list page's comments column keeps its own + * (objectstack#39085). */ -export function useCommentsPanelOpen(): [boolean, (open: boolean) => void] { - const key = COMMENTS_PANEL_OPEN_KEY; +export function useCommentsPanelOpen(key: string = COMMENTS_PANEL_OPEN_KEY): [boolean, (open: boolean) => void] { const [open, setOpenState] = useState(() => { try { return typeof window !== 'undefined' && window.localStorage.getItem(key) === 'open'; diff --git a/ui/packages/app-shell/src/views/useRecordDiscussion.ts b/ui/packages/app-shell/src/views/useRecordDiscussion.ts index 27052354f7e..8ffa68f5705 100644 --- a/ui/packages/app-shell/src/views/useRecordDiscussion.ts +++ b/ui/packages/app-shell/src/views/useRecordDiscussion.ts @@ -119,7 +119,7 @@ function mergeFeedRows(prev: readonly FeedItem[], incoming: readonly FeedItem[]) * it, or a list of ids or `{ id }` objects, as #36071's `threadsInvolvingUser` * reads it. Anything unreadable names nobody. */ -function rowMentionsUser(raw: unknown, userId: string | undefined): boolean { +export function rowMentionsUser(raw: unknown, userId: string | undefined): boolean { if (!userId || raw == null) return false; let list: unknown = raw; if (typeof raw === 'string') { @@ -144,7 +144,7 @@ function rowMentionsUser(raw: unknown, userId: string | undefined): boolean { * the resolver's id and when, and the resolver's name where this page knows * it — the viewer, or an author of the same discussion (`namesById`). */ -function commentResolutionOf( +export function commentResolutionOf( row: Record, namesById: ReadonlyMap, ): Pick { diff --git a/ui/packages/app-shell/src/views/useViewCommentThreads-39085.test.tsx b/ui/packages/app-shell/src/views/useViewCommentThreads-39085.test.tsx new file mode 100644 index 00000000000..ddfbf8cbe70 --- /dev/null +++ b/ui/packages/app-shell/src/views/useViewCommentThreads-39085.test.tsx @@ -0,0 +1,289 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#39085 — the list page's comments column, its read + * (`useViewCommentThreads`): one threads request per page, keyed on the + * list's scope and the column's filter by content; 「加载更多」 appends the + * next page; a comment write announced re-reads the pages loaded so far in + * one request; a filter the list cannot lower reads nothing; each refusal + * maps to the column state that names it; an answer to a superseded request + * is dropped. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { renderHook, act, waitFor, cleanup } from '@testing-library/react'; +import { notifyDataChanged } from '@object-ui/react'; +import { DEFAULT_COMMENT_THREAD_FILTER, type CommentThreadFilter } from '@object-ui/plugin-detail'; +import type { ListEffectiveFilter } from '@object-ui/plugin-list'; +import { + useViewCommentThreads, + viewCommentThreadOf, + viewCommentsStateOfError, +} from './useViewCommentThreads'; + +afterEach(() => cleanup()); + +function served(id: string, over: Record = {}) { + return { + comment: { id, body: `body ${id}`, author_id: 'u2', author_name: 'Grace', created_at: '2026-12-02T09:00:00Z', is_resolved: false, ...over }, + record: { id: `rec-${id}`, name: `Record ${id}` }, + replyCount: 1, + repliers: [{ id: 'u3', name: null, avatarUrl: null }], + }; +} + +type Props = { scope: ListEffectiveFilter | null; filter: CommentThreadFilter }; + +function mountHook(queryCommentThreads: (...args: any[]) => Promise, initial: Partial = {}) { + const dataSource = { queryCommentThreads: vi.fn(queryCommentThreads) } as any; + const hook = renderHook( + ({ scope, filter }: Props) => useViewCommentThreads({ + dataSource, + objectName: 'account', + scope, + filter, + viewerId: 'u1', + unknownName: 'Unknown', + }), + { initialProps: { scope: { kind: 'filter', filter: { status: 'open' } }, filter: DEFAULT_COMMENT_THREAD_FILTER, ...initial } as Props }, + ); + return { ...hook, door: dataSource.queryCommentThreads }; +} + +describe('objectstack#39085 — useViewCommentThreads', () => { + it('reads the first page once with the scope and the filter, and draws its threads', async () => { + const { result, door } = mountHook(async () => ({ threads: [served('c1'), served('c2')], nextCursor: null })); + + expect(result.current.state).toBe('loading'); + await waitFor(() => expect(result.current.state).toBe('ready')); + expect(result.current.threads.map((t) => t.id)).toEqual(['c1', 'c2']); + expect(result.current.hasMore).toBe(false); + expect(door).toHaveBeenCalledTimes(1); + expect(door).toHaveBeenCalledWith({ object: 'account', filter: { status: 'open' }, limit: 25 }); + }); + + it('reads nothing until the list reports, and nothing for a filter it cannot lower', async () => { + const { result, door, rerender } = mountHook(async () => ({ threads: [], nextCursor: null }), { scope: null }); + expect(result.current.state).toBe('loading'); + + rerender({ scope: { kind: 'unlowerable' }, filter: DEFAULT_COMMENT_THREAD_FILTER }); + expect(result.current.state).toBe('unscoped'); + await act(async () => {}); + expect(door).not.toHaveBeenCalled(); + }); + + it('re-reads from the first page when the scope or the toggles change, and not for an equal scope', async () => { + const { result, door, rerender } = mountHook(async () => ({ threads: [served('c1')], nextCursor: null })); + await waitFor(() => expect(result.current.state).toBe('ready')); + + rerender({ scope: { kind: 'filter', filter: { status: 'open' } }, filter: DEFAULT_COMMENT_THREAD_FILTER }); + await act(async () => {}); + expect(door).toHaveBeenCalledTimes(1); + + rerender({ scope: { kind: 'filter', filter: { status: 'won' } }, filter: DEFAULT_COMMENT_THREAD_FILTER }); + await waitFor(() => expect(door).toHaveBeenCalledTimes(2)); + expect(door.mock.calls[1][0]).toEqual({ object: 'account', filter: { status: 'won' }, limit: 25 }); + + rerender({ scope: { kind: 'filter', filter: { status: 'won' } }, filter: { showResolved: true, onlyMine: true } }); + await waitFor(() => expect(door).toHaveBeenCalledTimes(3)); + expect(door.mock.calls[2][0]).toEqual({ object: 'account', filter: { status: 'won' }, showResolved: true, onlyMine: true, limit: 25 }); + }); + + it('appends the next page on load more, each thread once', async () => { + const door = vi.fn() + .mockResolvedValueOnce({ threads: [served('c1'), served('c2')], nextCursor: 'p2' }) + .mockResolvedValueOnce({ threads: [served('c2'), served('c3')], nextCursor: null }); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.threads.map((t) => t.id)).toEqual(['c1', 'c2', 'c3'])); + expect(result.current.hasMore).toBe(false); + expect(door).toHaveBeenCalledTimes(2); + expect(door.mock.calls[1][0]).toMatchObject({ cursor: 'p2', limit: 25 }); + }); + + it('marks a failed next page for the load-more control to ask again', async () => { + const door = vi.fn() + .mockResolvedValueOnce({ threads: [served('c1')], nextCursor: 'p2' }) + .mockRejectedValueOnce(Object.assign(new Error('boom'), { httpStatus: 500 })); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.loadMoreFailed).toBe(true)); + expect(result.current.state).toBe('ready'); + expect(result.current.threads.map((t) => t.id)).toEqual(['c1']); + }); + + it('re-reads the pages loaded so far in one request when a comment write is announced', async () => { + const page = Array.from({ length: 30 }, (_, i) => served(`c${i}`)); + const door = vi.fn() + .mockResolvedValueOnce({ threads: page.slice(0, 25), nextCursor: 'p2' }) + .mockResolvedValueOnce({ threads: page.slice(25), nextCursor: null }) + .mockResolvedValueOnce({ threads: [{ ...page[0], replyCount: 2 }, ...page.slice(1)], nextCursor: null }); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.threads).toHaveLength(30)); + + act(() => notifyDataChanged({ objectName: 'sys_comment', recordId: 'c0' })); + await waitFor(() => expect(result.current.threads[0].replyCount).toBe(2)); + expect(door).toHaveBeenCalledTimes(3); + expect(door.mock.calls[2][0]).toEqual({ object: 'account', filter: { status: 'open' }, limit: 30 }); + }); + + it('keeps the cards held past the re-read ceiling, and their cursor, when a comment write is announced', async () => { + const all = Array.from({ length: 60 }, (_, i) => served(`c${i}`)); + const door = vi.fn() + .mockResolvedValue({ threads: [], nextCursor: null }) + .mockResolvedValueOnce({ threads: all.slice(0, 25), nextCursor: 'p2' }) + .mockResolvedValueOnce({ threads: all.slice(25, 50), nextCursor: 'p3' }) + .mockResolvedValueOnce({ threads: all.slice(50, 60), nextCursor: 'p4' }) + .mockResolvedValueOnce({ threads: [{ ...all[0], replyCount: 5 }, ...all.slice(1, 50)], nextCursor: 'fresh' }); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.threads).toHaveLength(50)); + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.threads).toHaveLength(60)); + + act(() => notifyDataChanged({ objectName: 'sys_comment', recordId: 'c55' })); + await waitFor(() => expect(result.current.threads[0].replyCount).toBe(5)); + expect(door.mock.calls[3][0]).toMatchObject({ limit: 50 }); + expect(door.mock.calls[3][0].cursor).toBeUndefined(); + expect(result.current.threads.map((t) => t.id)).toEqual(all.map((t) => t.comment.id)); + // The next page still follows the last card held. + act(() => result.current.loadMore()); + await waitFor(() => expect(door).toHaveBeenCalledTimes(5)); + expect(door.mock.calls[4][0]).toMatchObject({ cursor: 'p4' }); + }); + + it('keeps the cards on screen when a re-read fails', async () => { + const door = vi.fn() + .mockResolvedValueOnce({ threads: [served('c1'), served('c2')], nextCursor: null }) + .mockRejectedValueOnce(Object.assign(new Error('down'), { httpStatus: 503 })); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.state).toBe('ready')); + + act(() => notifyDataChanged({ objectName: 'sys_comment' })); + await waitFor(() => expect(door).toHaveBeenCalledTimes(2)); + await act(async () => {}); + expect(result.current.state).toBe('ready'); + expect(result.current.threads.map((t) => t.id)).toEqual(['c1', 'c2']); + }); + + it('releases a load-more that a failed re-read superseded', async () => { + let releaseMore: (v: unknown) => void = () => {}; + const door = vi.fn() + .mockResolvedValueOnce({ threads: [served('c1')], nextCursor: 'p2' }) + .mockImplementationOnce(() => new Promise((resolve) => { releaseMore = resolve; })) + .mockRejectedValueOnce(Object.assign(new Error('down'), { httpStatus: 503 })) + .mockResolvedValue({ threads: [served('c2')], nextCursor: null }); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + act(() => result.current.loadMore()); + expect(result.current.loadingMore).toBe(true); + + act(() => notifyDataChanged({ objectName: 'sys_comment' })); + await waitFor(() => expect(result.current.loadingMore).toBe(false)); + releaseMore({ threads: [served('c9')], nextCursor: null }); + await act(async () => {}); + expect(result.current.threads.map((t) => t.id)).toEqual(['c1']); + expect(result.current.hasMore).toBe(true); + act(() => result.current.loadMore()); + await waitFor(() => expect(result.current.threads.map((t) => t.id)).toEqual(['c1', 'c2'])); + }); + + it('drops the answer to a superseded request', async () => { + let releaseFirst: (value: unknown) => void = () => {}; + const door = vi.fn() + .mockImplementationOnce(() => new Promise((resolve) => { releaseFirst = resolve; })) + .mockResolvedValueOnce({ threads: [served('won')], nextCursor: null }); + const { result, rerender } = mountHook(door); + + rerender({ scope: { kind: 'filter', filter: { status: 'won' } }, filter: DEFAULT_COMMENT_THREAD_FILTER }); + await waitFor(() => expect(result.current.threads.map((t) => t.id)).toEqual(['won'])); + await act(async () => releaseFirst({ threads: [served('open')], nextCursor: null })); + expect(result.current.threads.map((t) => t.id)).toEqual(['won']); + }); + + it('answers a refused read with the state that names it, and retries a failed one', async () => { + const door = vi.fn() + .mockRejectedValueOnce(Object.assign(new Error('down'), { httpStatus: 503 })) + .mockResolvedValueOnce({ threads: [served('c1')], nextCursor: null }); + const { result } = mountHook(door); + await waitFor(() => expect(result.current.state).toBe('failed')); + + act(() => result.current.retry()); + await waitFor(() => expect(result.current.state).toBe('ready')); + expect(door).toHaveBeenCalledTimes(2); + }); + + it('is unavailable where the data source has no threads door', () => { + const { result } = renderHook(() => useViewCommentThreads({ + dataSource: { find: vi.fn() } as any, + objectName: 'account', + scope: { kind: 'filter', filter: undefined }, + filter: DEFAULT_COMMENT_THREAD_FILTER, + viewerId: 'u1', + unknownName: 'Unknown', + })); + expect(result.current.state).toBe('unavailable'); + }); +}); + +describe('objectstack#39085 — viewCommentsStateOfError', () => { + it.each([ + [{ httpStatus: 403, code: 'FEEDS_DISABLED' }, 'denied'], + [{ httpStatus: 403, code: 'PERMISSION_DENIED' }, 'denied'], + [{ httpStatus: 401 }, 'denied'], + [{ httpStatus: 400, code: 'INVALID_FILTER' }, 'unscoped'], + [{ httpStatus: 400, code: 'VALIDATION_ERROR' }, 'unscoped'], + [{ httpStatus: 404 }, 'unavailable'], + [{ httpStatus: 501 }, 'unavailable'], + [{ httpStatus: 404, code: 'OBJECT_NOT_FOUND' }, 'failed'], + [{ httpStatus: 500 }, 'failed'], + [new TypeError('Failed to fetch'), 'failed'], + ] as const)('%o → %s', (err, state) => { + expect(viewCommentsStateOfError(err)).toBe(state); + }); +}); + +describe('objectstack#39085 — viewCommentThreadOf', () => { + it('maps the row the way the record page maps its own', () => { + const item = viewCommentThreadOf( + served('c1', { author_id: 'u1', is_resolved: true, resolved_by: 'u9', mentions: '["u1"]', is_edited: true }) as any, + 'u1', + 'Unknown', + ); + expect(item).toMatchObject({ + id: 'c1', + recordId: 'rec-c1', + recordName: 'Record c1', + replyCount: 1, + repliers: [{ id: 'u3', name: 'Unknown', avatarUrl: undefined }], + comment: { + id: 'c1', + type: 'comment', + actor: 'Grace', + body: 'body c1', + authoredByViewer: true, + mentionsViewer: true, + edited: true, + resolved: true, + resolvedById: 'u9', + }, + }); + }); + + it('skips a row with no id', () => { + expect(viewCommentThreadOf(served('') as any, 'u1', 'Unknown')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/useViewCommentThreads.ts b/ui/packages/app-shell/src/views/useViewCommentThreads.ts new file mode 100644 index 00000000000..1ef12185f46 --- /dev/null +++ b/ui/packages/app-shell/src/views/useViewCommentThreads.ts @@ -0,0 +1,284 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The list page's comments column, its read (objectstack#39085): the comment + * threads on the records the list's filter selects, a page at a time, through + * the data source's threads door (`queryCommentThreads`, + * `POST /api/v1/comments/threads/query`). + * + * The scope is the list's effective filter as the list reports it + * (`ListView`'s `onEffectiveFilterChange`): the saved view's filter AND the + * reader's unsaved filter-bar and panel choices. The search box is not in it + * (the maintainer's ruling on the card). A filter the list cannot lower is + * never read without: the column shows its cannot-scope state instead. + * + * One request per page: the first page when the scope or the column's filter + * changes, the next on 「加载更多」, and the loaded pages again (one request, + * up to the door's 50) when a comment anywhere is written + * (`useDataInvalidation('sys_comment')`), so a reply raises a count and a + * thread resolved under 「显示已解决」 off drops out. Cards held past the + * 50th are kept as they were by that re-read (it cannot cover them), and a + * failed re-read keeps every card: a reader's own write never drops the card + * they are in. + */ + +import { useEffect, useRef, useState } from 'react'; +import { useDataInvalidation } from '@object-ui/react'; +import { isCommentAuthor } from '@object-ui/collaboration'; +import type { CommentThreadFilter, ViewCommentsState, ViewCommentThreadItem } from '@object-ui/plugin-detail'; +import type { ListEffectiveFilter } from '@object-ui/plugin-list'; +import type { CommentThreadsQueryRequest, CommentThreadsQueryResponse, DataSource, FeedItem } from '@object-ui/types'; +import { commentResolutionOf, rowMentionsUser } from './useRecordDiscussion.js'; + +/** The door's page size when the request names none, and its ceiling. */ +export const VIEW_COMMENTS_PAGE_SIZE = 25; +export const VIEW_COMMENTS_MAX_PAGE_SIZE = 50; + +type ServedThread = CommentThreadsQueryResponse['threads'][number]; + +const NO_RESOLVER_NAMES: ReadonlyMap = new Map(); + +/** + * One served thread as a card draws it. The comment row is mapped the way the + * record page maps its own (`useRecordDiscussion`): the stored author name and + * avatar, the resolution, whether the viewer wrote it or is mentioned in it. + */ +export function viewCommentThreadOf( + served: ServedThread, + viewerId: string | undefined, + unknownName: string, +): ViewCommentThreadItem | null { + const row = served.comment as Record; + const id = row.id; + if ((typeof id !== 'string' || id === '') && typeof id !== 'number') return null; + const text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined); + const comment: FeedItem = { + id, + type: 'comment', + actor: text(row.author_name) ?? unknownName, + actorAvatarUrl: text(row.author_avatar_url), + body: typeof row.body === 'string' ? row.body : '', + createdAt: typeof row.created_at === 'string' ? row.created_at : '', + updatedAt: text(row.updated_at), + replyCount: served.replyCount, + edited: row.is_edited === true, + authoredByViewer: isCommentAuthor(text(row.author_id) ?? null, viewerId ?? null), + ...commentResolutionOf(row, NO_RESOLVER_NAMES), + mentionsViewer: rowMentionsUser(row.mentions, viewerId), + }; + return { + id: String(id), + recordId: served.record.id, + recordName: served.record.name, + comment, + replyCount: served.replyCount, + repliers: served.repliers.map((replier) => ({ + id: replier.id, + name: replier.name ?? unknownName, + avatarUrl: replier.avatarUrl ?? undefined, + })), + }; +} + +/** + * The column's state for a refused or failed read. + * + * - The server does not answer the door (a route it does not mount: 404, 405 + * or 501 with no code of the door's own): `unavailable`. + * - Refused to this reader (401, 403, `FEEDS_DISABLED`): `denied`. + * - A filter the server will not run (400, `INVALID_FILTER`): `unscoped`. + * - Anything else (5xx, the network): `failed`, with a retry. + */ +export function viewCommentsStateOfError(err: unknown): ViewCommentsState { + const e = err as { httpStatus?: unknown; status?: unknown; statusCode?: unknown; code?: unknown; message?: unknown } | null; + let status = [e?.httpStatus, e?.status, e?.statusCode].find((s): s is number => typeof s === 'number'); + if (status === undefined) { + const m = /HTTP (\d{3})\b/.exec(String(e?.message ?? '')); + if (m) status = Number(m[1]); + } + const code = typeof e?.code === 'string' ? e.code.toUpperCase() : ''; + if (code === 'NOT_IMPLEMENTED' || code === 'ROUTE_NOT_FOUND' || code === 'NOT_FOUND') return 'unavailable'; + if (code === 'FEEDS_DISABLED' || code === 'PERMISSION_DENIED' || code === 'FORBIDDEN' || code === 'UNAUTHORIZED') return 'denied'; + if (code === 'INVALID_FILTER' || code === 'VALIDATION_ERROR') return 'unscoped'; + if (status === 401 || status === 403) return 'denied'; + if (status === 400) return 'unscoped'; + if ((status === 404 || status === 405 || status === 501) && code !== 'OBJECT_NOT_FOUND') return 'unavailable'; + return 'failed'; +} + +export interface ViewCommentThreadsInput { + /** The data source; its `queryCommentThreads` is the door read. */ + dataSource: DataSource | null | undefined; + /** The list's object. */ + objectName: string | undefined; + /** The list's effective filter, or `null` until the list has reported it. */ + scope: ListEffectiveFilter | null; + /** The column's filter menu. */ + filter: CommentThreadFilter; + /** The signed-in user's id. */ + viewerId: string | undefined; + /** The name a comment with no stored author name is drawn under. */ + unknownName: string; +} + +export interface ViewCommentThreads { + threads: ViewCommentThreadItem[]; + state: ViewCommentsState; + hasMore: boolean; + loadingMore: boolean; + loadMoreFailed: boolean; + loadMore: () => void; + retry: () => void; +} + +interface Held { + /** The request the threads answer, by content. */ + key: string; + threads: ViewCommentThreadItem[]; + nextCursor: string | null; + state: ViewCommentsState; + loadingMore: boolean; + loadMoreFailed: boolean; +} + +const NO_THREADS: ViewCommentThreadItem[] = []; + +/** Appends `incoming` to `prev`, a thread already held kept once, in place. */ +function appendThreads(prev: readonly ViewCommentThreadItem[], incoming: readonly ViewCommentThreadItem[]): ViewCommentThreadItem[] { + const seen = new Set(prev.map((thread) => thread.id)); + return [...prev, ...incoming.filter((thread) => !seen.has(thread.id))]; +} + +/** + * Reads the column's threads. Mounted only while the column is open, so a + * closed column reads nothing. + */ +export function useViewCommentThreads({ + dataSource, + objectName, + scope, + filter, + viewerId, + unknownName, +}: ViewCommentThreadsInput): ViewCommentThreads { + const door = dataSource?.queryCommentThreads ? dataSource : null; + const showResolved = filter.showResolved === true; + const onlyMine = filter.onlyMine === true; + // The request, by content (AGENTS.md #10: never a memo's identity). + const key = door && objectName && scope?.kind === 'filter' + ? JSON.stringify([objectName, scope.filter ?? null, showResolved, onlyMine]) + : null; + const commentWrites = useDataInvalidation('sys_comment'); + const [retries, setRetries] = useState(0); + const [held, setHeld] = useState(null); + const heldRef = useRef(held); + heldRef.current = held; + // The latest first-page read: an answer to any earlier one is dropped. + const readSeq = useRef(0); + const requestOf = (cursor: string | undefined, limit: number): CommentThreadsQueryRequest => { + const request: CommentThreadsQueryRequest = { object: objectName as string, limit }; + if (scope?.kind === 'filter' && scope.filter !== undefined) request.filter = scope.filter; + if (showResolved) request.showResolved = true; + if (onlyMine) request.onlyMine = true; + if (cursor) request.cursor = cursor; + return request; + }; + const requestOfRef = useRef(requestOf); + requestOfRef.current = requestOf; + const mapThreads = (served: readonly ServedThread[]): ViewCommentThreadItem[] => + served.map((thread) => viewCommentThreadOf(thread, viewerId, unknownName)).filter((t): t is ViewCommentThreadItem => t !== null); + const mapRef = useRef(mapThreads); + mapRef.current = mapThreads; + + useEffect(() => { + if (!key || !door?.queryCommentThreads) return undefined; + const seq = ++readSeq.current; + const prev = heldRef.current; + // The same request again (a comment was written, a retry): the pages + // loaded so far, in one request, keeping them on screen meanwhile. + const again = prev?.key === key && prev.state === 'ready'; + const limit = again + ? Math.min(Math.max(prev.threads.length, VIEW_COMMENTS_PAGE_SIZE), VIEW_COMMENTS_MAX_PAGE_SIZE) + : VIEW_COMMENTS_PAGE_SIZE; + if (!again) { + setHeld({ key, threads: NO_THREADS, nextCursor: null, state: 'loading', loadingMore: false, loadMoreFailed: false }); + } + // Past the door's ceiling a re-read cannot cover every card held: the + // cards after the first `limit` stay as they were, with the cursor that + // follows them, so a reader writing in a card past the 50th keeps it. + const kept = again && prev.threads.length > limit ? prev.threads.slice(limit) : null; + const keptCursor = kept && prev ? prev.nextCursor : null; + door.queryCommentThreads(requestOfRef.current(undefined, limit)).then( + (answer) => { + if (seq !== readSeq.current) return; + const fresh = mapRef.current(answer?.threads ?? []); + setHeld({ + key, + threads: kept ? appendThreads(fresh, kept) : fresh, + nextCursor: kept ? keptCursor : answer?.nextCursor ?? null, + state: 'ready', + loadingMore: false, + loadMoreFailed: false, + }); + }, + (err: unknown) => { + if (seq !== readSeq.current) return; + // A failed re-read leaves the cards on screen as they were; a + // load-more it superseded is released, so 「加载更多」 can be pressed + // again. + if (again) { + setHeld((h) => (h && h.key === key && h.loadingMore ? { ...h, loadingMore: false } : h)); + return; + } + setHeld({ key, threads: NO_THREADS, nextCursor: null, state: viewCommentsStateOfError(err), loadingMore: false, loadMoreFailed: false }); + }, + ); + return undefined; + // `door` is read for its presence: the data source's identity moves with + // the scope's key only when it changes the answer. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, commentWrites, retries, !!door]); + + const current = held && held.key === key ? held : null; + const state: ViewCommentsState = scope?.kind === 'unlowerable' + ? 'unscoped' + : !door + ? 'unavailable' + : current?.state ?? 'loading'; + + const loadMore = () => { + const now = heldRef.current; + if (!now || now.key !== key || now.state !== 'ready' || !now.nextCursor || now.loadingMore || !door?.queryCommentThreads) return; + const seq = readSeq.current; + const forKey = now.key; + setHeld({ ...now, loadingMore: true, loadMoreFailed: false }); + door.queryCommentThreads(requestOf(now.nextCursor, VIEW_COMMENTS_PAGE_SIZE)).then( + (answer) => { + if (seq !== readSeq.current) return; + setHeld((latest) => latest && latest.key === forKey + ? { + ...latest, + threads: appendThreads(latest.threads, mapRef.current(answer?.threads ?? [])), + nextCursor: answer?.nextCursor ?? null, + loadingMore: false, + loadMoreFailed: false, + } + : latest); + }, + () => { + if (seq !== readSeq.current) return; + setHeld((latest) => latest && latest.key === forKey ? { ...latest, loadingMore: false, loadMoreFailed: true } : latest); + }, + ); + }; + + return { + threads: state === 'ready' && current ? current.threads : NO_THREADS, + state, + hasMore: state === 'ready' && !!current?.nextCursor, + loadingMore: state === 'ready' && !!current?.loadingMore, + loadMoreFailed: state === 'ready' && !!current?.loadMoreFailed, + loadMore, + retry: () => setRetries((n) => n + 1), + }; +} diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index fa3702456f9..ebc8c5ea2e5 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -50,6 +50,8 @@ import { } from './metadata-client'; import type { AnalyticsResult, DatasetSelection } from '@objectstack/spec/contracts'; import type { + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, DataSource, RecordFieldAccess, RecordPagePayload, @@ -8503,6 +8505,28 @@ export class ObjectStackAdapter implements DataSource { } } + /** + * One page of the comment threads on the records a list filter selects + * (objectstack#39085): `POST /api/v1/comments/threads/query` through the + * client's `comments.queryThreads`. The filter is normalised exactly as + * `find` normalises its `$filter` (`translateFilterToAST`: a view rule + * list, any-of groups, the object form), so one stored filter means the + * same records on both reads; an empty one is no filter, and so is a bare + * string, number or boolean, as on `find`'s read. One it refuses throws + * before any request, as `find` does: `FilterOperatorError` for an operator + * it does not know, `MalformedFilterError` for a rule entry it cannot read + * (both `INVALID_FILTER`, `400`). The answer comes back as the route gave it; every refusal + * and failure is thrown, so the caller can tell a server that does not + * mount the route (`404`, `501`) and a filter it cannot lower (`400`) from + * a refused (`401` / `403`) or failed read. + */ + async queryCommentThreads(request: CommentThreadsQueryRequest): Promise { + const { filter, ...rest } = request; + const lowered = filter === undefined ? undefined : translateFilterToAST(filter); + await this.connect(); + return this.client.comments.queryThreads(lowered === undefined ? rest : { ...rest, filter: lowered }); + } + /** The one round trip behind {@link getRecordPage}, unshared. */ private async readRecordPage(resource: string, id: string, request: RecordPageRequest): Promise { await this.connect(); diff --git a/ui/packages/data-objectstack/src/queryCommentThreads-39085.test.ts b/ui/packages/data-objectstack/src/queryCommentThreads-39085.test.ts new file mode 100644 index 00000000000..7209f333019 --- /dev/null +++ b/ui/packages/data-objectstack/src/queryCommentThreads-39085.test.ts @@ -0,0 +1,82 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#39085 — the threads door of the list page's comments column: + * `queryCommentThreads` hands the request to the client's + * `comments.queryThreads` (`POST /api/v1/comments/threads/query`) with its + * filter normalised exactly as `find` normalises `$filter` (a filter `find` + * refuses is refused here before any request), answers the client's answer, + * and lets a refusal through as the client threw it, so the column can tell a + * refused read from a failed one. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ObjectStackAdapter } from './index'; + +function makeDS(queryThreads: (...args: unknown[]) => unknown) { + const ds: any = new ObjectStackAdapter({ + baseUrl: 'http://test.local', + fetch: vi.fn(async () => new Response(JSON.stringify({ success: true, data: { capabilities: {}, routes: {} } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + })), + }); + ds.connected = true; + ds.connectionState = 'connected'; + ds.client = { comments: { queryThreads } }; + return ds; +} + +describe('ObjectStackDataSource.queryCommentThreads (objectstack#39085)', () => { + it('sends the request through comments.queryThreads and answers its answer', async () => { + const answer = { + threads: [{ comment: { id: 'c1', body: 'hi' }, record: { id: 'r1', name: 'Acme' }, replyCount: 2, repliers: [] }], + nextCursor: 'next', + }; + const queryThreads = vi.fn(async () => answer); + const ds = makeDS(queryThreads); + const request = { object: 'account', filter: { status: 'open' }, showResolved: true, limit: 25 }; + + await expect(ds.queryCommentThreads(request)).resolves.toBe(answer); + expect(queryThreads).toHaveBeenCalledTimes(1); + const sent = (queryThreads.mock.calls[0] as unknown[])[0] as Record; + expect(sent).toMatchObject({ object: 'account', showResolved: true, limit: 25 }); + expect(JSON.stringify(sent.filter)).toContain('open'); + }); + + it('normalises the filter exactly as find does, and sends no filter for an empty one', async () => { + const queryThreads = vi.fn(async () => ({ threads: [], nextCursor: null })); + const ds = makeDS(queryThreads); + // A view rule list in the object form `find` takes as `$filter`. + const rules = [{ field: 'amount', operator: 'greater_than_or_equal', value: 10 }, { field: 'stage', operator: 'in', value: ['won', 'lost'] }]; + + await ds.queryCommentThreads({ object: 'deal', filter: rules }); + await ds.queryCommentThreads({ object: 'deal', filter: [] }); + + const sent = (queryThreads.mock.calls[0] as unknown[])[0] as Record; + expect(sent.filter).not.toEqual(rules); + expect(JSON.stringify(sent.filter)).toContain('>='); + expect((queryThreads.mock.calls[1] as unknown[])[0]).toEqual({ object: 'deal' }); + }); + + it('refuses a filter find refuses before any request', async () => { + const queryThreads = vi.fn(); + const ds = makeDS(queryThreads); + + await expect(ds.queryCommentThreads({ object: 'deal', filter: { name: { $regex: '^A' } } })).rejects.toMatchObject({ code: 'INVALID_FILTER' }); + expect(queryThreads).not.toHaveBeenCalled(); + }); + + it('lets a refusal through as the client threw it', async () => { + const refusal = Object.assign(new Error('Comments are off'), { httpStatus: 403, code: 'FEEDS_DISABLED' }); + const ds = makeDS(vi.fn(async () => { throw refusal; })); + + await expect(ds.queryCommentThreads({ object: 'account' })).rejects.toBe(refusal); + }); +}); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 64d32e8d418..3ac2b7f43a6 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1643,6 +1643,13 @@ const ar = { noUnresolvedComments: "لا توجد تعليقات غير محلولة", noCommentsInvolvingMe: "لا توجد تعليقات تشارك فيها", showAllComments: "إظهار كل التعليقات", + viewCommentsEmpty: "لا توجد تعليقات على سجلات هذا العرض", + viewCommentsDenied: "ليس لديك إذن لعرض التعليقات على هذا الكائن.", + viewCommentsLoadFailed: "تعذّر تحميل تعليقات هذا العرض.", + viewCommentsUnscoped: "لا يمكن سرد التعليقات وفق عامل تصفية هذا العرض.", + viewCommentsUnavailable: "لا يمكن لهذا الخادم سرد تعليقات العرض.", + viewCommentsLoadMore: "تحميل المزيد", + viewCommentsOpenRecord: "فتح {{name}}", commentResolveFailed: "لم يتم تحديث المناقشة. يرجى المحاولة مرة أخرى.", pinned: "مثبت", pin: "تثبيت", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 923c48b9a6c..e99abdc63be 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1486,6 +1486,13 @@ const de = { noUnresolvedComments: "Keine offenen Kommentare", noCommentsInvolvingMe: "Keine Kommentare, an denen Sie beteiligt sind", showAllComments: "Alle Kommentare anzeigen", + viewCommentsEmpty: "Keine Kommentare zu den Datensätzen dieser Ansicht", + viewCommentsDenied: "Sie haben keine Berechtigung, Kommentare zu diesem Objekt anzuzeigen.", + viewCommentsLoadFailed: "Die Kommentare dieser Ansicht konnten nicht geladen werden.", + viewCommentsUnscoped: "Für den Filter dieser Ansicht können keine Kommentare aufgelistet werden.", + viewCommentsUnavailable: "Dieser Server kann die Kommentare einer Ansicht nicht auflisten.", + viewCommentsLoadMore: "Mehr laden", + viewCommentsOpenRecord: "{{name}} öffnen", commentResolveFailed: "Die Unterhaltung wurde nicht aktualisiert. Bitte versuchen Sie es erneut.", pinned: "Angeheftet", pin: "Anheften", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index b051ea53622..158e9fa7622 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1998,6 +1998,13 @@ const en = { noUnresolvedComments: "No unresolved comments", noCommentsInvolvingMe: "No comments you're part of", showAllComments: "Show all comments", + viewCommentsEmpty: "No comments on the records in this view", + viewCommentsDenied: "You don't have permission to view comments on this object.", + viewCommentsLoadFailed: "We couldn't load the comments for this view.", + viewCommentsUnscoped: "Comments can't be listed for this view's filter.", + viewCommentsUnavailable: "This server can't list the comments of a view.", + viewCommentsLoadMore: "Load more", + viewCommentsOpenRecord: "Open {{name}}", commentResolveFailed: "The thread was not updated. Please try again.", pinned: 'Pinned', pin: 'Pin', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 845344453a0..6f8250f9116 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1525,6 +1525,13 @@ const es = { noUnresolvedComments: "No hay comentarios sin resolver", noCommentsInvolvingMe: "No hay comentarios en los que participes", showAllComments: "Mostrar todos los comentarios", + viewCommentsEmpty: "No hay comentarios en los registros de esta vista", + viewCommentsDenied: "No tienes permiso para ver los comentarios de este objeto.", + viewCommentsLoadFailed: "No pudimos cargar los comentarios de esta vista.", + viewCommentsUnscoped: "No se pueden listar comentarios con el filtro de esta vista.", + viewCommentsUnavailable: "Este servidor no puede listar los comentarios de una vista.", + viewCommentsLoadMore: "Cargar más", + viewCommentsOpenRecord: "Abrir {{name}}", commentResolveFailed: "No se actualizó la conversación. Inténtalo de nuevo.", pinned: "Fijado", pin: "Fijar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ea5d3d55153..1cf730bb3ef 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1529,6 +1529,13 @@ const fr = { noUnresolvedComments: "Aucun commentaire non résolu", noCommentsInvolvingMe: "Aucun commentaire auquel vous participez", showAllComments: "Afficher tous les commentaires", + viewCommentsEmpty: "Aucun commentaire sur les enregistrements de cette vue", + viewCommentsDenied: "Vous n'avez pas l'autorisation de voir les commentaires de cet objet.", + viewCommentsLoadFailed: "Impossible de charger les commentaires de cette vue.", + viewCommentsUnscoped: "Impossible de lister les commentaires avec le filtre de cette vue.", + viewCommentsUnavailable: "Ce serveur ne peut pas lister les commentaires d'une vue.", + viewCommentsLoadMore: "Charger plus", + viewCommentsOpenRecord: "Ouvrir {{name}}", commentResolveFailed: "La discussion n'a pas été mise à jour. Veuillez réessayer.", pinned: "Épinglé", pin: "Épingler", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8caf4f8dbce..415bb7154ea 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1570,6 +1570,13 @@ const ja = { noUnresolvedComments: "未解決のコメントはありません", noCommentsInvolvingMe: "参加しているコメントはありません", showAllComments: "すべてのコメントを表示", + viewCommentsEmpty: "このビューのレコードにはコメントがありません", + viewCommentsDenied: "このオブジェクトのコメントを表示する権限がありません。", + viewCommentsLoadFailed: "このビューのコメントを読み込めませんでした。", + viewCommentsUnscoped: "このビューのフィルターではコメントを一覧表示できません。", + viewCommentsUnavailable: "このサーバーはビューのコメントを一覧表示できません。", + viewCommentsLoadMore: "さらに読み込む", + viewCommentsOpenRecord: "{{name}} を開く", commentResolveFailed: "スレッドを更新できませんでした。もう一度お試しください。", pinned: "ピン留め", pin: "ピン留め", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index bf13eb281ea..db5761ab9cd 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1486,6 +1486,13 @@ const ko = { noUnresolvedComments: "해결되지 않은 댓글이 없습니다", noCommentsInvolvingMe: "참여한 댓글이 없습니다", showAllComments: "모든 댓글 표시", + viewCommentsEmpty: "이 보기의 레코드에 댓글이 없습니다", + viewCommentsDenied: "이 개체의 댓글을 볼 권한이 없습니다.", + viewCommentsLoadFailed: "이 보기의 댓글을 불러오지 못했습니다.", + viewCommentsUnscoped: "이 보기의 필터로는 댓글을 나열할 수 없습니다.", + viewCommentsUnavailable: "이 서버는 보기의 댓글을 나열할 수 없습니다.", + viewCommentsLoadMore: "더 불러오기", + viewCommentsOpenRecord: "{{name}} 열기", commentResolveFailed: "스레드를 업데이트하지 못했습니다. 다시 시도해 주세요.", pinned: "고정됨", pin: "고정", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 4f109cfe5f1..13911c27adc 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1529,6 +1529,13 @@ const pt = { noUnresolvedComments: "Nenhum comentário não resolvido", noCommentsInvolvingMe: "Nenhum comentário em que você participa", showAllComments: "Mostrar todos os comentários", + viewCommentsEmpty: "Nenhum comentário nos registros desta visualização", + viewCommentsDenied: "Você não tem permissão para ver os comentários deste objeto.", + viewCommentsLoadFailed: "Não foi possível carregar os comentários desta visualização.", + viewCommentsUnscoped: "Não é possível listar comentários com o filtro desta visualização.", + viewCommentsUnavailable: "Este servidor não consegue listar os comentários de uma visualização.", + viewCommentsLoadMore: "Carregar mais", + viewCommentsOpenRecord: "Abrir {{name}}", commentResolveFailed: "A conversa não foi atualizada. Tente novamente.", pinned: "Fixado", pin: "Fixar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index b04824012fd..4e0e8877172 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1670,6 +1670,13 @@ const ru = { noUnresolvedComments: "Нет нерешённых комментариев", noCommentsInvolvingMe: "Нет комментариев с вашим участием", showAllComments: "Показать все комментарии", + viewCommentsEmpty: "Нет комментариев к записям этого представления", + viewCommentsDenied: "У вас нет прав на просмотр комментариев к этому объекту.", + viewCommentsLoadFailed: "Не удалось загрузить комментарии этого представления.", + viewCommentsUnscoped: "Невозможно вывести комментарии по фильтру этого представления.", + viewCommentsUnavailable: "Этот сервер не может вывести комментарии представления.", + viewCommentsLoadMore: "Загрузить ещё", + viewCommentsOpenRecord: "Открыть {{name}}", commentResolveFailed: "Обсуждение не обновлено. Попробуйте ещё раз.", pinned: "Закреплено", pin: "Закрепить", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c75d466e65f..6fdfc68a186 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1687,6 +1687,13 @@ const zh = { noUnresolvedComments: "没有未解决的评论", noCommentsInvolvingMe: "没有你参与的评论", showAllComments: "显示全部评论", + viewCommentsEmpty: "此视图的记录上暂无评论", + viewCommentsDenied: "你没有查看此对象评论的权限。", + viewCommentsLoadFailed: "无法加载此视图的评论。", + viewCommentsUnscoped: "无法按此视图的筛选条件列出评论。", + viewCommentsUnavailable: "此服务器无法列出视图的评论。", + viewCommentsLoadMore: "加载更多", + viewCommentsOpenRecord: "打开 {{name}}", commentResolveFailed: "操作没有保存,请重试。", pinned: '已置顶', pin: '置顶', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 3b2ea2ce56c..61aaf9878b0 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1687,6 +1687,13 @@ const zhHant = { noUnresolvedComments: "沒有未解決的評論", noCommentsInvolvingMe: "沒有你參與的評論", showAllComments: "顯示全部評論", + viewCommentsEmpty: "此檢視的記錄上暫無評論", + viewCommentsDenied: "你沒有檢視此物件評論的權限。", + viewCommentsLoadFailed: "無法載入此檢視的評論。", + viewCommentsUnscoped: "無法按此檢視的篩選條件列出評論。", + viewCommentsUnavailable: "此伺服器無法列出檢視的評論。", + viewCommentsLoadMore: "載入更多", + viewCommentsOpenRecord: "開啟 {{name}}", commentResolveFailed: "操作沒有儲存,請重試。", pinned: '已置頂', pin: '置頂', diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 58d25f6f501..ac34d4c542f 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -1111,6 +1111,37 @@ export function RecordCommentsSwitch() { } ``` +### The list page's comments column (`ViewCommentsPanel`) + +`ViewCommentsPanel` (objectstack#39085) is the comment threads of many +records, for a list page: a host reads them (the console through the data +source's `queryCommentThreads`, the platform's +`POST /api/v1/comments/threads/query`) and hands them in as +`ViewCommentThreadItem`s, newest first, with the state of that read. It is +presentational and reads no `DiscussionContext` of its own. + +- `threads`, `state` (`loading`, `ready`, `denied`, `failed`, `unscoped` for a + list filter that cannot be sent, `unavailable` for a server without the + read), `onRetry`. +- `filter` / `onFilterChange`: the same `CommentsFilterMenu` as the record's + panel. Not drawn for `denied`, `unscoped` or `unavailable`. +- `hasMore`, `loadingMore`, `loadMoreFailed`, `onLoadMore`: 「加载更多」, which + says Retry after a failed page. +- `objectIcon` and `onOpenRecord(recordId)`: the record row of each card; its + name is a button that opens the record and expands nothing. +- `expandedIds`, `onExpand(id)` and `renderExpanded(thread)`: the card, or its + 「N 条回复」, asks to expand; an expanded card draws whatever the host + renders for it under the record row. The console renders the record's live + discussion there, a `DiscussionContextProvider` around `CommentThread + mode="expand"`, so its actions are the record page's. +- `mentionLabels`: names the cards highlight whole (`@Anna Lee`), longest + first; any other `@word` after a space is highlighted as one word. + `splitCommentMentions(text, labels)` is that cut, exported for other + surfaces. +- `onClose`: ✕, and Esc inside the column. + +There is no comment box: a new thread starts on the record. + ## Reference Rail on an authored page The "Reference Rail" is a right-hand column of summary cards for related diff --git a/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.test.tsx b/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.test.tsx new file mode 100644 index 00000000000..ebeb4bc5819 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.test.tsx @@ -0,0 +1,235 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#39085 — the list page's comments column, the panel the host + * fills: + * + * - 「评论」, the filter menu and ✕ at the top; ✕ and Esc close it. + * - One card per thread: the object's icon and the record's name (which opens + * the record and expands nothing), the first comment's author and text with + * its mentions highlighted, and 「N 条回复」 with the repliers' faces. + * - The comment, or 「N 条回复」, expands the thread in place, drawn by the + * host; no box for a new thread anywhere. + * - 「加载更多」 pages the list, and asks again after a failed page. + * - Loading, empty, filtered-empty with 「显示全部」, refused, failed with a + * retry, cannot-scope and unavailable each say so; the three that read + * nothing offer no filter menu. + * + * And `splitCommentMentions`, which cuts a comment's text for the highlight. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; +import type { FeedItem } from '@object-ui/types'; +import { ViewCommentsPanel, type ViewCommentsPanelProps, type ViewCommentThreadItem } from './ViewCommentsPanel'; +import { splitCommentMentions } from './commentMentions'; +import { DEFAULT_COMMENT_THREAD_FILTER } from './commentThreads'; + +afterEach(() => cleanup()); + +const at = (minute: number) => new Date(Date.UTC(2026, 11, 2, 9, minute)).toISOString(); + +function thread(id: string, over: Partial & { body?: string; actor?: string } = {}): ViewCommentThreadItem { + const comment: FeedItem = { id, type: 'comment', actor: over.actor ?? 'Ada Lovelace', body: over.body ?? `comment ${id}`, createdAt: at(1) }; + return { + id, + recordId: `rec-${id}`, + recordName: `Record ${id}`, + comment, + replyCount: 0, + repliers: [], + ...over, + }; +} + +function renderPanel(props: Partial = {}) { + const handlers = { + onFilterChange: vi.fn(), + onClose: vi.fn(), + onOpenRecord: vi.fn(), + onExpand: vi.fn(), + onRetry: vi.fn(), + onLoadMore: vi.fn(), + renderExpanded: vi.fn((t: ViewCommentThreadItem) =>
live thread
), + }; + const utils = render( + , + ); + return { ...handlers, ...utils }; +} + +const panel = () => document.querySelector('[data-view-comments-panel]') as HTMLElement; + +describe('objectstack#39085 — ViewCommentsPanel', () => { + it('draws one card per thread: the record, the first comment with its mention, the replies and their faces', () => { + renderPanel({ + threads: [ + thread('c1', { + body: '@Grace Hopper please check', + replyCount: 3, + repliers: [{ id: 'u2', name: 'Grace Hopper' }, { id: 'u3', name: 'Linus' }], + }), + thread('c2'), + ], + objectIcon: , + mentionLabels: ['Grace Hopper'], + }); + + const cards = document.querySelectorAll('[data-view-comment-card]'); + expect(cards).toHaveLength(2); + const first = cards[0] as HTMLElement; + expect(within(first).getByTestId('object-icon')).toBeInTheDocument(); + expect(within(first).getByText('Record c1')).toBeInTheDocument(); + expect(within(first).getByText('Ada Lovelace')).toBeInTheDocument(); + const mention = first.querySelector('[data-comment-mention]'); + expect(mention?.textContent).toBe('@Grace Hopper'); + const summary = first.querySelector('[data-comment-replies-summary]') as HTMLElement; + expect(summary.textContent).toMatch(/3/); + // No box for a new thread. + expect(panel().querySelector('textarea')).toBeNull(); + // The second thread has no replies: no summary. + expect((cards[1] as HTMLElement).querySelector('[data-comment-replies-summary]')).toBeNull(); + }); + + it('opens the record from its name without expanding, and expands the thread from the comment or its replies', () => { + const { onOpenRecord, onExpand } = renderPanel({ + threads: [thread('c1', { replyCount: 1, repliers: [{ id: 'u2', name: 'Grace' }] })], + }); + + fireEvent.click(document.querySelector('[data-view-comment-open-record]') as HTMLElement); + expect(onOpenRecord).toHaveBeenCalledWith('rec-c1'); + expect(onExpand).not.toHaveBeenCalled(); + + fireEvent.click(document.querySelector('[data-view-comment-expand]') as HTMLElement); + fireEvent.click(document.querySelector('[data-comment-replies-summary]') as HTMLElement); + expect(onExpand).toHaveBeenCalledTimes(2); + expect(onExpand).toHaveBeenCalledWith('c1'); + }); + + it('draws an expanded thread through the host, under the record row', () => { + const { renderExpanded } = renderPanel({ threads: [thread('c1'), thread('c2')], expandedIds: new Set(['c2']) }); + + expect(screen.getByTestId('live-c2')).toBeInTheDocument(); + expect(screen.queryByTestId('live-c1')).toBeNull(); + expect(renderExpanded).toHaveBeenCalledWith(expect.objectContaining({ id: 'c2' })); + const expanded = document.querySelector('[data-view-comment-expanded="true"]') as HTMLElement; + expect(within(expanded).getByText('Record c2')).toBeInTheDocument(); + }); + + it('closes on ✕ and on Esc inside it', () => { + const { onClose } = renderPanel({ threads: [thread('c1')] }); + + fireEvent.click(document.querySelector('[data-comments-panel-close]') as HTMLElement); + fireEvent.keyDown(document.querySelector('[data-view-comment-expand]') as HTMLElement, { key: 'Escape' }); + expect(onClose).toHaveBeenCalledTimes(2); + }); + + it('pages the list with load more, and asks again after a failed page', () => { + const { onLoadMore, rerender } = renderPanel({ threads: [thread('c1')], hasMore: true }); + + const more = document.querySelector('[data-view-comments-load-more]') as HTMLElement; + expect(more).toHaveTextContent('Load more'); + fireEvent.click(more); + expect(onLoadMore).toHaveBeenCalledTimes(1); + + rerender( + null} + onLoadMore={onLoadMore} + loadMoreFailed + />, + ); + expect(document.querySelector('[data-view-comments-load-more]')).toHaveTextContent('Retry'); + }); + + it('says the filter hides everything and offers all threads', () => { + const { onFilterChange } = renderPanel({ threads: [], filter: { showResolved: false, onlyMine: true } }); + + expect(document.querySelector('[data-comments-empty="filtered"]')).toBeInTheDocument(); + fireEvent.click(document.querySelector('[data-comments-show-all]') as HTMLElement); + expect(onFilterChange).toHaveBeenCalledWith({ showResolved: true, onlyMine: false }); + }); + + it('says the view has no comments when nothing is filtered out', () => { + renderPanel({ threads: [], filter: { showResolved: true, onlyMine: false } }); + + expect(document.querySelector('[data-comments-empty=""]')).toHaveTextContent('No comments on the records in this view'); + }); + + it('draws loading, and a failed read with a retry', () => { + const { onRetry, rerender } = renderPanel({ state: 'loading' }); + expect(panel().getAttribute('data-view-comments-state')).toBe('loading'); + expect(screen.getByRole('status')).toBeInTheDocument(); + + rerender( + null} + onRetry={onRetry} + />, + ); + expect(document.querySelector('[data-comments-note="failed"]')).toHaveTextContent("We couldn't load the comments for this view."); + fireEvent.click(document.querySelector('[data-view-comments-retry]') as HTMLElement); + expect(onRetry).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['denied', "You don't have permission to view comments on this object."], + ['unscoped', "Comments can't be listed for this view's filter."], + ['unavailable', "This server can't list the comments of a view."], + ] as const)('says %s and offers no filter menu', (state, text) => { + renderPanel({ state, threads: [thread('c1')] }); + + expect(document.querySelector(`[data-comments-note="${state}"]`)).toHaveTextContent(text); + expect(document.querySelector('[data-view-comment-card]')).toBeNull(); + expect(panel().querySelector('[data-comments-filter]')).toBeNull(); + }); +}); + +describe('objectstack#39085 — splitCommentMentions', () => { + it('marks a known name whole, longest first, and a bare @word otherwise', () => { + expect(splitCommentMentions('hi @Anna Lee and @bob.', ['Anna', 'Anna Lee'])).toEqual([ + { text: 'hi ', mention: false }, + { text: '@Anna Lee', mention: true }, + { text: ' and ', mention: false }, + { text: '@bob', mention: true }, + { text: '.', mention: false }, + ]); + }); + + it('leaves an address and a name run into a word as text', () => { + expect(splitCommentMentions('mail a@b.com', ['b'])).toEqual([{ text: 'mail a@b.com', mention: false }]); + expect(splitCommentMentions('@Annabel', ['Anna'])).toEqual([{ text: '@Annabel', mention: true }]); + }); + + it('answers nothing for no text and the text alone with no @', () => { + expect(splitCommentMentions('')).toEqual([]); + expect(splitCommentMentions('plain')).toEqual([{ text: 'plain', mention: false }]); + }); +}); diff --git a/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.tsx b/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.tsx new file mode 100644 index 00000000000..cba6f344cc3 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/ViewCommentsPanel.tsx @@ -0,0 +1,392 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import * as React from 'react'; +import { Button, cn } from '@object-ui/components'; +import { useDisplayLocale } from '@object-ui/i18n'; +import { Check, Loader2, MessageSquare, X } from 'lucide-react'; +import type { FeedItem } from '@object-ui/types'; +import { useDetailTranslation } from '../useDetailTranslation'; +import { CommentAuthorAvatar } from '../CommentAuthorAvatar'; +import { CommentsFilterMenu } from './CommentsFilterMenu'; +import type { CommentThreadFilter } from './commentThreads'; +import { formatCommentTime } from './commentTime'; +import { splitCommentMentions } from './commentMentions'; + +/** One person who replied in a thread, as the threads read names them. */ +export interface ViewCommentReplier { + id: string; + name: string; + avatarUrl?: string; +} + +/** One thread on a card of the list page's comments column. */ +export interface ViewCommentThreadItem { + /** The thread's top-level comment id. */ + id: string; + /** The record the thread is on. */ + recordId: string; + /** The record's display name, as the server names it to the reader. */ + recordName: string; + /** The thread's top-level comment, as a feed item. */ + comment: FeedItem; + /** How many replies the thread has, as the reader may read them. */ + replyCount: number; + /** The latest distinct repliers, newest first. */ + repliers: ViewCommentReplier[]; +} + +/** + * Where the column's read stands. + * + * - `loading`: the first page is on its way. + * - `ready`: the threads are the answer (none is the empty state). + * - `denied`: the server refused the read to this reader. + * - `failed`: the read failed (5xx, network); `onRetry` reads it again. + * - `unscoped`: the list's filter cannot be sent as a scope, so nothing is + * read rather than every record's threads. + * - `unavailable`: the server does not answer the threads read. + */ +export type ViewCommentsState = 'loading' | 'ready' | 'denied' | 'failed' | 'unscoped' | 'unavailable'; + +export interface ViewCommentsPanelProps { + /** The threads read so far, newest first. */ + threads: readonly ViewCommentThreadItem[]; + state: ViewCommentsState; + /** The column's filter menu: 「显示已解决」 (off by default) and 「只看我参与的」. */ + filter: CommentThreadFilter; + onFilterChange: React.Dispatch>; + onRetry?: () => void; + /** More threads are there to read. */ + hasMore?: boolean; + /** The next page is on its way. */ + loadingMore?: boolean; + /** The last next-page read failed: the load-more control asks again. */ + loadMoreFailed?: boolean; + onLoadMore?: () => void; + /** Closes the column (its ✕, and Esc while focus is inside it). */ + onClose?: () => void; + /** The object's icon, drawn on every card. */ + objectIcon?: React.ReactNode; + /** Opens a record the way the list opens it. */ + onOpenRecord?: (recordId: string) => void; + /** The threads expanded in place, by id. */ + expandedIds: ReadonlySet; + /** Expands a thread in place. */ + onExpand: (id: string) => void; + /** + * Draws an expanded thread: its comment, replies and reply box, with the + * record page's actions. The host reads the record's discussion for it. + */ + renderExpanded: (thread: ViewCommentThreadItem) => React.ReactNode; + /** Names the cards may mention, highlighted as one `@` name each. */ + mentionLabels?: readonly string[]; + className?: string; +} + +/** + * The list page's comments column (objectstack#39085): the comment threads on + * the records the list's filter selects, newest first, one card per thread, + * read a page at a time. A card names its record (which opens it), the + * thread's first comment and 「N 条回复」; pressing it expands the thread in + * place, where it is replied to, resolved, reacted to, edited and deleted as + * on the record page. There is no box for a new thread here. + * + * Presentational: the host reads the threads and hands them in, with the + * state of that read and the live thread for each expanded card. + */ +export const ViewCommentsPanel: React.FC = ({ + threads, + state, + filter, + onFilterChange, + onRetry, + hasMore = false, + loadingMore = false, + loadMoreFailed = false, + onLoadMore, + onClose, + objectIcon, + onOpenRecord, + expandedIds, + onExpand, + renderExpanded, + mentionLabels, + className, +}) => { + const { t } = useDetailTranslation(); + const title = t('detail.comments'); + const filtering = filter.onlyMine || !filter.showResolved; + + let body: React.ReactNode; + if (state === 'denied') { + body = ; + } else if (state === 'unscoped') { + body = ; + } else if (state === 'unavailable') { + body = ; + } else if (state === 'failed') { + body = ( + + {onRetry && ( + + )} + + ); + } else if (state === 'loading') { + body = ( +
+ +
+ ); + } else if (threads.length === 0 && filtering) { + // The filter hides what there is, or there is nothing: say what the + // filter asked, and offer every thread. + body = ( +
+

+ {filter.onlyMine ? t('detail.noCommentsInvolvingMe') : t('detail.noUnresolvedComments')} +

+ +
+ ); + } else if (threads.length === 0) { + body = ( +
+
+ ); + } else { + body = ( + <> +
    + {threads.map((thread) => ( +
  • + onExpand(thread.id)} + renderExpanded={renderExpanded} + mentionLabels={mentionLabels} + /> +
  • + ))} +
+ {(hasMore || loadMoreFailed) && onLoadMore && ( +
+ +
+ )} + + ); + } + + return ( +
{ + if (e.key !== 'Escape' || !onClose) return; + // A layer opened from here (a menu, the emoji picker) is portaled out + // and closes on its own Esc; a field inside that takes the key (the + // mention list, the inline editor) stops it before it gets here. + if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return; + e.stopPropagation(); + onClose(); + }} + data-view-comments-panel="" + data-view-comments-state={state} + data-owns-escape="" + > +
+

{title}

+
+ {state !== 'denied' && state !== 'unscoped' && state !== 'unavailable' && ( + + )} + {onClose && ( + + )} +
+
+
+ {body} +
+
+ ); +}; + +interface ViewCommentCardProps { + thread: ViewCommentThreadItem; + objectIcon?: React.ReactNode; + onOpenRecord?: (recordId: string) => void; + expanded: boolean; + onExpand: () => void; + renderExpanded: (thread: ViewCommentThreadItem) => React.ReactNode; + mentionLabels?: readonly string[]; +} + +/** + * One thread's card: the object's icon and the record's name, then the + * thread's first comment (its author, when, the text with its mentions + * highlighted) and 「N 条回复」 with the latest repliers' faces. The comment, + * or 「N 条回复」, expands the thread in place; the record's name opens the + * record and expands nothing. + */ +const ViewCommentCard: React.FC = ({ + thread, + objectIcon, + onOpenRecord, + expanded, + onExpand, + renderExpanded, + mentionLabels, +}) => { + const { t } = useDetailTranslation(); + const locale = useDisplayLocale(); + const { comment, recordName, replyCount, repliers } = thread; + const resolved = comment.resolved === true; + const recordLabel = t('detail.viewCommentsOpenRecord', { name: recordName }); + const recordRow = ( +
+ {objectIcon && {objectIcon}} + {onOpenRecord ? ( + + ) : ( + {recordName} + )} + {resolved && ( + + + )} +
+ ); + + if (expanded) { + return ( +
+ {recordRow} + {renderExpanded(thread)} +
+ ); + } + + const parts = splitCommentMentions(comment.body ?? '', mentionLabels); + return ( +
+ {recordRow} + + {replyCount > 0 && ( + + )} +
+ ); +}; + +const ColumnNote: React.FC<{ kind: Exclude; text: string; children?: React.ReactNode }> = ({ + kind, + text, + children, +}) => ( +
+

{text}

+ {children} +
+); diff --git a/ui/packages/plugin-detail/src/comments/commentMentions.ts b/ui/packages/plugin-detail/src/comments/commentMentions.ts new file mode 100644 index 00000000000..e5ed516b2af --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/commentMentions.ts @@ -0,0 +1,46 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** One run of a comment's text: plain, or an `@` mention to highlight. */ +export interface CommentTextPart { + text: string; + mention: boolean; +} + +const LABEL_ESCAPE = /[.*+?^${}()|[\]\\]/g; + +/** + * A comment's text cut into plain runs and `@` mentions (objectstack#39085: + * the list page's comment cards highlight who a comment names). + * + * A mention is `@` and a name this surface knows (`labels`: the people it + * draws, longest first, so 「@Anna Lee」 wins over 「@Anna」), not followed by + * a letter, digit or `_`; else `@` and the word after it (a trailing `.` or + * `-` ends the sentence, not the name). Only an `@` at the + * start of the text or after a space starts a mention, so an address such as + * `a@b.com` stays text. + */ +export function splitCommentMentions(text: string, labels: readonly string[] = []): CommentTextPart[] { + if (!text.includes('@')) return text ? [{ text, mention: false }] : []; + const known = [...new Set(labels.filter((label) => label.trim() !== ''))] + .sort((a, b) => b.length - a.length) + .map((label) => label.replace(LABEL_ESCAPE, '\\$&')); + const word = '[\\p{L}\\p{N}_](?:[\\p{L}\\p{N}_.-]*[\\p{L}\\p{N}_])?'; + const name = known.length > 0 ? `(?:${known.join('|')})(?![\\p{L}\\p{N}_])|${word}` : word; + const re = new RegExp(`(^|\\s)(@(?:${name}))`, 'gu'); + const parts: CommentTextPart[] = []; + let last = 0; + for (const match of text.matchAll(re)) { + const start = (match.index ?? 0) + match[1].length; + if (start > last) parts.push({ text: text.slice(last, start), mention: false }); + parts.push({ text: match[2], mention: true }); + last = start + match[2].length; + } + if (last < text.length) parts.push({ text: text.slice(last), mention: false }); + return parts; +} diff --git a/ui/packages/plugin-detail/src/comments/index.ts b/ui/packages/plugin-detail/src/comments/index.ts index 172511d081a..f5f9da0d58d 100644 --- a/ui/packages/plugin-detail/src/comments/index.ts +++ b/ui/packages/plugin-detail/src/comments/index.ts @@ -47,4 +47,14 @@ export { CommentsButton, type CommentsButtonProps } from './CommentsButton'; export { CommentsFilterMenu, type CommentsFilterMenuProps } from './CommentsFilterMenu'; export { CommentActionSheet, type CommentActionSheetProps } from './CommentActionSheet'; export { CommentsPage, type CommentsPageProps } from './CommentsPage'; +// objectstack#39085 — the list page's comments column: the threads on the +// records a list's filter selects, one card each, expanded in place. +export { + ViewCommentsPanel, + type ViewCommentsPanelProps, + type ViewCommentsState, + type ViewCommentThreadItem, + type ViewCommentReplier, +} from './ViewCommentsPanel'; +export { splitCommentMentions, type CommentTextPart } from './commentMentions'; export { useCommentPress, COMMENT_LONG_PRESS_MS, COMMENT_PRESS_SLOP, type CommentPress, type CommentPressOptions } from './useCommentPress'; diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 4fdbd5a09f4..a4fe68e4208 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -325,6 +325,9 @@ export { CommentsPanel, CommentsButton, CommentsPage, + // objectstack#39085 — the list page's comments column. + ViewCommentsPanel, + splitCommentMentions, } from './comments'; export type { RecordCommentsData, @@ -341,6 +344,11 @@ export type { CommentsPanelProps, CommentsButtonProps, CommentsPageProps, + ViewCommentsPanelProps, + ViewCommentsState, + ViewCommentThreadItem, + ViewCommentReplier, + CommentTextPart, } from './comments'; // objectstack#27055 — the reader's arrangement of the related cards: the pure // merge rule and the stored record's codec halves, for the host's diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index 8394e49ad92..e805f50919a 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -181,6 +181,14 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.noUnresolvedComments': "No unresolved comments", 'detail.noCommentsInvolvingMe': "No comments you're part of", 'detail.showAllComments': "Show all comments", + // objectstack#39085 — the list page's comments column. + 'detail.viewCommentsEmpty': "No comments on the records in this view", + 'detail.viewCommentsDenied': "You don't have permission to view comments on this object.", + 'detail.viewCommentsLoadFailed': "We couldn't load the comments for this view.", + 'detail.viewCommentsUnscoped': "Comments can't be listed for this view's filter.", + 'detail.viewCommentsUnavailable': "This server can't list the comments of a view.", + 'detail.viewCommentsLoadMore': "Load more", + 'detail.viewCommentsOpenRecord': "Open {{name}}", 'detail.commentResolveFailed': "The thread was not updated. Please try again.", 'detail.pinned': 'Pinned', 'detail.pin': 'Pin', diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index a9aa37b45da..082160541b8 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -239,6 +239,24 @@ Without it every row is unchanged. The console uses it on Setup → Users on a cloud-managed environment, to mark a user who holds no permission set beyond the baseline. +### Host prop: `onEffectiveFilterChange` + +A host that reads past the rows on show with the list's own scope passes +`onEffectiveFilterChange`. The list calls it with the filter it applies: the +view's `filter`, the Filter panel's conditions, the filter bar's choices and a +queue's conditions, ANDed exactly as its own read sends them as `$filter` +(`{ kind: 'filter', filter }`, `filter` `undefined` when nothing narrows the +list). It reports on every layout, a grid, a board or a calendar alike, unlike +`onFindParamsChange`, which a board answers with `null`. The search box is not +a filter and is not in it, nor is a calendar's date window. A filter the list +cannot lower (a malformed authored filter) is reported as +`{ kind: 'unlowerable' }`, never as no filter, so a host never widens its read +to every record. It is called once the object's definition has loaded and then +only when the filter changes by content; nothing is built while the prop is +absent. It is a React prop for the host app, not a schema key. The console's +list page passes it while its comments column is open (objectstack#39085), to +read the comment threads of the records the list scopes. + ### Host prop: `rowOpensRecord` A host whose `onRowClick` opens nothing for these rows passes diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index be0f1962a2e..88aaf2f695a 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -58,6 +58,7 @@ import { type CalendarVisibleRange, type CalendarWindow, } from './calendarWindow'; +import { useListEffectiveFilterReport, type ListEffectiveFilter } from './listEffectiveFilter'; import { SchemaRenderer, useNavigationOverlay, classifyLoadError, answeredLoadFailure, isPermissionError, usePredicateScope, useDataInvalidation, useFilterScope, useResolvedFilter, NonGridRowCeilingNote, OwnWritesContext, createOwnWrites } from '@object-ui/react'; import type { LoadErrorKind, AnsweredLoadFailure } from '@object-ui/react'; import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; @@ -780,6 +781,18 @@ export interface ListViewProps { * A HOST prop, never a schema key: the query is the list's runtime state. */ onFindParamsChange?: (findParams: Readonly> | null) => void; + /** + * Called with the list's effective filter — the saved view's filter AND the + * reader's filter panel AND filter bar, the node this list's fetch sends as + * `$filter`, never the search box — each time it changes by content, on + * every layout (objectstack#39085). A host that reads past the rows with + * the list's own scope keys on it: the list page's comments column reads + * the threads on exactly the records this filter selects. `unlowerable` + * when the list cannot build one; see {@link ListEffectiveFilter}. + * + * A HOST prop, never a schema key: the filter is the list's runtime state. + */ + onEffectiveFilterChange?: (report: ListEffectiveFilter) => void; /** * The page a paged grid shows, 1-based, for a host that keeps it * (objectstack#30850): the console keeps it in the address, so Back from a @@ -2473,6 +2486,7 @@ export const ListView = React.forwardRef(({ onTotalChange, onRowsChange, onFindParamsChange, + onEffectiveFilterChange, viewDefaults, onRestoreViewDefaults, onPersonalizationChange, @@ -3292,6 +3306,14 @@ export const ListView = React.forwardRef(({ ? QUEUE_SITTING_CONDITIONS : NO_QUEUE_SITTING_CONDITIONS; + // objectstack#39085 — the effective filter, told to a host that asks + // (`listEffectiveFilter.ts`): the node the fetch sends, on every layout. + useListEffectiveFilterReport( + onEffectiveFilterChange, + () => buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, queryDropFields), + objectDefLoaded, + ); + /** * objectstack#34807 — the draft-only fields a sort or filter on this list * names, each left out of the request (`serverSort`, `buildEffectiveFilter`) diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index a6ab7d0642c..5061e2b6aa5 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -1559,6 +1559,106 @@ describe('ListView.onFindParamsChange-36554', () => { }); }); +// ── ListView.onEffectiveFilterChange-39085 ─────────────────────────────────── + +/** + * objectstack#39085 — the list tells its host the filter it applies, for the + * list page's comments column: the saved view's filter AND the reader's + * choices, exactly the `$filter` its own read sends, on a grid and on a board + * alike (a board answers `onFindParamsChange` with `null`). The search box is + * not in it. A filter the list cannot lower is reported as such, never as no + * filter. + */ +describe('ListView.onEffectiveFilterChange-39085', () => { + restoreAfterBlock(); + + const OBJECT = 'crm_lead'; + const objectDef = { + name: OBJECT, + label: 'Lead', + fields: { + id: { name: 'id', type: 'text' }, + name: { name: 'name', type: 'text', label: 'Name' }, + status: { + name: 'status', type: 'select', label: 'Status', + options: [{ value: 'new', label: 'New' }, { value: 'won', label: 'Won' }], + }, + }, + }; + const ROWS = [ + { id: 'l_3', name: 'Mira Costa', status: 'new' }, + { id: 'l_1', name: 'Kai Watanabe', status: 'won' }, + ]; + + function mount(schemaExtra: Record, props: Record = {}) { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: 2 })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async (name: string) => (name === OBJECT ? objectDef : null)), + } as any; + const onEffectiveFilterChange = vi.fn(); + render( + + + , + ); + return { dataSource, onEffectiveFilterChange }; + } + + afterEach(() => cleanup()); + + it('a grid reports the $filter its own read sends, once', async () => { + const { dataSource, onEffectiveFilterChange } = mount({ viewType: 'grid', filter: [['status', '=', 'new']] }); + await waitFor(() => expect(dataSource.find).toHaveBeenCalled()); + await waitFor(() => expect(onEffectiveFilterChange).toHaveBeenCalled()); + const report = onEffectiveFilterChange.mock.calls.at(-1)?.[0]; + expect(report.kind).toBe('filter'); + expect(report.filter).toEqual(dataSource.find.mock.calls.at(-1)?.[1].$filter); + expect(JSON.stringify(report.filter)).toContain('new'); + // A re-render with an equal filter is no change. + expect(onEffectiveFilterChange).toHaveBeenCalledTimes(1); + }); + + it('a board reports its filter too', async () => { + const { onEffectiveFilterChange } = mount({ + viewType: 'kanban', + filter: [['status', '=', 'won']], + options: { kanban: { groupBy: 'status' } }, + }); + await waitFor(() => expect(onEffectiveFilterChange).toHaveBeenCalled()); + const report = onEffectiveFilterChange.mock.calls.at(-1)?.[0]; + expect(report.kind).toBe('filter'); + expect(JSON.stringify(report.filter)).toContain('won'); + }); + + it('leaves the search term out', async () => { + const { dataSource, onEffectiveFilterChange } = mount( + { viewType: 'grid', filter: [['status', '=', 'new']] }, + { initialSearchTerm: 'Mira' }, + ); + await waitFor(() => expect(dataSource.find).toHaveBeenCalled()); + await waitFor(() => expect(onEffectiveFilterChange).toHaveBeenCalled()); + const report = onEffectiveFilterChange.mock.calls.at(-1)?.[0]; + expect(report.kind).toBe('filter'); + expect(JSON.stringify(report.filter)).toContain('new'); + expect(JSON.stringify(report.filter)).not.toContain('Mira'); + }); + + it('reports a filter it cannot lower as unlowerable, never as no filter', async () => { + const { onEffectiveFilterChange } = mount({ viewType: 'grid', filter: { name: { $regex: '^A' } } }); + await waitFor(() => expect(onEffectiveFilterChange).toHaveBeenCalled()); + expect(onEffectiveFilterChange.mock.calls.map(([report]) => report)).toEqual([{ kind: 'unlowerable' }]); + }); +}); + // ── ListView.printButtonSemantics ──────────────────────────────────────────── /** diff --git a/ui/packages/plugin-list/src/index.tsx b/ui/packages/plugin-list/src/index.tsx index beb40dc1b53..7117a11c31f 100644 --- a/ui/packages/plugin-list/src/index.tsx +++ b/ui/packages/plugin-list/src/index.tsx @@ -37,6 +37,8 @@ export type { ConditionCandidateField } from './ListView'; // compare it against the `en` pack from a package that depends on both. export { LIST_DEFAULT_TRANSLATIONS } from './ListView'; export type { ListViewProps, ListViewHandle, ListViewRowGroup, ListExportDoor, ListToolbarTrailingState } from './ListView'; +// objectstack#39085 — what `onEffectiveFilterChange` tells a host. +export type { ListEffectiveFilter } from './listEffectiveFilter'; export type { ObjectGalleryProps } from './ObjectGallery'; // The switcher's views are `@object-ui/core`'s `ListViewVisualization`. This // barrel no longer re-exports them as `ViewType`, the name `@object-ui/types` diff --git a/ui/packages/plugin-list/src/listEffectiveFilter.ts b/ui/packages/plugin-list/src/listEffectiveFilter.ts new file mode 100644 index 00000000000..021cef29994 --- /dev/null +++ b/ui/packages/plugin-list/src/listEffectiveFilter.ts @@ -0,0 +1,77 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The list's effective filter, told to its host (objectstack#39085): the + * saved view's filter AND the reader's filter panel AND the filter bar's + * choices, exactly the node the list's own fetch sends as `$filter`, for + * every layout — a grid, a board, a calendar alike. A host that reads past + * the rows on show with the same scope (the list page's comments column) + * keys its read on it. + * + * The search box is not a filter and is not in it: a host that wants the + * term has `onFindParamsChange`, which a board answers `null` to. + */ + +import * as React from 'react'; +import { FilterOperatorError } from '@object-ui/core'; + +/** + * What the list tells its host about the filter it applies. + * + * - `filter`: the effective filter node, or `undefined` when nothing narrows + * the list (every record the reader may read). + * - `unlowerable`: the list cannot build a filter from what it holds (a + * malformed authored filter, an operator the lowering refuses). The list + * raises its own load error; a host that reads with the list's scope must + * not read without it, which would widen its answer to every record. + */ +export type ListEffectiveFilter = + | { kind: 'filter'; filter: unknown } + | { kind: 'unlowerable' }; + +const UNLOWERABLE: ListEffectiveFilter = { kind: 'unlowerable' }; + +/** + * Builds the effective filter and tells `onChange` each time it changes, by + * content: an equal filter in a new object is not a change (AGENTS.md #10). + * Nothing is built while no host listens, and nothing is told before + * `settled` (the object definition the filter's draft-only and withheld + * fields are read from has loaded), so a host is never told a filter the + * list does not send. + */ +export function useListEffectiveFilterReport( + onChange: ((report: ListEffectiveFilter) => void) | undefined, + build: () => unknown, + settled: boolean, +): void { + let report: ListEffectiveFilter | null = null; + let key: string | null = null; + if (onChange && settled) { + try { + const filter = build(); + report = { kind: 'filter', filter }; + key = JSON.stringify(['filter', filter ?? null]); + } catch (error) { + if (!(error instanceof FilterOperatorError)) throw error; + report = UNLOWERABLE; + key = '["unlowerable"]'; + } + } + const reportRef = React.useRef(report); + reportRef.current = report; + const onChangeRef = React.useRef(onChange); + React.useEffect(() => { + onChangeRef.current = onChange; + }); + React.useEffect(() => { + const current = reportRef.current; + if (key === null || !current) return; + onChangeRef.current?.(current); + }, [key]); +} diff --git a/ui/packages/types/src/data.ts b/ui/packages/types/src/data.ts index a259c34faaf..7d3282cd702 100644 --- a/ui/packages/types/src/data.ts +++ b/ui/packages/types/src/data.ts @@ -21,6 +21,8 @@ // is what makes the claim true, and what makes a spec change break the build // instead of drifting quietly. import type { + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, ImportJobStatus, ImportRowResult, ImportWriteMode, @@ -385,6 +387,13 @@ export interface RecordFieldAccess { /** A record-grained operation a record page's header asks a verdict for. */ export type RecordPageOperation = RecordPageExplainOperation; +// The comment threads read a list page's comments column asks +// (`POST /api/v1/comments/threads/query`, objectstack#39085): the spec's shapes. +export type { + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, +} from '@objectstack/spec/api'; + // What a record page asks when it opens (`POST /data/{object}/{id}/page`) and // the refusal a replaced read answers are the spec's own shapes. export type { @@ -760,6 +769,27 @@ export interface DataSource { */ prefetchRecordPage?(resource: string, id: string, request: RecordPageRequest): void; + /** + * One page of the comment threads on the records a list filter selects + * (objectstack#39085): `POST /api/v1/comments/threads/query`, its request + * and answer the spec's `CommentThreadsQueryRequest` / + * `CommentThreadsQueryResponse`. The object's own read plans the records, + * as the caller, from the filter the request carries — any filter `find` + * takes as `$filter`, which the source normalises exactly as `find` does, + * so one stored filter selects the same records on both reads — and the + * answer names no thread on a record the caller cannot open. + * + * A refused or failed read is thrown, as a read's: the caller tells a + * server that does not mount the route (`404`, `501`) and a filter it + * cannot lower (`400`) from a refusal (`401` / `403`) and a failure. + * + * Optional, and presence is the capability: a list page offers its + * comments column only over a data source that declares it. A source that + * cannot plan the caller's read leaves it undeclared rather than answer + * part of the view. + */ + queryCommentThreads?(request: CommentThreadsQueryRequest): Promise; + /** * Get object schema/metadata. * Used by ObjectQL-aware components to auto-generate UI from object metadata. diff --git a/ui/packages/types/src/index.ts b/ui/packages/types/src/index.ts index 456c38405f3..ad2b9b09a0f 100644 --- a/ui/packages/types/src/index.ts +++ b/ui/packages/types/src/index.ts @@ -463,6 +463,8 @@ export type { RecordPageRequest, RecordPagePartRefusal, RecordPagePayload, + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, GlobalSearchHit, GlobalSearchResult, BatchRef,