Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e97dab74f5
|
||
|
|
c8f79847f3
|
||
|
|
4d28309be7
|
||
|
|
13abaa795d
|
||
|
|
2f556afadf
|
||
|
|
dce92cfba1
|
||
|
|
8d372142f8
|
||
|
|
0f0ebc524f
|
||
|
|
dad2a79824
|
||
|
|
de5c1bd066
|
No files matched your search
@@ -6,5 +6,3 @@ playwright-report
|
||||
coverage
|
||||
.env*
|
||||
*.log
|
||||
|
||||
.pnpm-store
|
||||
@@ -1 +0,0 @@
|
||||
dynamic-components/** -text
|
||||
@@ -1,13 +0,0 @@
|
||||
# Copyright 2026 QRun.IO, Inc.
|
||||
# Licensed under the Apache License, Version 2.0.
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
jobs:
|
||||
maven:
|
||||
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
|
||||
secrets: inherit
|
||||
with:
|
||||
node-version: '22.20.0'
|
||||
prebuild: corepack enable && pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint && pnpm test && pnpm build:export
|
||||
@@ -24,11 +24,11 @@ jobs:
|
||||
ci:
|
||||
if: (github.event_name == 'pull_request' && !contains(fromJSON('["labeled","unlabeled"]'),
|
||||
github.event.action)) || (github.event_name == 'push' && github.ref == 'refs/heads/main')
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-ci.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-ci.yml@eeb76914ad49fcdb2197529481de55d1e35a008a
|
||||
acceptance:
|
||||
if: github.event_name != 'pull_request' || !contains(fromJSON('["labeled","unlabeled"]'),
|
||||
github.event.action) || github.event.label.name == 'full-acceptance'
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-acceptance.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-acceptance.yml@eeb76914ad49fcdb2197529481de55d1e35a008a
|
||||
with:
|
||||
qqq_ref: ${{ inputs.qqq_ref || '' }}
|
||||
dashboard-image:
|
||||
@@ -38,4 +38,4 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-dashboard-image.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-dashboard-image.yml@eeb76914ad49fcdb2197529481de55d1e35a008a
|
||||
@@ -43,6 +43,3 @@ target/
|
||||
/log/
|
||||
/.playwright-mcp/
|
||||
/storybook-static/
|
||||
/public/scripting-generated/
|
||||
/public/pdf-generated/
|
||||
/public/dynamic-qfmd-components/
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
|
||||
# Reviewed findings committed before the Gitea migration; exact historical fingerprints only.
|
||||
0969231c95f876bb0a41529e8c6c4621a0257aee:src/lib/qa-capture/sanitizers.test.ts:jwt:33
|
||||
23a855297de0f84b564b20d782e01180a68b5257:tests/acceptance/specs/security/restrictions.spec.ts:generic-api-key:248
|
||||
@@ -1,9 +0,0 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -1,11 +1,8 @@
|
||||
# QQQ Frontend Next
|
||||
|
||||
> **QBit integration branch (2026-11-04).** File delivery/preview, TypeScript editing and generic process controls use the QQQ UIUX APIs. See [current verification and dependency setup](docs/QBIT-RELEASE-STATUS.md) and [remaining release requirements](docs/QBIT-KNOWN-ISSUES.md). These changes are source/local snapshots, not part of the published RC.36 baseline described below.
|
||||
|
||||
|
||||
A metadata-driven admin UI for the QQQ low-code application framework, rewritten from React + Material UI to Next.js 16 + Tailwind CSS + shadcn/ui. The UI renders entirely from backend metadata — no table names, field lists, or navigation items are hardcoded in the frontend.
|
||||
|
||||
**Published baseline: Next UI 1.0.0-RC.36**, which adds accessibility fixes: readable link text, 24px clear targets, h2 widget titles and skip-link focus to RC35. Confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing; see the [RC36 notes](docs/releases/1.0.0-RC.36.md) for the preparation checkpoint and verification scope. [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35) was the previously verified public candidate at that checkpoint and remains immutable. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
**This checkout targets Next UI 1.0.0-RC.36**, which adds accessibility fixes: readable link text, 24px clear targets, h2 widget titles and skip-link focus to RC35. Confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing; see the [RC36 notes](docs/releases/1.0.0-RC.36.md) for the preparation checkpoint and verification scope. [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35) was the previously verified public candidate at that checkpoint and remains immutable. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
**Current roadmap and known issues:** [Next UI 1.0 tracker](https://github.com/QRun-IO/qqq/issues/713). GitHub issues are the source of truth for status and remaining work; see [issue tracking](docs/ISSUE-TRACKING.md).
|
||||
|
||||
@@ -78,60 +75,6 @@ Set `supplementalAppMetaData.nextUi.showChildGrid` on the app to override this d
|
||||
widgets already cover its sections and child apps.
|
||||
Only boolean values override the default. Existing visibility and permission rules still apply.
|
||||
|
||||
### Account menu links
|
||||
|
||||
An application can add a small, labelled group of links to the account menu (the avatar at the
|
||||
right of the header), for the tools that go with one environment: on a local development stack,
|
||||
the mail capture inbox, the identity provider's admin page, the message broker's console. The
|
||||
group is shown only when the application declares it, under Preferences and above Sign out.
|
||||
|
||||
Declare a widget of type `ACCOUNT_MENU_LINKS` in the instance. Nothing in QQQ itself changes: the
|
||||
metadata response already publishes every widget's `type`, `label`, `hasPermission` and
|
||||
`defaultValues`, and the Tools shortcut in the same menu is found the same way. The frontend reads
|
||||
this from `GET /qqq/v1/metaData`:
|
||||
|
||||
```json
|
||||
{
|
||||
"widgets": {
|
||||
"localTools": {
|
||||
"name": "localTools",
|
||||
"label": "Local tools",
|
||||
"type": "ACCOUNT_MENU_LINKS",
|
||||
"hasPermission": true,
|
||||
"defaultValues": {
|
||||
"links": [
|
||||
{ "label": "Mail inbox", "url": "http://localhost:8025/", "icon": "mail" },
|
||||
{ "label": "Identity provider", "url": "https://id.example.com/admin/", "icon": "admin_panel_settings" },
|
||||
{ "label": "Message broker", "url": "http://127.0.0.1:15672/" }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Part | Meaning |
|
||||
|---|---|
|
||||
| widget `type` | `ACCOUNT_MENU_LINKS`. Each such widget is one group; groups appear in metadata order. |
|
||||
| widget `label` | The group's heading (`Links` when blank). |
|
||||
| widget `hasPermission` | `false` hides the group, so a group can be limited with the widget's permission rules. |
|
||||
| `defaultValues.links` | An array of links, shown in order; at most 12 are shown. |
|
||||
| link `label` | Required text of the menu item. |
|
||||
| link `url` | Required. An absolute `https:` URL, or `http:` to `localhost`, `127.0.0.1` or `[::1]`. No user name or password. |
|
||||
| link `icon` | Optional Material icon name (`mail`, `key`, `dns`, ...), as for other metadata icons. Without one the item shows an external-link icon. |
|
||||
|
||||
A link with any other URL (plain `http:` to another host, `javascript:`, `data:`, a relative path,
|
||||
credentials in the URL), or without a label, is dropped and never rendered; the rest of the group
|
||||
still shows, and a group left without links does not show. Each link opens in a new tab with
|
||||
`rel="noopener noreferrer"` and is a keyboard-reachable menu item. Do not put a secret in a URL:
|
||||
the metadata response reaches every signed-in user who may see the widget.
|
||||
|
||||
On the backend the widget needs a name, the type, a label and a code reference like any other
|
||||
widget (a renderer that returns no data is enough: the menu never asks for the widget's data), and
|
||||
`defaultValues.links` as a list of maps. Do not add the widget to an app: it is not a dashboard
|
||||
widget. Declare it only in the environments that have the tools, for example from an environment
|
||||
variable.
|
||||
|
||||
### Known limitations
|
||||
|
||||
- Release candidates only; final 1.0 is held for application soak and owner approval ([#712](https://github.com/QRun-IO/qqq/issues/712), tracker [#713](https://github.com/QRun-IO/qqq/issues/713)).
|
||||
@@ -279,38 +222,3 @@ Saved views and legacy stored visibility (including `{}`, meaning all base colum
|
||||
are preserved. New View and Reset All Changes on an unsaved view restore these
|
||||
metadata defaults. Quick search searches only visible string fields. Responsive
|
||||
card/grid behavior is unchanged.
|
||||
## Default sort
|
||||
|
||||
A record list opens sorted by primary key, descending. An application can declare another
|
||||
sort for a table (newest first by a date field, for example) in the same hint object:
|
||||
|
||||
```json
|
||||
{
|
||||
"supplementalMetaData": {
|
||||
"nextUi": {
|
||||
"defaultSort": [
|
||||
{ "fieldName": "receivedAt", "isAscending": false }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`defaultSort` is an array of order-bys in the shape a query filter uses (`QFilterOrderBy`):
|
||||
`fieldName` is a field of the table, or of an exposed join as `joinTable.fieldName`, and
|
||||
`isAscending` is a boolean (ascending when absent). Several entries sort by the first, then
|
||||
the next. The legacy `supplementalTableMetaData.nextUi.defaultSort` path is also accepted.
|
||||
|
||||
The declared sort is the table's default, not a setting that overrides people: a sort in the
|
||||
address, the sort of a saved view, and the sort the browser remembers for the table from an
|
||||
earlier visit are each used instead. New View and Reset All Changes return to the declared
|
||||
sort, and it is not counted as an unsaved change. An entry that names an unknown field, a
|
||||
field the user may not sort by, or carries a non-boolean `isAscending` is ignored; when no
|
||||
entry is usable, or the hint is malformed, the list sorts by primary key, descending, as
|
||||
before.
|
||||
|
||||
QQQ has no table-level default sort of its own (as of 4.1.0-RC.32), so the application supplies
|
||||
the hint: a `QSupplementalTableMetaData` subclass whose `getType()` is `nextUi`, that returns
|
||||
`true` from `includeInFullFrontendMetaData()` and exposes `getDefaultSort()` as a list of
|
||||
`QFilterOrderBy` (and `getDefaultColumns()` for the hint above), attached to the table with
|
||||
`withSupplementalMetaData(...)`. The table metadata response publishes it as shown.
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM registry-1.docker.io/library/node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS frontend
|
||||
FROM registry-1.docker.io/library/node:22-bookworm-slim AS frontend
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN corepack enable && corepack prepare pnpm@9.15.9 --activate
|
||||
@@ -9,12 +9,8 @@ ENV QQQ_BACKEND_URL=http://host.docker.internal:8000
|
||||
ENV NEXT_PUBLIC_MOCK_API=false
|
||||
RUN pnpm build
|
||||
|
||||
FROM registry-1.docker.io/library/node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runtime
|
||||
FROM registry-1.docker.io/library/node:22-bookworm-slim AS runtime
|
||||
LABEL org.opencontainers.image.source="https://github.com/QRun-IO/qqq-frontend-next"
|
||||
# Standalone production starts node directly; package managers are build-only.
|
||||
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack /opt/yarn-* \
|
||||
&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
|
||||
/usr/local/bin/pnpm /usr/local/bin/pnpx /usr/local/bin/yarn /usr/local/bin/yarnpkg
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 HOSTNAME=0.0.0.0 PORT=3000
|
||||
COPY --from=frontend --chown=node:node /app/.next/standalone ./
|
||||
|
||||
+46
-57
@@ -23,12 +23,10 @@ Axios interceptor
|
||||
▼
|
||||
TanStack Query cache (onError)
|
||||
│ 401 → silently ignored (already handled)
|
||||
│ 403 → toast the server's message, or "Permission denied"
|
||||
│ 403 → toast "Permission denied" / "You do not have permission…"
|
||||
│ 404 → toast "Resource not found"
|
||||
│ 5xx → toast "Server error — retrying…" / "Server error — please try again"
|
||||
│ other status → toast the server's message, or "Request failed (HTTP 409)"
|
||||
│ no response → toast "No response from the server" / "The server took too long to respond"
|
||||
│ every toast names the request, and a repeat of the same failure updates it
|
||||
│ network → toast "Something went wrong"
|
||||
▼
|
||||
Component (optional per-query onError)
|
||||
│ Only needed when generic toast is wrong for the specific UX
|
||||
@@ -68,60 +66,52 @@ The `unauthorizedCallback` is wired to the auth provider's logout/redirect funct
|
||||
|
||||
**Location:** `src/lib/query-client.ts` — `handleQueryError` function
|
||||
|
||||
It is registered on both `QueryCache.onError` and `MutationCache.onError`. A query or mutation whose
|
||||
component renders its own error opts out with `meta: HANDLES_OWN_ERRORS`.
|
||||
```typescript
|
||||
function handleQueryError(error: unknown, context: 'query' | 'mutation'): void {
|
||||
const status = getErrorStatusCode(error)
|
||||
|
||||
| Failure | Banner text |
|
||||
|---|---|
|
||||
| Cancelled request (an axios cancel or an aborted `fetch`), 401 | none |
|
||||
| 403 | the server's message (of a JSON body), or `Permission denied` |
|
||||
| 404 | `Resource not found` |
|
||||
| 5xx | `Server error — retrying…` (query), `Server error — please try again` (mutation) |
|
||||
| Any other status (400, 409, 422, …) | the server's message (`userFacingError`, `error` or `message` of a JSON body), or `Request failed (HTTP 409)` |
|
||||
| No response (connection failed) | `No response from the server` |
|
||||
| No response (the 30 s timeout) | `The server took too long to respond` |
|
||||
| An error the application raised (`throw new Error('Invalid audit response')`) | that sentence |
|
||||
| A runtime error (`TypeError`, a schema error, …) | `The page hit an unexpected error (TypeError)` |
|
||||
if (status === 401) return // handled by axios interceptor
|
||||
|
||||
Under the text, every banner names what failed: the request as `POST /qqq/v1/table/order/query (HTTP 409)`,
|
||||
or `While loading records` (the query key's namespace in plain words: `possibleValues` reads
|
||||
`possible values`) for a query that failed outside a request. The
|
||||
request is written without its query string, and every path segment that is not a plain word (a record
|
||||
id, a UUID, an encoded value) is shown as `{id}`. Nothing else of the request or response is shown.
|
||||
if (status === 403) {
|
||||
toast.error(
|
||||
context === 'mutation'
|
||||
? 'You do not have permission to perform this action'
|
||||
: 'Permission denied'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
**One banner per failure.** The banner's sonner `id` is its text plus the request, so a failure that
|
||||
repeats (a polling query that fails on every attempt) updates the banner already on screen instead of
|
||||
adding one. A different failure gets its own banner. A lost connection is one cause whichever request
|
||||
met it, so it has a single banner, which names the request that failed most recently. Without the id
|
||||
every failed poll added a banner, and sonner pauses a toast's timer while the tab is hidden or the
|
||||
pointer rests on the stack, so the banners could pile up.
|
||||
if (status === 404) {
|
||||
toast.error('Resource not found')
|
||||
return
|
||||
}
|
||||
|
||||
**Console.** Each banner is also logged once with `console.warn('[API] Request failed:', { context,
|
||||
status, code, name, request, area })`: the HTTP status, the axios error code (`ERR_NETWORK`,
|
||||
`ECONNABORTED`, `ERR_BAD_REQUEST`), the error's name, the request as above and the query namespace.
|
||||
It never logs a message, body, header or query string, because those can carry record data.
|
||||
if (status !== undefined && status >= 500) {
|
||||
toast.error(
|
||||
context === 'mutation'
|
||||
? 'Server error — please try again'
|
||||
: 'Server error — retrying…'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
**Background requests show no banner.** A request the page makes on its own, for something the page
|
||||
works without, sets `meta: BACKGROUND_REQUEST`: a poll that keeps an indicator fresh, or a write nobody
|
||||
asked for. Its failure is logged to the console as above (with `background: true`) and never raises the
|
||||
banner: the person did nothing that failed and can do nothing about it, and a poll would raise the banner
|
||||
again on every attempt. The indicator shows its own quiet state, or nothing, until a later attempt
|
||||
succeeds. A request the person started (opening a page, saving, running something) is never a background
|
||||
request. Today's background requests:
|
||||
// Network failure or unexpected status
|
||||
toast.error('Something went wrong')
|
||||
}
|
||||
```
|
||||
|
||||
| Request | Where | While it fails |
|
||||
|---|---|---|
|
||||
| Presence poll (`GET …/collaboration/presence`) | `use-collaboration-presence.ts` | `Presence is reconnecting…` in place of the viewer count on a table; on a record, the same line only if other people were shown when the connection was lost, otherwise nothing. Presence leases are renewed outside TanStack Query and never raised a banner. |
|
||||
| Notification bell summary | `AlertsBell.tsx` (`useAlertsInbox`) | the bell keeps its last count, or stays hidden |
|
||||
| Jobs count in the header | `use-my-jobs.ts` (`background` argument, set by `JobsHeaderButton`) | the button keeps its last count; the Jobs page itself still reports its failures |
|
||||
| Break-glass session status | `BreakGlassBanner.tsx` | no banner |
|
||||
| Recently viewed (`POST …/collaboration/recents`) | `use-collaboration-core.ts` (`useRecordRecentView`) | the visit is not added to recents |
|
||||
This handler is registered on both `QueryCache` and `MutationCache`:
|
||||
|
||||
A background poll should also back off while it fails. `backoffDelay` in `src/lib/utils/backoff.ts`
|
||||
gives the wait: a ceiling that doubles per consecutive failure, half of it random, so clients that failed
|
||||
together (a server restart) do not all return together. Presence waits 2.5 to 5 s after the first failure
|
||||
and up to a minute after many, instead of its healthy 20 s interval, and does not use the automatic
|
||||
retries described below.
|
||||
```typescript
|
||||
export const queryClient = new QueryClient({
|
||||
queryCache: new QueryCache({
|
||||
onError: (error) => handleQueryError(error, 'query'),
|
||||
}),
|
||||
mutationCache: new MutationCache({
|
||||
onError: (error) => handleQueryError(error, 'mutation'),
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
**Implication for components:** For most queries and mutations, you do not need `onError` at all. The global handler covers toasting. Add per-query handling only when you need to do something the global handler cannot — such as mapping a 400 error's field messages back to form fields.
|
||||
|
||||
@@ -149,7 +139,7 @@ Returns `undefined` for anything else (non-object errors, null, network failures
|
||||
|
||||
### 400 — Validation Error
|
||||
|
||||
The global handler toasts the server's message for a 400 (or `Request failed (HTTP 400)` when it sent none). 400s typically carry field-level validation messages that belong beside individual form fields, so a form handles 400 explicitly, and sets `meta: HANDLES_OWN_ERRORS` on the mutation when the toast would repeat what the form shows.
|
||||
The global handler does NOT toast on 400 because 400s typically carry field-level validation messages that must be mapped back to individual form fields. Handle 400 explicitly wherever you submit a form.
|
||||
|
||||
```typescript
|
||||
import { getErrorStatusCode } from '@/lib/utils/error-utils'
|
||||
@@ -217,7 +207,7 @@ No additional per-component handling is needed for 5xx unless you want a custom
|
||||
|
||||
### Network Failure (no response)
|
||||
|
||||
Treated as non-4xx by the retry logic — queries retry up to 3 times. After all retries are exhausted the global handler toasts "No response from the server" (or "The server took too long to respond" for the 30 s timeout) with the request that failed. No per-component handling needed for the common case.
|
||||
Treated as non-4xx by the retry logic — queries retry up to 3 times. The global handler toasts "Something went wrong" after all retries are exhausted. No per-component handling needed for the common case.
|
||||
|
||||
---
|
||||
|
||||
@@ -284,8 +274,8 @@ export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
|
||||
onError: (error) => {
|
||||
if (getErrorStatusCode(error) === 400) {
|
||||
// Map field errors from the server response body to form fields.
|
||||
// The global handler toasts the server's message for a 400; the form
|
||||
// places each field's message beside it.
|
||||
// The global handler does NOT toast on 400, so we must do it here or
|
||||
// rely on inline field error messages in the form UI.
|
||||
const body = (error as AxiosError<{ errors: Record<string, string> }>).response?.data
|
||||
if (body?.errors) {
|
||||
for (const [field, message] of Object.entries(body.errors)) {
|
||||
@@ -315,7 +305,6 @@ export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
|
||||
| Layer | File | Handles |
|
||||
|---|---|---|
|
||||
| Axios interceptor | `src/lib/api/client.ts` | 401 → redirect to login |
|
||||
| Global query handler | `src/lib/query-client.ts` | Every status but 401, no response, page errors → one toast per failure, naming the request |
|
||||
| `meta: BACKGROUND_REQUEST` | `src/lib/query-client.ts` | A poll or write the page makes on its own → logged, no toast |
|
||||
| Global query handler | `src/lib/query-client.ts` | 403, 404, 5xx, network → toast |
|
||||
| Per-component `onError` | Your component | 400 field errors, custom empty states, navigation |
|
||||
| `getErrorStatusCode` | `src/lib/utils/error-utils.ts` | Normalize `AxiosError` and plain-object errors to HTTP status code |
|
||||
@@ -1,29 +0,0 @@
|
||||
# Isolated scripting editor
|
||||
|
||||
ScriptViewer routes explicit server-controlled ISOLATED projects before legacy hooks mount. Unknown nonempty modes fail closed. The native scripting extension must be advertised; otherwise isolated source stays unavailable. Developer page provides semantic project creation and opens the same IDE; project names never imply execution mode or actor identity.
|
||||
|
||||
The isolated CodeMirror editor supports multi-file TypeScript, immutable source history, explicit save/build/test/publish, server compiler diagnostics, scoped API declarations, JSON context tests and exact-commit GitHub imports with retained provenance. Edits invalidate build/test evidence. Saves and imports carry the observed latest revision. No browser credential fields or background repository synchronization.
|
||||
|
||||
## Semantic language service
|
||||
|
||||
Pinned editor-only typescript-editor alias6.0.3 powers a same-origin classic worker. It receives a bounded virtual filesystem and host-generated SDK declarations, with57 trusted ES2022 standard-library files bundled at build time. Diagnostics, completion, hover, go-to-definition(F12), formatting(Ctrl+Shift+F), file navigation and compiler diagnostic selection operate on the same workspace. Text remains ordinary undoable editor state. Tab moves focus.
|
||||
|
||||
There is no source execution, compiler emit, runtime fetch, arbitrary package loading, filesystem, DOM/Node declarations or user npm hooks. Browser analysis is advisory; authoritative strict builds still use the qualified isolated server. Worker cold deadline10s/warm3s terminates it on timeout; bounded request/result sizes, four pending calls, idle30s termination and recycling after200 requests limit work. The next explicit request may start a new worker; no hidden retry of timed-out source analysis. A browser worker supplies termination responsiveness, not an OS-enforced memory sandbox. Debugging and automatic imports are not implemented.
|
||||
|
||||
scripts/build-scripting-worker.mjs assembles only trusted package/compiler and our own session source into public/scripting-generated/typescript-6.0.3.worker.js, with license/notices. Generated9.6MB artifact is ignored and built before dev/build/build:export. Runtime worker requests no other resource. Exact compiler and library dependencies remain independent from server runtime qualification.
|
||||
|
||||
The alias package also exports tsc and would shadow the existing compiler under pnpm exec tsc. Use **pnpm typecheck** or **pnpm tsc**: both explicitly call node_modules/typescript/bin/tsc (the existing5.9 build compiler). Existing CI typecheck scripts follow that path. Do not replace frontend build TypeScript with the editor compiler. Compatible CodeMirror versions are pinned through pnpm overrides to avoid duplicate nominal EditorView/state classes.
|
||||
|
||||
## Authorization and uncertainty
|
||||
|
||||
Server permissions and worker availability control lifecycle actions, with backend checks authoritative. Use the matching Core `4.1.0-SNAPSHOT` dependency set described in [current integration status](QBIT-RELEASE-STATUS.md); the old mixed private-artifact/RC20 setup is superseded. Project creation and publication use typed core authority; isolated revision/file content and ownership are immutable. Real native HTTP lifecycle succeeds with protocol-only fixture worker; no production provider is implied.
|
||||
|
||||
Stop waiting or network timeout makes mutation outcome uncertain and prevents another mutation. History refresh does not prove completion; inspect history/reopen. Creation uncertainty directs the user to Scripts before retrying. Abort does not undo committed work. GitHub import needs a server-installed managed access provider and full immutable commit.
|
||||
|
||||
## Verification
|
||||
|
||||
2026-10-30: **114 focused tests across12 files**, existing build-compiler typecheck and changed-file ESLint passed. Real Playwright Chromium worker check exercises strict diagnostics, multi-file completion/hover/definition/format, rejects remote types and proves source does not execute or fetch. Final optimized production build with typecheck, static generation and standalone packaging passed at 21:36, including the creation panel (parent run20209, editor-build-verification.log). Native server tests separately cover create/save/build/context-test/publish and permission/association/legacy denials. No live browser-to-deployed-worker end-to-end or production sandbox qualification claim.
|
||||
|
||||
Run pnpm scripting:worker:check after generating the worker; this environment uses PLAYWRIGHT_BROWSERS_PATH=C:/Users/james/AppData/Local/ms-playwright. The harness serves only a local trusted page/worker with connect-src none and closes browser/server on completion.
|
||||
|
||||
Current integration verification (2026-11-04): the real Chromium offline-worker check passes strict diagnostics, multi-file completion/hover/definition and formatting, with no source execution or external requests. Typecheck, lint and production worker packaging pass on the canonical integration branch. See [current status](QBIT-RELEASE-STATUS.md) for the final full-suite evidence. This frontend result does not qualify the server's untrusted-code runtime.
|
||||
@@ -1,47 +0,0 @@
|
||||
# PDF preview boundary
|
||||
|
||||
The generic file lightbox uses pinned Mozilla `pdfjs-dist` **6.4.299**, loaded only for
|
||||
PDFs, and a locally packaged worker. It no longer embeds uploaded PDF responses in an
|
||||
application-origin iframe or offers a PDF "Open original" navigation. Downloads retain
|
||||
the existing owner authorization callback.
|
||||
|
||||
Retained attachment previews reach it only after the tracked-download helper verifies
|
||||
server receipt, byte length and SHA-256, and assigns `application/pdf` from the fixed
|
||||
PDF signature. The generic renderer accepts local same-origin blob URLs or native
|
||||
file endpoints at the exact configured API origin and base path. Both dashboard hosts must permit `blob:` in CSP `connect-src` so the verified local bytes can be read; the current Javalin and standalone defaults include it. It never forwards API
|
||||
credentials to arbitrary external URLs. Uploaded MIME labels alone are insufficient.
|
||||
|
||||
The renderer supplies bytes (not a document URL) to an explicitly created parser
|
||||
Worker, preventing the library's fake-worker fallback. It creates a canvas and an
|
||||
optional plain-text view only: no PDF annotation/action, form, XFA, scripting or HTML
|
||||
viewer layer. Auxiliary resource requests are rejected, worker fetching and WASM are
|
||||
disabled, and no document-selected external URL is followed. Missing auxiliary fonts
|
||||
or unsupported resources can limit fidelity; the retained original is downloadable.
|
||||
|
||||
Limits: 20 MiB input, 1000 pages, one visible page at a time, 8 million canvas pixels,
|
||||
8192 pixels per edge, 30 seconds to load/parse, 15 seconds per page render/text read.
|
||||
Text is streamed and stopped at 10,000 items or 100,000 characters, slicing each
|
||||
string before aggregation. The stream is cancelled on page change, close or timeout;
|
||||
page controls remain busy through text completion.
|
||||
Closing the dialog aborts input loading, cancels rendering, destroys the loading task
|
||||
and terminates the worker. These are application limits, not a browser-process memory
|
||||
quota: compressed PDF complexity can allocate parser memory before page checks.
|
||||
Canvas rendering and a Web Worker do **not** constitute a full hostile-parser security
|
||||
sandbox. Browser/library patching, CSP and deployment qualification remain necessary.
|
||||
|
||||
Primary references checked on 2026-10-30:
|
||||
|
||||
- [Mozilla release 6.4.299](https://github.com/mozilla/pdf.js/releases/tag/v6.4.299)
|
||||
- [Mozilla PDF.js API](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html)
|
||||
- [Mozilla prior arbitrary-JavaScript advisory](https://github.com/mozilla/pdf.js/security/advisories/GHSA-wgrm-67xf-hhpq)
|
||||
|
||||
The prior advisory affected versions through 4.1.392 and was fixed in 4.2.67. The current
|
||||
6.4.299 API no longer exposes the old `isEvalSupported` option; this integration does
|
||||
not pretend an obsolete option supplies isolation. It uses the pinned current release,
|
||||
no PDF scripting manager, and the application's restrictive script CSP.
|
||||
|
||||
## Current verification (2026-11-04)
|
||||
|
||||
The production export and local Maven JAR include the pinned worker. Twelve Chromium browser scenarios pass against that packaged UI, including actual PDF worker/canvas pixels, page navigation, no executed PDF OpenAction, separate retained preview/download receipts, refusal of incomplete receipts, and ordered-file submission. Real Core/Collaboration API sessions separately pass ordinary signed-PDF canvas preview, page controls and PDF download.
|
||||
|
||||
Signed attachment PDFs are read with credentials omitted and redirects refused, bounded to 20 MiB and 30 seconds, and checked by byte signature before a local preview URL is exposed. Their storage origin needs host CSP/CORS configuration. Tracked deliveries retain the receipt/hash path. Cancellation and streaming-limit tests cover both paths. See [current status](QBIT-RELEASE-STATUS.md) for the full suite and [release requirements](QBIT-KNOWN-ISSUES.md) for remaining deployment qualifications.
|
||||
@@ -1,13 +0,0 @@
|
||||
# Metadata-driven process result fields
|
||||
|
||||
`ViewFormComponent` delegates adorned result fields to the shared `FieldValue` component. Hidden fields remain in the result value map so native metadata can supply display companions; they are not rendered as separate controls. Ordinary process values and validation errors keep their existing behavior.
|
||||
|
||||
`LINK` supports either `toRecordFromTable` (a static table name) or `toRecordFromTableField` (the name of another result field containing the table name). The field value is the record identity. Navigation uses the native encoded table/record route. A missing companion table produces no link. Possible-value sources that identify a known instance table also retain native record navigation.
|
||||
|
||||
`FILE_DOWNLOAD` can specify `fileNameField` and `deliveryModeField`. If the latter is present, its companion value must be `SIGNED_URL` or `AUTHENTICATED_FETCH`; missing or unknown modes render no access action. Older fields without that metadata retain their existing behavior.
|
||||
|
||||
For `AUTHENTICATED_FETCH`, the issued URL is never placed in an `href`, image source or iframe. Download uses the shared authenticated transfer helper, which checks the configured origin, response bounds, exact digest/length and completed durable receipt. An additional `FILE_PREVIEW` adornment enables an explicit preview action. Only verified PDF/raster blobs reach the shared preview component; component-owned blob URLs are revoked when closed or unmounted. Unsupported content and transfer/audit errors remain visible and never fall back to direct access.
|
||||
|
||||
`CODE_EDITOR` result fields use the shared read-only source display, including renderer-supplied plain catalog help and HTML/JSON examples. No template or script evaluation occurs in a process result.
|
||||
|
||||
Verification for this increment: 178 focused tests across 18 files, owned ESLint and the explicit build-compiler typecheck passed. Each actual transfer creates a fresh correlation UUID only after validating the configured endpoint, preserving the immutable file coordinate and using that same fresh attempt for its receipt. Source changes and unmount abort active body/receipt work. Final integrated production-build/browser acceptance remains pending. These generic components do not embed a QBit name or depend on its backend implementation.
|
||||
@@ -1,11 +0,0 @@
|
||||
# QBit integration known issues and release requirements
|
||||
|
||||
Updated: 2026-11-05.
|
||||
|
||||
- The Core, Collaboration and Next UI changes are verified source branches and local snapshots, not a published dependency set. Public Core RC.21 / Collaboration RC.6 lack the required retention contracts. Merge and publication through the existing release process remain separate from local verification.
|
||||
- The frontend checks include real Core/Collaboration sessions and file storage, plus browser protocol fixtures for retained receipts. They do not establish end-to-end document generation/printing or deployed untrusted-script execution. Those QBits and workers retain their own qualification requirements.
|
||||
- External signed PDF storage needs CORS for the dashboard origin and its origin in CSP `connect-src`. Application credentials are never sent to those URLs. Hosts replacing dashboard CSP must retain `blob:` in `connect-src` for verified local previews.
|
||||
- Lint reports six existing warnings in unchanged files. The unit suite has one existing skipped test. Canonical Next 16.4.1 and Zod 3 are preserved; dependency patch upgrades remain a separate release review.
|
||||
- The local artifact is `qqq-frontend-next:1.0.0-SNAPSHOT`, built with an explicit Maven revision override. It includes generated PDF and TypeScript workers. The prepared release-managed version is `1.0.0-RC.38`; RC.36 and RC.37 already exist in Central and must never be overwritten.
|
||||
- Next publisher support and the shared producer are merged (Praetor PR238, platform-ci PR67); the local caller pins327e9b3a9d45a08665fa9468f0f9741e972d8e3e. Runtime qualification passed736 Linux tests and its vulnerability scan. GitOps PR269 deployed the qualified runtime and exact workflow/GAV enrollment; ArgoCD adoption and the scheduled publisher startup are verified. The signed application tag and resulting Central artifact still remain. The existing tag, package.json and POM version agreement, typecheck/lint/tests/static export and signed Central delivery are preserved. Neither the local JAR nor source merge proves publication.
|
||||
- The full application acceptance matrix across all browsers and deployment-specific storage/printer/scanner behavior is not claimed by the scoped QBit integration checks.
|
||||
@@ -1,58 +0,0 @@
|
||||
# Next UI QBit integration status
|
||||
|
||||
Updated: 2026-11-05. Source integration is prepared; no published release or deployment is claimed.
|
||||
|
||||
Current main `090f5febeaacf3f9c39a22952e5c93c859cdbeb7` (permission editor and companion Tools workspace) is integrated. The latest merge passed all 110 affected Authentik/widget/process tests, typecheck and the copyright-header gate. Both branches supplied the same worker limit; the merged configuration retains one setting. Prior focused Tools/UI-API checks covered 61 cases. These are integration checks, not completed release CI.
|
||||
|
||||
Core PR1343 merged as7825261ab after full CI4482 passed; promotion PR1345 merged as1bef44cf and immutable publication4629 is running. Collaboration must consume the resulting published version. Next publisher support merged in Praetor PR238 and platform-ci PR67. GitOps PR269 merged as883e1ce3; ArgoCD adopted the exact configuration and a scheduled publisher is running image sha256:ea068b2a02147280cacedd095fbc55114daa9e3db72f1b0ca8511bc43bfd12c7 with the exact Next enrollment. Its 736 Linux tests and vulnerability scan passed. The dashboard candidate version is 1.0.0-RC.38; this source preparation is not a published release.
|
||||
|
||||
Candidate CI4602 passed 3,800 tests but hit the unchanged five-second timeout in two `RecordQuery` filter tests. These also timed out on an earlier baseline; the newer main baseline's Node job passed. Profiling the focused cases identified repeated whole-page accessibility lookups. Scoping those lookups to the existing filter controls and confirmation dialog reduced their sampled CPU cost from 387 to 261 samples; the same assertions, interactions and timeouts are preserved. All 17 tests in the affected file and focused lint pass after the change. Release CI for this correction remains required; these focused results do not replace it.
|
||||
|
||||
## Changes
|
||||
|
||||
The canonical Next UI integration renders file preview/download adornments, retained-transfer receipts, isolated TypeScript editing and generic process results through QQQ metadata and UIUX APIs. It adds no table-specific application routes. The completion pass fixes Windows static-export execution, local PDF reads under dashboard CSP, and ordinary signed-storage PDF previews. Signed storage reads omit credentials, refuse redirects and enforce byte/time limits before canvas rendering. Retained transfers preserve their receipt/hash checks. Tests now use four workers by default to avoid high-core host contention; no timeout or coverage threshold was relaxed.
|
||||
|
||||
## Verified dependencies
|
||||
|
||||
- Core `feat/standalone-scripting-api`, code commit `d384d1c753cb0ac2ee4d0f6ccd564a3e47488a1c`, locally installed as `4.1.0-SNAPSHOT`.
|
||||
- Collaboration `feat/record-files-standalone`, `53bd8f00d8a180b0fa4eb6cd029dc31044b6d4b3`, locally installed as `0.1.0-SNAPSHOT`.
|
||||
- Next UI retains canonical Next 16.4.1, Zod 3 and existing dependencies. Local packaging explicitly overrides Maven revision to `1.0.0-SNAPSHOT`; it does not replace public RC.36.
|
||||
|
||||
## Completed verification
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Full `pnpm test:coverage` | 359 files; **3,784 passed**, 1 existing skip; all coverage gates passed |
|
||||
| Coverage | 93.14% statements, 87.00% branches, 94.57% functions, 94.95% lines; API/utility sub-gates also passed |
|
||||
| Lint and license headers | Zero errors, six existing warnings in unchanged files; Apache headers passed |
|
||||
| Typecheck | Passed |
|
||||
| Offline TypeScript worker in Chromium | Strict diagnostics, multi-file completion/hover/definition and formatting passed; no source execution or external fetch |
|
||||
| Windows production static export | Passed using `pnpm build:export` |
|
||||
| Local Maven snapshot JAR | Built successfully with PDF/TypeScript workers included |
|
||||
| Browser file/process regressions | **12 passed** against the packaged production UI; API fixtures exercise PDF canvas, separate audit receipts, incomplete-receipt refusal and keyboard ordering |
|
||||
| Live Core + Collaboration file workflow | Upload, thumbnail, preview, open, exact-byte download, rename/describe, reload and delete passed with synthetic data |
|
||||
| Live PDF and authorization | Signed PDF canvas/page controls and download passed; another session was denied access to the parent record |
|
||||
| Live UI API specification check | Bundled 1.8.0 compatible with running Core 1.10.0 |
|
||||
|
||||
The live tests used the existing disposable `CollaborationDevServer`, synthetic Alice/Bob sessions and the current UI JAR on loopback. No API mocks were used for those file/permission checks. The separate 12-case browser suite uses its existing API fixtures, not a deployed Record Files or scripting worker. Test-owned services and browsers were stopped after verification.
|
||||
|
||||
## Reproduce
|
||||
|
||||
```shell
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm test:coverage
|
||||
pnpm lint
|
||||
pnpm typecheck
|
||||
pnpm scripting:worker:check
|
||||
pnpm build:export
|
||||
mvn -B -Drevision=1.0.0-SNAPSHOT package
|
||||
pnpm ui-api:check --server-url http://localhost:18098
|
||||
```
|
||||
|
||||
Start the matching Collaboration demo using its README and place the resulting UI JAR first on its classpath. The live check used port 18098. The standard `pnpm test:e2e` owns its frontend fixture for the browser scenarios. Maven was invoked through the sibling Collaboration wrapper during this Windows run.
|
||||
|
||||
Local JAR SHA-256: `0626B33DF49569476E17FA080E2777A7AD9C7AF717CB75DFABF9EB40BE0A46A8`.
|
||||
|
||||
## Release boundary
|
||||
|
||||
See [known issues and release requirements](QBIT-KNOWN-ISSUES.md). Compatible public artifact publication, the complete application acceptance matrix and deployed document/script worker qualification are not implied by these source and local integration results.
|
||||
@@ -1,21 +0,0 @@
|
||||
# Record Files client integration
|
||||
|
||||
Updated: 2026-11-04. Current canonical integration branch: `feat/standalone-qbits-ui`. See [verification and dependencies](QBIT-RELEASE-STATUS.md).
|
||||
|
||||
## Standard controls and APIs
|
||||
|
||||
The Files tab uses standard themed buttons for Preview, Open, Download and Rename / describe. Navigation uses Next links with keyboard focus. Attachment metadata supplies independent `canEdit` and `canDelete` permissions; an explicitly denied edit capability never falls back to deletion permission. The server remains authoritative.
|
||||
|
||||
Every download requests a fresh owner-issued descriptor. `AUTHENTICATED_FETCH` deliveries use the configured native Record Files route, a new correlation identifier, and a separately verified completion receipt, byte count and SHA-256. Preview and save are separate attempts. A failed receipt never becomes a direct link or a successful save. Generic `FILE_DOWNLOAD` and `FILE_PREVIEW` adornments use the same controls; they do not require table-specific pages.
|
||||
|
||||
Tracked raster/PDF previews expose a local object URL only after verification. Ordinary signed PDF previews read bounded bytes with credentials omitted, redirects refused and a 30-second deadline. Both use the same canvas PDF renderer; uploaded PDFs are never framed. Closing the preview aborts work and revokes local URLs. Hosts serving signed files from another origin must allow that storage origin in CSP `connect-src` and configure storage CORS for the dashboard origin. This never forwards QQQ credentials to storage.
|
||||
|
||||
Open previews supported media; unsupported types use the authorized download action. The UI does not claim that a browser saved bytes or that a printer physically printed them. Retention, upload sessions, collections and durable audits belong to their server QBits.
|
||||
|
||||
## Dependency order
|
||||
|
||||
Install matching Core, then Collaboration, then Record Files and other feature QBits before the matching frontend. Public Core RC.21 and Collaboration RC.6 do not contain the new retention contracts. Local verification uses Core `4.1.0-SNAPSHOT` and Collaboration `0.1.0-SNAPSHOT`; see their branch status files for exact source commits. Core's dashboard CSP must include `blob:` in `connect-src` for local PDF-byte reads.
|
||||
|
||||
## Verification scope
|
||||
|
||||
The full component/API suite and coverage gates, production export, browser PDF/receipt/ordering scenarios and live Collaboration file workflow are recorded in [current status](QBIT-RELEASE-STATUS.md). Live tests use disposable synthetic data and real Core/Collaboration APIs. Browser mocks of the retained-transfer protocol do not establish production storage or worker qualification.
|
||||
@@ -94,7 +94,7 @@ Permissions apply to metadata and data: check table capabilities and the corresp
|
||||
| `/app/search?q=...` | Navigation, recent-record, and available record search results. |
|
||||
| `/app/developer` | Developer information available to permitted users. |
|
||||
|
||||
The header search and `/` dialog locate navigation targets and recent records; record search is offered when the backend supports it. RC8 includes the search-focus correction: Tab/Shift+Tab remain within the search dialog, Clear returns focus to the search input, and Escape or backdrop dismissal restores focus to the opener. A pointer-opened phone search restores focus to its actual button in verified Chromium/mobile cases. RC8 tablet WebKit has two open Clear-search focus failures; see the release notes for remaining browser issues. RC7 does not include this correction. The command palette opens with `.` or Cmd/Ctrl+K and has a header button; `?` opens keyboard help. Keyboard shortcuts on query and record pages are listed in the [feature matrix](../acceptance/feature-matrix.md). The sidebar has a phone drawer, nested app groups, banners, and a user menu. An application can add a labelled group of external links to the account menu (an environment's companion tools) by declaring a widget of type `ACCOUNT_MENU_LINKS`; the contract and its URL rules are in the README under [Account menu links](../../README.md#account-menu-links). Branding can add a company footer and a themed bar above the shell. `?helpHelp` reveals help-slot keys for content authors.
|
||||
The header search and `/` dialog locate navigation targets and recent records; record search is offered when the backend supports it. RC8 includes the search-focus correction: Tab/Shift+Tab remain within the search dialog, Clear returns focus to the search input, and Escape or backdrop dismissal restores focus to the opener. A pointer-opened phone search restores focus to its actual button in verified Chromium/mobile cases. RC8 tablet WebKit has two open Clear-search focus failures; see the release notes for remaining browser issues. RC7 does not include this correction. The command palette opens with `.` or Cmd/Ctrl+K and has a header button; `?` opens keyboard help. Keyboard shortcuts on query and record pages are listed in the [feature matrix](../acceptance/feature-matrix.md). The sidebar has a phone drawer, nested app groups, banners, and a user menu. Branding can add a company footer and a themed bar above the shell. `?helpHelp` reveals help-slot keys for content authors.
|
||||
|
||||
Material's nested `/{app}/{table}/{id}` URLs are not the native Next route. A not-found page now checks the signed-in instance metadata, applies exact or `/*` redirect rules, and resolves nested Material app paths to `/app/...` while preserving query/hash ([`legacy-paths.ts`](../../src/lib/utils/legacy-paths.ts), [`LegacyPathRedirect.tsx`](../../src/components/layout/LegacyPathRedirect.tsx)). Verify a specific old bookmark rather than assuming arbitrary legacy URLs match. For links generated by widgets use [`material-links.ts`](../../src/lib/utils/material-links.ts), which normalizes supported legacy links and preserves a trailing slash for static-export routes.
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Next UI 1.0.0-RC.37 — published collaboration candidate
|
||||
|
||||
This candidate is published. Artifacts are
|
||||
`com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.37` and
|
||||
`ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.37`. RC.36 remains immutable.
|
||||
Publication does not deploy Kof22 or authorize final 1.0.
|
||||
|
||||
## Source and changes
|
||||
|
||||
Prepared from collaboration source `dce92cfba1f02f7969c19b59d4442f5488b3821e`.
|
||||
The RC preparation changes the package and Maven versions together and retains
|
||||
main's managed orb 0.8 publication configuration. This source
|
||||
includes the previously tested collaboration source
|
||||
`8d372142f8af0c41a75a353edc6d150c33ccf613` plus a My Work browser regression test.
|
||||
|
||||
- Presence opens server-issued leases and renews them through
|
||||
`/presence/leases` and `/presence/leases/renew`. Record/table viewers and
|
||||
editors receive updates through the existing SSE/HTTP transport.
|
||||
- Authentication retains the Auth0 display profile while using canonical
|
||||
backend presence identity. Departure, expired leases and reconnect behavior
|
||||
remain covered by the collaboration test suite.
|
||||
- Marking a mention read refreshes My Work; the additional browser test checks
|
||||
that behavior.
|
||||
- Changes since RC.36 also include assistant conversation navigation, unread
|
||||
state and attachment recovery, startup branding, shared HTML sanitization,
|
||||
dependency fixes and centralized CI. This is not a presence-only diff from
|
||||
RC.36.
|
||||
- Development dependencies are aligned on Storybook 10.6.2 and Vitest 4.1.12
|
||||
(including `@vitest/mocker`) for
|
||||
[GHSA-f2ph-cmg5-wxc8](https://github.com/storybookjs/storybook/security/advisories/GHSA-f2ph-cmg5-wxc8)
|
||||
and [GHSA-xp26-3454-mjgp](https://github.com/vitest-dev/vitest/security/advisories/GHSA-xp26-3454-mjgp).
|
||||
These advisories affect development-server tooling; they do not describe a
|
||||
Storybook server in the static dashboard package. Integration is tracked in
|
||||
[QQQ #1327](https://github.com/QRun-IO/qqq/issues/1327).
|
||||
|
||||
## Backend pairing
|
||||
|
||||
Use a backend implementing the issued-lease collaboration API. The verified
|
||||
earlier pair is QQQ `4.1.0-collab-33464d37e-SNAPSHOT` with collaboration
|
||||
`0.1.0-collab-8f348da-SNAPSHOT` and Redis `0.1.0-redis-7fe5492-SNAPSHOT`.
|
||||
The selectable-field follow-up pair is QQQ
|
||||
`4.1.0-virtual-field-values-1196-cc3981bb3-SNAPSHOT` with collaboration
|
||||
`0.1.0-field-values-1196-ecff347-SNAPSHOT`; that pair's independent API probe
|
||||
does not establish packaged frontend acceptance.
|
||||
|
||||
Configure authenticated scope, Redis namespaces and lifecycle, SSE delivery and
|
||||
connection affinity in the host. Presence is advisory; stale-save protection
|
||||
still requires backend record versions. Kof22 PR338's RC.36 frontend must be
|
||||
updated only after this artifact is published and independently verified.
|
||||
|
||||
## Qualification and release gates
|
||||
|
||||
- [x] Local typecheck and all 3,664 unit tests pass. Lint passes with six
|
||||
warnings and no errors; license headers pass.
|
||||
- [x] Canonical Circle caller and immutable GitHub worker bridge validate locally.
|
||||
- [x] Patched toolchain passes TypeScript, all 3,664 unit tests and Storybook
|
||||
static build (bundle-size warnings remain).
|
||||
- [x] Exact RC source passes hosted CI and full browser acceptance.
|
||||
- [x] Local static export builds and packages under `next-dashboard/`; development
|
||||
mock worker is excluded.
|
||||
- [x] Fresh immutable RC tag publishes matching Maven and image versions.
|
||||
- [x] Public JAR/POM checksums and image digest are recorded.
|
||||
- [x] Browser acceptance runs against the downloaded frontend JAR and the
|
||||
selected published backend pair.
|
||||
- [ ] Kof22 integration and isolated staging qualification are complete before
|
||||
production rollout is proposed.
|
||||
|
||||
Earlier source acceptance run
|
||||
[39683690943](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/39683690943)
|
||||
is supporting evidence, not qualification of this RC package. The versioned tag
|
||||
triggers Maven and container publication; the inspected workflows contain no
|
||||
host deployment step.
|
||||
|
||||
Local Java 21 Maven packaging passed on October 26. ZIP inspection confirmed
|
||||
the home and dynamic record fallback pages, both issued-lease endpoint strings
|
||||
in the packaged JavaScript, and exclusion of `mockServiceWorker.js`. This is
|
||||
package-content evidence, not a substitute for browser protocol acceptance.
|
||||
|
||||
## Published artifact evidence
|
||||
|
||||
Signed tag `v1.0.0-RC.37` points to
|
||||
`13abaa795d71f0a2213409fb910003920b82f3c3`. Source acceptance
|
||||
[40333860200](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/40333860200)
|
||||
passed all 18 real-backend browser shards and the aggregate gate. One shard
|
||||
required a targeted retry after a 40-minute system-package download timeout;
|
||||
its initial attempt never reached browser tests. CodeQL, unit/coverage,
|
||||
collaboration browser profiles and both image architectures passed.
|
||||
|
||||
Circle publisher 758 and node build 759 passed. The tag's separate acceptance
|
||||
run [40342829221](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/40342829221)
|
||||
published its images successfully, but its tablet shard and one targeted retry
|
||||
both timed out after 40 minutes downloading Ubuntu browser dependencies, before
|
||||
browser tests started. The aggregate gate therefore did not pass. Candidate CI
|
||||
now pins verified orb commit `eeb76914ad49fcdb2197529481de55d1e35a008a`, whose
|
||||
browser installation steps use bounded APT retries/timeouts and the official
|
||||
HTTPS mirror fallbacks. This changes candidate CI only; the signed RC tag and
|
||||
published artifacts remain unchanged. Updated-worker qualification
|
||||
[40357830356](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/40357830356)
|
||||
passed on candidate commit `c8f79847f3174425f02538c3c1b345eff86fda53`: all 18
|
||||
real-backend browser shards and the aggregate gate succeeded, with no failed
|
||||
jobs. This qualifies the corrected candidate workflow; it does not change the
|
||||
failed historical tag run or replace the earlier source acceptance evidence.
|
||||
|
||||
| Public artifact | SHA-256 / OCI digest |
|
||||
| --- | --- |
|
||||
| Maven POM | `4761d2fd07f60da226fb179837b053a30a5a198e8238189d3912fcb3a69849f9` |
|
||||
| Maven JAR | `c9fa2eb2381a47c8104f82f4e940d2bfa8ba67e2341298dde0de4e21ad3ff1ab` |
|
||||
| Multi-platform image index | `sha256:0b0fa9906eed60df1d23f28390888708587361a168b20fef92f49e6090723822` |
|
||||
| Linux AMD64 image | `sha256:a6e5ee0947b5e12cbf821741a2a72fdac7c705d1276f59bb9497807cdd020f75` |
|
||||
| Linux ARM64 image | `sha256:91999495b5958a2b1d67a43fd768c274690fea3eb3e79eaaab0e5924c8335eb4` |
|
||||
|
||||
The POM and JAR were downloaded directly from Maven Central; both match the
|
||||
repository's SHA-512 checksums. Coordinate and JAR resource checks passed.
|
||||
Repository checksums establish transfer integrity, not signature identity.
|
||||
The immutable AMD64 image served `/app/person` with HTTP 200 in a disposable
|
||||
container; ARM64 has hosted build verification, not a local runtime claim.
|
||||
|
||||
The downloaded public JAR passed Chromium acceptance with six mock identities
|
||||
across two independent JVMs using the published selectable-field backend pair
|
||||
above: each browser saw the other five users; all four viewers saw exactly two
|
||||
editors; editor field focus, retained drafts, table projection and departure
|
||||
passed. Redis connection/subscription metrics, persisted framework UP health
|
||||
results and standard health-record navigation also passed. There were no browser
|
||||
page errors, and all test-owned processes and Redis resources were cleaned up.
|
||||
The hosts use independently seeded memory records and mock authentication;
|
||||
these checks do not prove production identity-provider or shared-database save
|
||||
behavior. Kof22 staging adoption remains outstanding.
|
||||
|
||||
## Limits and rollback
|
||||
|
||||
This branch does not include separate frontend PR194/195 or the independent
|
||||
backend attachment, My Work and Redis-recovery follow-ups. Those remain tracked
|
||||
in the QQQ project.
|
||||
|
||||
If packaged acceptance fails, withhold adoption and fix the candidate. After
|
||||
deployment, restore a previously qualified frontend/backend pair together;
|
||||
RC.36 must not be substituted against a backend requiring issued leases.
|
||||
No host data migration, production deployment or GA approval is implied.
|
||||
@@ -1,11 +0,0 @@
|
||||
# 1.0.0-RC.38 — prepared candidate
|
||||
|
||||
This candidate is not yet released. Merge and publication follow the compatible Core and Collaboration releases.
|
||||
|
||||
- Record file controls support previews, opening and downloading through the documented delivery APIs, including PDF previews.
|
||||
- Script authoring includes the isolated TypeScript editor, server lifecycle actions and record hook controls.
|
||||
- Process results support file delivery, PDF preview and ordered record lists through standard metadata.
|
||||
- Record queries respect authorization-filtered pagination; record layouts preserve section metadata.
|
||||
- The current permission editor and companion Tools workspace remain integrated.
|
||||
|
||||
The release uses the standard UI API and extension documents. Worker execution, storage configuration and printer/scanner qualification remain responsibilities of the respective QBits and host application. See [verification and release status](../QBIT-RELEASE-STATUS.md) and [known requirements](../QBIT-KNOWN-ISSUES.md).
|
||||
@@ -1,13 +1,12 @@
|
||||
# Next UI — unreleased
|
||||
|
||||
[RC37 collaboration candidate](1.0.0-RC.37.md) records the published issued-lease
|
||||
frontend, artifact receipts, backend pairing and outstanding host qualification.
|
||||
|
||||
[RC36 preparation](1.0.0-RC.36.md) collects every change merged since [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35). RC35 is published and immutable. Changes merged after the RC36 preparation commit are listed below. Central tracking: [qqq#713](https://github.com/QRun-IO/qqq/issues/713), [browser investigations #985](https://github.com/QRun-IO/qqq/issues/985), and [QQQ Roadmap Project 12](https://github.com/orgs/QRun-IO/projects/12).
|
||||
|
||||
## Features
|
||||
|
||||
- **Tools:** the `QQQ_TOOLS` widget provides a shared setup workspace for CLI/TUI, mobile scanners and Print Client, with platform-specific install commands, copyable scripts and instance connection details. An account-menu shortcut follows visible Tools metadata. Requires the Tools Qbit; existing device enrollment and permissions remain unchanged.
|
||||
|
||||
- **Application-declared links in the account menu.** An application can add a labelled group of links to the tools that go with one environment (a mail capture inbox, an identity provider's admin page, a message broker's console) by declaring a widget of type `ACCOUNT_MENU_LINKS` whose `defaultValues.links` is a list of `{ "label", "url", "icon" }`. No QQQ change is needed: the metadata response already publishes a widget's type, label, permission and default values. Only absolute `https:` URLs, or `http:` to `localhost`, `127.0.0.1` or `[::1]`, without credentials, are shown; any other link is dropped. Links open in a new tab with `rel="noopener noreferrer"`, are keyboard-reachable menu items, and the group renders nothing when the application declares none. The account menu now scrolls within the space it has when it is taller than the window. Contract: README, [Account menu links](../../README.md#account-menu-links).
|
||||
|
||||
- **UI API 1.6.0 (QQQ 4.1.0-RC.15).** Next reads the typed `clientCapabilities` of table metadata for saved views, sharing, bulk processes and audits, applies `field.validation` (required, length, inclusive and exclusive bounds, patterns) before a request, reads client-neutral `uiSettings` setting by setting with the deprecated `materialDashboard` values as fallback, and shows the process error `traceId`. The full `materialDashboardTheme` still wins over the `uiSettings.theme` subset. Error messages keep their order (`userFacingError`, `error`, then the new `message`). Audits fall back to the permission-filtered instance metadata when a table's capability is unavailable, since RC.15 marks unaudited tables unavailable although explicit audits can exist. Off-spec calls stay at 0.
|
||||
- **What's new:** a paged release history with new badges, safe links and screenshots, notification deep links, and an unread count in the user menu. Uses UI API extension `release-notes` 1.0.0; requires qbit-release-notes 0.1.0-RC.1+.
|
||||
- **Profile photo and avatars everywhere** (QQQ 4.1.0-RC.17, UI API 1.8.0 `avatars`):
|
||||
@@ -15,29 +14,11 @@
|
||||
- One `UserAvatar` (photo via one batched `POST /avatars/lookup` and `GET /avatars/{avatarId}`, otherwise initials) shows people in the user menu, presence, comments, mention candidates, the people picker, activity and your own assistant messages. A missing avatar is remembered for the session, so it isn't requested again.
|
||||
- **Privacy:** branding `gravatarDefault` no longer sends your email hash to Gravatar. A Gravatar appears only if you turn it on in your Profile, and the server serves it.
|
||||
- Image fields take a full form row at every width. e2e coverage is `tests/e2e/profile-avatars.spec.ts`, including the 6-width light/dark screenshot matrix.
|
||||
- **A table can declare the sort its record list opens with.** The list's initial sort was fixed at primary key descending and read nothing from the table's metadata, so an application could not make a list open newest first by a date field. A table's Next UI hint now takes `defaultSort` beside `defaultColumns`: `supplementalMetaData.nextUi.defaultSort`, an array of `{ "fieldName", "isAscending" }` in the shape of a query filter's order-bys. The list opens with it when the address carries no sort, no saved view is open and the browser remembers no sort for the table; each of those wins when present. New View and Reset All Changes return to it, and it is not counted as an unsaved change. Unknown or unsortable fields are ignored, and a table without a usable hint sorts by primary key descending as before. QQQ itself has no table-level default sort (as of 4.1.0-RC.32), so the application supplies the hint through a supplemental table metadata object of type `nextUi`; see the README, [Default sort](../../README.md#default-sort).
|
||||
|
||||
## Product fixes
|
||||
|
||||
- **A preference action that connects another service takes you there.** A provider that starts an OAuth connection (Connect Slack, for example) answers with the address of the service's consent page in the action result's `message`, since the UI API has no redirect field. That address was shown as the text of a success toast: long, not clickable and gone in seconds. A message that is nothing but one absolute `https:` address is now where the browser goes, in the same tab, and is never shown. A message that only mentions an address is still a message. Plain `http:`, addresses with credentials and every other scheme are not followed.
|
||||
- **Preferences says how a connection ended.** A flow that left the dashboard returns to `/app/preferences?section=<name>&result=<code>` when it succeeded or `&error=<code>` when it did not. The section now shows the outcome once, above its form, as the section's label and the code as words (`Slack: connected.`, `Slack: authorization denied.`), as a status or an alert, and takes it off the address so a reload does not repeat it. Only a fixed lowercase code is read from the address, never a sentence.
|
||||
- **Links in process HTML look like links.** An `HTML` process component rendered links in the text color with no underline, so a link the backend put on a screen (a bulk load template, a "Continue to Slack" link) could not be told from the words around it. They now use the link color and an underline; a link's own inline style still wins.
|
||||
|
||||
- **Explore views leave a way back.** Pivot, Compare, Correlation, Crosstab, Shift over time and a saved analysis are states of a table's record list, named by the query string (`?view=correlation`), so the breadcrumb, which read only the path, kept showing the table as the current page and offered no link back to the list. The breadcrumb now ends with the view (`… / People / Correlation`) and the table before it links to the list with its filter, sort, page and quick search as they were. "Back to records" is one step back in history when the list it returns to is the one the view was opened from, so the view stays one Forward away and the browser's Back button no longer meets the same list twice; after a drill changed the filter, or on a link straight to a view, it replaces the view with the list in place, as before. A Back or Forward step between the list and a view now takes the page and page size from the address as well as the filter and search, instead of returning the list to page 1. The views are registered in one place (`src/lib/utils/table-sub-views.ts`), which the list, the breadcrumb and the tests read, so a new view cannot ship without a label and a way back.
|
||||
|
||||
- **The Ask button's activity dot sits on its icon.** While a reply was being written, the dot was placed in the bottom-right corner of the button's hit area, which has no visible edge and, from 1440 px, extends past the "Ask" label, so the dot floated under and to the right of the label. The dot and the unread badge are now positioned against the sparkles icon, at every width and with the panel open or closed. The bell and Jobs badges use the same anchor and keep their place.
|
||||
|
||||
- **A presence outage is no longer shown as a server error.** The collaboration presence endpoint answers 503 on purpose for a while after its shared store restarts, and every table and record with presence showed that as a red `Server error — retrying…` banner, again and again. Presence is not essential to the page, so its failures now raise no banner. On a table the viewer count reads `Presence is reconnecting…` in muted text (a polite status, not an alert) until the server answers; on a record or an edit form that line appears only when other people were shown at the moment the connection was lost, and otherwise nothing changes. The poll and the lease renewal no longer repeat at a fixed 20 seconds or retry three times in seven: after a failure the next attempt waits 2.5 to 5 seconds, then twice as long per failure up to a minute, with jitter, and the first success restores the usual rhythm. In a 45 second outage one table made eleven presence requests and raised the banner twice; it now makes about eight and raises none.
|
||||
- **Background requests do not raise the error banner.** The rule behind the presence fix is general: a request the page makes on its own for something the page works without (`meta: BACKGROUND_REQUEST`) is logged to the console and shows no banner. It now also covers the notification bell's summary poll, the header's jobs count, the break-glass status check and the note of a recently viewed table or record. Requests a person starts are unchanged. See `docs/API-ERROR-HANDLING.md`.
|
||||
|
||||
- **Logout no longer races an in-flight request.** Logout ends the API client's session generation first: every request still in flight (axios and the realtime and assistant streams) is aborted, and any response of the old generation that still arrives is discarded, so none can refresh the `sessionId` cookie the logout expires or change client auth state (SEC-037, SEC-048).
|
||||
|
||||
- **The audit dialog holds a long record identifier, and sorts without asking again.** With a long unbroken record label (a 64 character identifier) the dialog's heading could not shrink or wrap, so it filled the card and pushed the sort and close buttons out of it, to its right. The heading now takes the space the controls leave, wraps at any character and is cut after three lines, with the whole text in its tooltip and a copy button beside the sort buttons; the controls stay inside the card from 320 px up, in both themes. An empty history is one block (a small icon over `No audits were found for this record.`) instead of a status line with a large icon in a band of its own below it; loading and error states no longer leave an empty band either. Opening the dialog makes one request, as before. Changing the sort order made another request every time; a history under the 1,000 row cap is complete, so the other order is now shown at once from what is loaded, and only a capped history goes back to the server. The audit process is given 25 seconds to answer in the same request instead of the server's default 3, after which the server answers that the run continues as a job, which the dialog showed as `Error loading audits`.
|
||||
|
||||
- **The error banner says what failed, and no longer stacks.** The banner for a failed request used to read "Something went wrong" for every failure without an expected status, and a polling request that kept failing added one banner per attempt. It now reads `No response from the server`, `The server took too long to respond`, the server's own message, or `Request failed (HTTP 409)`, and names the request below it (`POST /qqq/v1/table/order/query`, without the query string, with ids shown as `{id}`). A repeat of the same failure updates the banner on screen; a lost connection shows one banner whichever requests met it. The 403, 404 and 5xx banners keep their wording and gain the request line; a 403 without a server message reads `Permission denied`. A cancelled request, an aborted `fetch` and a 401 show no banner. Each banner logs its status, axios code, error name and request to the console once (`[API] Request failed:`), never a message, body, header or query string.
|
||||
|
||||
- **An assistant card for a set of records says how many, and lists them all.** The assistant can propose one confirmation card for a set of records (one run over many, for example a table's bulk delete). The server sends the total and every record of the set by name with a link (qbit-assistant 0.1.0-RC.32 and later), but the panel drew only the card's lines, which name five, so a person confirmed 27 records while seeing 5. The card now says before its buttons how many records it acts on and how many are named in view (`27 Printer records · showing 5`), and its confirm button carries the count (`Delete 27`, `Save 27`, `Run on 27`); a table's own bulk delete confirms as a delete, where it used to read "Save". `See all 27` opens every record by name inside the card, in a scroll area of bounded height that the keyboard reaches, and `Show fewer` closes it; a name is a link when its address passes the panel's internal-link check and plain text otherwise. Only the first five names are drawn until the list is asked for, so a set of 500 costs nothing up front. The count and the list stay on the card after it is confirmed, rejected or expired. When the list does not hold as many names as the count, the card shows the server's count and says so (`showing 20 of 27 names`, `The list holds 20 names, not 27.`). A card for one record, and a card from a server that sends no list, are unchanged.
|
||||
|
||||
## Browser testing and infrastructure
|
||||
|
||||
None yet.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"q-sequential-workflow.bundle.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD;AAClD;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,0CAA0C;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;AACA;AACA;AACA,4BAA4B,4BAA4B;AACxD;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB,mC;;;;;;;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,yCAAyC,iBAAiB;AAC1D;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC,6EAA6E,OAAO;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACmD;AACE;AACH;AACJ;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,8BAA8B;AAC1D,yCAAyC,2DAAc;AACvD;AACA;AACA;AACA;AACA,4BAA4B,yGAAyG;AACrI,wDAAwD,2DAAc;AACtE;AACA;AACA,4BAA4B,uDAAY;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,6DAAY;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,4BAA4B;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,gBAAgB;AAClF;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,gBAAgB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,gBAAgB;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,2DAA2D,WAAW,iJAAiJ;AACvN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yBAAyB;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yBAAyB;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,wBAAwB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,gDAAgD;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACuB;AACxB,wC;;;;;;;;;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,8CAA8C;AAC/C,6C;;;;;;;;;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC,6EAA6E,OAAO;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAC0B;AAC3B,2C;;;;;;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACoD;AACF;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,6EAA6E;AACrG;AACA,8BAA8B,6DAAe;AAC7C;AACA,wBAAwB,6EAA6E;AACrG;AACA,8BAA8B,2DAAc;AAC5C;AACA,wBAAwB,+EAA+E;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,gBAAgB;AACjE;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,gBAAgB;AACjE;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,gBAAgB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACuB;AACxB,wC;;;;;;;;;;;;;;;;;;ACjHA;AACgG;AACjB;AAC/E,8BAA8B,sEAA2B,CAAC,+EAAqC;AAC/F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACALine truncated
|
||||
+12
-28
@@ -1,15 +1,12 @@
|
||||
{
|
||||
"name": "qqq-frontend-next",
|
||||
"version": "1.0.0-RC.38",
|
||||
"version": "1.0.0-RC.37",
|
||||
"private": true,
|
||||
"packageManager": "pnpm@9.15.9",
|
||||
"scripts": {
|
||||
"scripting:worker": "node scripts/build-scripting-worker.mjs",
|
||||
"scripting:worker:check": "node scripts/build-scripting-worker.mjs && node scripts/check-scripting-worker.mjs",
|
||||
"dev": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && next dev --turbopack",
|
||||
"build": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && next build",
|
||||
"build:export": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && node scripts/build-export.mjs",
|
||||
"workflow:bundle": "node scripts/stage-dynamic-components.mjs",
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"build:export": "QQQ_NEXT_OUTPUT=export NEXT_PUBLIC_MOCK_API=false next build",
|
||||
"build:jar": "pnpm build:export && mvn -B -q clean package",
|
||||
"start": "next start",
|
||||
"lint": "eslint src && node scripts/check-license-headers.mjs",
|
||||
@@ -25,20 +22,17 @@
|
||||
"test:acceptance": "node scripts/acceptance.mjs",
|
||||
"perf:budget": "node scripts/perf-budget.mjs",
|
||||
"ui-api:check": "node scripts/check-ui-api-spec.mjs",
|
||||
"tsc": "node node_modules/typescript/bin/tsc",
|
||||
"typecheck": "node node_modules/typescript/bin/tsc --noEmit",
|
||||
"tsc": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"prepare": "git config core.hooksPath .githooks || true",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build",
|
||||
"pdf:worker": "node scripts/build-pdf-worker.mjs"
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "6.18.6",
|
||||
"@codemirror/commands": "6.8.1",
|
||||
"@codemirror/lang-javascript": "6.2.5",
|
||||
"@codemirror/lang-sql": "6.9.0",
|
||||
"@codemirror/language": "6.11.2",
|
||||
"@codemirror/lint": "6.8.5",
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "6.38.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
@@ -60,11 +54,10 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.4.17",
|
||||
"dompurify": "^3.4.16",
|
||||
"lodash": "^4.18.1",
|
||||
"lucide-react": "^0.485.0",
|
||||
"next": "16.4.3",
|
||||
"pdfjs-dist": "6.4.299",
|
||||
"next": "16.3.8",
|
||||
"rapidoc": "10.1.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
@@ -77,8 +70,7 @@
|
||||
"sonner": "^2.0.7",
|
||||
"sql-formatter": "15.6.6",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"typescript-editor": "npm:typescript@6.0.3",
|
||||
"zod": "^4.6.7"
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.11.1",
|
||||
@@ -101,7 +93,7 @@
|
||||
"@vitest/ui": "^4.1.12",
|
||||
"autoprefixer": "^10.4.27",
|
||||
"eslint": "^9.39.3",
|
||||
"eslint-config-next": "16.4.1",
|
||||
"eslint-config-next": "16.3.6",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-jsdoc": "^62.7.1",
|
||||
"jest-axe": "^10.0.0",
|
||||
@@ -122,19 +114,11 @@
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"@codemirror/autocomplete": "6.18.6",
|
||||
"@codemirror/commands": "6.8.1",
|
||||
"@codemirror/language": "6.11.2",
|
||||
"@codemirror/lint": "6.8.5",
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "6.38.1",
|
||||
"serialize-javascript": ">=7.0.3",
|
||||
"@humanfs/node": ">=0.16.8",
|
||||
"@babel/core": ">=7.29.6 <8",
|
||||
"source-map-js": ">=1.2.2",
|
||||
"follow-redirects": ">=1.16.2",
|
||||
"undici@>=7 <8": ">=7.30.1 <8",
|
||||
"fast-uri@>=3 <4": ">=3.1.9 <4"
|
||||
"follow-redirects@<1.16.1": "1.16.1"
|
||||
},
|
||||
"ignoredOptionalDependencies": [
|
||||
"electron"
|
||||
|
||||
Generated
+120
-269
@@ -5,19 +5,11 @@ settings:
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
'@codemirror/autocomplete': 6.18.6
|
||||
'@codemirror/commands': 6.8.1
|
||||
'@codemirror/language': 6.11.2
|
||||
'@codemirror/lint': 6.8.5
|
||||
'@codemirror/state': 6.5.2
|
||||
'@codemirror/view': 6.38.1
|
||||
serialize-javascript: '>=7.0.3'
|
||||
'@humanfs/node': '>=0.16.8'
|
||||
'@babel/core': '>=7.29.6 <8'
|
||||
source-map-js: '>=1.2.2'
|
||||
follow-redirects: '>=1.16.2'
|
||||
undici@>=7 <8: '>=7.30.1 <8'
|
||||
fast-uri@>=3 <4: '>=3.1.9 <4'
|
||||
follow-redirects@<1.16.1: 1.16.1
|
||||
|
||||
importers:
|
||||
|
||||
@@ -29,18 +21,12 @@ importers:
|
||||
'@codemirror/commands':
|
||||
specifier: 6.8.1
|
||||
version: 6.8.1
|
||||
'@codemirror/lang-javascript':
|
||||
specifier: 6.2.5
|
||||
version: 6.2.5
|
||||
'@codemirror/lang-sql':
|
||||
specifier: 6.9.0
|
||||
version: 6.9.0
|
||||
'@codemirror/language':
|
||||
specifier: 6.11.2
|
||||
version: 6.11.2
|
||||
'@codemirror/lint':
|
||||
specifier: 6.8.5
|
||||
version: 6.8.5
|
||||
'@codemirror/state':
|
||||
specifier: 6.5.2
|
||||
version: 6.5.2
|
||||
@@ -105,8 +91,8 @@ importers:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
dompurify:
|
||||
specifier: ^3.4.17
|
||||
version: 3.4.17
|
||||
specifier: ^3.4.16
|
||||
version: 3.4.16
|
||||
lodash:
|
||||
specifier: ^4.18.1
|
||||
version: 4.18.1
|
||||
@@ -114,11 +100,8 @@ importers:
|
||||
specifier: ^0.485.0
|
||||
version: 0.485.0(react@19.2.4)
|
||||
next:
|
||||
specifier: 16.4.3
|
||||
version: 16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
pdfjs-dist:
|
||||
specifier: 6.4.299
|
||||
version: 6.4.299
|
||||
specifier: 16.3.8
|
||||
version: 16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
rapidoc:
|
||||
specifier: 10.1.0
|
||||
version: 10.1.0
|
||||
@@ -155,12 +138,9 @@ importers:
|
||||
tailwind-merge:
|
||||
specifier: ^3.5.0
|
||||
version: 3.5.0
|
||||
typescript-editor:
|
||||
specifier: npm:typescript@6.0.3
|
||||
version: typescript@6.0.3
|
||||
zod:
|
||||
specifier: ^4.6.7
|
||||
version: 4.6.7
|
||||
specifier: ^3.25.76
|
||||
version: 3.25.76
|
||||
devDependencies:
|
||||
'@axe-core/playwright':
|
||||
specifier: ^4.11.1
|
||||
@@ -176,7 +156,7 @@ importers:
|
||||
version: 10.6.2(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))
|
||||
'@storybook/nextjs-vite':
|
||||
specifier: 10.6.2
|
||||
version: 10.6.2(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
version: 10.6.2(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
'@storybook/react':
|
||||
specifier: 10.6.2
|
||||
version: 10.6.2(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)
|
||||
@@ -223,8 +203,8 @@ importers:
|
||||
specifier: ^9.39.3
|
||||
version: 9.39.3(jiti@2.7.0)
|
||||
eslint-config-next:
|
||||
specifier: 16.4.1
|
||||
version: 16.4.1(@typescript-eslint/parser@8.70.1(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3)
|
||||
specifier: 16.3.6
|
||||
version: 16.3.6(@typescript-eslint/parser@8.70.1(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3)
|
||||
eslint-config-prettier:
|
||||
specifier: ^10.1.8
|
||||
version: 10.1.8(eslint@9.39.3(jiti@2.7.0))
|
||||
@@ -401,18 +381,12 @@ packages:
|
||||
'@codemirror/commands@6.8.1':
|
||||
resolution: {integrity: sha512-KlGVYufHMQzxbdQONiLyGQDUW0itrLZwq3CcY7xpv9ZLRHqzkBSoteocBHtMCoY7/Ci4xhzSrToIeLg7FxHuaw==}
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
|
||||
|
||||
'@codemirror/lang-sql@6.9.0':
|
||||
resolution: {integrity: sha512-xmtpWqKSgum1B1J3Ro6rf7nuPqf2+kJQg5SjrofCAcyCThOe0ihSktSoXfXuhQBnwx1QbmreBbLJM5Jru6zitg==}
|
||||
|
||||
'@codemirror/language@6.11.2':
|
||||
resolution: {integrity: sha512-p44TsNArL4IVXDTbapUmEkAlvWs2CFQbcfc0ymDsis1kH2wh0gcY96AS29c/vp2d0y2Tquk1EDSaawpzilUiAw==}
|
||||
|
||||
'@codemirror/lint@6.8.5':
|
||||
resolution: {integrity: sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA==}
|
||||
|
||||
'@codemirror/state@6.5.2':
|
||||
resolution: {integrity: sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==}
|
||||
|
||||
@@ -971,9 +945,6 @@ packages:
|
||||
'@lezer/highlight@1.2.1':
|
||||
resolution: {integrity: sha512-Z5duk4RN/3zuVO7Jq0pGLJ3qynpxUVsh7IbUbGj88+uV2ApSAn6kWg2au3iJb+0Zi7kKtqffIESgNcRXWZWmSA==}
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
resolution: {integrity: sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==}
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
resolution: {integrity: sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==}
|
||||
|
||||
@@ -996,76 +967,6 @@ packages:
|
||||
resolution: {integrity: sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@napi-rs/canvas-android-arm64@1.1.0':
|
||||
resolution: {integrity: sha512-mKrSmRyhWK4q699Q1xthbZIZi7JBvLtsRNnOZAeFaLPOFT1yo8y82aRC2nNZbXTGJXU7fVDONgGQPr0vo3kerw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@napi-rs/canvas-darwin-arm64@1.1.0':
|
||||
resolution: {integrity: sha512-iqwST4g0oH+x8VCpBIYh+MYokv/mVvkM+v9oJGB0d9A3P2qBh42ogJlVyWq9SpPCrAjS7tplMb1D3OIfxl+utw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@napi-rs/canvas-darwin-x64@1.1.0':
|
||||
resolution: {integrity: sha512-jkeA8eVTxDum03LTvc32YJ28F6KB1U0gYwnWMfOAUQZvWWEh/kvONby4iWGJx3+Tw45UqMGMXjtw2GKNVZDhVg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@napi-rs/canvas-linux-arm-gnueabihf@1.1.0':
|
||||
resolution: {integrity: sha512-Y4YkKG1ijoqkgUdTEEBNG4k+2BK5bR5jGL6S56YxCXYPwGfUd5nED8/74xyc7z+bpixPasCjSYoP3xYPOIGNxw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-linux-arm64-gnu@1.1.0':
|
||||
resolution: {integrity: sha512-dE/XthqYkiWcBVtKFlZbUXwAYfDuQGqDWixznipJNmevLGpprNnTVQZyftm1RZJudkIOn2EkzYZDMMETM08Row==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-linux-arm64-musl@1.1.0':
|
||||
resolution: {integrity: sha512-DqZ/CMcHlhU56pPjv9AP0h3U7MFQ5LzC1HzMyRMotL+PFsJmZJA/ziApPYVyyz78DaVLhI8t3So3ztqtijbYpg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-linux-riscv64-gnu@1.1.0':
|
||||
resolution: {integrity: sha512-kJ7m5n2VffxWXM5QGa5lfq8ZN4LdOJEoz3aAJAmIqYvKiZw1gRdXqpucnRXsF6D9nLYiiIlevaAtAclR7c5ilg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-linux-x64-gnu@1.1.0':
|
||||
resolution: {integrity: sha512-uQ9JuJlRhQdHyttcMWOiwLkfIqkqaB0YFUVe835LUe12THt2b51HXkTItq0fxWT1jdhUPX2ylWZ1walkJyD6GQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-linux-x64-musl@1.1.0':
|
||||
resolution: {integrity: sha512-has4CPPAkkCac/LZ13VAw5p+MJLdaKVoyrhumN/A7uJd6960xYkJNDZgUebyxiha82AFzXx6RV+QJg5qGG079g==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@napi-rs/canvas-win32-arm64-msvc@1.1.0':
|
||||
resolution: {integrity: sha512-MJnktLKNijmXqdjTughHDZ9TDLZ9uUm2hvFXqaOqn0+w7lphXFnft6bpSgQAc9U1exc20UGIBlzGu9+kiCj9Ag==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@napi-rs/canvas-win32-x64-msvc@1.1.0':
|
||||
resolution: {integrity: sha512-08575bFk7iiadxap4h+JxgGut9xDCHAGum6wh0eInN53zEMImkmEHi5MushX2FOmNO7qRNX7BPiDC5ZYBwHeEg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@napi-rs/canvas@1.1.0':
|
||||
resolution: {integrity: sha512-k+ph/D8H9GS8ZZ48okvHrKeJynkqAA1kMUZRuzRWNlQUDHXngq7oRaWMZBdmSfd9ZhVy9bwNKei/7wMboI/uMg==}
|
||||
engines: {node: '>= 10'}
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||
@@ -1079,56 +980,59 @@ packages:
|
||||
'@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4
|
||||
'@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4
|
||||
|
||||
'@next/env@16.4.3':
|
||||
resolution: {integrity: sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==}
|
||||
'@next/env@16.3.8':
|
||||
resolution: {integrity: sha512-Al9zqHVV7TJv0eFuOU4U7Lvv74PTih4Ch63sk2xCIpSTkE3udFnaOcnzP2lQVymiL7yS9Cj2iClUXlR3EQ5sEw==}
|
||||
|
||||
'@next/eslint-plugin-next@16.4.1':
|
||||
resolution: {integrity: sha512-2io6M+wAqe7nT5mt2gEVy6FOzye2DmwhjaYCpSvHfrIKL11SXNTwSARxpPHJacRmfgSBSDnNmnEXSp0DaJ23BQ==}
|
||||
'@next/env@16.4.0':
|
||||
resolution: {integrity: sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ==}
|
||||
|
||||
'@next/swc-darwin-arm64@16.4.3':
|
||||
resolution: {integrity: sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==}
|
||||
'@next/eslint-plugin-next@16.3.6':
|
||||
resolution: {integrity: sha512-jowwDX+7DOlDIjJLgTMxudw+k37QnWu1JkZLkSi9MaJBfDYcfhAPMKBhXL0idYzFN/AGg//axnOR4cLkHX/Rng==}
|
||||
|
||||
'@next/swc-darwin-arm64@16.3.8':
|
||||
resolution: {integrity: sha512-2JPRMh2nmQG5CiL7cXGL9AGwnPWJQ//cTtAUCT+w511QHk79SYz3LGv/pc5X643B/WEO0rvu3Yww0hqwt3kgeA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@next/swc-darwin-x64@16.4.3':
|
||||
resolution: {integrity: sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==}
|
||||
'@next/swc-darwin-x64@16.3.8':
|
||||
resolution: {integrity: sha512-GZtCCOBKJ4leVIT/Th0llWKhD1ca92lzbQiS5R5ON9QkoiFnilFsebDae1JU2a3HWoKMEmEZWGs1AGLavVM72Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@next/swc-linux-arm64-gnu@16.4.3':
|
||||
resolution: {integrity: sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==}
|
||||
'@next/swc-linux-arm64-gnu@16.3.8':
|
||||
resolution: {integrity: sha512-O659ygeQYqneJ1fBKMpFxIFqYkYswu8IAS1OCKK/4f3ZgJJm1dRz4fVJZRi/kLLWjnBKnebOePA4WNv+sV1pVA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@next/swc-linux-arm64-musl@16.4.3':
|
||||
resolution: {integrity: sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==}
|
||||
'@next/swc-linux-arm64-musl@16.3.8':
|
||||
resolution: {integrity: sha512-dSjKSyWpzxoO1d3DIZZcP4XJcNaKeLmxQMFOiYl5vuBRMmweIqnAhty8tAmRsvTss779cK1FtYnDMj40e4TQlg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@next/swc-linux-x64-gnu@16.4.3':
|
||||
resolution: {integrity: sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==}
|
||||
'@next/swc-linux-x64-gnu@16.3.8':
|
||||
resolution: {integrity: sha512-lbqOuz3RPRcv+o9msNsJw5x4+Y1ZwPTs6vmL6DCf7i0fZfvng/F59wyeDwqHIvV0mK//RBy/jJkZ+nCKsSMXjQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@next/swc-linux-x64-musl@16.4.3':
|
||||
resolution: {integrity: sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==}
|
||||
'@next/swc-linux-x64-musl@16.3.8':
|
||||
resolution: {integrity: sha512-+316WswI8ScVgZeUd+1KGaXkHhaYQzCjvH/05TZSpJ8zBizb1a4G7DtO7F12jcBIqMOtsz9ji1t48fmKtzqsGA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@next/swc-win32-arm64-msvc@16.4.3':
|
||||
resolution: {integrity: sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==}
|
||||
'@next/swc-win32-arm64-msvc@16.3.8':
|
||||
resolution: {integrity: sha512-ji0gd4kMYUxO+1fJBIbiBVRCjzG/lloiyCccnlebvb1ZJ5qXCPZqYg4Jl1DrrixnWNMKylzgpmMWx0yNDYXlzw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@next/swc-win32-x64-msvc@16.4.3':
|
||||
resolution: {integrity: sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==}
|
||||
'@next/swc-win32-x64-msvc@16.3.8':
|
||||
resolution: {integrity: sha512-WcTlaKt/TWkh5kUjdJcUmB1XgZ+1c6fz4Y9fDHL73YNSdGaUWjceeWrrlwF0nv19iABYWC4iAq1oX1w4Bn0vfg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -2761,6 +2665,10 @@ packages:
|
||||
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
call-bind@1.0.8:
|
||||
resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
call-bind@1.0.9:
|
||||
resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3055,8 +2963,8 @@ packages:
|
||||
dom-helpers@5.2.1:
|
||||
resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}
|
||||
|
||||
dompurify@3.4.17:
|
||||
resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==}
|
||||
dompurify@3.4.16:
|
||||
resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==}
|
||||
|
||||
dunder-proto@1.0.1:
|
||||
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
|
||||
@@ -3147,8 +3055,8 @@ packages:
|
||||
resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
eslint-config-next@16.4.1:
|
||||
resolution: {integrity: sha512-6AsojbCfRdpWkP6BIUnMBv3MH4OvtfmH9p4hSfLh8ZgsW7nfhu7DpUMNBB7leisDyyMz+YYxTc+NAdBOQfovlA==}
|
||||
eslint-config-next@16.3.6:
|
||||
resolution: {integrity: sha512-1Upt3U7BDwU+ilpe2byZjAfts9oNq4d4fv/zXEvs8/4yS+cwOQW/WCxUNy8gCDquX67SzeehDvKblVC6ZBMocQ==}
|
||||
peerDependencies:
|
||||
eslint: '>=9.0.0'
|
||||
typescript: '>=3.3.1'
|
||||
@@ -3329,8 +3237,8 @@ packages:
|
||||
fast-levenshtein@2.0.6:
|
||||
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
|
||||
|
||||
fast-uri@3.1.9:
|
||||
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
|
||||
fast-uri@3.1.8:
|
||||
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
|
||||
|
||||
fastq@1.20.3:
|
||||
resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==}
|
||||
@@ -3366,8 +3274,8 @@ packages:
|
||||
flatted@3.4.4:
|
||||
resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==}
|
||||
|
||||
follow-redirects@1.16.2:
|
||||
resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
|
||||
follow-redirects@1.16.1:
|
||||
resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==}
|
||||
engines: {node: '>=4.0'}
|
||||
peerDependencies:
|
||||
debug: '*'
|
||||
@@ -4251,8 +4159,8 @@ packages:
|
||||
engines: {node: '>= 4.4.x'}
|
||||
hasBin: true
|
||||
|
||||
next@16.4.3:
|
||||
resolution: {integrity: sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==}
|
||||
next@16.3.8:
|
||||
resolution: {integrity: sha512-U7QEZaTini6wKrb8A8hqLLqYQyCetegKjCpJOyxk642vWoMoU1x5PyZCJFvgYgiptA8xc5j/9xYlZFO7w9Sjmw==}
|
||||
engines: {node: '>=20.9.0'}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
@@ -4393,10 +4301,6 @@ packages:
|
||||
resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
|
||||
engines: {node: '>= 14.16'}
|
||||
|
||||
pdfjs-dist@6.4.299:
|
||||
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
|
||||
engines: {node: '>=22.13.0 || >=24'}
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -5091,11 +4995,6 @@ packages:
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
typescript@6.0.3:
|
||||
resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
unbox-primitive@1.1.0:
|
||||
resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -5103,8 +5002,8 @@ packages:
|
||||
undici-types@6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
|
||||
undici@7.30.1:
|
||||
resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==}
|
||||
undici@7.29.1:
|
||||
resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==}
|
||||
engines: {node: '>=20.18.1'}
|
||||
|
||||
unified@11.0.5:
|
||||
@@ -5313,6 +5212,10 @@ packages:
|
||||
resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
which-typed-array@1.1.20:
|
||||
resolution: {integrity: sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
which-typed-array@1.1.24:
|
||||
resolution: {integrity: sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -5396,6 +5299,9 @@ packages:
|
||||
peerDependencies:
|
||||
zod: ^3.25.0 || ^4.0.0
|
||||
|
||||
zod@3.25.76:
|
||||
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
|
||||
|
||||
zod@4.6.7:
|
||||
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
|
||||
|
||||
@@ -5575,16 +5481,6 @@ snapshots:
|
||||
'@codemirror/view': 6.38.1
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.18.6
|
||||
'@codemirror/language': 6.11.2
|
||||
'@codemirror/lint': 6.8.5
|
||||
'@codemirror/state': 6.5.2
|
||||
'@codemirror/view': 6.38.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
'@codemirror/lang-sql@6.9.0':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.18.6
|
||||
@@ -5603,12 +5499,6 @@ snapshots:
|
||||
'@lezer/lr': 1.4.11
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/lint@6.8.5':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.5.2
|
||||
'@codemirror/view': 6.38.1
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/state@6.5.2':
|
||||
dependencies:
|
||||
'@marijn/find-cluster-break': 1.0.4
|
||||
@@ -6074,12 +5964,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.1
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
@@ -6107,54 +5991,6 @@ snapshots:
|
||||
outvariant: 1.4.3
|
||||
strict-event-emitter: 0.5.1
|
||||
|
||||
'@napi-rs/canvas-android-arm64@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-darwin-arm64@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-darwin-x64@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-arm-gnueabihf@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-arm64-gnu@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-arm64-musl@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-riscv64-gnu@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-x64-gnu@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-linux-x64-musl@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-win32-arm64-msvc@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas-win32-x64-msvc@1.1.0':
|
||||
optional: true
|
||||
|
||||
'@napi-rs/canvas@1.1.0':
|
||||
optionalDependencies:
|
||||
'@napi-rs/canvas-android-arm64': 1.1.0
|
||||
'@napi-rs/canvas-darwin-arm64': 1.1.0
|
||||
'@napi-rs/canvas-darwin-x64': 1.1.0
|
||||
'@napi-rs/canvas-linux-arm-gnueabihf': 1.1.0
|
||||
'@napi-rs/canvas-linux-arm64-gnu': 1.1.0
|
||||
'@napi-rs/canvas-linux-arm64-musl': 1.1.0
|
||||
'@napi-rs/canvas-linux-riscv64-gnu': 1.1.0
|
||||
'@napi-rs/canvas-linux-x64-gnu': 1.1.0
|
||||
'@napi-rs/canvas-linux-x64-musl': 1.1.0
|
||||
'@napi-rs/canvas-win32-arm64-msvc': 1.1.0
|
||||
'@napi-rs/canvas-win32-x64-msvc': 1.1.0
|
||||
optional: true
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
optional: true
|
||||
|
||||
@@ -6179,37 +6015,39 @@ snapshots:
|
||||
'@tybys/wasm-util': 0.10.4
|
||||
optional: true
|
||||
|
||||
'@next/env@16.4.3': {}
|
||||
'@next/env@16.3.8': {}
|
||||
|
||||
'@next/eslint-plugin-next@16.4.1(eslint@9.39.3(jiti@2.7.0))':
|
||||
'@next/env@16.4.0': {}
|
||||
|
||||
'@next/eslint-plugin-next@16.3.6(eslint@9.39.3(jiti@2.7.0))':
|
||||
dependencies:
|
||||
'@eslint-community/eslint-utils': 4.9.1(eslint@9.39.3(jiti@2.7.0))
|
||||
fast-glob: 3.3.1
|
||||
transitivePeerDependencies:
|
||||
- eslint
|
||||
|
||||
'@next/swc-darwin-arm64@16.4.3':
|
||||
'@next/swc-darwin-arm64@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-darwin-x64@16.4.3':
|
||||
'@next/swc-darwin-x64@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-linux-arm64-gnu@16.4.3':
|
||||
'@next/swc-linux-arm64-gnu@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-linux-arm64-musl@16.4.3':
|
||||
'@next/swc-linux-arm64-musl@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-linux-x64-gnu@16.4.3':
|
||||
'@next/swc-linux-x64-gnu@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-linux-x64-musl@16.4.3':
|
||||
'@next/swc-linux-x64-musl@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-win32-arm64-msvc@16.4.3':
|
||||
'@next/swc-win32-arm64-msvc@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@next/swc-win32-x64-msvc@16.4.3':
|
||||
'@next/swc-win32-x64-msvc@16.3.8':
|
||||
optional: true
|
||||
|
||||
'@nodelib/fs.scandir@2.1.5':
|
||||
@@ -6831,7 +6669,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@scalar/helpers': 0.16.3
|
||||
pathe: 2.0.3
|
||||
undici: 7.30.1
|
||||
undici: 7.29.1
|
||||
yaml: 2.9.1
|
||||
|
||||
'@scalar/json-schema-validator@0.1.12':
|
||||
@@ -6911,18 +6749,18 @@ snapshots:
|
||||
dependencies:
|
||||
react: 19.2.4
|
||||
|
||||
'@storybook/nextjs-vite@10.6.2(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))':
|
||||
'@storybook/nextjs-vite@10.6.2(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))':
|
||||
dependencies:
|
||||
'@storybook/builder-vite': 10.6.2(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
'@storybook/react': 10.6.2(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)
|
||||
'@storybook/react-vite': 10.6.2(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
next: 16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
next: 16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
react: 19.2.4
|
||||
react-dom: 19.2.4(react@19.2.4)
|
||||
storybook: 10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4)
|
||||
styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.2.4)
|
||||
vite: 7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1)
|
||||
vite-plugin-storybook-nextjs: 10.6.2(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
vite-plugin-storybook-nextjs: 10.6.2(next@16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1))
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.14
|
||||
'@types/react-dom': 19.2.3(@types/react@19.2.14)
|
||||
@@ -7550,7 +7388,7 @@ snapshots:
|
||||
ajv@8.20.0:
|
||||
dependencies:
|
||||
fast-deep-equal: 3.1.3
|
||||
fast-uri: 3.1.9
|
||||
fast-uri: 3.1.8
|
||||
json-schema-traverse: 1.0.0
|
||||
require-from-string: 2.0.2
|
||||
|
||||
@@ -7684,7 +7522,7 @@ snapshots:
|
||||
|
||||
axios@1.20.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.2
|
||||
follow-redirects: 1.16.1
|
||||
form-data: 4.0.6
|
||||
https-proxy-agent: 5.0.1
|
||||
proxy-from-env: 2.1.0
|
||||
@@ -7735,6 +7573,13 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
function-bind: 1.1.2
|
||||
|
||||
call-bind@1.0.8:
|
||||
dependencies:
|
||||
call-bind-apply-helpers: 1.0.2
|
||||
es-define-property: 1.0.1
|
||||
get-intrinsic: 1.3.0
|
||||
set-function-length: 1.2.2
|
||||
|
||||
call-bind@1.0.9:
|
||||
dependencies:
|
||||
call-bind-apply-helpers: 1.0.2
|
||||
@@ -7992,7 +7837,7 @@ snapshots:
|
||||
'@babel/runtime': 7.28.6
|
||||
csstype: 3.2.3
|
||||
|
||||
dompurify@3.4.17:
|
||||
dompurify@3.4.16:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
@@ -8171,9 +8016,9 @@ snapshots:
|
||||
|
||||
escape-string-regexp@5.0.0: {}
|
||||
|
||||
eslint-config-next@16.4.1(@typescript-eslint/parser@8.70.1(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3):
|
||||
eslint-config-next@16.3.6(@typescript-eslint/parser@8.70.1(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.3(jiti@2.7.0))(typescript@5.9.3):
|
||||
dependencies:
|
||||
'@next/eslint-plugin-next': 16.4.1(eslint@9.39.3(jiti@2.7.0))
|
||||
'@next/eslint-plugin-next': 16.3.6(eslint@9.39.3(jiti@2.7.0))
|
||||
eslint: 9.39.3(jiti@2.7.0)
|
||||
eslint-import-resolver-node: 0.3.10
|
||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.3(jiti@2.7.0))
|
||||
@@ -8303,8 +8148,8 @@ snapshots:
|
||||
'@babel/parser': 7.29.9
|
||||
eslint: 9.39.3(jiti@2.7.0)
|
||||
hermes-parser: 0.25.1
|
||||
zod: 4.6.7
|
||||
zod-validation-error: 4.0.2(zod@4.6.7)
|
||||
zod: 3.25.76
|
||||
zod-validation-error: 4.0.2(zod@3.25.76)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -8447,7 +8292,7 @@ snapshots:
|
||||
|
||||
fast-levenshtein@2.0.6: {}
|
||||
|
||||
fast-uri@3.1.9: {}
|
||||
fast-uri@3.1.8: {}
|
||||
|
||||
fastq@1.20.3:
|
||||
dependencies:
|
||||
@@ -8479,7 +8324,7 @@ snapshots:
|
||||
|
||||
flatted@3.4.4: {}
|
||||
|
||||
follow-redirects@1.16.2: {}
|
||||
follow-redirects@1.16.1: {}
|
||||
|
||||
for-each@0.3.5:
|
||||
dependencies:
|
||||
@@ -8816,7 +8661,7 @@ snapshots:
|
||||
call-bound: 1.0.4
|
||||
gopd: 1.2.0
|
||||
has-tostringtag: 1.0.2
|
||||
hasown: 2.0.4
|
||||
hasown: 2.0.2
|
||||
|
||||
is-set@2.0.3: {}
|
||||
|
||||
@@ -8837,7 +8682,7 @@ snapshots:
|
||||
|
||||
is-typed-array@1.1.15:
|
||||
dependencies:
|
||||
which-typed-array: 1.1.24
|
||||
which-typed-array: 1.1.20
|
||||
|
||||
is-weakmap@2.0.2: {}
|
||||
|
||||
@@ -9595,9 +9440,9 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
|
||||
next@16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
|
||||
dependencies:
|
||||
'@next/env': 16.4.3
|
||||
'@next/env': 16.3.8
|
||||
'@swc/helpers': 0.5.23
|
||||
baseline-browser-mapping: 2.11.28
|
||||
caniuse-lite: 1.0.30001815
|
||||
@@ -9606,14 +9451,14 @@ snapshots:
|
||||
react-dom: 19.2.4(react@19.2.4)
|
||||
styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.2.4)
|
||||
optionalDependencies:
|
||||
'@next/swc-darwin-arm64': 16.4.3
|
||||
'@next/swc-darwin-x64': 16.4.3
|
||||
'@next/swc-linux-arm64-gnu': 16.4.3
|
||||
'@next/swc-linux-arm64-musl': 16.4.3
|
||||
'@next/swc-linux-x64-gnu': 16.4.3
|
||||
'@next/swc-linux-x64-musl': 16.4.3
|
||||
'@next/swc-win32-arm64-msvc': 16.4.3
|
||||
'@next/swc-win32-x64-msvc': 16.4.3
|
||||
'@next/swc-darwin-arm64': 16.3.8
|
||||
'@next/swc-darwin-x64': 16.3.8
|
||||
'@next/swc-linux-arm64-gnu': 16.3.8
|
||||
'@next/swc-linux-arm64-musl': 16.3.8
|
||||
'@next/swc-linux-x64-gnu': 16.3.8
|
||||
'@next/swc-linux-x64-musl': 16.3.8
|
||||
'@next/swc-win32-arm64-msvc': 16.3.8
|
||||
'@next/swc-win32-x64-msvc': 16.3.8
|
||||
'@playwright/test': 1.64.0-alpha-2026-10-01
|
||||
sharp: 0.35.5(@types/node@22.19.11)
|
||||
transitivePeerDependencies:
|
||||
@@ -9642,10 +9487,10 @@ snapshots:
|
||||
|
||||
object.assign@4.1.7:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
call-bind: 1.0.8
|
||||
call-bound: 1.0.4
|
||||
define-properties: 1.2.1
|
||||
es-object-atoms: 1.1.2
|
||||
es-object-atoms: 1.1.1
|
||||
has-symbols: 1.1.0
|
||||
object-keys: 1.1.1
|
||||
|
||||
@@ -9799,10 +9644,6 @@ snapshots:
|
||||
|
||||
pathval@2.0.1: {}
|
||||
|
||||
pdfjs-dist@6.4.299:
|
||||
optionalDependencies:
|
||||
'@napi-rs/canvas': 1.1.0
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
picomatch@2.3.2: {}
|
||||
@@ -10638,8 +10479,6 @@ snapshots:
|
||||
|
||||
typescript@5.9.3: {}
|
||||
|
||||
typescript@6.0.3: {}
|
||||
|
||||
unbox-primitive@1.1.0:
|
||||
dependencies:
|
||||
call-bound: 1.0.4
|
||||
@@ -10649,7 +10488,7 @@ snapshots:
|
||||
|
||||
undici-types@6.21.0: {}
|
||||
|
||||
undici@7.30.1: {}
|
||||
undici@7.29.1: {}
|
||||
|
||||
unified@11.0.5:
|
||||
dependencies:
|
||||
@@ -10776,13 +10615,13 @@ snapshots:
|
||||
d3-time: 3.1.0
|
||||
d3-timer: 3.0.1
|
||||
|
||||
vite-plugin-storybook-nextjs@10.6.2(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1)):
|
||||
vite-plugin-storybook-nextjs@10.6.2(next@16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.64.6)(storybook@10.6.2(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.7(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)(yaml@2.9.1)):
|
||||
dependencies:
|
||||
'@next/env': 16.4.3
|
||||
'@next/env': 16.4.0
|
||||
'@rollup/pluginutils': 5.4.0(rollup@4.64.6)
|
||||
magic-string: 0.30.21
|
||||
module-alias: 2.3.4
|
||||
next: 16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
next: 16.3.8(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
|
||||
pathe: 2.0.3
|
||||
probe-image-size: 7.4.0
|
||||
semver: 7.8.5
|
||||
@@ -10904,6 +10743,16 @@ snapshots:
|
||||
is-weakmap: 2.0.2
|
||||
is-weakset: 2.0.4
|
||||
|
||||
which-typed-array@1.1.20:
|
||||
dependencies:
|
||||
available-typed-arrays: 1.0.7
|
||||
call-bind: 1.0.8
|
||||
call-bound: 1.0.4
|
||||
for-each: 0.3.5
|
||||
get-proto: 1.0.1
|
||||
gopd: 1.2.0
|
||||
has-tostringtag: 1.0.2
|
||||
|
||||
which-typed-array@1.1.24:
|
||||
dependencies:
|
||||
available-typed-arrays: 1.0.7
|
||||
@@ -10969,9 +10818,11 @@ snapshots:
|
||||
|
||||
yoctocolors-cjs@2.1.3: {}
|
||||
|
||||
zod-validation-error@4.0.2(zod@4.6.7):
|
||||
zod-validation-error@4.0.2(zod@3.25.76):
|
||||
dependencies:
|
||||
zod: 4.6.7
|
||||
zod: 3.25.76
|
||||
|
||||
zod@3.25.76: {}
|
||||
|
||||
zod@4.6.7: {}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
</developers>
|
||||
|
||||
<properties>
|
||||
<revision>1.0.0-RC.38</revision>
|
||||
<revision>1.0.0-RC.37</revision>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.build.outputTimestamp>2026-09-24T00:00:00Z</project.build.outputTimestamp>
|
||||
</properties>
|
||||
@@ -89,10 +89,8 @@
|
||||
<files>
|
||||
<file>${project.basedir}/out/index.html</file>
|
||||
<file>${project.basedir}/out/app/_/_/index.html</file>
|
||||
<file>${project.basedir}/out/dynamic-qfmd-components/q-sequential-workflow.bundle.js</file>
|
||||
<file>${project.basedir}/out/dynamic-qfmd-components/q-sequential-workflow.bundle.js.map</file>
|
||||
</files>
|
||||
<message>Run pnpm build:export (or pnpm build:jar) before packaging; the export must contain the QSequentialWorkflow editor bundle staged from dynamic-components/.</message>
|
||||
<message>Run "QQQ_NEXT_OUTPUT=export pnpm build" (or pnpm build:jar) before packaging.</message>
|
||||
</requireFilesExist>
|
||||
</rules>
|
||||
</configuration>
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
|
||||
// Pass build settings through the child environment on Windows and POSIX alike.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const result = spawnSync(process.execPath, [require.resolve('next/dist/bin/next'), 'build'], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, QQQ_NEXT_OUTPUT: 'export', NEXT_PUBLIC_MOCK_API: 'false' },
|
||||
})
|
||||
if (result.error) console.error(result.error.message)
|
||||
process.exit(result.status ?? 1)
|
||||
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Copy the pinned trusted PDF worker; never copy uploaded files. */
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFile, mkdir, copyFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
const require = createRequire(import.meta.url)
|
||||
const entry = require.resolve('pdfjs-dist/package.json')
|
||||
const root = path.dirname(entry)
|
||||
const pkg = JSON.parse(await readFile(entry, 'utf8'))
|
||||
if (pkg.version !== '6.4.299') throw new Error('Pinned PDF.js 6.4.299 is required')
|
||||
const output = new URL('../public/pdf-generated/', import.meta.url)
|
||||
await mkdir(output, { recursive: true })
|
||||
await copyFile(path.join(root, 'build/pdf.worker.min.mjs'), new URL('pdf-6.4.299.worker.js', output))
|
||||
await copyFile(path.join(root, 'LICENSE'), new URL('LICENSE', output))
|
||||
console.log('Prepared pinned PDF.js 6.4.299 worker and Apache-2.0 license')
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
/** @file Build the offline editor worker from pinned trusted dependencies; never reads a script project. */
|
||||
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript-editor')
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
if (ts.version !== '6.0.3') throw new Error('Pinned editor TypeScript 6.0.3 is required')
|
||||
const libraryDirectory = path.dirname(require.resolve('typescript-editor'))
|
||||
const libraries = Object.create(null)
|
||||
|
||||
/** Include only the standard ES2022 library closure, never DOM, Node or project packages. */
|
||||
async function includeLibrary(name) {
|
||||
if (!/^lib\.[a-z0-9.]+\.d\.ts$/.test(name)) throw new Error('Invalid shipped library name')
|
||||
if (libraries['/lib/' + name] !== undefined) return
|
||||
const source = await readFile(path.join(libraryDirectory, name), 'utf8')
|
||||
libraries['/lib/' + name] = source
|
||||
for (const reference of source.matchAll(/<reference lib="([a-z0-9.]+)"\s*\/>/g)) await includeLibrary('lib.' + reference[1] + '.d.ts')
|
||||
}
|
||||
await includeLibrary('lib.es2022.d.ts')
|
||||
const compiler = (await readFile(require.resolve('typescript-editor'), 'utf8')).replace(/\/\/# sourceMappingURL=.*$/gm, '')
|
||||
const source = await readFile(path.join(root, 'src/lib/scripting/typescript-session.ts'), 'utf8')
|
||||
const engine = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||
if (/require\s*\(/.test(engine)) throw new Error('Editor engine must have no runtime module imports')
|
||||
const worker = compiler + '\n;(() => {\nconst exports = {};\n' + engine + '\n' +
|
||||
'const session = new exports.TypeScriptSession(ts, ' + JSON.stringify(libraries) + ');\n' +
|
||||
`self.onmessage = (event) => {
|
||||
const id = event.data?.id;
|
||||
try {
|
||||
const result = session.run(event.data);
|
||||
if (new TextEncoder().encode(JSON.stringify(result)).length > 262144) throw new Error("Result limit");
|
||||
self.postMessage({ protocol: "qqq-typescript-ide/1", id, version: "6.0.3", result });
|
||||
} catch {
|
||||
self.postMessage({ protocol: "qqq-typescript-ide/1", id, version: "6.0.3", error: "Editor analysis could not be completed" });
|
||||
}
|
||||
};\n})();\n`
|
||||
const destination = path.join(root, 'public/scripting-generated')
|
||||
await mkdir(destination, { recursive: true })
|
||||
await writeFile(path.join(destination, 'typescript-6.0.3.worker.js'), worker)
|
||||
await writeFile(path.join(destination, 'LICENSE.txt'), await readFile(path.join(libraryDirectory, '../LICENSE.txt'), 'utf8'))
|
||||
await writeFile(path.join(destination, 'ThirdPartyNoticeText.txt'), await readFile(path.join(libraryDirectory, '../ThirdPartyNoticeText.txt'), 'utf8'))
|
||||
console.log('Generated offline TypeScript 6.0.3 worker (' + Buffer.byteLength(worker) + ' bytes, ' + Object.keys(libraries).length + ' standard libraries)')
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
/** @file Real Chromium smoke test for the generated offline worker, served only on loopback. */
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import http from 'node:http'
|
||||
import { chromium } from '@playwright/test'
|
||||
|
||||
const workerBytes = await readFile(new URL('../public/scripting-generated/typescript-6.0.3.worker.js', import.meta.url))
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.url === '/worker.js') {
|
||||
response.writeHead(200, { 'Content-Type': 'text/javascript', 'Cache-Control': 'no-store' }); response.end(workerBytes)
|
||||
} else if (request.url === '/') {
|
||||
response.writeHead(200, { 'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; worker-src 'self'; connect-src 'none'" })
|
||||
response.end('<!doctype html><title>Offline TypeScript fixture</title>')
|
||||
} else { response.writeHead(404); response.end() }
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
let browser
|
||||
try {
|
||||
browser = await chromium.launch({ headless: true })
|
||||
const page = await browser.newPage()
|
||||
const requested = []
|
||||
page.on('request', (request) => requested.push(new URL(request.url()).pathname))
|
||||
await page.goto('http://127.0.0.1:' + server.address().port)
|
||||
const result = await page.evaluate(async () => {
|
||||
const worker = new Worker('/worker.js')
|
||||
let id = 0
|
||||
const request = (operation, files, position = 0) => new Promise((resolve, reject) => {
|
||||
const requestId = ++id
|
||||
const timer = setTimeout(() => { worker.terminate(); reject(new Error('Worker deadline exceeded')) }, 10_000)
|
||||
worker.onmessage = (event) => { clearTimeout(timer); if (event.data.id !== requestId || event.data.error) reject(new Error('Worker protocol failed')); else resolve(event.data.result) }
|
||||
worker.onerror = () => { clearTimeout(timer); reject(new Error('Worker failed')) }
|
||||
worker.postMessage({ id: requestId, operation, files, file: 'src/main.ts', position, declarations: '' })
|
||||
})
|
||||
try {
|
||||
const diagnostics = await request('diagnostics', [{ path: 'src/main.ts', content: 'export const count: number = "wrong";' }])
|
||||
const source = 'import { order } from "./order.js";\norder.status;\norder.'
|
||||
const files = [{ path: 'src/main.ts', content: source }, { path: 'src/order.ts', content: 'export const order = { status: "READY" };' }]
|
||||
const completion = await request('completion', files, source.length)
|
||||
const hover = await request('hover', files, source.indexOf('status') + 1)
|
||||
const definition = await request('definition', files, source.indexOf('order.status') + 1)
|
||||
const formatting = await request('format', [{ path: 'src/main.ts', content: 'export const value={a:1,b:2};' }])
|
||||
await request('diagnostics', [{ path: 'src/main.ts', content: 'fetch("https://example.invalid/leak"); globalThis.__qqqNeverExecute = true;' }])
|
||||
return { diagnostics, completion, hover, definition, formatting, executed: globalThis.__qqqNeverExecute === true }
|
||||
} finally { worker.terminate() }
|
||||
})
|
||||
assert(result.diagnostics.diagnostics.some((item) => item.code === 2322))
|
||||
assert(result.completion.completions.some((item) => item.label === 'status'))
|
||||
assert.match(result.hover.hover.text, /string/)
|
||||
assert.equal(result.definition.definitions[0].file, 'src/order.ts')
|
||||
assert(result.formatting.edits.length > 0)
|
||||
assert.equal(result.executed, false)
|
||||
assert.deepEqual(requested.sort(), ['/', '/worker.js'])
|
||||
console.log('PASS real Chromium: strict diagnostics, multi-file completion/hover/definition, formatting, no source execution or external requests')
|
||||
} finally {
|
||||
await browser?.close()
|
||||
await new Promise((resolve) => server.close(resolve))
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"component": {
|
||||
"repository": "QRun-IO/qqq-frontend-component-sequential-workflow",
|
||||
"sourceCommit": "e6036d2a474a90d80c72bc4c5f242e666b3415f6",
|
||||
"sourceTree": "9efc09210a81dc4121aa53e156443b7f4fcb6dd7",
|
||||
"mainCommit": "ede4eba875ca17c5921ad4caf61a08bdff6f794d",
|
||||
"build": {
|
||||
"node": "v22.20.0",
|
||||
"npm": "10.9.3",
|
||||
"image": "node@sha256:b21fe589dfbe5cc39365d0544b9be3f1f33f55f3c86c87a76ff65a02f8f5848e",
|
||||
"commands": [
|
||||
"npm ci --ignore-scripts",
|
||||
"npm test (existing 3 suites, 62 tests)",
|
||||
"npx webpack"
|
||||
],
|
||||
"packageLockSha256": "737cc1a3e416d942c050076dfae36345e9ba3f62d679dec71f04c2a2382b1a21",
|
||||
"qualifiedUtc": "2026-11-05T12:31Z"
|
||||
},
|
||||
"mainTree": "9efc09210a81dc4121aa53e156443b7f4fcb6dd7",
|
||||
"mainMerge": "normal merge of PR 5 (parents a32a7b4d437f09c09b03eb8828fccfd7de4eae7a, e6036d2a474a90d80c72bc4c5f242e666b3415f6); its tree equals the qualified source tree, so the qualified assets are the canonical main build output"
|
||||
},
|
||||
"assetDirectory": "dynamic-components/q-sequential-workflow",
|
||||
"files": {
|
||||
"q-sequential-workflow.bundle.js": "9f8358b105d0c157cb32a476313a7750281549f8e9423dd7d125ceaaafe8f32d",
|
||||
"q-sequential-workflow.bundle.js.map": "776c716690a357213e00d109652ab7eb9c9025073b362c995564e11ca5c5ee92"
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file Stage the versioned, precompiled QSequentialWorkflow editor bundle (the qbit-workflows `QSequentialWorkflow` editor)
|
||||
* under `public/dynamic-qfmd-components/`, which is where qbit-workflows' widget metadata points
|
||||
* (`/dynamic-qfmd-components/q-sequential-workflow.bundle.js`) and where the single-origin host serves the UI from.
|
||||
* The bundle and its map are tracked library assets in `dynamic-components/q-sequential-workflow/`, compiled from the
|
||||
* canonical component repository (source commit and toolchain recorded in `dynamic-components.lock.json`). Nothing is
|
||||
* downloaded or built here, and a file is refused unless its sha256 matches the lock. A missing or altered bundle fails the
|
||||
* build, so a release can never silently omit the workflow editor.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { copyFile, mkdir, readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
/** Copies every locked file from `assetDir` to `outDir`; throws on a missing file or a hash mismatch. */
|
||||
export async function stageDynamicComponents({ assetDir, lock, outDir }) {
|
||||
await mkdir(outDir, { recursive: true })
|
||||
const staged = []
|
||||
for (const [name, expected] of Object.entries(lock.files)) {
|
||||
if (path.basename(name) !== name) throw new Error(`Locked file name must be a plain file name: ${name}`)
|
||||
if (!/^[0-9a-f]{64}$/.test(expected ?? '')) throw new Error(`${name} has no sha256 in the dynamic component lock`)
|
||||
const source = path.join(assetDir, name)
|
||||
const actual = sha256(await readFile(source).catch(() => { throw new Error(`Missing ${name} in ${assetDir}`) }))
|
||||
if (actual !== expected) throw new Error(`${name} sha256 ${actual} does not match the lock ${expected}`)
|
||||
await copyFile(source, path.join(outDir, name))
|
||||
staged.push(name)
|
||||
}
|
||||
return staged
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const lock = JSON.parse(await readFile(path.join(here, 'dynamic-components.lock.json'), 'utf8'))
|
||||
const staged = await stageDynamicComponents({ assetDir: path.join(here, '..', lock.assetDirectory), lock, outDir: path.join(here, '../public/dynamic-qfmd-components') })
|
||||
console.log(`Staged dynamic components compiled from ${lock.component.repository}@${lock.component.sourceCommit.slice(0, 8)}: ${staged.join(', ')}`)
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
import { QContextProvider, useQContext } from '@/lib/context/q-context'
|
||||
@@ -113,9 +113,6 @@ function renderPage() {
|
||||
}
|
||||
|
||||
describe('RecordDeveloperViewPage', () => {
|
||||
// The page lazy-loads this view; transforming its module graph cold must not count against the first test's waits
|
||||
beforeAll(async () => { await import('@/components/developer/RecordDeveloperView') }, 120_000)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getRecord).mockResolvedValue(record)
|
||||
vi.mocked(getRecordDeveloperData).mockResolvedValue({
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { QContextProvider } from '@/lib/context/q-context'
|
||||
@@ -54,8 +54,6 @@ function renderPage(page: React.ReactNode) {
|
||||
}
|
||||
|
||||
describe('Create and base edit use full metadata and actual write contracts', () => {
|
||||
// The pages lazy-load the form; transforming its module graph cold must not count against the first test's waits
|
||||
beforeAll(async () => { await import('@/components/forms/EntityForm') }, 120_000)
|
||||
beforeEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); localStorage.clear(); fixture() })
|
||||
|
||||
it('edits the base without requesting denied children or replacing associations', async () => {
|
||||
|
||||
@@ -43,7 +43,6 @@ import { loadMetaData } from '@/lib/api/metadata'
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { CreateIsolatedScript } from '@/components/scripts/CreateIsolatedScript'
|
||||
|
||||
/** Duration in milliseconds before the "copied!" feedback resets to the copy icon. */
|
||||
const COPY_RESET_MS = 2000
|
||||
@@ -253,8 +252,6 @@ export default function DeveloperPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CreateIsolatedScript />
|
||||
|
||||
{/* Session Info */}
|
||||
<SectionCard
|
||||
title="Session Info"
|
||||
|
||||
@@ -32,10 +32,10 @@ import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import { useUiApiExtensionInstalled, UI_API_EXTENSION } from '@/lib/api/ui-api-extensions'
|
||||
import { getAlertsInboxSummary } from '@/lib/api/alerts'
|
||||
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import type { AlertsInboxSummary } from '@/types/alerts'
|
||||
import type { QInstance } from '@/types/metadata'
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
|
||||
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
|
||||
|
||||
const AlertsBellPopover = lazy(() => import('./AlertsBellPopover'))
|
||||
|
||||
@@ -99,8 +99,6 @@ export function useAlertsInbox(enabled: boolean) {
|
||||
staleTime: 30_000,
|
||||
refetchInterval: (query) => pollDelay(query.state.data, failures),
|
||||
refetchIntervalInBackground: false,
|
||||
// A poll for the bell's badge: a failure leaves the bell as it was and raises no banner.
|
||||
meta: BACKGROUND_REQUEST,
|
||||
refetchOnWindowFocus: (query) => (query.state.data === null ? false : 'always'),
|
||||
})
|
||||
}
|
||||
@@ -134,18 +132,16 @@ export function AlertsBell(_props: { metaData: QInstance | undefined }) {
|
||||
aria-expanded={open}
|
||||
data-qqq-id="button-notifications"
|
||||
>
|
||||
<HeaderIconAnchor>
|
||||
<Bell className="h-5 w-5" aria-hidden="true" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
className={`${HEADER_BADGE_CLASS} ${critical ? 'bg-destructive text-white' : 'bg-primary text-primary-foreground'}`}
|
||||
aria-hidden="true"
|
||||
data-qqq-id="alerts-unread-badge"
|
||||
>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
</HeaderIconAnchor>
|
||||
<Bell className="h-5 w-5" aria-hidden="true" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
className={`absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none ${critical ? 'bg-destructive text-white' : 'bg-primary text-primary-foreground'}`}
|
||||
aria-hidden="true"
|
||||
data-qqq-id="alerts-unread-badge"
|
||||
>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<span className="sr-only" aria-live="polite" data-qqq-id="alerts-unread-announcer">{label}</span>
|
||||
{open && (
|
||||
|
||||
@@ -198,12 +198,7 @@ describe('AlertsBell', () => {
|
||||
expect(bell).toHaveAttribute('aria-expanded', 'false')
|
||||
// severity is in the name, not only in the badge color
|
||||
expect(bell).toHaveAccessibleName('Notifications, 2 unread, critical')
|
||||
const badge = screen.getByText('2', { selector: '[data-qqq-id="alerts-unread-badge"]' })
|
||||
expect(badge).toHaveClass('bg-destructive')
|
||||
// the badge is positioned against the icon (the header's shared anchor), inside the button
|
||||
expect(badge.parentElement).toHaveAttribute('data-qqq-id', 'header-icon-anchor')
|
||||
expect(badge.parentElement).toHaveClass('relative')
|
||||
expect(badge.parentElement?.parentElement).toBe(bell)
|
||||
expect(screen.getByText('2', { selector: '[data-qqq-id="alerts-unread-badge"]' })).toHaveClass('bg-destructive')
|
||||
expect(document.querySelector('[data-qqq-id="alerts-unread-announcer"]')).toHaveAttribute('aria-live', 'polite')
|
||||
first.unmount()
|
||||
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// The header's Ask button: its busy dot and unread badge stay on the sparkles icon in every state.
|
||||
// jsdom has no layout, so these tests assert what decides the layout: which element is each
|
||||
// indicator's containing block, what gives that element its size, and the indicator's offsets.
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HEADER_ICON_ANCHOR_CLASS, HEADER_STATUS_DOT_CLASS } from '@/components/layout/HeaderMenu'
|
||||
import { assistantKeys, type AssistantController } from './assistant-context'
|
||||
import { AssistantHeaderButton } from './AssistantHeaderButton'
|
||||
import { AssistantProvider } from './AssistantProvider'
|
||||
|
||||
const ANCHOR = '[data-qqq-id="header-icon-anchor"]'
|
||||
const BUSY = '[data-qqq-id="assistant-busy"]'
|
||||
const UNREAD = '[data-qqq-id="assistant-unread-badge"]'
|
||||
|
||||
/**
|
||||
* The class tokens of an element (an SVG element's `className` is not a string).
|
||||
*
|
||||
* @param element - The element.
|
||||
* @returns Its classes.
|
||||
*/
|
||||
function classes(element: Element): string[] {
|
||||
return (element.getAttribute('class') ?? '').split(/\s+/).filter(Boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* The containing block of an absolutely positioned element: its nearest positioned ancestor.
|
||||
*
|
||||
* @param element - The absolutely positioned element.
|
||||
* @returns The ancestor its offsets are measured from, or null (the viewport).
|
||||
*/
|
||||
function containingBlock(element: Element): Element | null {
|
||||
for (let parent = element.parentElement; parent; parent = parent.parentElement) {
|
||||
if (classes(parent).some((name) => ['relative', 'absolute', 'fixed', 'sticky'].includes(name))) return parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The children that give an element its size: every child that is not absolutely positioned.
|
||||
*
|
||||
* @param element - The element.
|
||||
* @returns Its in-flow children.
|
||||
*/
|
||||
function inFlowChildren(element: Element): Element[] {
|
||||
return Array.from(element.children).filter((child) => !classes(child).includes('absolute'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the button in a given state.
|
||||
*
|
||||
* @param state - The state.
|
||||
* @param state.busy - Whether a reply is being written.
|
||||
* @param state.unreadCount - Unread replies.
|
||||
* @param state.open - Whether the panel is open.
|
||||
* @param state.enabled - Whether the assistant is available.
|
||||
* @returns The button, or null when it renders nothing.
|
||||
*/
|
||||
function renderButton({ busy = false, unreadCount = 0, open = false, enabled = true }: { busy?: boolean; unreadCount?: number; open?: boolean; enabled?: boolean }): HTMLElement | null {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
client.setQueryData(assistantKeys.busy(), busy)
|
||||
const controller: AssistantController = {
|
||||
config: null,
|
||||
enabled,
|
||||
open,
|
||||
setOpen: vi.fn(),
|
||||
toggle: vi.fn(),
|
||||
activeConversationId: null,
|
||||
setActiveConversationId: vi.fn(),
|
||||
unreadCount,
|
||||
openWith: vi.fn(),
|
||||
pendingRequest: null,
|
||||
consumeRequest: vi.fn(),
|
||||
triggerRef: React.createRef<HTMLButtonElement>(),
|
||||
}
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AssistantProvider value={controller}>
|
||||
<header><AssistantHeaderButton /></header>
|
||||
</AssistantProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return screen.queryByRole('button', { name: /^Ask the assistant/ })
|
||||
}
|
||||
|
||||
describe('AssistantHeaderButton', () => {
|
||||
it('renders nothing when the assistant is unavailable', () => {
|
||||
expect(renderButton({ enabled: false, busy: true, unreadCount: 2 })).toBeNull()
|
||||
})
|
||||
|
||||
it('idle: the icon anchor holds only the icon, and the label sits beside it', () => {
|
||||
const button = renderButton({})!
|
||||
const anchor = button.querySelector(ANCHOR)!
|
||||
expect(anchor.parentElement).toBe(button)
|
||||
expect(Array.from(anchor.children).map((child) => child.tagName.toLowerCase())).toEqual(['svg'])
|
||||
expect(button.querySelector(BUSY)).toBeNull()
|
||||
expect(button.querySelector(UNREAD)).toBeNull()
|
||||
const label = screen.getByText('Ask')
|
||||
expect(label.parentElement).toBe(button)
|
||||
expect(anchor.contains(label)).toBe(false)
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false')
|
||||
})
|
||||
|
||||
const states = [
|
||||
{ name: 'a reply being written', busy: true, unreadCount: 0 },
|
||||
{ name: 'unread replies', busy: false, unreadCount: 3 },
|
||||
{ name: 'a reply being written and unread replies', busy: true, unreadCount: 12 },
|
||||
]
|
||||
const cases = states.flatMap((state) => [{ ...state, open: false, panel: 'closed' }, { ...state, open: true, panel: 'open' }])
|
||||
|
||||
it.each(cases)('$name, panel $panel: every indicator is positioned against the icon, never the button', ({ busy, unreadCount, open }) => {
|
||||
const button = renderButton({ busy, unreadCount, open })!
|
||||
expect(button).toHaveAttribute('aria-pressed', String(open))
|
||||
const anchor = button.querySelector(ANCHOR)!
|
||||
const indicators = Array.from(button.querySelectorAll(`${BUSY}, ${UNREAD}`))
|
||||
expect(indicators).toHaveLength((busy ? 1 : 0) + (unreadCount > 0 ? 1 : 0))
|
||||
for (const indicator of indicators) {
|
||||
expect(classes(indicator)).toContain('absolute')
|
||||
// the button is positioned too (its focus ring and the Jobs ring need that), so only an
|
||||
// indicator inside the anchor is measured from the icon
|
||||
expect(containingBlock(indicator)).toBe(anchor)
|
||||
expect(containingBlock(indicator)).not.toBe(button)
|
||||
}
|
||||
// the anchor is exactly the icon: nothing else in flow, so the label and the button's
|
||||
// padding cannot move an indicator
|
||||
expect(classes(anchor)).toContain('relative')
|
||||
expect(inFlowChildren(anchor).map((child) => child.tagName.toLowerCase())).toEqual(['svg'])
|
||||
expect(anchor.contains(screen.getByText('Ask'))).toBe(false)
|
||||
})
|
||||
|
||||
it('places the dot on the icon\'s bottom-right corner and the badge over its top-right corner', () => {
|
||||
const button = renderButton({ busy: true, unreadCount: 3 })!
|
||||
const dot = screen.getByRole('status', { name: 'Assistant is answering' })
|
||||
expect(dot).toBe(button.querySelector(BUSY))
|
||||
expect(classes(dot)).toEqual(expect.arrayContaining(['-bottom-0.5', '-right-0.5', 'h-2', 'w-2', 'rounded-full']))
|
||||
const badge = button.querySelector(UNREAD)!
|
||||
expect(badge).toHaveTextContent('3')
|
||||
expect(classes(badge)).toEqual(expect.arrayContaining(['-right-2', '-top-2', 'h-4', 'min-w-4']))
|
||||
// the offsets of the button's own corner (the defect: past the label, under its baseline)
|
||||
for (const indicator of [dot, badge]) {
|
||||
for (const offset of ['bottom-0', 'right-0', 'right-0.5', 'top-0.5']) expect(classes(indicator)).not.toContain(offset)
|
||||
}
|
||||
})
|
||||
|
||||
it('caps the badge at 9+ and names the unread count', () => {
|
||||
const button = renderButton({ unreadCount: 12 })!
|
||||
expect(button.querySelector(UNREAD)).toHaveTextContent('9+')
|
||||
expect(button).toHaveAccessibleName('Ask the assistant, 12 unread (Ctrl+J or ⌘J)')
|
||||
})
|
||||
|
||||
it('shares one anchor and one badge geometry with the bell and Jobs', () => {
|
||||
expect(HEADER_ICON_ANCHOR_CLASS.split(' ')).toEqual(expect.arrayContaining(['relative', 'shrink-0']))
|
||||
expect(HEADER_BADGE_CLASS.split(' ')).toEqual(expect.arrayContaining(['absolute', '-right-2', '-top-2']))
|
||||
expect(HEADER_STATUS_DOT_CLASS.split(' ')).toEqual(expect.arrayContaining(['absolute', '-bottom-0.5', '-right-0.5']))
|
||||
// an 8 px offset from a 20 px icon stays inside the 10 px padding of the 40 px button
|
||||
expect(HEADER_BUTTON_CLASS.split(' ')).toEqual(expect.arrayContaining(['h-10', 'min-w-10', 'px-2.5']))
|
||||
})
|
||||
})
|
||||
@@ -25,14 +25,13 @@ import React from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HEADER_STATUS_DOT_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
|
||||
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { assistantKeys, useAssistant } from './assistant-context'
|
||||
|
||||
/**
|
||||
* Toggles the assistant panel ("Ask"); the badge counts unread replies and the dot shows a reply
|
||||
* being written. The sparkles icon alone is ambiguous, so from 1440 px it carries the text label
|
||||
* "Ask" (its tooltip says so below that).
|
||||
* Toggles the assistant panel ("Ask"); the badge counts unread replies. The sparkles icon alone is
|
||||
* ambiguous, so from 1440 px it carries the text label "Ask" (its tooltip says so below that).
|
||||
*
|
||||
* @returns The button, or null when the assistant is unavailable.
|
||||
*/
|
||||
@@ -51,23 +50,24 @@ export function AssistantHeaderButton() {
|
||||
event.currentTarget.focus({ preventScroll: true })
|
||||
toggle()
|
||||
}}
|
||||
className={cn(HEADER_BUTTON_CLASS, 'gap-2')}
|
||||
className={cn(HEADER_BUTTON_CLASS, 'gap-1.5')}
|
||||
aria-label={label}
|
||||
title="Ask the assistant (Ctrl+J or ⌘J)"
|
||||
aria-pressed={open}
|
||||
data-qqq-id="button-assistant"
|
||||
>
|
||||
{/* the indicators sit on the icon: the button's corner is past the label from 1440 px */}
|
||||
<HeaderIconAnchor>
|
||||
<Sparkles className="h-5 w-5" aria-hidden="true" />
|
||||
{busy && <span className={cn(HEADER_STATUS_DOT_CLASS, 'bg-primary motion-safe:animate-pulse')} role="status" aria-label="Assistant is answering" data-qqq-id="assistant-busy" />}
|
||||
{unreadCount > 0 && (
|
||||
<span className={cn(HEADER_BADGE_CLASS, 'bg-primary text-primary-foreground')} aria-hidden="true" data-qqq-id="assistant-unread-badge">
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</HeaderIconAnchor>
|
||||
<Sparkles className="h-5 w-5" aria-hidden="true" />
|
||||
<span className="hidden text-sm font-medium min-[1440px]:inline" aria-hidden="true">Ask</span>
|
||||
{busy && <span className="absolute bottom-0 right-0 h-2 w-2 rounded-full bg-primary motion-safe:animate-pulse" role="status" aria-label="Assistant is answering" data-qqq-id="assistant-busy" />}
|
||||
{unreadCount > 0 && (
|
||||
<span
|
||||
className="absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground"
|
||||
aria-hidden="true"
|
||||
data-qqq-id="assistant-unread-badge"
|
||||
>
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* AssistantPendingActionCard stories — the confirmation card of a proposed write: a change to
|
||||
* one record, and one run over a set of records (its count, the names in view, the whole list
|
||||
* on request, and a count the list does not match). The action's state is served by the story.
|
||||
*/
|
||||
import React from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
|
||||
import type { AssistantPendingAction, AssistantPendingActionRender } from '@/types/assistant'
|
||||
import apiClient from '@/lib/api/client'
|
||||
import AssistantPendingActionCard from './AssistantPendingActionCard'
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } })
|
||||
|
||||
/** The action as the card loads it, and as it is after a decision. */
|
||||
const ACTION: AssistantPendingAction = { id: 7, status: 'PENDING', toolName: 'update_record', tableName: 'printer', summary: 'Proposed change' }
|
||||
|
||||
const meta = {
|
||||
title: 'Assistant/AssistantPendingActionCard',
|
||||
component: AssistantPendingActionCard,
|
||||
parameters: { layout: 'padded' },
|
||||
tags: ['autodocs'],
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<div className="@container w-full max-w-[390px] space-y-4 bg-card p-3">
|
||||
<Story />
|
||||
</div>
|
||||
</QueryClientProvider>
|
||||
),
|
||||
],
|
||||
// no server behind a story: the card's own requests are answered here
|
||||
beforeEach: () => {
|
||||
const { get, post } = apiClient
|
||||
apiClient.get = (async () => ACTION) as typeof apiClient.get
|
||||
apiClient.post = (async (url: string) => (
|
||||
url.endsWith('/confirm') ? { ...ACTION, status: 'EXECUTED', resultSummary: 'Ran to its end' } : { ...ACTION, status: 'REJECTED' }
|
||||
)) as typeof apiClient.post
|
||||
return () => {
|
||||
apiClient.get = get
|
||||
apiClient.post = post
|
||||
}
|
||||
},
|
||||
} satisfies Meta<typeof AssistantPendingActionCard>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/**
|
||||
* A card for one run over a set of records, as the server sends it.
|
||||
*
|
||||
* @param count - How many records the set has.
|
||||
* @param listed - How many of them the list holds.
|
||||
* @returns The render.
|
||||
*/
|
||||
function setOf(count: number, listed = count): AssistantPendingActionRender {
|
||||
const names = ['Dock 1', 'Dock 2', 'Dock 3', 'Dock 4', 'Dock 5'].slice(0, count).join(', ')
|
||||
return {
|
||||
type: 'pending_action',
|
||||
actionId: 7,
|
||||
toolName: 'update_record',
|
||||
actionKind: 'process_run',
|
||||
processName: 'printer.bulkDelete',
|
||||
processLabel: 'Printer Bulk Delete',
|
||||
tableName: 'printer',
|
||||
tableLabel: 'Printer',
|
||||
summary: `Run Printer Bulk Delete on ${count} Printer records`,
|
||||
changes: [
|
||||
{ field: 'process', label: 'Process', value: 'Printer Bulk Delete' },
|
||||
{ field: 'records', label: 'Records', value: `${count} Printer records: ${names}${count > 5 ? ` and ${count - 5} more` : ''} (Status equals Retired)` },
|
||||
{ field: 'runs', label: 'Runs', value: 'When you confirm, to its end.' },
|
||||
],
|
||||
recordCount: count,
|
||||
records: Array.from({ length: listed }, (_, index) => ({ id: String(index + 1), label: `Dock ${index + 1}`, href: `/app/printer/${index + 1}` })),
|
||||
}
|
||||
}
|
||||
|
||||
/** A change to one record: no count and no list. */
|
||||
export const OneRecord: Story = {
|
||||
args: {
|
||||
render: {
|
||||
type: 'pending_action', actionId: 7, toolName: 'update_record', tableName: 'printer', tableLabel: 'Printer', recordId: '4',
|
||||
summary: 'Update Printer Dock 4: Location = Bay 2',
|
||||
changes: [{ field: 'location', label: 'Location', value: 'Bay 2' }],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
/** One run over 27 records: the count, five names in view, "See all 27", and "Delete 27". */
|
||||
export const SetOfRecords: Story = { args: { render: setOf(27) } }
|
||||
|
||||
/** The largest set a server sends: the list is drawn only when asked for, and scrolls inside the card. */
|
||||
export const FiveHundredRecords: Story = { args: { render: setOf(500) } }
|
||||
|
||||
/** The list holds fewer names than the count: the card shows the count and says so. */
|
||||
export const CountAndListDisagree: Story = { args: { render: setOf(27, 20) } }
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
@@ -87,321 +87,3 @@ describe('AssistantPendingActionCard', () => {
|
||||
expect(calls).not.toContain('confirm')
|
||||
})
|
||||
})
|
||||
|
||||
/** The lines a card for a run over a set carries, as the server writes them. */
|
||||
const SET_LINES = [
|
||||
{ field: 'process', label: 'Process', value: 'Printer Bulk Delete' },
|
||||
{ field: 'records', label: 'Records', value: '27 Printer records: Dock 1, Dock 2, Dock 3, Dock 4, Dock 5 and 22 more' },
|
||||
{ field: 'runs', label: 'Runs', value: 'When you confirm, to its end.' },
|
||||
]
|
||||
|
||||
/**
|
||||
* A card for one run over a set of records, as the server sends it: an update by tool name, a
|
||||
* process run by kind, the count, and every record with its name and link.
|
||||
*
|
||||
* @param count - How many records the set has.
|
||||
* @param overrides - Fields to replace.
|
||||
* @returns The render.
|
||||
*/
|
||||
function setRender(count: number, overrides: Partial<AssistantPendingActionRender> = {}): AssistantPendingActionRender {
|
||||
return {
|
||||
type: 'pending_action',
|
||||
actionId: 7,
|
||||
toolName: 'update_record',
|
||||
actionKind: 'process_run',
|
||||
processName: 'printer.bulkDelete',
|
||||
processLabel: 'Printer Bulk Delete',
|
||||
tableName: 'printer',
|
||||
tableLabel: 'Printer',
|
||||
summary: `Run Printer Bulk Delete on ${count} Printer records`,
|
||||
changes: SET_LINES,
|
||||
recordCount: count,
|
||||
records: Array.from({ length: count }, (_, index) => ({ id: String(index + 1), label: `Dock ${index + 1}`, href: `/app/printer/${index + 1}` })),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the action of a card for a set.
|
||||
*
|
||||
* @param loaded - The status the card loads with.
|
||||
* @returns The calls made, by kind.
|
||||
*/
|
||||
function serveSet(loaded: 'PENDING' | 'EXPIRED' = 'PENDING') {
|
||||
const calls: string[] = []
|
||||
const action = { id: 7, toolName: 'update_record', tableName: 'printer', summary: 'Run Printer Bulk Delete' }
|
||||
server.use(
|
||||
http.get('*/assistant/actions/7', () => {
|
||||
calls.push('get')
|
||||
return HttpResponse.json({ ...action, status: loaded })
|
||||
}),
|
||||
http.post('*/assistant/actions/7/confirm', () => {
|
||||
calls.push('confirm')
|
||||
return HttpResponse.json({ ...action, status: 'EXECUTED', resultSummary: 'Printer Bulk Delete ran to its end', outcome: 'OK' })
|
||||
}),
|
||||
http.post('*/assistant/actions/7/reject', () => {
|
||||
calls.push('reject')
|
||||
return HttpResponse.json({ ...action, status: 'REJECTED', resultSummary: 'Cancelled by the user; nothing changed.' })
|
||||
})
|
||||
)
|
||||
return calls
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a card and waits for it to load its action.
|
||||
*
|
||||
* @param card - The render to draw.
|
||||
* @param loaded - The status the card loads with.
|
||||
* @returns The container and the calls made.
|
||||
*/
|
||||
async function draw(card: AssistantPendingActionRender, loaded: 'PENDING' | 'EXPIRED' = 'PENDING') {
|
||||
const calls = serveSet(loaded)
|
||||
const { container } = render(<QueryClientProvider client={new QueryClient()}><AssistantPendingActionCard render={card} /></QueryClientProvider>)
|
||||
await waitFor(() => expect(calls).toContain('get'))
|
||||
return { container, calls }
|
||||
}
|
||||
|
||||
/** The names the card draws now, in order, links and plain text alike. */
|
||||
function drawnNames(container: HTMLElement): string[] {
|
||||
return Array.from(container.querySelectorAll('[data-qqq-id="assistant-pending-action-record"]')).map((name) => name.textContent ?? '')
|
||||
}
|
||||
|
||||
/** What the card says of its set, before its buttons. */
|
||||
function countText(container: HTMLElement): string {
|
||||
return container.querySelector('[data-qqq-id="assistant-pending-action-record-count"]')?.textContent ?? ''
|
||||
}
|
||||
|
||||
/**
|
||||
* The card's markup as it was before cards for a set existed, for a pending update with the
|
||||
* given summary and lines. Icons are reduced to their classes.
|
||||
*
|
||||
* @param summary - The card's summary.
|
||||
* @param lines - The markup of its lines, inside the list.
|
||||
* @returns The markup.
|
||||
*/
|
||||
function markupBeforeSets(summary: string, lines: string): string {
|
||||
return `<div class="rounded-lg border border-border bg-card" data-qqq-id="assistant-pending-action" role="group" aria-label="Proposed change: ${summary}">`
|
||||
+ '<div class="flex items-start gap-2 border-b border-border px-3 py-2"><svg class="lucide lucide-pencil-line mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"/>'
|
||||
+ `<div class="min-w-0 flex-1"><p class="text-sm font-medium text-foreground break-words">${summary}</p>`
|
||||
+ '<p class="text-xs text-muted-foreground" aria-live="polite" data-qqq-id="assistant-pending-action-status">Waiting for your confirmation</p></div></div>'
|
||||
+ `<dl class="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-1 px-3 py-2 text-xs">${lines}</dl>`
|
||||
+ '<div class="flex flex-wrap items-center gap-2 border-t border-border px-3 py-2">'
|
||||
+ '<button type="button" class="inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 bg-primary text-primary-foreground hover:bg-primary/90" data-qqq-id="assistant-pending-action-confirm"><svg class="lucide lucide-check h-3.5 w-3.5"/>Save</button>'
|
||||
+ '<button type="button" class="inline-flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60" data-qqq-id="assistant-pending-action-cancel"><svg class="lucide lucide-x h-3.5 w-3.5"/>Cancel</button>'
|
||||
+ '</div></div>'
|
||||
}
|
||||
|
||||
/** A card's markup with each icon reduced to its classes (an icon's drawing is not the card's). */
|
||||
function markupOf(container: HTMLElement): string {
|
||||
return container.innerHTML.replace(/<svg[^>]*class="([^"]*)"[^>]*>.*?<\/svg>/g, '<svg class="$1"/>')
|
||||
}
|
||||
|
||||
describe('AssistantPendingActionCard for a set of records', () => {
|
||||
it('says how many records it acts on and how many it names, before its buttons', async () => {
|
||||
const { container } = await draw(setRender(27))
|
||||
expect(countText(container)).toBe('27 Printer records · showing 5')
|
||||
expect(drawnNames(container)).toEqual(['Dock 1', 'Dock 2', 'Dock 3', 'Dock 4', 'Dock 5'])
|
||||
expect(screen.getAllByRole('link').map((link) => link.getAttribute('href'))).toEqual(['/app/printer/1', '/app/printer/2', '/app/printer/3', '/app/printer/4', '/app/printer/5'])
|
||||
|
||||
const count = container.querySelector('[data-qqq-id="assistant-pending-action-record-count"]') as HTMLElement
|
||||
const confirm = container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]') as HTMLElement
|
||||
expect(count.compareDocumentPosition(confirm) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-record-mismatch"]')).toBeNull()
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a bulk delete', {}, 'Delete 27', 'Delete 27 Printer records', true],
|
||||
['a bulk edit', { processName: 'printer.bulkEdit' }, 'Save 27', 'Save 27 Printer records', false],
|
||||
['another process', { processName: 'reprintLabels' }, 'Run on 27', 'Run on 27 Printer records', false],
|
||||
['a set of one', { recordCount: 1, records: [{ id: '1', label: 'Dock 1', href: '/app/printer/1' }] }, 'Delete 1', 'Delete 1 Printer record', true],
|
||||
['a set of a table with no label', { tableLabel: '' }, 'Delete 27', 'Delete 27 records', true],
|
||||
])('carries the count on the confirm button of %s', async (_name, overrides, text, name, destructive) => {
|
||||
const { container } = await draw(setRender(27, overrides))
|
||||
const confirm = container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]') as HTMLElement
|
||||
expect(confirm).toHaveTextContent(text)
|
||||
expect(confirm).toHaveAccessibleName(name)
|
||||
expect(confirm.className.includes('bg-destructive')).toBe(destructive)
|
||||
})
|
||||
|
||||
it('lists every record with a link into the application on request, and goes back', async () => {
|
||||
const { container } = await draw(setRender(27))
|
||||
const toggle = screen.getByRole('button', { name: 'See all 27' })
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false')
|
||||
|
||||
await userEvent.click(toggle)
|
||||
expect(countText(container)).toBe('27 Printer records · showing all 27')
|
||||
expect(drawnNames(container)).toEqual(Array.from({ length: 27 }, (_, index) => `Dock ${index + 1}`))
|
||||
const list = screen.getByRole('group', { name: 'All 27 names' })
|
||||
expect(within(list).getAllByRole('link').map((link) => link.getAttribute('href'))).toEqual(Array.from({ length: 27 }, (_, index) => `/app/printer/${index + 1}`))
|
||||
// a scroll area of bounded height that the keyboard reaches
|
||||
expect(list).toHaveAttribute('tabindex', '0')
|
||||
expect(list).toHaveClass('max-h-48', 'overflow-y-auto')
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(toggle).toHaveAttribute('aria-controls', list.id)
|
||||
expect(toggle).toHaveTextContent('Show fewer')
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Show fewer' }))
|
||||
expect(countText(container)).toBe('27 Printer records · showing 5')
|
||||
expect(drawnNames(container)).toHaveLength(5)
|
||||
expect(screen.queryByRole('group', { name: 'All 27 names' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens and closes the list from the keyboard', async () => {
|
||||
const { container } = await draw(setRender(27))
|
||||
const toggle = screen.getByRole('button', { name: 'See all 27' })
|
||||
toggle.focus()
|
||||
await userEvent.keyboard('{Enter}')
|
||||
expect(drawnNames(container)).toHaveLength(27)
|
||||
await userEvent.tab()
|
||||
expect(screen.getByRole('group', { name: 'All 27 names' })).toHaveFocus()
|
||||
await userEvent.tab()
|
||||
expect(screen.getByRole('link', { name: 'Dock 1' })).toHaveFocus()
|
||||
toggle.focus()
|
||||
await userEvent.keyboard(' ')
|
||||
expect(drawnNames(container)).toHaveLength(5)
|
||||
expect(toggle).toHaveFocus()
|
||||
})
|
||||
|
||||
it('never makes a link of an address outside the application or a malformed one', async () => {
|
||||
const records = [
|
||||
{ id: '1', label: 'Inside', href: '/app/printer/1' },
|
||||
{ id: '2', label: 'Other site', href: 'https://example.com/app/printer/2' },
|
||||
{ id: '3', label: 'Protocol relative', href: '//example.com/app/printer/3' },
|
||||
{ id: '4', label: 'Script', href: 'javascript:alert(1)' },
|
||||
{ id: '5', label: 'Outside the app', href: '/elsewhere/printer/5' },
|
||||
{ id: '6', label: 'Backslashes', href: '/app\\printer\\6' },
|
||||
{ id: '7', label: 'No link' },
|
||||
{ id: '8', label: '', href: '/app/printer/8' },
|
||||
]
|
||||
const { container } = await draw(setRender(8, { records }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 8' }))
|
||||
// every record is named, also the ones without a link; a record with no name goes by its id
|
||||
expect(drawnNames(container)).toEqual(['Inside', 'Other site', 'Protocol relative', 'Script', 'Outside the app', 'Backslashes', 'No link', '8'])
|
||||
expect(screen.getAllByRole('link').map((link) => [link.textContent, link.getAttribute('href')])).toEqual([['Inside', '/app/printer/1'], ['8', '/app/printer/8']])
|
||||
expect(container.querySelector('a[href*="example.com"], a[href^="javascript"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('holds 500 records without drawing the list until it is asked for', async () => {
|
||||
const { container } = await draw(setRender(500))
|
||||
expect(countText(container)).toBe('500 Printer records · showing 5')
|
||||
expect(drawnNames(container)).toHaveLength(5)
|
||||
expect(container.querySelectorAll('a')).toHaveLength(5)
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 500')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 500' }))
|
||||
expect(countText(container)).toBe('500 Printer records · showing all 500')
|
||||
const list = screen.getByRole('group', { name: 'All 500 names' })
|
||||
expect(within(list).getAllByRole('link')).toHaveLength(500)
|
||||
expect(within(list).getByRole('link', { name: 'Dock 500' })).toHaveAttribute('href', '/app/printer/500')
|
||||
// the list scrolls inside the card: its height is bounded however many records it holds
|
||||
expect(list).toHaveClass('max-h-48', 'overflow-y-auto')
|
||||
})
|
||||
|
||||
it('offers no "See all" when every name is already in view', async () => {
|
||||
const { container } = await draw(setRender(3))
|
||||
expect(countText(container)).toBe('3 Printer records · showing all 3')
|
||||
expect(drawnNames(container)).toEqual(['Dock 1', 'Dock 2', 'Dock 3'])
|
||||
expect(screen.queryByRole('button', { name: /see all/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the count and the list readable after it is confirmed; only the buttons go', async () => {
|
||||
const { container, calls } = await draw(setRender(27))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Delete 27 Printer records' }))
|
||||
await waitFor(() => expect(screen.getByText(/Done · Printer Bulk Delete ran to its end/)).toBeInTheDocument())
|
||||
expect(calls.filter((call) => call === 'confirm')).toHaveLength(1)
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-cancel"]')).toBeNull()
|
||||
expect(countText(container)).toBe('27 Printer records · showing 5')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
|
||||
expect(drawnNames(container)).toHaveLength(27)
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it('keeps the count and the list readable after it is rejected', async () => {
|
||||
const { container, calls } = await draw(setRender(27))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: /cancel/i }))
|
||||
await waitFor(() => expect(screen.getByText(/Cancelled, nothing changed/)).toBeInTheDocument())
|
||||
expect(calls).not.toContain('confirm')
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
|
||||
// the list the person had open stays open
|
||||
expect(countText(container)).toBe('27 Printer records · showing all 27')
|
||||
expect(drawnNames(container)).toHaveLength(27)
|
||||
})
|
||||
|
||||
it('keeps the count and the list readable on a card that has expired', async () => {
|
||||
const { container } = await draw(setRender(27), 'EXPIRED')
|
||||
await waitFor(() => expect(screen.getByText(/Expired, nothing changed/)).toBeInTheDocument())
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
|
||||
expect(countText(container)).toBe('27 Printer records · showing 5')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
|
||||
expect(drawnNames(container)).toHaveLength(27)
|
||||
})
|
||||
|
||||
it('shows the count the server sent and says so when the list holds fewer names', async () => {
|
||||
const { container } = await draw(setRender(20, { recordCount: 27 }))
|
||||
expect(countText(container)).toBe('27 Printer records · showing 5 of 27 names')
|
||||
expect(screen.getByText('The list holds 20 names, not 27.')).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 27')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'See all 20' }))
|
||||
expect(countText(container)).toBe('27 Printer records · showing 20 of 27 names')
|
||||
expect(drawnNames(container)).toHaveLength(20)
|
||||
expect(screen.getByText('The list holds 20 names, not 27.')).toBeInTheDocument()
|
||||
expect(countText(container)).not.toContain('all')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['more names than the count', setRender(6, { recordCount: 3 }), '3 Printer records · showing 5 names', 'The list holds 6 names, not 3.', 'Delete 3'],
|
||||
['one name for many records', setRender(1, { recordCount: 27 }), '27 Printer records · showing 1 of 27 names', 'The list holds 1 name, not 27.', 'Delete 27'],
|
||||
['names and a count of none', setRender(2, { recordCount: 0 }), '0 Printer records · showing 2 names', 'The list holds 2 names, not 0.', 'Delete 0'],
|
||||
])('says so when the list holds %s', async (_name, card, count, note, button) => {
|
||||
const { container } = await draw(card)
|
||||
expect(countText(container)).toBe(count)
|
||||
expect(screen.getByText(note)).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent(button)
|
||||
})
|
||||
|
||||
it('says that no names are listed when the server sent a count and no list', async () => {
|
||||
const { container } = await draw(setRender(0, { recordCount: 27 }))
|
||||
expect(countText(container)).toBe('27 Printer records · no names listed')
|
||||
expect(drawnNames(container)).toEqual([])
|
||||
expect(screen.queryByRole('button', { name: /see all/i })).not.toBeInTheDocument()
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 27')
|
||||
})
|
||||
|
||||
it('counts its list when the server sent the records and no count', async () => {
|
||||
const { container } = await draw(setRender(8, { recordCount: undefined }))
|
||||
expect(countText(container)).toBe('8 Printer records · showing 5')
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 8')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AssistantPendingActionCard without a set', () => {
|
||||
it('draws a card for one record exactly as before', async () => {
|
||||
const { container } = await draw({
|
||||
type: 'pending_action', actionId: 7, toolName: 'update_record', tableName: 'printer', tableLabel: 'Printer', recordId: '4',
|
||||
summary: 'Update Printer 4: Location = Dock 2',
|
||||
changes: [{ field: 'location', label: 'Location', value: 'Dock 2' }, { field: 'note', label: 'Note', value: null }],
|
||||
records: [],
|
||||
})
|
||||
expect(markupOf(container)).toBe(markupBeforeSets(
|
||||
'Update Printer 4: Location = Dock 2',
|
||||
'<dt class="truncate text-muted-foreground">Location</dt><dd class="break-words text-foreground">Dock 2</dd>'
|
||||
+ '<dt class="truncate text-muted-foreground">Note</dt><dd class="break-words text-foreground"><span class="text-muted-foreground">(empty)</span></dd>'
|
||||
))
|
||||
})
|
||||
|
||||
it('draws a run over a set from an older server, which sends no records, exactly as before', async () => {
|
||||
const { container } = await draw(setRender(27, { recordCount: undefined, records: undefined }))
|
||||
expect(markupOf(container)).toBe(markupBeforeSets(
|
||||
'Run Printer Bulk Delete on 27 Printer records',
|
||||
'<dt class="truncate text-muted-foreground">Process</dt><dd class="break-words text-foreground">Printer Bulk Delete</dd>'
|
||||
+ '<dt class="truncate text-muted-foreground">Records</dt><dd class="break-words text-foreground">27 Printer records: Dock 1, Dock 2, Dock 3, Dock 4, Dock 5 and 22 more</dd>'
|
||||
+ '<dt class="truncate text-muted-foreground">Runs</dt><dd class="break-words text-foreground">When you confirm, to its end.</dd>'
|
||||
))
|
||||
expect(container.querySelector('[data-qqq-id="assistant-pending-action-records"]')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -19,20 +19,16 @@
|
||||
* record). Nothing changes until the user confirms; the server then runs the write through the
|
||||
* UI API with the user's own session, so the same permissions, record locks and validation apply.
|
||||
* The card loads the action's current state, so a reloaded conversation shows the outcome.
|
||||
*
|
||||
* A card for a set of records (one run over many) states how many records it acts on and how
|
||||
* many of them it names, carries that count on its confirm button, and lists every record of
|
||||
* the set on request. The count and the list stay on the card after it is decided.
|
||||
*/
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { useEffect, useId, useState } from 'react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { Check, PencilLine, Plus, Trash2, X } from 'lucide-react'
|
||||
|
||||
import type { AssistantPendingAction, AssistantPendingActionRecord, AssistantPendingActionRender } from '@/types/assistant'
|
||||
import type { AssistantPendingAction, AssistantPendingActionRender } from '@/types/assistant'
|
||||
import { confirmAssistantAction, getAssistantAction, rejectAssistantAction } from '@/lib/api/assistant'
|
||||
import { internalAppHref } from '@/lib/utils/assistant-links'
|
||||
import { getErrorMessage } from '@/lib/utils/error-utils'
|
||||
@@ -47,108 +43,6 @@ const STATUS_TEXT: Record<AssistantPendingAction['status'], string> = {
|
||||
EXPIRED: 'Expired, nothing changed',
|
||||
}
|
||||
|
||||
/** How many names of a set a card shows before the person asks for all of them. */
|
||||
const NAMES_IN_VIEW = 5
|
||||
|
||||
/** How a table's own bulk delete and bulk edit processes are named (`<table>.bulkDelete`). */
|
||||
const BULK_DELETE_SUFFIX = '.bulkDelete'
|
||||
const BULK_EDIT_SUFFIX = '.bulkEdit'
|
||||
|
||||
/**
|
||||
* How many of a set's names are in view, in words. When the list does not hold as many names as
|
||||
* the count says, the words never read as if it did.
|
||||
*
|
||||
* @param shown - Names drawn now.
|
||||
* @param listed - Names the list holds.
|
||||
* @param total - Records the card acts on.
|
||||
* @returns The words that follow the count.
|
||||
*/
|
||||
function showingText(shown: number, listed: number, total: number): string {
|
||||
if (listed === 0) return 'no names listed'
|
||||
if (listed === total) return shown === total && total > 1 ? `showing all ${total}` : `showing ${shown}`
|
||||
return listed < total ? `showing ${shown} of ${total} names` : `showing ${shown} names`
|
||||
}
|
||||
|
||||
/**
|
||||
* One record of a set by its name: a link into the application when its href passes the
|
||||
* internal-link check, plain text otherwise.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.record - The record.
|
||||
* @returns The link or the name.
|
||||
*/
|
||||
function RecordName({ record }: { record: AssistantPendingActionRecord }) {
|
||||
const name = record.label || String(record.id)
|
||||
const href = internalAppHref(record.href)
|
||||
if (!href) return <span className="break-words text-foreground" data-qqq-id="assistant-pending-action-record">{name}</span>
|
||||
// not prefetched: scrolling a list of hundreds of names must not request hundreds of pages
|
||||
return (
|
||||
<Link href={href} prefetch={false} className="rounded break-words font-medium text-primary hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-ring" data-qqq-id="assistant-pending-action-record">
|
||||
{name}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The records a card for a set acts on: how many, how many of them are named in view, the first
|
||||
* few by name, and on request every one of them in a scroll area of bounded height. The rest of
|
||||
* the list is not drawn until it is asked for.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.records - Every record the server listed.
|
||||
* @param props.total - How many records the card acts on (the server's count).
|
||||
* @param props.noun - What the records are called, e.g. "Printer records".
|
||||
* @returns The block.
|
||||
*/
|
||||
function RecordSet({ records, total, noun }: { records: AssistantPendingActionRecord[]; total: number; noun: string }) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const listId = useId()
|
||||
const listed = records.length
|
||||
const visible = expanded ? records : records.slice(0, NAMES_IN_VIEW)
|
||||
|
||||
return (
|
||||
<div className="border-t border-border px-3 py-2 text-xs" data-qqq-id="assistant-pending-action-records">
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
|
||||
<p className="font-medium text-foreground" data-qqq-id="assistant-pending-action-record-count">
|
||||
{total} {noun} · {showingText(visible.length, listed, total)}
|
||||
</p>
|
||||
{listed > NAMES_IN_VIEW && (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={listId}
|
||||
onClick={() => setExpanded((open) => !open)}
|
||||
className="rounded text-xs font-medium text-primary hover:underline pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
data-qqq-id="assistant-pending-action-records-toggle"
|
||||
>
|
||||
{expanded ? 'Show fewer' : `See all ${listed}`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{listed > 0 && listed !== total && (
|
||||
<p className="mt-0.5 text-amber-800 dark:text-amber-300" data-qqq-id="assistant-pending-action-record-mismatch">
|
||||
The list holds {listed} {listed === 1 ? 'name' : 'names'}, not {total}.
|
||||
</p>
|
||||
)}
|
||||
{listed > 0 && (
|
||||
<div
|
||||
id={listId}
|
||||
{...(expanded ? { role: 'group', 'aria-label': `All ${listed} names`, tabIndex: 0 } : {})}
|
||||
className={expanded ? 'mt-1.5 max-h-48 overflow-y-auto rounded-md border border-border px-2 py-1 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring' : 'mt-1.5'}
|
||||
>
|
||||
<ul className="space-y-0.5">
|
||||
{visible.map((record, index) => (
|
||||
<li key={`${index}:${record.id}`} className="min-w-0 pointer-coarse:flex pointer-coarse:min-h-11 pointer-coarse:items-center">
|
||||
<RecordName record={record} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The confirmation card of one proposed write.
|
||||
*
|
||||
@@ -178,18 +72,8 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
|
||||
|
||||
const status = action?.status ?? 'PENDING'
|
||||
const pending = status === 'PENDING'
|
||||
// a card for a set: the server sent how many records it acts on, or the records themselves
|
||||
const records = render.records ?? []
|
||||
const total = render.recordCount ?? records.length
|
||||
const isSet = total > 0 || records.length > 0
|
||||
const noun = `${render.tableLabel ? `${render.tableLabel} ` : ''}${total === 1 ? 'record' : 'records'}`
|
||||
// a run over a set arrives as an update; a table's own bulk delete is still a delete
|
||||
const deletes = render.toolName === 'delete_record' || (isSet && (render.processName ?? '').endsWith(BULK_DELETE_SUFFIX))
|
||||
const Icon = deletes ? Trash2 : render.toolName === 'create_record' ? Plus : PencilLine
|
||||
const verb = deletes ? 'Delete' : render.toolName === 'create_record' ? 'Create' : 'Save'
|
||||
const runsOther = isSet && render.actionKind === 'process_run' && !deletes && !(render.processName ?? '').endsWith(BULK_EDIT_SUFFIX)
|
||||
// the number being confirmed is on the control itself
|
||||
const confirmText = !isSet ? verb : runsOther ? `Run on ${total}` : `${verb} ${total}`
|
||||
const Icon = render.toolName === 'delete_record' ? Trash2 : render.toolName === 'create_record' ? Plus : PencilLine
|
||||
const verb = render.toolName === 'delete_record' ? 'Delete' : render.toolName === 'create_record' ? 'Create' : 'Save'
|
||||
const resultHref = internalAppHref(action?.href ?? render.href)
|
||||
const tone = status === 'EXECUTED' ? 'text-emerald-700 dark:text-emerald-400' : status === 'FAILED' ? 'text-destructive' : 'text-muted-foreground'
|
||||
|
||||
@@ -236,7 +120,6 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{isSet && <RecordSet records={records} total={total} noun={noun} />}
|
||||
{(error || action?.message) && status !== 'EXECUTED' && (
|
||||
<p className="px-3 pb-2 text-xs text-destructive" role="alert">{error ?? action?.message}</p>
|
||||
)}
|
||||
@@ -247,12 +130,11 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => decide(true)}
|
||||
className={`inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${deletes ? 'bg-destructive text-white hover:bg-destructive/90' : 'bg-primary text-primary-foreground hover:bg-primary/90'}`}
|
||||
className={`inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${render.toolName === 'delete_record' ? 'bg-destructive text-white hover:bg-destructive/90' : 'bg-primary text-primary-foreground hover:bg-primary/90'}`}
|
||||
data-qqq-id="assistant-pending-action-confirm"
|
||||
{...(isSet && !busy ? { 'aria-label': `${confirmText} ${noun}` } : {})}
|
||||
>
|
||||
<Check className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
{busy ? 'Working…' : confirmText}
|
||||
{busy ? 'Working…' : verb}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Access editor behavior: stable selections, grant sources and API failures. */
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { QWidgetMetaData } from '@/types'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { fetchPossibleValues } from '@/lib/api/possible-values'
|
||||
import AuthentikAccessEditorWidget from './AuthentikAccessEditorWidget'
|
||||
|
||||
vi.mock('@/lib/api/widgets', () => ({ fetchWidgetData: vi.fn() }))
|
||||
vi.mock('@/lib/api/possible-values', () => ({ fetchPossibleValues: vi.fn() }))
|
||||
const widget = { name: 'access', type: 'AUTHENTIK_ACCESS_EDITOR' } as QWidgetMetaData
|
||||
|
||||
/**
|
||||
* Render with an isolated query cache.
|
||||
* @param fields - Editor fields.
|
||||
* @returns Process value callback.
|
||||
*/
|
||||
function setup(fields: Record<string, unknown>[]) {
|
||||
const changed = vi.fn()
|
||||
render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<AuthentikAccessEditorWidget widgetMetaData={widget} data={{ fields }} onWidgetData={changed} />
|
||||
</QueryClientProvider>)
|
||||
return changed
|
||||
}
|
||||
|
||||
describe('Access editor', () => {
|
||||
it('preserves unknown grants and displays inherited access without making it editable', async () => {
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', selected: [{ id: 'legacy.read', label: 'legacy.read' }],
|
||||
choices: [{ id: 'posts.edit', label: 'Edit posts' }], inherited: { 'posts.read': ['Readers'] } }])
|
||||
expect(screen.getByLabelText('legacy.read')).toBeChecked()
|
||||
await userEvent.click(screen.getByLabelText('Edit posts'))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\nposts.edit' })
|
||||
expect(screen.queryByRole('checkbox', { name: /posts.read/ })).not.toBeInTheDocument()
|
||||
expect(screen.getByText('posts.read — Readers')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('searches the server and preserves selected IDs when results change', async () => {
|
||||
vi.mocked(fetchPossibleValues).mockImplementation(async (_source, request) => request?.searchTerm === 'alex'
|
||||
? [{ id: 42, label: 'Alex' }] : [{ id: 3, label: 'Sam' }])
|
||||
const changed = setup([{ name: 'userIds', label: 'Users', source: 'identityUsers', selected: [] }])
|
||||
await userEvent.click(await screen.findByLabelText('Sam'))
|
||||
await userEvent.type(screen.getByLabelText('Search users'), 'alex')
|
||||
await userEvent.click(await screen.findByLabelText('Alex'))
|
||||
expect(screen.getByLabelText('Sam')).toBeChecked()
|
||||
expect(changed).toHaveBeenLastCalledWith({ userIds: '3\n42' })
|
||||
expect(fetchPossibleValues).toHaveBeenLastCalledWith('identityUsers', { searchTerm: 'alex', useCase: 'form' })
|
||||
})
|
||||
|
||||
it('keeps existing assignments when the directory search fails', async () => {
|
||||
vi.mocked(fetchPossibleValues).mockRejectedValue(new Error('Offline'))
|
||||
const changed = setup([{ name: 'parentIds', label: 'Roles', source: 'roles', selected: [{ id: 'role-1', label: 'Reader' }] }])
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Could not load choices'))
|
||||
expect(screen.getByLabelText('Reader')).toBeChecked()
|
||||
expect(changed).toHaveBeenCalledWith({ parentIds: 'role-1' })
|
||||
})
|
||||
|
||||
it('rejects malformed payloads without submitting an empty permission list', () => {
|
||||
const changed = setup([{ name: 'permissions', label: 'Permissions', selected: 'broken' }])
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('unavailable')
|
||||
expect(changed).toHaveBeenCalledWith({ __accessEditorReady: false })
|
||||
expect(changed).not.toHaveBeenCalledWith({ permissions: '' })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Paged permission matrix', () => {
|
||||
it('accepts the live QQQ payload that omits empty application names and IDs', async () => {
|
||||
vi.mocked(fetchWidgetData).mockResolvedValue({ type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{
|
||||
total: 1, page: 0, pageSize: 25, apps: [{ label: 'Other' }],
|
||||
rows: [{ name: 'documents', label: 'Documents', kind: 'TABLE', permissions: [{ id: 'documents.read', label: 'read' }] }],
|
||||
}] })
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', catalogWidget: 'grantEditor', selected: [] }])
|
||||
await userEvent.click(await screen.findByRole('checkbox', { name: 'documents.read' }))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'documents.read' })
|
||||
await userEvent.selectOptions(screen.getByLabelText('Application'), '')
|
||||
await waitFor(() => expect(fetchWidgetData).toHaveBeenLastCalledWith('grantEditor', expect.objectContaining({ app: '' })))
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps unknown and off-page grants across bulk page edits and failed searches', async () => {
|
||||
vi.mocked(fetchWidgetData).mockImplementation(async (_widget, params) => {
|
||||
if (params?.search === 'offline') throw new Error('Offline')
|
||||
const page = Number(params?.page ?? 0)
|
||||
return { type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{ total: 1000, page, pageSize: 25, apps: [{ id: 'sales', label: 'Sales' }],
|
||||
rows: Array.from({ length: 25 }, (_, i) => ({ name: 'table' + (page * 25 + i), label: 'Table ' + (page * 25 + i), kind: 'TABLE', app: 'sales', permissions: [{ id: 'table' + (page * 25 + i) + '.read', label: 'read' }] })) }] }
|
||||
})
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', catalogWidget: 'grantEditor', selected: [{ id: 'legacy.read', label: 'legacy.read' }], inherited: { 'table999.read': ['Readers'] } }])
|
||||
await screen.findByLabelText('table0.read')
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(25)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Select 25 permissions on this page' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next' }))
|
||||
await screen.findByLabelText('table25.read')
|
||||
await userEvent.click(screen.getByLabelText('table25.read'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Previous' }))
|
||||
await screen.findByLabelText('table0.read')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clear 25 permissions on this page' }))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\ntable25.read' })
|
||||
await userEvent.type(screen.getByLabelText('Search permissions or resources'), 'offline')
|
||||
await screen.findByRole('alert')
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\ntable25.read' })
|
||||
await userEvent.clear(screen.getByLabelText('Search permissions or resources'))
|
||||
await userEvent.selectOptions(screen.getByLabelText('Show'), 'inherited')
|
||||
expect(screen.getByText('table999.read — Readers')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,104 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Structured named grants and searchable membership assignments. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import type { WidgetComponentProps } from '@/components/widgets/widget-types'
|
||||
import { fetchPossibleValues } from '@/lib/api/possible-values'
|
||||
import { PermissionMatrix } from './PermissionMatrix'
|
||||
import { INPUT_CLASS, ALERT_CLASS } from '@/components/ui/controls'
|
||||
|
||||
const optionSchema = z.object({ id: z.string(), label: z.string() })
|
||||
const fieldSchema = z.object({
|
||||
catalogWidget: z.string().optional(), name: z.string().min(1), label: z.string(), source: z.string().optional(),
|
||||
selected: z.array(optionSchema).default([]), choices: z.array(optionSchema).optional(),
|
||||
inherited: z.record(z.string(), z.array(z.string())).optional(), policyPermissions: z.array(z.string()).optional(),
|
||||
})
|
||||
const payloadSchema = z.object({ fields: z.array(fieldSchema) })
|
||||
type Field = z.infer<typeof fieldSchema>
|
||||
type Option = z.infer<typeof optionSchema>
|
||||
|
||||
/**
|
||||
* Edit one structured field while keeping selection independent of search results.
|
||||
* @param props - Server metadata and the process value callback.
|
||||
* @returns A checkbox list and, for assignments, a server-backed search box.
|
||||
*/
|
||||
function AccessField({ field, onChange }: { field: Field; onChange: (values: Record<string, unknown>) => void }) {
|
||||
const [selected, setSelected] = useState<Option[]>(field.selected)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [debounced, setDebounced] = useState('')
|
||||
const id = useId()
|
||||
useEffect(() => { const timer = setTimeout(() => setDebounced(search), 250); return () => clearTimeout(timer) }, [search])
|
||||
const options = useQuery({
|
||||
queryKey: ['access-editor-options', field.source, debounced],
|
||||
queryFn: () => fetchPossibleValues(field.source!, { searchTerm: debounced, useCase: 'form' }),
|
||||
enabled: Boolean(field.source),
|
||||
})
|
||||
useEffect(() => { onChange({ [field.name]: selected.map(option => option.id).join('\n') }) }, [selected, field.name, onChange])
|
||||
const choices: Option[] = field.source
|
||||
? (options.data ?? []).map(option => ({ id: String(option.id), label: option.label }))
|
||||
: (field.choices ?? []).filter(option => option.label.toLowerCase().includes(search.toLowerCase()))
|
||||
const selectedIds = new Set(selected.map(option => option.id))
|
||||
const displayed = [...selected, ...choices.filter(option => !selectedIds.has(option.id))].filter(option => Boolean(field.source) || option.label.toLowerCase().includes(search.toLowerCase()))
|
||||
const currentPage = Math.min(page, Math.max(0, Math.ceil(displayed.length / 25) - 1))
|
||||
return <fieldset className="space-y-3 rounded-lg border border-border p-4">
|
||||
<legend className="px-2 font-semibold">{field.label}</legend>
|
||||
<label htmlFor={id} className="block text-sm">Search {field.label.toLowerCase()}</label>
|
||||
<input id={id} data-qqq-id={'access-search-' + field.name} className={INPUT_CLASS} value={search} onChange={event => { setSearch(event.target.value); setPage(0) }} />
|
||||
{options.isFetching && field.source && <p role="status" className="text-sm">Searching…</p>}
|
||||
{options.isError && <p role="alert" className={ALERT_CLASS}>Could not load choices. Your selections are preserved. Change the search to try again.</p>}
|
||||
<p className="text-sm text-muted-foreground">{selected.length} selected. Review validates every change before saving.</p>
|
||||
<div className="max-h-80 space-y-2 overflow-auto">
|
||||
{displayed.slice(currentPage * 25, currentPage * 25 + 25).map(option => <label key={option.id} className="flex items-start gap-2 text-sm">
|
||||
<input type="checkbox" data-qqq-id={'access-choice-' + field.name + '-' + option.id} checked={selectedIds.has(option.id)}
|
||||
onChange={event => setSelected(current => event.target.checked ? [...current, option] : current.filter(item => item.id !== option.id))} />
|
||||
<span>{option.label}</span>
|
||||
</label>)}
|
||||
{!options.isFetching && displayed.length === 0 && <p className="text-sm text-muted-foreground">No choices found.</p>}
|
||||
</div>
|
||||
{displayed.length > 25 && <div className="flex gap-4">
|
||||
<button type="button" disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>Previous choices</button>
|
||||
<span>Page {currentPage + 1} of {Math.ceil(displayed.length / 25)}</span>
|
||||
<button type="button" disabled={(currentPage + 1) * 25 >= displayed.length} onClick={() => setPage(currentPage + 1)}>Next choices</button>
|
||||
</div>}
|
||||
{field.inherited && Object.keys(field.inherited).length > 0 && <details>
|
||||
<summary className="cursor-pointer text-sm font-medium">Inherited access — edit the source to remove it</summary>
|
||||
<ul className="mt-2 space-y-1 text-sm">{Object.entries(field.inherited).map(([permission, sources]) => <li key={permission}>{permission} — {sources.join(', ')}</li>)}</ul>
|
||||
</details>}
|
||||
{Boolean(field.policyPermissions?.length) && <details>
|
||||
<summary className="cursor-pointer text-sm font-medium">Access from this item’s policy — use Edit Policy to change it</summary>
|
||||
<ul className="mt-2 text-sm">{field.policyPermissions?.map(permission => <li key={permission}>{permission}</li>)}</ul>
|
||||
</details>}
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate server-provided metadata before rendering editable process values.
|
||||
* @param props - Standard widget payload and process callback.
|
||||
* @returns The access editor or a contained error.
|
||||
*/
|
||||
export default function AuthentikAccessEditorWidget({ data, onWidgetData }: WidgetComponentProps<Record<string, unknown>>) {
|
||||
const payload = payloadSchema.safeParse(data)
|
||||
const ready = payload.success
|
||||
useEffect(() => { onWidgetData?.({ __accessEditorReady: ready }) }, [ready, onWidgetData])
|
||||
if (!payload.success || !onWidgetData) return <p role="alert" className={ALERT_CLASS}>The access editor is unavailable. Reopen the action before continuing.</p>
|
||||
return <div className="space-y-4">{payload.data.fields.map(field => field.catalogWidget ? <PermissionMatrix key={field.name} field={field} onChange={onWidgetData} /> : <AccessField key={field.name} field={field} onChange={onWidgetData} />)}</div>
|
||||
}
|
||||
@@ -17,8 +17,6 @@
|
||||
// Tests for the AUTHENTIK_POLICY_EDITOR widget: matrix, select-all, search, unknowns, JSON output
|
||||
|
||||
import React from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { axe } from 'jest-axe'
|
||||
@@ -29,8 +27,6 @@ import { WidgetRenderer } from '@/components/widgets/WidgetRenderer'
|
||||
import { AuthentikPolicyEditorWidget, isPolicyPermission } from './AuthentikPolicyEditorWidget'
|
||||
import type { PolicyEditorPayload } from './AuthentikPolicyEditorWidget'
|
||||
|
||||
vi.mock('@/lib/api/widgets', () => ({ fetchWidgetData: vi.fn() }))
|
||||
|
||||
const widget = { name: 'authentikPolicyEditor', type: 'AUTHENTIK_POLICY_EDITOR', label: 'Policy' } as unknown as QWidgetMetaData
|
||||
|
||||
const payload = (overrides: Partial<PolicyEditorPayload> = {}): PolicyEditorPayload => ({
|
||||
@@ -78,7 +74,7 @@ const documentFor = (actions: string[], resources = ['person']) => JSON.stringif
|
||||
*/
|
||||
function setup(data: PolicyEditorPayload) {
|
||||
const onWidgetData = vi.fn()
|
||||
const view = render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}><AuthentikPolicyEditorWidget widgetMetaData={widget} data={data as unknown as Record<string, unknown>} onWidgetData={onWidgetData} /></QueryClientProvider>)
|
||||
const view = render(<AuthentikPolicyEditorWidget widgetMetaData={widget} data={data as unknown as Record<string, unknown>} onWidgetData={onWidgetData} />)
|
||||
const last = () => String(onWidgetData.mock.calls.at(-1)?.[0]?.policyDocument ?? '')
|
||||
return { onWidgetData, last, ...view }
|
||||
}
|
||||
@@ -379,41 +375,3 @@ describe('AuthentikPolicyEditorWidget', () => {
|
||||
expect(isPolicyPermission('a.b.read')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Large policy catalogs', () => {
|
||||
it('bounds rendering and preserves off-page grants when selecting one page', async () => {
|
||||
const { last } = setup(payload({ catalog: [{ app: 'large', label: 'Large', resources: Array.from({ length: 1000 }, (_, i) => ({ name: 'resource' + i, label: 'Resource ' + i, kind: 'TABLE', actions: ['read'] })) }] }))
|
||||
expect(screen.getByLabelText('Read: Resource 0')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Read: Resource 25')).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByLabelText('Everything in Large (this page)'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next resources' }))
|
||||
expect(screen.queryByLabelText('Read: Resource 0')).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByLabelText('Read: Resource 25'))
|
||||
const doc = JSON.parse(last())
|
||||
const resources = doc.Statement.flatMap((statement: { Resource: string[] }) => statement.Resource)
|
||||
expect(resources).toHaveLength(26)
|
||||
expect(resources).toContain('resource0')
|
||||
expect(resources).toContain('resource25')
|
||||
await userEvent.type(screen.getByLabelText('Find a resource'), 'Resource 999')
|
||||
expect(screen.getByLabelText('Read: Resource 999')).toBeInTheDocument()
|
||||
expect(JSON.parse(last())).toEqual(doc)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Server-paged policies', () => {
|
||||
it('keeps controlled selection synchronized with unknown removal and clear all', async () => {
|
||||
vi.mocked(fetchWidgetData).mockResolvedValue({ type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{ total: 1, page: 0, pageSize: 25, apps: [], rows: [{ name: 'cms_page', label: 'Pages', kind: 'TABLE', app: '', permissions: [{ id: 'cms_page.read', label: 'read' }, { id: 'cms_page.edit', label: 'edit' }] }] }] })
|
||||
const { last } = setup(payload({ catalog: [], catalogWidget: 'pagedPolicy', unknownPermissions: ['legacy.read'], document: documentFor(['read'], ['legacy']) }))
|
||||
await userEvent.click(await screen.findByLabelText('cms_page.read'))
|
||||
expect(last()).toContain('legacy')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Remove legacy.read' }))
|
||||
await userEvent.click(screen.getByLabelText('cms_page.edit'))
|
||||
expect(last()).not.toContain('legacy')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clear all' }))
|
||||
expect(screen.getByLabelText('cms_page.read')).not.toBeChecked()
|
||||
expect(screen.getByLabelText('cms_page.edit')).not.toBeChecked()
|
||||
expect(JSON.parse(last()).Statement).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -29,7 +29,6 @@ import React, { lazy, Suspense, useEffect, useId, useMemo, useRef, useState } fr
|
||||
import type { WidgetComponentProps } from '@/components/widgets/widget-types'
|
||||
import { asList, isPlainObject } from '@/components/widgets/widget-types'
|
||||
import { ALERT_CLASS, INPUT_CLASS, WARNING_CLASS, buttonClass } from '@/components/ui/controls'
|
||||
import { PermissionMatrix } from './PermissionMatrix'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import type { PolicyAction, PolicyFormat } from './policy-document'
|
||||
import { ACTION_LABELS, FULL_ACCESS_PERMISSION, POLICY_ACTIONS, generatePolicy, parsePolicy, permissionName, roundTrips, splitPermission } from './policy-document'
|
||||
@@ -66,10 +65,6 @@ export interface PolicyEditorPayload {
|
||||
/** The group the policy belongs to (display only). */
|
||||
groupLabel?: string
|
||||
catalog: PolicyCatalogGroup[]
|
||||
/** Server-paged catalog source; older hosts send the full catalog. */
|
||||
catalogWidget?: string
|
||||
/** Unknown grants identified against the complete server catalog. */
|
||||
unknownPermissions?: string[]
|
||||
/** The group's current document (JSON text), or empty for none. */
|
||||
document?: string
|
||||
/** Whether the current document grants full access; older servers omit this. */
|
||||
@@ -177,12 +172,11 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(initial.permissions))
|
||||
const fullAccess = selected.has(FULL_ACCESS_PERMISSION)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [memberUsername, setMemberUsername] = useState('')
|
||||
const member = payload.members?.find((candidate) => candidate.username === memberUsername)
|
||||
|
||||
const generated = useMemo(() => generatePolicy(selected, format), [format, selected])
|
||||
const unknown = useMemo(() => fullAccess ? [] : [...selected].filter((permission) => payload.catalogWidget ? payload.unknownPermissions?.includes(permission) : !known.has(permission)).sort(), [fullAccess, known, selected, payload.catalogWidget, payload.unknownPermissions])
|
||||
const unknown = useMemo(() => fullAccess ? [] : [...selected].filter((permission) => !known.has(permission)).sort(), [fullAccess, known, selected])
|
||||
const valid = useMemo(() => roundTrips(selected, format), [format, selected])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -200,16 +194,6 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
}))
|
||||
.filter((group) => group.resources.length > 0), [catalog, term])
|
||||
|
||||
const matchingCount = visibleGroups.reduce((sum, group) => sum + group.resources.length, 0)
|
||||
const currentPage = Math.min(page, Math.max(0, Math.ceil(matchingCount / 25) - 1))
|
||||
const pageResources = visibleGroups.flatMap((group) => group.resources.map((resource) => ({ group, resource })))
|
||||
.slice(currentPage * 25, (currentPage + 1) * 25)
|
||||
const pageGroups = visibleGroups.map((group) => ({
|
||||
...group,
|
||||
resources: pageResources.filter((entry) => entry.group === group).map((entry) => entry.resource),
|
||||
label: matchingCount > 25 ? group.label + ' (this page)' : group.label,
|
||||
})).filter((group) => group.resources.length > 0)
|
||||
|
||||
const set = (permissions: string[], on: boolean) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current)
|
||||
@@ -251,7 +235,7 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
|
||||
<fieldset disabled={fullAccess} aria-disabled={fullAccess} hidden={fullAccess} className="min-w-0">
|
||||
<div className="flex flex-col gap-2 @xl:flex-row @xl:items-end @xl:justify-between">
|
||||
<div hidden={Boolean(payload.catalogWidget)} className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<label htmlFor={searchId} className="text-sm font-medium text-foreground">Find a resource</label>
|
||||
<input
|
||||
id={searchId}
|
||||
@@ -260,7 +244,7 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
placeholder="App, table, process or report"
|
||||
value={search}
|
||||
aria-disabled={fullAccess}
|
||||
onChange={(event) => { setSearch(event.target.value); setPage(0) }}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
data-qqq-id="policy-editor-search"
|
||||
/>
|
||||
</div>
|
||||
@@ -278,18 +262,11 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
{fullAccess && <p className="rounded-md border border-border bg-muted p-3 text-sm text-muted-foreground">Individual resource selection is disabled while full access is on.</p>}
|
||||
<div hidden={fullAccess}>
|
||||
<div className="flex min-w-0 flex-col gap-3">
|
||||
{payload.catalogWidget ? <PermissionMatrix field={{ name: 'policyPermissions', label: 'Policy permissions', catalogWidget: payload.catalogWidget, selected: [] }} selection={selected} onSelectionChange={setSelected} /> : <>
|
||||
{resourceCount === 0 && <p className="text-sm text-muted-foreground">This app has no resources that a policy can grant.</p>}
|
||||
{resourceCount > 0 && visibleGroups.length === 0 && <p className="text-sm text-muted-foreground" role="status">No resource matches the search.</p>}
|
||||
{matchingCount > 25 && <div className="flex items-center gap-3 text-sm">
|
||||
<button type="button" className={buttonClass('secondary', 'sm')} disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>Previous resources</button>
|
||||
<span role="status">{matchingCount} resources · Page {currentPage + 1} of {Math.ceil(matchingCount / 25)}. Bulk controls affect only this page.</span>
|
||||
<button type="button" className={buttonClass('secondary', 'sm')} disabled={(currentPage + 1) * 25 >= matchingCount} onClick={() => setPage(currentPage + 1)}>Next resources</button>
|
||||
</div>}
|
||||
{pageGroups.map((group) => (
|
||||
{visibleGroups.map((group) => (
|
||||
<PolicyGroupSection key={group.app ?? '(other)'} group={group} selected={selected} onSet={set} />
|
||||
))}
|
||||
</>}
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Bounded permission catalog and grant source views. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { INPUT_CLASS, ALERT_CLASS } from '@/components/ui/controls'
|
||||
|
||||
const optionSchema = z.object({ id: z.string(), label: z.string() })
|
||||
// QQQ omits empty strings on the wire. Only application membership uses the
|
||||
// empty string as a valid identity (the Other/unassigned application bucket).
|
||||
const appOptionSchema = optionSchema.extend({ id: z.string().default('') })
|
||||
const pageSchema = z.object({ fields: z.array(z.object({
|
||||
rows: z.array(z.object({ name: z.string(), label: z.string(), kind: z.string(), app: z.string().default(''), permissions: z.array(optionSchema) })),
|
||||
total: z.number().int().nonnegative(), page: z.number().int().nonnegative(), pageSize: z.number().int().positive(), apps: z.array(appOptionSchema),
|
||||
})).min(1) })
|
||||
type Option = z.infer<typeof optionSchema>
|
||||
interface Field {
|
||||
name: string; label: string; catalogWidget?: string; selected: Option[]
|
||||
inherited?: Record<string, string[]>; policyPermissions?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Paged resource matrix. Selection is independent of catalog pages and requests.
|
||||
* @param props - Initial grants, catalog source, and process output callback.
|
||||
* @returns A searchable matrix with page-scoped bulk actions.
|
||||
*/
|
||||
export function PermissionMatrix({ field, onChange, selection, onSelectionChange }: {
|
||||
field: Field; onChange?: (values: Record<string, unknown>) => void
|
||||
selection?: Set<string>; onSelectionChange?: (selection: Set<string>) => void
|
||||
}) {
|
||||
const [localSelected, setSelected] = useState(() => new Map(field.selected.map(option => [option.id, option])))
|
||||
const selected = useMemo(() => selection ? new Map([...selection].map(id => [id, { id, label: id }])) : localSelected, [selection, localSelected])
|
||||
const [search, setSearch] = useState('')
|
||||
const [debounced, setDebounced] = useState('')
|
||||
const [app, setApp] = useState('*')
|
||||
const [kind, setKind] = useState('*')
|
||||
const [page, setPage] = useState(0)
|
||||
const [view, setView] = useState('catalog')
|
||||
const id = useId()
|
||||
useEffect(() => { const timer = setTimeout(() => { setDebounced(search); setPage(0) }, 250); return () => clearTimeout(timer) }, [search])
|
||||
useEffect(() => { if (!selection) onChange?.({ [field.name]: [...selected.keys()].join('\n') }) }, [selected, field.name, onChange, selection])
|
||||
const catalog = useQuery({
|
||||
queryKey: ['access-catalog', field.catalogWidget, debounced, app, kind, page],
|
||||
queryFn: async () => pageSchema.parse(await fetchWidgetData(field.catalogWidget!, { accessCatalog: true, search: debounced, app, kind, page })).fields[0],
|
||||
enabled: view === 'catalog',
|
||||
})
|
||||
const data = catalog.data
|
||||
const busy = catalog.isFetching || search !== debounced
|
||||
const visible = data?.rows.flatMap(row => row.permissions) ?? []
|
||||
const actions = [...new Set(visible.map(option => option.label))]
|
||||
const change = (options: Option[], checked: boolean) => {
|
||||
const next = new Map(selected)
|
||||
options.forEach(option => { if (checked) next.set(option.id, option); else next.delete(option.id) })
|
||||
if (selection) onSelectionChange?.(new Set(next.keys()))
|
||||
else setSelected(next)
|
||||
}
|
||||
const localEntries = (view === 'selected' ? [...selected.values()].map(option => [option.id, 'Direct grant'] as const)
|
||||
: [...Object.entries(field.inherited ?? {}).map(([permission, sources]) => [permission, sources.join(', ')] as const),
|
||||
...(field.policyPermissions ?? []).map(permission => [permission, 'This item’s policy'] as const)])
|
||||
.filter(([permission, source]) => (permission + ' ' + source).toLowerCase().includes(search.toLowerCase()))
|
||||
const localPage = Math.min(page, Math.max(0, Math.ceil(localEntries.length / 25) - 1))
|
||||
const currentPage = view === 'catalog' ? (data?.page ?? 0) : localPage
|
||||
const total = view === 'catalog' ? (data?.total ?? 0) : localEntries.length
|
||||
return <fieldset className="space-y-3 rounded-lg border border-border p-4" data-qqq-id="access-permission-matrix">
|
||||
<legend className="px-2 font-semibold">{field.label}</legend>
|
||||
<p className="text-sm">{selected.size} direct permissions selected. Changes affect named permissions on existing resources. Future resources are not included.</p>
|
||||
<label htmlFor={id + '-view'}>Show</label>
|
||||
<select id={id + '-view'} className={INPUT_CLASS} value={view} onChange={event => { setView(event.target.value); setPage(0) }}>
|
||||
<option value="catalog">Permission catalog</option><option value="selected">Selected direct grants</option><option value="inherited">Why access is granted</option>
|
||||
</select>
|
||||
<label htmlFor={id + '-search'}>Search permissions or resources</label>
|
||||
<input id={id + '-search'} className={INPUT_CLASS} value={search} onChange={event => setSearch(event.target.value)} />
|
||||
{view === 'catalog' && <>
|
||||
<label htmlFor={id + '-app'}>Application</label>
|
||||
<select id={id + '-app'} className={INPUT_CLASS} value={app} onChange={event => { setApp(event.target.value); setPage(0) }}>
|
||||
<option value="*">All applications</option>{data?.apps.map(option => <option key={option.id} value={option.id}>{option.label}</option>)}
|
||||
</select>
|
||||
<label htmlFor={id + '-kind'}>Resource type</label>
|
||||
<select id={id + '-kind'} className={INPUT_CLASS} value={kind} onChange={event => { setKind(event.target.value); setPage(0) }}>
|
||||
<option value="*">All resource types</option>{['APP', 'TABLE', 'PROCESS', 'REPORT', 'WIDGET', 'OTHER'].map(value => <option key={value}>{value}</option>)}
|
||||
</select>
|
||||
{busy && <p role="status">Loading permission page…</p>}
|
||||
{catalog.isError && <p role="alert" className={ALERT_CLASS}>Could not load permissions. Your selections are preserved. <button type="button" onClick={() => void catalog.refetch()}>Retry</button></p>}
|
||||
<div className="flex gap-4">
|
||||
<button type="button" disabled={busy || !visible.length || catalog.isError} onClick={() => change(visible, true)}>Select {visible.length} permissions on this page</button>
|
||||
<button type="button" disabled={busy || !visible.length || catalog.isError} onClick={() => change(visible, false)}>Clear {visible.length} permissions on this page</button>
|
||||
</div>
|
||||
<div className="overflow-auto"><table className="w-full text-sm"><caption className="sr-only">Direct permissions by resource and action</caption>
|
||||
<thead><tr><th scope="col" className="text-left">Resource</th>{actions.map(action => <th scope="col" key={action}>{action === 'insert' ? 'Create' : action === 'hasAccess' ? 'Access' : action}</th>)}</tr></thead>
|
||||
<tbody>{data?.rows.map(row => <tr key={row.name}><th scope="row" className="text-left"><span>{row.label}</span><small className="block font-normal">{row.name} · {row.kind}</small></th>
|
||||
{actions.map(action => { const option = row.permissions.find(item => item.label === action); return <td key={action} className="p-2 text-center">{option ? <input type="checkbox" aria-label={option.id} data-qqq-id={'access-choice-permissions-' + option.id} checked={selected.has(option.id)} disabled={busy} onChange={event => change([option], event.target.checked)} /> : '—'}</td> })}
|
||||
</tr>)}</tbody>
|
||||
</table></div>
|
||||
</>}
|
||||
{view !== 'catalog' && <ul className="space-y-2">{localEntries.slice(localPage * 25, localPage * 25 + 25).map(([permission, source]) => <li key={permission + source}>
|
||||
{view === 'selected' ? <label><input type="checkbox" checked aria-label={permission} onChange={() => change([{ id: permission, label: permission }], false)} /> {permission}</label> : <span>{permission} — {source}</span>}
|
||||
</li>)}</ul>}
|
||||
<p role="status">{total} {view === 'catalog' ? 'resources' : 'permissions'} · Page {currentPage + 1} of {Math.max(1, Math.ceil(total / 25))}</p>
|
||||
<div className="flex gap-4"><button type="button" disabled={currentPage === 0 || (view === 'catalog' && busy)} onClick={() => setPage(currentPage - 1)}>Previous</button>
|
||||
<button type="button" disabled={(currentPage + 1) * 25 >= total || (view === 'catalog' && busy)} onClick={() => setPage(currentPage + 1)}>Next</button></div>
|
||||
{view === 'inherited' && <p className="text-sm">Inherited grants must be changed at their source. Policy grants use Edit Policy.</p>}
|
||||
</fieldset>
|
||||
}
|
||||
@@ -28,7 +28,7 @@ import { useCollaborationPresence } from '@/lib/hooks/use-collaboration-presence
|
||||
import { getErrorStatusCode } from '@/lib/utils/error-utils'
|
||||
import { recordVersion } from '@/lib/utils/record-version'
|
||||
import { CollaborationDialog, collaborationButton } from './CollaborationDialog'
|
||||
import { PresenceAvatars, PresenceReconnecting } from './PresenceAvatars'
|
||||
import { PresenceAvatars } from './PresenceAvatars'
|
||||
|
||||
export interface CollaborationEditProps {
|
||||
table: QTableMetaData
|
||||
@@ -167,7 +167,7 @@ export function CollaborationEdit({
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<PresenceAvatars viewers={presence.viewers} />
|
||||
{presence.hadViewers && <PresenceReconnecting />}
|
||||
{presence.unavailable && <span role="status">Presence temporarily unavailable</span>}
|
||||
{conflict && (
|
||||
<div
|
||||
role="alert"
|
||||
|
||||
@@ -1,306 +1,306 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import * as api from '@/lib/api/collaboration'
|
||||
import { getRecord } from '@/lib/api/tables'
|
||||
import type { RealtimeEvent } from '@/lib/realtime/client'
|
||||
import { ShareDialog } from './ShareDialog'
|
||||
import { RequestAccess } from './RequestAccess'
|
||||
import { TasksTab } from './TasksTab'
|
||||
import { CollaborationEdit } from './CollaborationEdit'
|
||||
import { MyWork } from './MyWork'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
let receive: ((event: RealtimeEvent) => void) | undefined
|
||||
vi.mock('@/lib/hooks/use-realtime-channel', () => ({
|
||||
useRealtimeChannel: (_channel: string, callback?: typeof receive) => {
|
||||
receive = callback
|
||||
},
|
||||
}))
|
||||
vi.mock('@/lib/hooks/use-collaboration-presence', () => ({
|
||||
useCollaborationPresence: () => ({ viewers: [] }),
|
||||
}))
|
||||
vi.mock('@/lib/context/q-context', async () => {
|
||||
const { createContext } = await import('react')
|
||||
return { useQContext: () => ({ userId: 'me' }), QContext: createContext({ userId: 'me' }) }
|
||||
})
|
||||
vi.mock('@/lib/hooks/use-collaboration-core', () => ({
|
||||
useCollaborationAvailable: () => ({ data: true }),
|
||||
}))
|
||||
vi.mock('@/lib/hooks/use-metadata', () => ({
|
||||
useMetaData: () => ({ data: qInstance }),
|
||||
useTableMetaData: () => ({ data: qInstance.tables.person }),
|
||||
}))
|
||||
vi.mock('@/lib/api/tables', () => ({
|
||||
getRecord: vi.fn(),
|
||||
queryRecords: vi.fn().mockResolvedValue({
|
||||
records: [{ tableName: 'person', values: { id: 1 }, recordLabel: 'Alice' }],
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/api/collaboration', () => ({
|
||||
searchPeople: vi.fn(),
|
||||
mentionCandidates: vi.fn(),
|
||||
getRecordLink: vi.fn(),
|
||||
previewShares: vi.fn(),
|
||||
shareRecord: vi.fn(),
|
||||
requestAccess: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
createTask: vi.fn(),
|
||||
patchTask: vi.fn(),
|
||||
getMyWork: vi.fn(),
|
||||
markMentionsRead: vi.fn().mockResolvedValue({ success: true }),
|
||||
listMyTasks: vi.fn(),
|
||||
}))
|
||||
const record = { table: 'person', pk: '1' }
|
||||
function mount(node: React.ReactNode) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(api.searchPeople).mockResolvedValue({
|
||||
items: [
|
||||
{ userId: 'sam', displayName: 'Sam Parker', email: null },
|
||||
{ userId: 'alex', displayName: 'Alex Rivera', email: null },
|
||||
{ userId: 'unknown', displayName: 'Taylor', email: null },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.previewShares).mockImplementation(async (_record, ids) => ({
|
||||
recipients: ids.map((id) => ({
|
||||
userId: id,
|
||||
displayName: id === 'sam' ? 'Sam Parker' : id,
|
||||
canRead: id === 'unknown' ? null : id === 'alex',
|
||||
})),
|
||||
}))
|
||||
vi.mocked(api.mentionCandidates).mockResolvedValue({
|
||||
items: [
|
||||
{ person: { userId: 'sam', displayName: 'Sam Parker' }, canRead: 'false' },
|
||||
{ person: { userId: 'alex', displayName: 'Alex Rivera' }, canRead: 'true' },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.getRecordLink).mockResolvedValue({ url: 'https://example.test/app/person/1' })
|
||||
vi.mocked(api.shareRecord).mockResolvedValue({
|
||||
items: [
|
||||
{ id: 1, toUserId: 'sam', recipientCouldRead: false },
|
||||
{ id: 2, toUserId: 'alex', recipientCouldRead: true },
|
||||
],
|
||||
})
|
||||
vi.mocked(api.listTasks).mockResolvedValue({
|
||||
items: [{ id: 1, title: 'Review order', status: 'OPEN' }],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.listMyTasks).mockResolvedValue({ items: [], nextCursor: null })
|
||||
vi.mocked(api.createTask).mockResolvedValue({ id: 2 })
|
||||
vi.mocked(api.patchTask).mockResolvedValue({ id: 1 })
|
||||
vi.mocked(getRecord).mockResolvedValue({
|
||||
tableName: 'person',
|
||||
values: { id: 1, firstName: 'Their value', modifyDate: 'v2' },
|
||||
})
|
||||
})
|
||||
it('previews inaccessible and unknown recipients, then reports notified and offered access', async () => {
|
||||
mount(<ShareDialog record={record} canShare onClose={vi.fn()} />)
|
||||
expect(await screen.findByText("can't open this record")).toBeVisible()
|
||||
expect(screen.getByText('unknown')).toBeVisible()
|
||||
fireEvent.click(screen.getByLabelText(/Sam Parker/))
|
||||
fireEvent.click(screen.getByLabelText(/Alex Rivera/))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled())
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send' }))
|
||||
expect(await screen.findByText('Sam Parker: Offered access')).toBeVisible()
|
||||
expect(screen.getByText('alex: Notified')).toBeVisible()
|
||||
})
|
||||
it('leaves the signed-in user out of share recipients even when the service returns them', async () => {
|
||||
vi.mocked(api.searchPeople).mockResolvedValueOnce({
|
||||
items: [
|
||||
{ userId: 'ME', displayName: 'Me Myself', email: null },
|
||||
{ userId: 'x9', displayName: 'Mail Match', email: 'Me' },
|
||||
{ userId: 'alex', displayName: 'Alex Rivera', email: null },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<ShareDialog record={record} canShare onClose={vi.fn()} />)
|
||||
expect(await screen.findByLabelText(/Alex Rivera/)).toBeVisible()
|
||||
expect(screen.queryByLabelText(/Me Myself/)).toBeNull()
|
||||
expect(screen.queryByLabelText(/Mail Match/)).toBeNull()
|
||||
})
|
||||
it('uses identical non-disclosing access copy even when the server reports missing record', async () => {
|
||||
vi.mocked(api.requestAccess).mockRejectedValue(
|
||||
new Error('Record does not exist: sensitive detail')
|
||||
)
|
||||
mount(<RequestAccess tableName="person" recordId="missing" shareId={12} />)
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Message' }), {
|
||||
target: { value: 'Please review' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request access' }))
|
||||
expect(await screen.findByRole('alert')).not.toHaveTextContent('sensitive detail')
|
||||
expect(document.body).not.toHaveTextContent('does not exist')
|
||||
expect(api.requestAccess).toHaveBeenCalledWith({
|
||||
tableName: 'person',
|
||||
recordId: 'missing',
|
||||
shareId: 12,
|
||||
message: 'Please review',
|
||||
})
|
||||
})
|
||||
it('shows a stream warning, compares theirs and mine, and uses the same dialog on 409', async () => {
|
||||
const props = {
|
||||
table: qInstance.tables.person,
|
||||
pk: '1',
|
||||
available: true,
|
||||
realtime: true,
|
||||
error: null,
|
||||
getValues: () => ({ firstName: 'My value' }),
|
||||
onViewers: vi.fn(),
|
||||
onOverwrite: vi.fn(),
|
||||
onReload: vi.fn(),
|
||||
pending: false,
|
||||
}
|
||||
mount(<CollaborationEdit {...props} />)
|
||||
act(() =>
|
||||
receive?.({
|
||||
event: 'record.changed',
|
||||
data: { table: 'person', pk: '1', changedBy: 'sam', fields: ['firstName'] },
|
||||
})
|
||||
)
|
||||
expect(await screen.findByText(/Sam Parker saved changes/)).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Review changes' }))
|
||||
expect(await screen.findByText('Their value')).toBeVisible()
|
||||
expect(screen.getByText('My value')).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Keep mine (overwrite)' })).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use theirs' }))
|
||||
expect(props.onReload).toHaveBeenCalled()
|
||||
})
|
||||
it('opens 409 review automatically and overwrites only with the refreshed version', async () => {
|
||||
const overwrite = vi.fn()
|
||||
const error = Object.assign(new Error('Conflict'), {
|
||||
status: 409,
|
||||
response: {
|
||||
status: 409,
|
||||
data: { currentVersion: 'v2', changedFields: ['firstName'], modifiedByUserId: 'sam' },
|
||||
},
|
||||
})
|
||||
mount(
|
||||
<CollaborationEdit
|
||||
table={qInstance.tables.person}
|
||||
pk="1"
|
||||
available
|
||||
realtime
|
||||
error={error}
|
||||
getValues={() => ({ firstName: 'Mine' })}
|
||||
onViewers={vi.fn()}
|
||||
onOverwrite={overwrite}
|
||||
onReload={vi.fn()}
|
||||
pending={false}
|
||||
/>
|
||||
)
|
||||
expect(await screen.findByText('Their value')).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Keep mine (overwrite)' }))
|
||||
expect(overwrite).toHaveBeenCalledWith('v2')
|
||||
})
|
||||
it('refuses unreadable assignees, creates and toggles a task', async () => {
|
||||
mount(<TasksTab record={record} features={{ capabilities: { task: true } }} />)
|
||||
fireEvent.click(await screen.findByRole('checkbox', { name: 'Complete Review order' }))
|
||||
await waitFor(() => expect(api.patchTask).toHaveBeenCalledWith(1, { status: 'DONE' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create task' }))
|
||||
await waitFor(() => expect(screen.getByLabelText(/Sam Parker/)).toBeDisabled())
|
||||
await waitFor(() => expect(screen.getByLabelText(/Alex Rivera/)).toBeEnabled())
|
||||
expect(api.previewShares).not.toHaveBeenCalled()
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Title' }), {
|
||||
target: { value: 'New task' },
|
||||
})
|
||||
fireEvent.click(screen.getByLabelText(/Alex Rivera/))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save task' }))
|
||||
await waitFor(() =>
|
||||
expect(api.createTask).toHaveBeenCalledWith(
|
||||
record,
|
||||
expect.objectContaining({ title: 'New task', assigneeUserId: 'alex' })
|
||||
)
|
||||
)
|
||||
})
|
||||
it('names task people by display name and falls back to the user id', async () => {
|
||||
vi.mocked(api.listTasks).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Named',
|
||||
status: 'DONE',
|
||||
assigneeUserId: 'alex',
|
||||
assigneeDisplayName: 'Alex Rivera',
|
||||
createdByUserId: 'morgan',
|
||||
createdByDisplayName: 'Morgan Lee',
|
||||
completedByUserId: 'sam',
|
||||
completedByDisplayName: 'Sam Parker',
|
||||
},
|
||||
{ id: 2, title: 'Unnamed', status: 'OPEN', assigneeUserId: 'u7', createdByUserId: 'u8' },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<TasksTab record={record} features={{ capabilities: { task: true } }} />)
|
||||
expect(await screen.findByText('Assigned to u7')).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Show done' }))
|
||||
expect(await screen.findByText('Assigned to Alex Rivera')).toBeVisible()
|
||||
expect(screen.getByText('Created by Morgan Lee · Completed by Sam Parker')).toBeVisible()
|
||||
expect(screen.getByText('Assigned to u7')).toBeVisible()
|
||||
expect(screen.getByText('Created by u8')).toBeVisible()
|
||||
})
|
||||
it('renders My work with overdue task, assigned table and unread mentions links', async () => {
|
||||
vi.mocked(api.getMyWork).mockResolvedValue({
|
||||
openTaskCount: 1,
|
||||
tasks: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Review order',
|
||||
status: 'OPEN',
|
||||
tableName: 'person',
|
||||
recordId: '1',
|
||||
dueAt: '2020-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
assignedRecordsByTable: { person: 1 },
|
||||
unreadMentionCount: 3,
|
||||
})
|
||||
vi.mocked(api.listMyTasks).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Review order',
|
||||
status: 'OPEN',
|
||||
tableName: 'person',
|
||||
recordId: '1',
|
||||
dueAt: '2020-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<MyWork />)
|
||||
expect(await screen.findByRole('link', { name: 'Review order' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/person/1'
|
||||
)
|
||||
expect(await screen.findByRole('link', { name: 'Alice' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/person/1'
|
||||
)
|
||||
expect(screen.getByText(/Overdue:/)).toBeVisible()
|
||||
expect(screen.getByRole('link', { name: '3 unread mentions' })).toBeVisible()
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import * as api from '@/lib/api/collaboration'
|
||||
import { getRecord } from '@/lib/api/tables'
|
||||
import type { RealtimeEvent } from '@/lib/realtime/client'
|
||||
import { ShareDialog } from './ShareDialog'
|
||||
import { RequestAccess } from './RequestAccess'
|
||||
import { TasksTab } from './TasksTab'
|
||||
import { CollaborationEdit } from './CollaborationEdit'
|
||||
import { MyWork } from './MyWork'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
let receive: ((event: RealtimeEvent) => void) | undefined
|
||||
vi.mock('@/lib/hooks/use-realtime-channel', () => ({
|
||||
useRealtimeChannel: (_channel: string, callback?: typeof receive) => {
|
||||
receive = callback
|
||||
},
|
||||
}))
|
||||
vi.mock('@/lib/hooks/use-collaboration-presence', () => ({
|
||||
useCollaborationPresence: () => ({ viewers: [] }),
|
||||
}))
|
||||
vi.mock('@/lib/context/q-context', async () => {
|
||||
const { createContext } = await import('react')
|
||||
return { useQContext: () => ({ userId: 'me' }), QContext: createContext({ userId: 'me' }) }
|
||||
})
|
||||
vi.mock('@/lib/hooks/use-collaboration-core', () => ({
|
||||
useCollaborationAvailable: () => ({ data: true }),
|
||||
}))
|
||||
vi.mock('@/lib/hooks/use-metadata', () => ({
|
||||
useMetaData: () => ({ data: qInstance }),
|
||||
useTableMetaData: () => ({ data: qInstance.tables.person }),
|
||||
}))
|
||||
vi.mock('@/lib/api/tables', () => ({
|
||||
getRecord: vi.fn(),
|
||||
queryRecords: vi.fn().mockResolvedValue({
|
||||
records: [{ tableName: 'person', values: { id: 1 }, recordLabel: 'Alice' }],
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/api/collaboration', () => ({
|
||||
searchPeople: vi.fn(),
|
||||
mentionCandidates: vi.fn(),
|
||||
getRecordLink: vi.fn(),
|
||||
previewShares: vi.fn(),
|
||||
shareRecord: vi.fn(),
|
||||
requestAccess: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
createTask: vi.fn(),
|
||||
patchTask: vi.fn(),
|
||||
getMyWork: vi.fn(),
|
||||
markMentionsRead: vi.fn().mockResolvedValue({ success: true }),
|
||||
listMyTasks: vi.fn(),
|
||||
}))
|
||||
const record = { table: 'person', pk: '1' }
|
||||
function mount(node: React.ReactNode) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(api.searchPeople).mockResolvedValue({
|
||||
items: [
|
||||
{ userId: 'sam', displayName: 'Sam Parker', email: null },
|
||||
{ userId: 'alex', displayName: 'Alex Rivera', email: null },
|
||||
{ userId: 'unknown', displayName: 'Taylor', email: null },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.previewShares).mockImplementation(async (_record, ids) => ({
|
||||
recipients: ids.map((id) => ({
|
||||
userId: id,
|
||||
displayName: id === 'sam' ? 'Sam Parker' : id,
|
||||
canRead: id === 'unknown' ? null : id === 'alex',
|
||||
})),
|
||||
}))
|
||||
vi.mocked(api.mentionCandidates).mockResolvedValue({
|
||||
items: [
|
||||
{ person: { userId: 'sam', displayName: 'Sam Parker' }, canRead: 'false' },
|
||||
{ person: { userId: 'alex', displayName: 'Alex Rivera' }, canRead: 'true' },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.getRecordLink).mockResolvedValue({ url: 'https://example.test/app/person/1' })
|
||||
vi.mocked(api.shareRecord).mockResolvedValue({
|
||||
items: [
|
||||
{ id: 1, toUserId: 'sam', recipientCouldRead: false },
|
||||
{ id: 2, toUserId: 'alex', recipientCouldRead: true },
|
||||
],
|
||||
})
|
||||
vi.mocked(api.listTasks).mockResolvedValue({
|
||||
items: [{ id: 1, title: 'Review order', status: 'OPEN' }],
|
||||
nextCursor: null,
|
||||
})
|
||||
vi.mocked(api.listMyTasks).mockResolvedValue({ items: [], nextCursor: null })
|
||||
vi.mocked(api.createTask).mockResolvedValue({ id: 2 })
|
||||
vi.mocked(api.patchTask).mockResolvedValue({ id: 1 })
|
||||
vi.mocked(getRecord).mockResolvedValue({
|
||||
tableName: 'person',
|
||||
values: { id: 1, firstName: 'Their value', modifyDate: 'v2' },
|
||||
})
|
||||
})
|
||||
it('previews inaccessible and unknown recipients, then reports notified and offered access', async () => {
|
||||
mount(<ShareDialog record={record} canShare onClose={vi.fn()} />)
|
||||
expect(await screen.findByText("can't open this record")).toBeVisible()
|
||||
expect(screen.getByText('unknown')).toBeVisible()
|
||||
fireEvent.click(screen.getByLabelText(/Sam Parker/))
|
||||
fireEvent.click(screen.getByLabelText(/Alex Rivera/))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled())
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send' }))
|
||||
expect(await screen.findByText('Sam Parker: Offered access')).toBeVisible()
|
||||
expect(screen.getByText('alex: Notified')).toBeVisible()
|
||||
})
|
||||
it('leaves the signed-in user out of share recipients even when the service returns them', async () => {
|
||||
vi.mocked(api.searchPeople).mockResolvedValueOnce({
|
||||
items: [
|
||||
{ userId: 'ME', displayName: 'Me Myself', email: null },
|
||||
{ userId: 'x9', displayName: 'Mail Match', email: 'Me' },
|
||||
{ userId: 'alex', displayName: 'Alex Rivera', email: null },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<ShareDialog record={record} canShare onClose={vi.fn()} />)
|
||||
expect(await screen.findByLabelText(/Alex Rivera/)).toBeVisible()
|
||||
expect(screen.queryByLabelText(/Me Myself/)).toBeNull()
|
||||
expect(screen.queryByLabelText(/Mail Match/)).toBeNull()
|
||||
})
|
||||
it('uses identical non-disclosing access copy even when the server reports missing record', async () => {
|
||||
vi.mocked(api.requestAccess).mockRejectedValue(
|
||||
new Error('Record does not exist: sensitive detail')
|
||||
)
|
||||
mount(<RequestAccess tableName="person" recordId="missing" shareId={12} />)
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Message' }), {
|
||||
target: { value: 'Please review' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request access' }))
|
||||
expect(await screen.findByRole('alert')).not.toHaveTextContent('sensitive detail')
|
||||
expect(document.body).not.toHaveTextContent('does not exist')
|
||||
expect(api.requestAccess).toHaveBeenCalledWith({
|
||||
tableName: 'person',
|
||||
recordId: 'missing',
|
||||
shareId: 12,
|
||||
message: 'Please review',
|
||||
})
|
||||
})
|
||||
it('shows a stream warning, compares theirs and mine, and uses the same dialog on 409', async () => {
|
||||
const props = {
|
||||
table: qInstance.tables.person,
|
||||
pk: '1',
|
||||
available: true,
|
||||
realtime: true,
|
||||
error: null,
|
||||
getValues: () => ({ firstName: 'My value' }),
|
||||
onViewers: vi.fn(),
|
||||
onOverwrite: vi.fn(),
|
||||
onReload: vi.fn(),
|
||||
pending: false,
|
||||
}
|
||||
mount(<CollaborationEdit {...props} />)
|
||||
act(() =>
|
||||
receive?.({
|
||||
event: 'record.changed',
|
||||
data: { table: 'person', pk: '1', changedBy: 'sam', fields: ['firstName'] },
|
||||
})
|
||||
)
|
||||
expect(await screen.findByText(/Sam Parker saved changes/)).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Review changes' }))
|
||||
expect(await screen.findByText('Their value')).toBeVisible()
|
||||
expect(screen.getByText('My value')).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Keep mine (overwrite)' })).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use theirs' }))
|
||||
expect(props.onReload).toHaveBeenCalled()
|
||||
})
|
||||
it('opens 409 review automatically and overwrites only with the refreshed version', async () => {
|
||||
const overwrite = vi.fn()
|
||||
const error = Object.assign(new Error('Conflict'), {
|
||||
status: 409,
|
||||
response: {
|
||||
status: 409,
|
||||
data: { currentVersion: 'v2', changedFields: ['firstName'], modifiedByUserId: 'sam' },
|
||||
},
|
||||
})
|
||||
mount(
|
||||
<CollaborationEdit
|
||||
table={qInstance.tables.person}
|
||||
pk="1"
|
||||
available
|
||||
realtime
|
||||
error={error}
|
||||
getValues={() => ({ firstName: 'Mine' })}
|
||||
onViewers={vi.fn()}
|
||||
onOverwrite={overwrite}
|
||||
onReload={vi.fn()}
|
||||
pending={false}
|
||||
/>
|
||||
)
|
||||
expect(await screen.findByText('Their value')).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Keep mine (overwrite)' }))
|
||||
expect(overwrite).toHaveBeenCalledWith('v2')
|
||||
})
|
||||
it('refuses unreadable assignees, creates and toggles a task', async () => {
|
||||
mount(<TasksTab record={record} features={{ capabilities: { task: true } }} />)
|
||||
fireEvent.click(await screen.findByRole('checkbox', { name: 'Complete Review order' }))
|
||||
await waitFor(() => expect(api.patchTask).toHaveBeenCalledWith(1, { status: 'DONE' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create task' }))
|
||||
await waitFor(() => expect(screen.getByLabelText(/Sam Parker/)).toBeDisabled())
|
||||
await waitFor(() => expect(screen.getByLabelText(/Alex Rivera/)).toBeEnabled())
|
||||
expect(api.previewShares).not.toHaveBeenCalled()
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Title' }), {
|
||||
target: { value: 'New task' },
|
||||
})
|
||||
fireEvent.click(screen.getByLabelText(/Alex Rivera/))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save task' }))
|
||||
await waitFor(() =>
|
||||
expect(api.createTask).toHaveBeenCalledWith(
|
||||
record,
|
||||
expect.objectContaining({ title: 'New task', assigneeUserId: 'alex' })
|
||||
)
|
||||
)
|
||||
})
|
||||
it('names task people by display name and falls back to the user id', async () => {
|
||||
vi.mocked(api.listTasks).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Named',
|
||||
status: 'DONE',
|
||||
assigneeUserId: 'alex',
|
||||
assigneeDisplayName: 'Alex Rivera',
|
||||
createdByUserId: 'morgan',
|
||||
createdByDisplayName: 'Morgan Lee',
|
||||
completedByUserId: 'sam',
|
||||
completedByDisplayName: 'Sam Parker',
|
||||
},
|
||||
{ id: 2, title: 'Unnamed', status: 'OPEN', assigneeUserId: 'u7', createdByUserId: 'u8' },
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<TasksTab record={record} features={{ capabilities: { task: true } }} />)
|
||||
expect(await screen.findByText('Assigned to u7')).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Show done' }))
|
||||
expect(await screen.findByText('Assigned to Alex Rivera')).toBeVisible()
|
||||
expect(screen.getByText('Created by Morgan Lee · Completed by Sam Parker')).toBeVisible()
|
||||
expect(screen.getByText('Assigned to u7')).toBeVisible()
|
||||
expect(screen.getByText('Created by u8')).toBeVisible()
|
||||
})
|
||||
it('renders My work with overdue task, assigned table and unread mentions links', async () => {
|
||||
vi.mocked(api.getMyWork).mockResolvedValue({
|
||||
openTaskCount: 1,
|
||||
tasks: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Review order',
|
||||
status: 'OPEN',
|
||||
tableName: 'person',
|
||||
recordId: '1',
|
||||
dueAt: '2020-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
assignedRecordsByTable: { person: 1 },
|
||||
unreadMentionCount: 3,
|
||||
})
|
||||
vi.mocked(api.listMyTasks).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Review order',
|
||||
status: 'OPEN',
|
||||
tableName: 'person',
|
||||
recordId: '1',
|
||||
dueAt: '2020-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
nextCursor: null,
|
||||
})
|
||||
mount(<MyWork />)
|
||||
expect(await screen.findByRole('link', { name: 'Review order' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/person/1'
|
||||
)
|
||||
expect(await screen.findByRole('link', { name: 'Alice' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/person/1'
|
||||
)
|
||||
expect(screen.getByText(/Overdue:/)).toBeVisible()
|
||||
expect(screen.getByRole('link', { name: '3 unread mentions' })).toBeVisible()
|
||||
vi.mocked(api.getMyWork).mockResolvedValue({
|
||||
openTaskCount: 1,
|
||||
tasks: [],
|
||||
@@ -311,8 +311,8 @@ it('renders My work with overdue task, assigned table and unread mentions links'
|
||||
await waitFor(() => expect(api.markMentionsRead).toHaveBeenCalledTimes(1))
|
||||
expect(await screen.findByRole('link', { name: '0 unread mentions' })).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Mark all mentions read' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: /People \(1\)|Person \(1\)/ })).toHaveAttribute(
|
||||
'href',
|
||||
expect.stringContaining('CurrentUser')
|
||||
)
|
||||
})
|
||||
expect(screen.getByRole('link', { name: /People \(1\)|Person \(1\)/ })).toHaveAttribute(
|
||||
'href',
|
||||
expect.stringContaining('CurrentUser')
|
||||
)
|
||||
})
|
||||
@@ -18,24 +18,16 @@
|
||||
'use client'
|
||||
import { useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import Link from 'next/link'
|
||||
import type { Attachment, CollaborationRecord, RecordFeaturesV1 } from '@/types/collaboration'
|
||||
import type { FilePreviewKind } from '@/lib/utils/file-preview'
|
||||
import { formatBytes } from '@/lib/utils/file-preview'
|
||||
import { attachmentUrl } from '@/lib/api/collaboration'
|
||||
import { saveAttachmentDownload } from '@/lib/api/attachment-download'
|
||||
import { useAttachmentPreview } from '@/lib/hooks/use-attachment-preview'
|
||||
import { attachmentRecoveryView } from '@/lib/utils/attachment-recovery-view'
|
||||
import {
|
||||
useAttachments,
|
||||
useAttachmentActions,
|
||||
useAttachmentUrl,
|
||||
} from '@/lib/hooks/use-collaboration-record'
|
||||
import { FileKindIcon } from '@/components/preview/FileKindIcon'
|
||||
import { INPUT_CLASS, LABEL_CLASS, buttonClass } from '@/components/ui/controls'
|
||||
/** Standard in-text link: themed color, underline on hover, visible keyboard focus. */
|
||||
const LINK_CLASS =
|
||||
'inline-flex min-h-11 items-center rounded-sm font-medium text-primary underline-offset-2 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'
|
||||
const ROW_ACTION = buttonClass('secondary', 'sm')
|
||||
const Lightbox = dynamic(
|
||||
() => import('@/components/preview/FilePreviewLightbox').then((m) => m.FilePreviewLightbox),
|
||||
{ ssr: false }
|
||||
@@ -62,35 +54,20 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
const [description, setDescription] = useState(file.description ?? '')
|
||||
const [preview, setPreview] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [downloading, setDownloading] = useState(false)
|
||||
const kind = kindFor(file.contentType)
|
||||
const canEdit = Object.prototype.hasOwnProperty.call(file, 'canEdit') ? file.canEdit === true : file.canDelete === true
|
||||
const url = useAttachmentPreview(file.id, kind === 'image' || preview, kind === 'pdf')
|
||||
const download = async () => {
|
||||
setError('')
|
||||
setDownloading(true)
|
||||
try {
|
||||
const result = await attachmentUrl(file.id, 'download')
|
||||
await saveAttachmentDownload(result, file.fileName ?? 'Attachment')
|
||||
} catch {
|
||||
// Backend/storage diagnostics are not display messages. The lightbox and
|
||||
// direct action share this safe error and the same verified download path.
|
||||
throw new Error('Download unavailable. Please try again.')
|
||||
} finally {
|
||||
setDownloading(false)
|
||||
}
|
||||
}
|
||||
const url = useAttachmentUrl(file.id, 'preview', kind === 'image' || preview)
|
||||
const open = async () => {
|
||||
setError('')
|
||||
try {
|
||||
if (kind === 'other') {
|
||||
await download()
|
||||
const result = await attachmentUrl(file.id, 'download')
|
||||
window.location.assign(result.url)
|
||||
} else {
|
||||
setPreview(true)
|
||||
void url.refetch()
|
||||
}
|
||||
} catch {
|
||||
setError('Download unavailable. Please try again.')
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Could not open file.')
|
||||
}
|
||||
}
|
||||
return (
|
||||
@@ -99,8 +76,7 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
data-qqq-id={`attachment-${file.id}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full min-w-0 items-start gap-3 rounded-md text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="flex w-full min-w-0 items-start gap-3 text-left"
|
||||
data-qqq-id={`attachment-open-${file.id}`}
|
||||
onClick={() => void open()}
|
||||
>
|
||||
@@ -124,40 +100,10 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
{file.description && !editing && (
|
||||
<p className="break-words text-xs text-muted-foreground">{file.description}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{kind !== 'other' && <button
|
||||
type="button"
|
||||
className={ROW_ACTION}
|
||||
data-qqq-id={`attachment-preview-${file.id}`}
|
||||
onClick={() => void open()}
|
||||
>
|
||||
Preview
|
||||
</button>}
|
||||
<button
|
||||
type="button"
|
||||
className={ROW_ACTION}
|
||||
data-qqq-id={`attachment-open-action-${file.id}`}
|
||||
disabled={downloading}
|
||||
onClick={() => void open()}
|
||||
>
|
||||
Open
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={ROW_ACTION}
|
||||
data-qqq-id={`attachment-download-${file.id}`}
|
||||
disabled={downloading}
|
||||
onClick={() => void download().catch(() => setError('Download unavailable. Please try again.'))}
|
||||
>
|
||||
{downloading ? 'Downloading…' : 'Download'}
|
||||
</button>
|
||||
</div>
|
||||
{(canEdit || file.canDelete) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{canEdit && <button
|
||||
type="button"
|
||||
className={ROW_ACTION}
|
||||
data-qqq-id={`attachment-edit-${file.id}`}
|
||||
{file.canDelete && (
|
||||
<div className="flex gap-3 text-xs">
|
||||
<button
|
||||
data-qqq-id={`attachment-edit-${file.id}`}
|
||||
onClick={() => {
|
||||
setName(file.fileName ?? '')
|
||||
setDescription(file.description ?? '')
|
||||
@@ -165,10 +111,8 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
}}
|
||||
>
|
||||
Rename / describe
|
||||
</button>}
|
||||
{file.canDelete && <button
|
||||
type="button"
|
||||
className={buttonClass('destructive', 'sm')}
|
||||
</button>
|
||||
<button
|
||||
data-qqq-id={`attachment-delete-${file.id}`}
|
||||
disabled={actions.remove.isPending}
|
||||
onClick={() => {
|
||||
@@ -177,10 +121,10 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{editing && canEdit && (
|
||||
{editing && (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(event) => {
|
||||
@@ -191,37 +135,38 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
)
|
||||
}}
|
||||
>
|
||||
<label className={`block ${LABEL_CLASS}`}>
|
||||
<label className="block text-xs">
|
||||
File name
|
||||
<input
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
className={`mt-1 ${INPUT_CLASS}`}
|
||||
className="mt-1 w-full rounded border border-border bg-background p-2"
|
||||
data-qqq-id="attachment-name"
|
||||
/>
|
||||
</label>
|
||||
<label className={`block ${LABEL_CLASS}`}>
|
||||
<label className="block text-xs">
|
||||
Description
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
className={`mt-1 ${INPUT_CLASS}`}
|
||||
className="mt-1 w-full rounded border border-border bg-background p-2"
|
||||
data-qqq-id="attachment-description"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
disabled={actions.patch.isPending || !name.trim()}
|
||||
className={buttonClass('primary', 'md')}
|
||||
className="rounded border border-border px-3 py-2 text-xs"
|
||||
data-qqq-id="attachment-save"
|
||||
>
|
||||
Save file details
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{url.isError && <p role="alert" className="text-sm text-destructive">Preview unavailable. Try again or use Download.</p>}
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
{actions.patch.isError && <p role="alert" className="text-sm text-destructive">Could not save file details. Please try again.</p>}
|
||||
{actions.remove.isError && <p role="alert" className="text-sm text-destructive">Could not delete this file. Please try again.</p>}
|
||||
{(error || actions.patch.isError || actions.remove.isError || (preview && url.isError)) && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error || 'Could not update or open this file. Please try again.'}
|
||||
</p>
|
||||
)}
|
||||
{preview && url.data && (
|
||||
<Lightbox
|
||||
items={[
|
||||
@@ -239,7 +184,6 @@ function AttachmentRow({ file, record }: { file: Attachment; record: Collaborati
|
||||
index={0}
|
||||
onIndexChange={() => undefined}
|
||||
onClose={() => setPreview(false)}
|
||||
onDownload={download}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
@@ -266,11 +210,6 @@ export function FilesTab({
|
||||
const setting = features.settings?.ATTACHMENTS?.maxBytes
|
||||
const maxBytes = typeof setting === 'number' && setting > 0 ? setting : 100 * 1024 * 1024
|
||||
const files = query.data?.pages.flatMap((page) => page.items) ?? []
|
||||
const recovery = attachmentRecoveryView(features.settings?.ATTACHMENTS?.recoveryView, record)
|
||||
const relatedSettings = features.settings?.ATTACHMENTS?.relatedViews
|
||||
const relatedViews = Array.isArray(relatedSettings) && relatedSettings.length <= 10
|
||||
? relatedSettings.map((value) => attachmentRecoveryView(value, record)).filter((value) => value !== null)
|
||||
: []
|
||||
const upload = async (selection: File[]) => {
|
||||
if (!canAttach) return
|
||||
for (const file of selection) {
|
||||
@@ -311,27 +250,6 @@ export function FilesTab({
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4" data-qqq-id="collaboration-files">
|
||||
{relatedViews.length > 0 && (
|
||||
<div className="flex flex-wrap gap-4 text-sm" data-qqq-id="files-related-views">
|
||||
{relatedViews.map((view, index) => (
|
||||
<Link key={index} href={view.href} className={LINK_CLASS} data-qqq-id={`files-related-view-${index}`}>
|
||||
{view.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{recovery && (
|
||||
<div className="space-y-1 text-sm">
|
||||
<Link href={recovery.href} className={LINK_CLASS} data-qqq-id="files-upload-recovery">
|
||||
{recovery.label}
|
||||
</Link>
|
||||
{uploads.some((item) => item.error) && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
An interrupted upload may have saved the file. Review it before uploading again.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{canAttach ? (
|
||||
<div
|
||||
className={`rounded-lg border-2 border-dashed p-4 text-center ${dragging ? 'border-primary bg-accent' : 'border-border'}`}
|
||||
@@ -349,7 +267,7 @@ export function FilesTab({
|
||||
>
|
||||
<p className="text-sm font-medium">Drop files here</p>
|
||||
{/* the native picker's "Choose Files / No file chosen" text ignores the theme; a styled label opens it */}
|
||||
<label className={`mt-3 min-h-11 cursor-pointer focus-within:ring-2 focus-within:ring-ring ${buttonClass('secondary', 'md')}`}>
|
||||
<label className="mt-3 inline-flex min-h-11 cursor-pointer items-center rounded-md border border-border bg-background px-4 text-sm font-medium hover:bg-accent focus-within:ring-2 focus-within:ring-ring">
|
||||
Choose files
|
||||
<input
|
||||
type="file"
|
||||
@@ -398,7 +316,7 @@ export function FilesTab({
|
||||
{query.isError && (
|
||||
<p role="alert">
|
||||
Could not load files.{' '}
|
||||
<button type="button" className={buttonClass('secondary', 'sm')} data-qqq-id="files-retry" onClick={() => void query.refetch()}>
|
||||
<button data-qqq-id="files-retry" onClick={() => void query.refetch()}>
|
||||
Retry
|
||||
</button>
|
||||
</p>
|
||||
@@ -413,10 +331,9 @@ export function FilesTab({
|
||||
</ul>
|
||||
{query.hasNextPage && (
|
||||
<button
|
||||
type="button"
|
||||
data-qqq-id="files-more"
|
||||
disabled={query.isFetchingNextPage}
|
||||
className={`w-full ${buttonClass('secondary', 'md')}`}
|
||||
className="w-full rounded border border-border py-2 text-sm"
|
||||
onClick={() => void query.fetchNextPage()}
|
||||
>
|
||||
Load more
|
||||
|
||||
@@ -20,22 +20,6 @@ import { Pencil } from 'lucide-react'
|
||||
import * as Tooltip from '@radix-ui/react-tooltip'
|
||||
import type { PresenceViewer } from '@/types/collaboration'
|
||||
import { UserAvatar } from '@/components/ui/UserAvatar'
|
||||
/**
|
||||
* The quiet state of a presence indicator while the server cannot answer: one muted line.
|
||||
*
|
||||
* Accessibility: `role="status"` is a polite live region, so a screen reader says it once when it
|
||||
* appears and never interrupts; it is plain muted text, not an alert, and takes no focus.
|
||||
*
|
||||
* @returns The line.
|
||||
*/
|
||||
export function PresenceReconnecting() {
|
||||
return (
|
||||
<span role="status" className="text-xs text-muted-foreground" data-qqq-id="presence-reconnecting">
|
||||
Presence is reconnecting…
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Other viewers' avatars (photo or initials), wrapping at narrow widths.
|
||||
* @param props - Merged people.
|
||||
* @returns Avatars.
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// What a presence indicator shows while presence is reconnecting: a quiet status where the
|
||||
// indicator always shows something, and nothing where it shows nothing when nobody else is there.
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { axe } from 'jest-axe'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { QRecord, QTableMetaData } from '@/types'
|
||||
import type { PresenceViewer } from '@/types/collaboration'
|
||||
import { useCollaborationPresence } from '@/lib/hooks/use-collaboration-presence'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
import { PresenceReconnecting } from './PresenceAvatars'
|
||||
import { RecordCollaborationHeader, TablePresence } from './RecordCollaborationHeader'
|
||||
|
||||
vi.mock('@/lib/hooks/use-collaboration-presence', () => ({ useCollaborationPresence: vi.fn() }))
|
||||
vi.mock('@/lib/hooks/use-realtime-channel', () => ({ useRealtimeChannel: vi.fn() }))
|
||||
vi.mock('@/lib/api/collaboration', () => ({ getRecordFeatures: vi.fn(async () => ({})), putAssignment: vi.fn() }))
|
||||
|
||||
const sam: PresenceViewer = { userId: 'sam', displayName: 'Sam', mode: 'VIEWING' }
|
||||
const table: QTableMetaData = { ...structuredClone(qInstance.tables.person), recordFeatures: { features: ['PRESENCE'] } } as QTableMetaData
|
||||
const record = { tableName: 'person', recordLabel: 'Alice', values: { id: 1 } } as QRecord
|
||||
|
||||
type Presence = ReturnType<typeof useCollaborationPresence>
|
||||
const presence = (state: { reconnecting: boolean; hadViewers?: boolean; viewers?: PresenceViewer[] }) =>
|
||||
vi.mocked(useCollaborationPresence).mockReturnValue({ hadViewers: false, viewers: [], ...state } as unknown as Presence)
|
||||
|
||||
function mount(node: React.ReactNode) {
|
||||
return render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>{node}</QueryClientProvider>)
|
||||
}
|
||||
|
||||
describe('presence while reconnecting', () => {
|
||||
beforeEach(() => vi.mocked(useCollaborationPresence).mockReset())
|
||||
|
||||
it('is one muted, polite status line: no alert, no error color, nothing to focus', async () => {
|
||||
const { container } = render(<PresenceReconnecting />)
|
||||
const line = screen.getByRole('status')
|
||||
expect(line).toHaveTextContent('Presence is reconnecting…')
|
||||
expect(line).toHaveAttribute('data-qqq-id', 'presence-reconnecting')
|
||||
expect(line).toHaveClass('text-muted-foreground')
|
||||
expect(line.className).not.toMatch(/destructive|red/)
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('button, a, [tabindex]')).toBeNull()
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it('a table shows it in place of the viewer count, and the count again once presence is back', () => {
|
||||
presence({ reconnecting: true })
|
||||
const { rerender } = mount(<TablePresence table={table} available />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Presence is reconnecting…')
|
||||
expect(screen.queryByText(/viewing/)).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
|
||||
presence({ reconnecting: false, viewers: [sam] })
|
||||
rerender(<QueryClientProvider client={new QueryClient()}><TablePresence table={table} available /></QueryClientProvider>)
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('1 person viewing')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('a record shows nothing when nobody else was there, as when nobody else is there', () => {
|
||||
presence({ reconnecting: true, hadViewers: false })
|
||||
const { container } = mount(<RecordCollaborationHeader table={table} record={record} available />)
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/presence/i)).not.toBeInTheDocument()
|
||||
expect(container.querySelector('[data-qqq-id="presence-avatars"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('a record says so when the people it showed had to be taken away', () => {
|
||||
presence({ reconnecting: true, hadViewers: true })
|
||||
mount(<RecordCollaborationHeader table={table} record={record} available />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Presence is reconnecting…')
|
||||
expect(screen.queryByRole('button', { name: /Sam/ })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -72,35 +72,6 @@ beforeEach(() => {
|
||||
})
|
||||
vi.mocked(api.putRecordTags).mockResolvedValue({ items: [], nextCursor: null })
|
||||
})
|
||||
it('shows metadata recovery navigation pinned to the source after an interrupted upload', async () => {
|
||||
vi.mocked(api.uploadAttachment).mockRejectedValue(new Error('Registration interrupted'))
|
||||
const recoveryView = {
|
||||
tableName: 'owner_pending_uploads', label: 'Review interrupted uploads',
|
||||
filter: { booleanOperator: 'AND', criteria: [
|
||||
{ fieldName: 'createdByUserId', operator: 'EQUALS', values: [{ type: 'CurrentUser' }] },
|
||||
{ fieldName: 'state', operator: 'IN', values: ['PREPARED', 'REGISTERED'] },
|
||||
] },
|
||||
}
|
||||
const source = { table: 'purchase_order', pk: 'a/b & 雪' }
|
||||
const { container } = mount(<FilesTab record={source} features={{ ...features, settings: { ATTACHMENTS: { maxBytes: 10, recoveryView } } }} />)
|
||||
const link = screen.getByRole('link', { name: recoveryView.label })
|
||||
const target = new URL(link.getAttribute('href')!, 'https://app.example')
|
||||
expect(target.pathname).toBe('/app/owner_pending_uploads')
|
||||
expect(JSON.parse(target.searchParams.get('filter')!).criteria).toEqual([
|
||||
...recoveryView.filter.criteria,
|
||||
{ fieldName: 'tableName', operator: 'EQUALS', values: [source.table] },
|
||||
{ fieldName: 'recordId', operator: 'EQUALS', values: [source.pk] },
|
||||
])
|
||||
fireEvent.change(container.querySelector('input[type=file]')!, { target: { files: [new File(['a'], 'bol.txt')] } })
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Registration interrupted')
|
||||
expect(screen.getByText('An interrupted upload may have saved the file. Review it before uploading again.')).toBeVisible()
|
||||
expect(screen.queryByText('bol.txt Uploaded')).not.toBeInTheDocument()
|
||||
})
|
||||
it('preserves ordinary Files tabs when no recovery metadata is supplied', async () => {
|
||||
mount(<FilesTab record={record} features={features} />)
|
||||
expect(await screen.findByText('No files yet.')).toBeVisible()
|
||||
expect(document.querySelector('[data-qqq-id="files-upload-recovery"]')).toBeNull()
|
||||
})
|
||||
it('inserts a mention with the keyboard, warns and submits the literal token', async () => {
|
||||
const submit = vi.fn().mockResolvedValue(undefined)
|
||||
mount(<CommentComposer record={record} onSubmit={submit} />)
|
||||
@@ -202,76 +173,6 @@ it('does not offer file uploads without attach permission', async () => {
|
||||
expect(document.querySelector('[data-qqq-id="files-picker"]')).toBeNull()
|
||||
expect(screen.getByText(/permission to attach/)).toBeVisible()
|
||||
})
|
||||
it.each([
|
||||
{ canEdit: true, canDelete: false, edit: true, remove: false },
|
||||
{ canEdit: false, canDelete: true, edit: false, remove: true },
|
||||
{ canEdit: null, canDelete: true, edit: false, remove: true },
|
||||
{ canEdit: undefined, canDelete: true, edit: false, remove: true },
|
||||
{ canDelete: true, edit: true, remove: true },
|
||||
])('keeps attachment editing separate from deletion: %j', async (permissions) => {
|
||||
const { edit, remove, ...capabilities } = permissions
|
||||
vi.mocked(api.listAttachments).mockResolvedValue({ items: [{ id: 9, fileName: 'retained.txt', ...capabilities }], nextCursor: null })
|
||||
mount(<FilesTab record={record} features={features} />)
|
||||
await screen.findByText('retained.txt')
|
||||
expect(screen.queryByRole('button', { name: 'Rename / describe' }) !== null).toBe(edit)
|
||||
expect(screen.queryByRole('button', { name: 'Delete' }) !== null).toBe(remove)
|
||||
})
|
||||
|
||||
it('resolves a fresh download action from an attachment preview', async () => {
|
||||
vi.mocked(api.listAttachments).mockResolvedValue({ items: [{ id: 9, fileName: 'retained.png', contentType: 'image/png' }], nextCursor: null })
|
||||
vi.mocked(api.attachmentUrl).mockImplementation(async (_id, mode) => ({ url: mode === 'preview' ? '/preview.png' : '/authorized-download.png' }))
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
try {
|
||||
mount(<FilesTab record={record} features={features} />)
|
||||
fireEvent.click(await screen.findByRole('button', { name: /retained.png/ }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Download retained.png' }))
|
||||
await waitFor(() => expect(api.attachmentUrl).toHaveBeenCalledWith(9, 'download'))
|
||||
await waitFor(() => expect(click).toHaveBeenCalledTimes(1))
|
||||
expect(click.mock.instances[0]).toHaveAttribute('href', '/authorized-download.png')
|
||||
expect(dialog.querySelector('[data-qqq-id="file-preview-download"]')).not.toHaveAttribute('href')
|
||||
} finally {
|
||||
click.mockRestore()
|
||||
}
|
||||
})
|
||||
it('reports a failed thumbnail as preview unavailable and still offers a separate native download', async () => {
|
||||
vi.mocked(api.listAttachments).mockResolvedValue({ items: [{ id: 9, fileName: 'scan.jpg', contentType: 'image/jpeg', canEdit: false, canDelete: false }], nextCursor: null })
|
||||
vi.mocked(api.attachmentUrl).mockImplementation(async (_id, mode) => {
|
||||
if (mode === 'preview') throw new Error('HTTP 500: private storage diagnostics')
|
||||
return { url: '/authorized-original.jpg' }
|
||||
})
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
try {
|
||||
mount(<FilesTab record={record} features={features} />)
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Preview unavailable. Try again or use Download.')
|
||||
expect(screen.queryByText(/private storage|update or open/i)).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Preview' })).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'Open' })).toBeVisible()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Download' }))
|
||||
await waitFor(() => expect(api.attachmentUrl).toHaveBeenCalledWith(9, 'download'))
|
||||
await waitFor(() => expect(click).toHaveBeenCalledTimes(1))
|
||||
expect(click.mock.instances[0]).toHaveAttribute('href', '/authorized-original.jpg')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
} finally {
|
||||
click.mockRestore()
|
||||
}
|
||||
})
|
||||
it('keeps a denied direct download separate from preview and editing errors without exposing server details', async () => {
|
||||
vi.mocked(api.listAttachments).mockResolvedValue({ items: [{ id: 9, fileName: 'original.bin', contentType: 'application/octet-stream' }], nextCursor: null })
|
||||
vi.mocked(api.attachmentUrl).mockRejectedValue(new Error('private backend path'))
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
try {
|
||||
mount(<FilesTab record={record} features={features} />)
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Download' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Download unavailable. Please try again.')
|
||||
expect(screen.queryByText(/private backend|update or open/i)).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Preview' })).toBeNull()
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
expect(api.attachmentUrl).toHaveBeenCalledExactlyOnceWith(9, 'download')
|
||||
} finally {
|
||||
click.mockRestore()
|
||||
}
|
||||
})
|
||||
it('pages activity with the returned cursor and shows audit details', async () => {
|
||||
vi.mocked(api.listTimeline)
|
||||
.mockResolvedValueOnce({
|
||||
@@ -384,18 +285,3 @@ it('follows and exposes notification preferences and follower count', async () =
|
||||
expect(await screen.findByText('1 follower')).toBeVisible()
|
||||
expect(within(screen.getByRole('dialog')).getByLabelText('Notify me about changes')).toBeChecked()
|
||||
})
|
||||
|
||||
it('renders only valid server-defined related views pinned to this source record', async () => {
|
||||
mount(<FilesTab record={record} features={{ ...features, settings: { ATTACHMENTS: { relatedViews: [
|
||||
{ tableName: 'evidence_history', label: 'Retained evidence', filter: { booleanOperator: 'AND', criteria: [{ fieldName: 'tableName', operator: 'EQUALS', values: [record.table] }] } },
|
||||
{ tableName: '../outside', label: 'Unsafe', filter: { booleanOperator: 'AND', criteria: [] } },
|
||||
] } } }} />)
|
||||
const link = screen.getByRole('link', { name: 'Retained evidence' })
|
||||
const url = new URL(link.getAttribute('href')!, 'https://app.example')
|
||||
expect(url.pathname).toBe('/app/evidence_history')
|
||||
expect(JSON.parse(url.searchParams.get('filter')!).criteria).toEqual(expect.arrayContaining([
|
||||
{ fieldName: 'tableName', operator: 'EQUALS', values: [record.table] },
|
||||
{ fieldName: 'recordId', operator: 'EQUALS', values: [record.pk] },
|
||||
]))
|
||||
expect(screen.queryByRole('link', { name: 'Unsafe' })).toBeNull()
|
||||
})
|
||||
@@ -27,7 +27,7 @@ import { queryKeys } from '@/lib/query-client'
|
||||
import { updateRecord } from '@/lib/api/tables'
|
||||
import { recordVersion } from '@/lib/utils/record-version'
|
||||
import { pluralize } from '@/lib/utils/string-utils'
|
||||
import { PresenceAvatars, PresenceReconnecting } from './PresenceAvatars'
|
||||
import { PresenceAvatars } from './PresenceAvatars'
|
||||
import { CollaborationDialog, collaborationButton } from './CollaborationDialog'
|
||||
import { PeoplePicker } from './PeoplePicker'
|
||||
const Share = dynamic(() => import('./ShareDialog').then((m) => m.ShareDialog), { ssr: false })
|
||||
@@ -107,9 +107,7 @@ export function RecordCollaborationHeader({
|
||||
data-qqq-id="record-collaboration-header"
|
||||
>
|
||||
{presence.viewers.length > 0 && <PresenceAvatars viewers={presence.viewers} />}
|
||||
{/* Nobody else here looks like nothing, so a lost connection does too; it is only said when
|
||||
the people who were shown had to be taken away. */}
|
||||
{presence.hadViewers && <PresenceReconnecting />}
|
||||
{presence.unavailable && <span role="status">Presence temporarily unavailable</span>}
|
||||
{(owner != null || assignee != null) && (
|
||||
<dl className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{owner != null && (
|
||||
@@ -197,12 +195,11 @@ export function TablePresence({ table, available }: { table: QTableMetaData; ava
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm" data-qqq-id="table-presence">
|
||||
<PresenceAvatars viewers={presence.viewers} />
|
||||
{/* The count is always here, so its place says when the count is not known for now. */}
|
||||
{presence.reconnecting ? (
|
||||
<PresenceReconnecting />
|
||||
) : (
|
||||
<span>{`${pluralize(presence.viewers.length, 'person', 'people')} viewing`}</span>
|
||||
)}
|
||||
<span role={presence.unavailable ? 'status' : undefined}>
|
||||
{presence.unavailable
|
||||
? 'Presence temporarily unavailable'
|
||||
: `${pluralize(presence.viewers.length, 'person', 'people')} viewing`}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -57,8 +57,6 @@ export function RecordCollaborationPanel({
|
||||
{ id: 'TASKS', label: 'Tasks' },
|
||||
{ id: 'TIMELINE', label: 'Activity' },
|
||||
].filter((tab) => enabled.includes(tab.id as NonNullable<RecordFeaturesV1['features']>[number]))
|
||||
// A panel whose only feature is attachments is a file list, not a collaboration surface.
|
||||
const title = tabs.length === 1 && tabs[0].id === 'ATTACHMENTS' ? 'Files' : 'Collaboration'
|
||||
const [selected, setSelected] = useState(tabs[0]?.id)
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
useEffect(() => {
|
||||
@@ -89,15 +87,15 @@ export function RecordCollaborationPanel({
|
||||
const active = tabs.some((tab) => tab.id === selected) ? selected : tabs[0]?.id
|
||||
return (
|
||||
<aside
|
||||
aria-label={title}
|
||||
aria-label="Collaboration"
|
||||
className={`min-w-0 self-start rounded-xl border border-border bg-card ${collapsed ? 'xl:w-12' : 'xl:w-[360px]'}`}
|
||||
data-qqq-id="record-collaboration-panel"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border p-3">
|
||||
<h2 className={`text-sm font-semibold ${collapsed ? 'xl:hidden' : ''}`}>{title}</h2>
|
||||
<h2 className={`text-sm font-semibold ${collapsed ? 'xl:hidden' : ''}`}>Collaboration</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={collapsed ? `Expand ${title.toLowerCase()}` : `Collapse ${title.toLowerCase()}`}
|
||||
aria-label={collapsed ? 'Expand collaboration' : 'Collapse collaboration'}
|
||||
aria-expanded={!collapsed}
|
||||
className="hidden rounded p-1 hover:bg-accent xl:inline-flex"
|
||||
data-qqq-id="collaboration-collapse"
|
||||
|
||||
@@ -35,7 +35,7 @@ import { cn } from '@/lib/utils/cn'
|
||||
import { CodeEditor } from '@/components/scripts/CodeEditor'
|
||||
|
||||
/** Languages the editor badge names. */
|
||||
export type ScriptEditorLanguage = 'javascript' | 'typescript' | 'groovy' | 'java' | 'python' | 'sql' | 'json' | 'velocity' | 'html' | 'text'
|
||||
export type ScriptEditorLanguage = 'javascript' | 'groovy' | 'java' | 'python' | 'sql' | 'json' | 'velocity' | 'html' | 'text'
|
||||
|
||||
/**
|
||||
* Props for the {@link ScriptEditor} component.
|
||||
@@ -71,7 +71,6 @@ export interface ScriptEditorProps {
|
||||
/** Human-readable display names for each supported language. */
|
||||
const LANGUAGE_LABELS: Record<ScriptEditorLanguage, string> = {
|
||||
javascript: 'JavaScript',
|
||||
typescript: 'TypeScript',
|
||||
groovy: 'Groovy',
|
||||
java: 'Java',
|
||||
python: 'Python',
|
||||
@@ -91,7 +90,6 @@ const LANGUAGE_LABELS: Record<ScriptEditorLanguage, string> = {
|
||||
export function scriptEditorLanguage(mode: string | null | undefined): ScriptEditorLanguage {
|
||||
const normalized = (mode ?? '').trim().toLowerCase()
|
||||
if (normalized === 'js') return 'javascript'
|
||||
if (normalized === 'ts') return 'typescript'
|
||||
if (normalized === 'xml') return 'html'
|
||||
return normalized in LANGUAGE_LABELS ? normalized as ScriptEditorLanguage : 'text'
|
||||
}
|
||||
|
||||
@@ -106,12 +106,6 @@ describe('JobsHeaderButton and JobsPopover', () => {
|
||||
it('shows an active badge, both lists, keyboard trap and restores focus on Escape', async () => {
|
||||
renderConnected(<JobsHeaderButton />)
|
||||
const button = await screen.findByRole('button', { name: 'Jobs, 1 active' })
|
||||
// the badge is positioned against the icon (the header's shared anchor), inside the button
|
||||
const badge = button.querySelector('[data-qqq-id="jobs-active-badge"]')
|
||||
expect(badge).toHaveTextContent('1')
|
||||
expect(badge?.parentElement).toHaveAttribute('data-qqq-id', 'header-icon-anchor')
|
||||
expect(badge?.parentElement).toHaveClass('relative')
|
||||
expect(badge?.parentElement?.parentElement).toBe(button)
|
||||
fireEvent.click(button)
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Jobs' })
|
||||
expect(await screen.findByText('Import')).toBeInTheDocument()
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
'use client'
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { BriefcaseBusiness } from 'lucide-react'
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
|
||||
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
|
||||
import { useJobsInstalled, useMyJobs } from '@/lib/hooks/use-my-jobs'
|
||||
import './jobs.css'
|
||||
|
||||
@@ -34,7 +34,7 @@ const JobsPopover = lazy(() => import('./JobsPopover'))
|
||||
*/
|
||||
export function JobsHeaderButton() {
|
||||
const installed = useJobsInstalled()
|
||||
const active = useMyJobs(installed, { scope: 'mine', state: 'active', limit: 20 }, true)
|
||||
const active = useMyJobs(installed, { scope: 'mine', state: 'active', limit: 20 })
|
||||
const [open, setOpen] = useState(false)
|
||||
const recent = useMyJobs(installed && open, { scope: 'mine', state: 'recent', limit: 5 })
|
||||
const trigger = useRef<HTMLButtonElement>(null)
|
||||
@@ -76,18 +76,16 @@ export function JobsHeaderButton() {
|
||||
className="qqq-job-ring absolute inset-1 rounded-full border border-primary"
|
||||
/>
|
||||
)}
|
||||
<HeaderIconAnchor>
|
||||
<BriefcaseBusiness aria-hidden="true" className="h-5 w-5" />
|
||||
{count > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`${HEADER_BADGE_CLASS} bg-primary text-primary-foreground`}
|
||||
data-qqq-id="jobs-active-badge"
|
||||
>
|
||||
{count > 99 ? '99+' : count}
|
||||
</span>
|
||||
)}
|
||||
</HeaderIconAnchor>
|
||||
<BriefcaseBusiness aria-hidden="true" className="h-5 w-5" />
|
||||
{count > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground"
|
||||
data-qqq-id="jobs-active-badge"
|
||||
>
|
||||
{count > 99 ? '99+' : count}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<span aria-live="polite" className="sr-only" data-qqq-id="jobs-announcer">
|
||||
{announcement}
|
||||
|
||||
@@ -18,9 +18,8 @@
|
||||
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render as renderWithoutProviders, screen, waitFor, within } from '@testing-library/react'
|
||||
import { render as renderWithoutProviders, screen } from '@testing-library/react'
|
||||
import { userEvent } from '@testing-library/user-event'
|
||||
import { axe } from 'jest-axe'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
|
||||
@@ -33,7 +32,6 @@ vi.mock('next/navigation', () => ({
|
||||
import { server } from '@/mocks/node'
|
||||
import { uiApiVersionHandler } from '@/mocks/ui-api-version'
|
||||
import { preferencesFixture } from '@/mocks/fixtures/preferences'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
import { ThemeProvider } from '@/lib/theme/theme-provider'
|
||||
import { setSingleKeyShortcutsEnabled } from '@/lib/keyboard/single-key-shortcuts'
|
||||
import { AccountMenu } from './AccountMenu'
|
||||
@@ -108,109 +106,6 @@ describe('AccountMenu', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('AccountMenu application-declared links', () => {
|
||||
/**
|
||||
* Serves instance metadata with one more widget.
|
||||
*
|
||||
* @param widgets - Widgets to add, by name.
|
||||
*/
|
||||
function declare(widgets: Record<string, unknown>) {
|
||||
const named = Object.fromEntries(Object.entries(widgets).map(([name, widget]) => [name, { name, hasPermission: true, ...(widget as object) }]))
|
||||
server.use(http.get('/qqq/v1/metaData', () => HttpResponse.json({ ...qInstance, widgets: { ...qInstance.widgets, ...named } })))
|
||||
}
|
||||
const localTools = {
|
||||
label: 'Local tools',
|
||||
type: 'ACCOUNT_MENU_LINKS',
|
||||
defaultValues: {
|
||||
links: [
|
||||
{ label: 'Mail inbox', url: 'http://localhost:8025/', icon: 'mail' },
|
||||
{ label: 'Identity provider', url: 'https://id.example.com/admin/' },
|
||||
{ label: 'Plain http elsewhere', url: 'http://tools.example.com/' },
|
||||
{ label: 'Script', url: 'javascript:alert(1)' },
|
||||
{ label: 'Credentials', url: 'https://admin:secret@id.example.com/' },
|
||||
{ label: 'Message broker', url: 'http://127.0.0.1:15672/' },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
it('shows a declared group under the account menu: safe links only, each a menu item that opens in a new tab', async () => {
|
||||
declare({ localTools })
|
||||
const user = userEvent.setup()
|
||||
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
|
||||
const group = await screen.findByRole('group', { name: 'Local tools' })
|
||||
expect(group).toHaveAttribute('data-qqq-id', 'account-menu-links-localTools')
|
||||
|
||||
const items = within(group).getAllByRole('menuitem')
|
||||
expect(items.map((item) => [item.textContent, item.getAttribute('href')])).toEqual([
|
||||
['Mail inbox(opens in a new tab)', 'http://localhost:8025/'],
|
||||
['Identity provider(opens in a new tab)', 'https://id.example.com/admin/'],
|
||||
['Message broker(opens in a new tab)', 'http://127.0.0.1:15672/'],
|
||||
])
|
||||
for (const item of items) {
|
||||
expect(item).toHaveAttribute('target', '_blank')
|
||||
expect(item).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
expect(item.tagName).toBe('A')
|
||||
}
|
||||
expect(items[0]).toHaveAccessibleName('Mail inbox (opens in a new tab)')
|
||||
expect(items[0]).toHaveAttribute('data-qqq-id', 'menu-item-link-localTools-0')
|
||||
// the declared icon, from the set the menu's other metadata icons use
|
||||
expect(items[0].querySelector('[data-qqq-icon="mail"]')).not.toBeNull()
|
||||
|
||||
// nothing of a refused link reaches the page
|
||||
const menu = screen.getByRole('menu', { name: 'Account: Alice' })
|
||||
expect(menu).not.toHaveTextContent(/Plain http elsewhere|Script|Credentials/)
|
||||
expect(menu.innerHTML).not.toMatch(/javascript:|secret|tools\.example\.com/)
|
||||
expect(await axe(menu)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it('reaches the links with the arrow keys, between Preferences and Sign out, and closes when one is chosen', async () => {
|
||||
declare({ localTools })
|
||||
const user = userEvent.setup()
|
||||
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
|
||||
const mail = await screen.findByRole('menuitem', { name: /Mail inbox/ })
|
||||
await user.keyboard('{End}')
|
||||
expect(screen.getByRole('menuitem', { name: 'Sign out' })).toHaveFocus()
|
||||
await user.keyboard('{ArrowUp}')
|
||||
expect(screen.getByRole('menuitem', { name: /Message broker/ })).toHaveFocus()
|
||||
await user.keyboard('{ArrowUp}{ArrowUp}')
|
||||
expect(mail).toHaveFocus()
|
||||
await user.keyboard('{ArrowUp}')
|
||||
expect(screen.getByRole('menuitemcheckbox', { name: 'Dark mode' })).toHaveFocus()
|
||||
|
||||
mail.addEventListener('click', (event) => event.preventDefault())
|
||||
await user.click(mail)
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing for links when the application declares none', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
|
||||
await screen.findByRole('menuitem', { name: 'Preferences' })
|
||||
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Sign out' })).toBeInTheDocument())
|
||||
expect(screen.queryByRole('group')).toBeNull()
|
||||
expect(document.querySelector('[data-qqq-id^="account-menu-links"], [data-qqq-id^="menu-item-link"]')).toBeNull()
|
||||
expect(document.querySelector('a[target="_blank"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing for a group whose links are all refused, or that the user may not see', async () => {
|
||||
declare({
|
||||
allBad: { label: 'Refused', type: 'ACCOUNT_MENU_LINKS', defaultValues: { links: [{ label: 'Script', url: 'javascript:alert(1)' }, { label: 'Http', url: 'http://example.com/' }] } },
|
||||
denied: { ...localTools, label: 'Hidden', hasPermission: false },
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<AccountMenu userName="Alice" />)
|
||||
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
|
||||
await screen.findByRole('menuitem', { name: 'Preferences' })
|
||||
// metadata has loaded once the instance's own widgets are known; give the menu a turn to use it
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
expect(screen.queryByRole('group')).toBeNull()
|
||||
expect(screen.getByRole('menu')).not.toHaveTextContent(/Refused|Hidden|Mail inbox/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('HelpMenu', () => {
|
||||
it('opens help, not shortcuts: Keyboard shortcuts is one of its items (WCAG 3.2.6)', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
/**
|
||||
* @file AccountMenu — the signed-in user's avatar at the far right of the header (the usual
|
||||
* "my account" place): name and email, Preferences and the sections that opt into the menu,
|
||||
* dark mode, QA mode status, the links the application declares for its environment, and sign out.
|
||||
* dark mode, QA mode status, and sign out.
|
||||
*/
|
||||
|
||||
'use client'
|
||||
@@ -25,10 +25,7 @@
|
||||
import React from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Bug, ChevronDown, ExternalLink, LogOut, Moon, Settings, Wrench } from 'lucide-react'
|
||||
|
||||
import { useMetaData } from '@/lib/hooks/use-metadata'
|
||||
import { toolsTarget } from '@/components/tools/tools-catalog'
|
||||
import { Bug, ChevronDown, LogOut, Moon, Settings } from 'lucide-react'
|
||||
|
||||
import { getPreferences } from '@/lib/api/preferences'
|
||||
import { useMediaQuery } from '@/lib/hooks/use-media-query'
|
||||
@@ -39,7 +36,6 @@ import { cn } from '@/lib/utils/cn'
|
||||
import { useMyProfile } from '@/lib/hooks/use-my-profile'
|
||||
import { UserAvatar } from '@/components/ui/UserAvatar'
|
||||
import { MetadataIcon } from './MetadataIcon'
|
||||
import { accountMenuLinkGroups } from './account-menu-links'
|
||||
import { HEADER_MENU_ITEM_CLASS, HeaderMenu, HeaderMenuSeparator } from './HeaderMenu'
|
||||
|
||||
/** Below this width the header shows only Search, Jobs, Notifications and the avatar. */
|
||||
@@ -81,8 +77,6 @@ export function AccountMenu({ userName, userEmail, logout, compactItems }: Accou
|
||||
label={qaMode ? `Account: ${displayName} (QA mode on)` : `Account: ${displayName}`}
|
||||
qqqId="button-account"
|
||||
triggerClassName="gap-1 px-1"
|
||||
// declared links can make the menu taller than a phone: it scrolls within the space it has
|
||||
menuClassName="max-h-[var(--radix-popover-content-available-height)] overflow-y-auto"
|
||||
trigger={(
|
||||
<>
|
||||
<span className="relative">
|
||||
@@ -113,9 +107,6 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
|
||||
compactItems?: (close: (then?: () => void) => void) => React.ReactNode
|
||||
}) {
|
||||
const { theme, isDarkMode, setDarkMode } = useTheme()
|
||||
const metadata = useMetaData()
|
||||
const tools = toolsTarget(metadata.data)
|
||||
const linkGroups = accountMenuLinkGroups(metadata.data)
|
||||
const capability = useQaCaptureCapability()
|
||||
const preferences = useQuery({ queryKey: queryKeys.preferencesIndex(), queryFn: getPreferences, retry: false })
|
||||
const qaSection = capability?.enabled && capability.reason === 'QA_MODE' ? capability.qaMode.preferenceSection : undefined
|
||||
@@ -136,9 +127,6 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
|
||||
<HeaderMenuSeparator />
|
||||
</div>
|
||||
)}
|
||||
{tools && <Link href={tools.path} role="menuitem" onClick={() => close()} className={HEADER_MENU_ITEM_CLASS} data-qqq-id="menu-item-tools">
|
||||
<Wrench className="h-4 w-4 text-muted-foreground" aria-hidden="true" />{tools.label}
|
||||
</Link>}
|
||||
<Link href="/app/preferences" role="menuitem" onClick={() => close()} className={HEADER_MENU_ITEM_CLASS} data-qqq-id="menu-item-preferences">
|
||||
<Settings className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
Preferences
|
||||
@@ -181,31 +169,6 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
{/* Links the application declares for this environment (`account-menu-links`): nothing is
|
||||
rendered when it declares none. Accessibility: each group is a `group` named by its
|
||||
heading; each link is a `menuitem`, so the arrow keys, Home and End reach it like any
|
||||
other item; it opens in a new tab, which its name says ("opens in a new tab") and a
|
||||
trailing icon shows; `rel="noopener noreferrer"` keeps the opened page from reaching
|
||||
back into this one or learning the address it came from. */}
|
||||
{linkGroups.map((group) => (
|
||||
<div key={group.name} role="group" aria-labelledby={`account-menu-links-${group.name}`} data-qqq-id={`account-menu-links-${group.name}`}>
|
||||
<HeaderMenuSeparator />
|
||||
<p id={`account-menu-links-${group.name}`} className="truncate px-4 pb-1 pt-2 text-xs font-semibold text-muted-foreground" data-qqq-id="account-menu-links-label">
|
||||
{group.label}
|
||||
</p>
|
||||
{group.links.map((link, index) => (
|
||||
<a key={`${index}:${link.href}`} href={link.href} target="_blank" rel="noopener noreferrer" role="menuitem" onClick={() => close()}
|
||||
className={HEADER_MENU_ITEM_CLASS} data-qqq-id={`menu-item-link-${group.name}-${index}`}>
|
||||
{link.icon
|
||||
? <MetadataIcon iconName={link.icon} kind="section" className="h-4 w-4 text-muted-foreground" />
|
||||
: <ExternalLink className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />}
|
||||
<span className="min-w-0 flex-1 truncate" title={link.label}>{link.label}</span>
|
||||
<span className="sr-only">(opens in a new tab)</span>
|
||||
{link.icon && <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{logout && (
|
||||
<>
|
||||
<HeaderMenuSeparator />
|
||||
|
||||
@@ -21,16 +21,13 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
|
||||
let currentPathname = '/app/person'
|
||||
let currentSearch = ''
|
||||
vi.mock('next/navigation', () => ({
|
||||
usePathname: () => currentPathname,
|
||||
useSearchParams: () => new URLSearchParams(currentSearch),
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
}))
|
||||
|
||||
import Breadcrumbs, { buildBreadcrumbs, buildDocumentTitle, humanizeSegment } from './Breadcrumbs'
|
||||
import type { ParentAppInfo } from '@/lib/hooks/use-routes'
|
||||
import { TABLE_SUB_VIEWS } from '@/lib/utils/table-sub-views'
|
||||
|
||||
beforeEach(() => vi.stubGlobal('ResizeObserver', class {
|
||||
observe() {}
|
||||
@@ -105,30 +102,6 @@ describe('buildBreadcrumbs', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildBreadcrumbs with a sub-view in the query string', () => {
|
||||
const list = 'page=3&filter=abc&q=smith'
|
||||
|
||||
it.each(Object.values(TABLE_SUB_VIEWS))('$name is the last crumb and the table links back to the list as it was', (view) => {
|
||||
const search = `${list}&view=${view.name}&${view.params.map((name) => `${name}=layout`).join('&')}`
|
||||
const crumbs = buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, search)
|
||||
expect(crumbs.map((crumb) => crumb.label)).toEqual(['People App', 'Greetings App', 'Person', view.label])
|
||||
expect(crumbs.at(-2)).toEqual({ path: '/app/person', label: 'Person', href: `/app/person?${list}` })
|
||||
})
|
||||
|
||||
it('links back to a saved view with its own path, and to a bare list without a query string', () => {
|
||||
const saved = buildBreadcrumbs('/app/person/savedView/3', pathToLabelMap, ancestorAppMap, new URLSearchParams('view=pivot&pivot=x'))
|
||||
expect(saved.slice(-2).map((crumb) => crumb.label)).toEqual(['Saved View', 'Pivot'])
|
||||
expect(saved.at(-2)?.href).toBe('/app/person/savedView/3')
|
||||
})
|
||||
|
||||
it('leaves the trail alone for the list, an unknown view, and a record page that has its own view parameter', () => {
|
||||
const plain = buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap)
|
||||
expect(buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, 'page=3&filter=abc')).toEqual(plain)
|
||||
expect(buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, 'view=nope')).toEqual(plain)
|
||||
expect(buildBreadcrumbs('/app/person/7', pathToLabelMap, ancestorAppMap, 'view=pivot').map((crumb) => crumb.label)).toEqual(['People App', 'Greetings App', 'Person', '7'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildDocumentTitle', () => {
|
||||
const crumbs = buildBreadcrumbs('/app/person/1', pathToLabelMap, ancestorAppMap)
|
||||
|
||||
@@ -148,14 +121,6 @@ describe('buildDocumentTitle', () => {
|
||||
describe('Breadcrumbs', () => {
|
||||
beforeEach(() => {
|
||||
currentPathname = '/app/person'
|
||||
currentSearch = ''
|
||||
})
|
||||
|
||||
it.each(Object.values(TABLE_SUB_VIEWS))('inside $name the view is the current page and the table is a link back to the list', (view) => {
|
||||
currentSearch = `page=2&filter=abc&view=${view.name}`
|
||||
render(<Breadcrumbs pathToLabelMap={pathToLabelMap} ancestorAppMap={ancestorAppMap} />)
|
||||
expect(screen.getByText(view.label)).toHaveAttribute('aria-current', 'page')
|
||||
expect(screen.getByRole('link', { name: 'Person' })).toHaveAttribute('href', '/app/person?page=2&filter=abc')
|
||||
})
|
||||
|
||||
it('renders the app hierarchy as links and the current page as text', () => {
|
||||
|
||||
@@ -20,13 +20,12 @@
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { Suspense } from 'react'
|
||||
import React from 'react'
|
||||
import Link from 'next/link'
|
||||
import { usePathname, useSearchParams } from 'next/navigation'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { Home } from 'lucide-react'
|
||||
|
||||
import type { ParentAppInfo } from '@/lib/hooks/use-routes'
|
||||
import { listSearch, tableSubView } from '@/lib/utils/table-sub-views'
|
||||
|
||||
/**
|
||||
* Props for the Breadcrumbs component.
|
||||
@@ -48,8 +47,6 @@ export interface Breadcrumb {
|
||||
path: string
|
||||
/** Human-readable label. */
|
||||
label: string
|
||||
/** Where the crumb links when that is more than its path: the list behind a sub-view keeps its query string. */
|
||||
href?: string
|
||||
}
|
||||
|
||||
/** Labels for the fixed sub-page segments under a table or record. */
|
||||
@@ -105,21 +102,15 @@ export function humanizeSegment(segment: string): string {
|
||||
* and `/app/{table}/{id}/{process}` URLs) takes that object's label; other
|
||||
* segments without a label are humanized, except a record id, which stays as is.
|
||||
*
|
||||
* A sub-view of a record list lives in the query string, not the path (`?view=correlation`, see
|
||||
* `table-sub-views`). With `search`, an open sub-view becomes the last crumb, and the list's own
|
||||
* crumb before it links back to the list with the rest of the query string (filter, sort, page).
|
||||
*
|
||||
* @param pathname - Current browser path.
|
||||
* @param pathToLabelMap - Route path → label.
|
||||
* @param ancestorAppMap - Node path → enclosing apps.
|
||||
* @param search - Current query string; omit to build the trail from the path alone.
|
||||
* @returns Breadcrumbs from the outermost app to the current page.
|
||||
*/
|
||||
export function buildBreadcrumbs(
|
||||
pathname: string,
|
||||
pathToLabelMap: Record<string, string>,
|
||||
ancestorAppMap: Record<string, ParentAppInfo[]> = {},
|
||||
search?: URLSearchParams | string | null
|
||||
ancestorAppMap: Record<string, ParentAppInfo[]> = {}
|
||||
): Breadcrumb[] {
|
||||
const segments = pathname.split('/').filter(Boolean)
|
||||
if (segments[0] !== 'app' || segments.length < 2) return []
|
||||
@@ -142,14 +133,6 @@ export function buildBreadcrumbs(
|
||||
?? (index === 0 ? decoded : humanizeSegment(decoded))
|
||||
crumbs.push({ path, label })
|
||||
}
|
||||
|
||||
// Only a record list hosts sub-views: the table itself, or one of its saved views.
|
||||
const subView = rest.length === 0 || rest[0] === 'savedView' ? tableSubView(search) : undefined
|
||||
if (subView) {
|
||||
const list = crumbs[crumbs.length - 1]
|
||||
crumbs[crumbs.length - 1] = { ...list, href: `${list.path}${listSearch(search)}` }
|
||||
crumbs.push({ path: `${list.path}?view=${subView.name}`, label: subView.label })
|
||||
}
|
||||
return crumbs
|
||||
}
|
||||
|
||||
@@ -172,43 +155,14 @@ export function buildDocumentTitle(crumbs: Breadcrumb[], pageTitle: string | und
|
||||
/**
|
||||
* Renders a horizontal breadcrumb trail for the current page.
|
||||
*
|
||||
* The trail follows the query string as well as the path, so a sub-view of a record list shows as
|
||||
* the current page with the list as a link back. The query string is read inside a Suspense
|
||||
* boundary (a static export cannot prerender it); until it is known the trail is built from the
|
||||
* path alone.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @returns A `<nav aria-label="Breadcrumb">` element with slash-separated
|
||||
* `<Link>` crumbs (ancestor pages) followed by a `<span aria-current="page">`
|
||||
* for the current page, or `null` on the dashboard root and before labels load.
|
||||
*/
|
||||
export default function Breadcrumbs(props: BreadcrumbsProps) {
|
||||
return (
|
||||
<Suspense fallback={<BreadcrumbTrail {...props} search={null} />}>
|
||||
<BreadcrumbsForLocation {...props} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the query string for {@link Breadcrumbs}.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @returns The trail for the current path and query string.
|
||||
*/
|
||||
function BreadcrumbsForLocation(props: BreadcrumbsProps) {
|
||||
return <BreadcrumbTrail {...props} search={useSearchParams()} />
|
||||
}
|
||||
|
||||
/**
|
||||
* The trail itself.
|
||||
*
|
||||
* @param props - Component properties, and the query string when it is known.
|
||||
* @returns The `<nav>`, or `null`.
|
||||
*/
|
||||
function BreadcrumbTrail({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app', search }: BreadcrumbsProps & { search: URLSearchParams | null }) {
|
||||
export default function Breadcrumbs({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app' }: BreadcrumbsProps) {
|
||||
const pathname = usePathname()
|
||||
const breadcrumbs = buildBreadcrumbs(pathname, pathToLabelMap, ancestorAppMap, search)
|
||||
const breadcrumbs = buildBreadcrumbs(pathname, pathToLabelMap, ancestorAppMap)
|
||||
const hasLabels = Object.keys(pathToLabelMap).length > 0
|
||||
|
||||
// Until metadata supplies labels, raw URL segments would flash in place of labels
|
||||
@@ -232,8 +186,7 @@ function BreadcrumbTrail({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app
|
||||
<Home className="h-4 w-4" aria-hidden="true" />
|
||||
</Link>
|
||||
{/* Every crumb stays a link, in order. A long label truncates with an ellipsis (full text in the title) and the
|
||||
trail wraps onto another line instead of scrolling or hiding crumbs. Accessibility: the last crumb is text
|
||||
with aria-current="page"; every crumb before it, including the list behind an open sub-view, is a link. */}
|
||||
trail wraps onto another line instead of scrolling or hiding crumbs. */}
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<React.Fragment key={crumb.path + index}>
|
||||
<span className="shrink-0 text-muted-foreground/60" aria-hidden="true">/</span>
|
||||
@@ -249,7 +202,7 @@ function BreadcrumbTrail({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app
|
||||
) : (
|
||||
<Link
|
||||
title={crumb.label}
|
||||
href={crumb.href ?? crumb.path}
|
||||
href={crumb.path}
|
||||
className="min-w-0 max-w-[10rem] truncate text-muted-foreground hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-w-11 pointer-coarse:py-3 pointer-coarse:text-center"
|
||||
data-qqq-id={`breadcrumb-link-${index}`}
|
||||
>
|
||||
|
||||
@@ -33,34 +33,6 @@ export const HEADER_BUTTON_CLASS = cn(
|
||||
'hover:bg-accent hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'
|
||||
)
|
||||
|
||||
/**
|
||||
* The positioning context of a header button's indicators: a box exactly the size of its icon.
|
||||
* The button's own box is the hit area (padding, and a text label from 1440 px on Ask) with no
|
||||
* visible edge at rest, so an indicator placed against it drifts away from the icon.
|
||||
*/
|
||||
export const HEADER_ICON_ANCHOR_CLASS = 'relative flex shrink-0'
|
||||
|
||||
/**
|
||||
* A count badge over the icon's top-right corner (unread, active). On a 40 px icon-only button this
|
||||
* is 2 px inside the button's top-right corner. Add the fill and text colors.
|
||||
*/
|
||||
export const HEADER_BADGE_CLASS = 'absolute -right-2 -top-2 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none'
|
||||
|
||||
/** A status dot on the icon's bottom-right corner (activity). Add the fill color. */
|
||||
export const HEADER_STATUS_DOT_CLASS = 'absolute -bottom-0.5 -right-0.5 h-2 w-2 rounded-full'
|
||||
|
||||
/**
|
||||
* A header button's icon together with its indicators ({@link HEADER_BADGE_CLASS},
|
||||
* {@link HEADER_STATUS_DOT_CLASS}), which stay on the icon whatever else the button holds.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.children - The icon, then its indicators.
|
||||
* @returns The anchor.
|
||||
*/
|
||||
export function HeaderIconAnchor({ children }: { children: React.ReactNode }) {
|
||||
return <span className={HEADER_ICON_ANCHOR_CLASS} data-qqq-id="header-icon-anchor">{children}</span>
|
||||
}
|
||||
|
||||
/** A menu row: full width, 44 px tall on touch. */
|
||||
export const HEADER_MENU_ITEM_CLASS = cn(
|
||||
'flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm font-medium text-foreground pointer-coarse:min-h-11',
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { QInstance, QWidgetMetaData } from '@/types'
|
||||
import { ACCOUNT_MENU_LINKS_MAX, ACCOUNT_MENU_LINKS_WIDGET_TYPE, accountMenuLinkGroups, accountMenuLinkHref } from './account-menu-links'
|
||||
|
||||
/**
|
||||
* Instance metadata with the given widgets.
|
||||
*
|
||||
* @param widgets - Widgets by name.
|
||||
* @returns The metadata slice the reader takes.
|
||||
*/
|
||||
function instance(widgets: Record<string, Partial<QWidgetMetaData>>): Pick<QInstance, 'widgets'> {
|
||||
return { widgets: Object.fromEntries(Object.entries(widgets).map(([name, widget]) => [name, { name, label: name, hasPermission: true, ...widget }])) } as Pick<QInstance, 'widgets'>
|
||||
}
|
||||
|
||||
const links = (...declared: unknown[]) => ({ type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, label: 'Local tools', defaultValues: { links: declared } })
|
||||
|
||||
describe('accountMenuLinkHref', () => {
|
||||
it.each([
|
||||
['https://mail.example.com/inbox?folder=1#top', 'https://mail.example.com/inbox?folder=1#top'],
|
||||
['https://example.com', 'https://example.com/'],
|
||||
[' https://example.com/a ', 'https://example.com/a'],
|
||||
['http://localhost:8025/', 'http://localhost:8025/'],
|
||||
['http://LOCALHOST:8025', 'http://localhost:8025/'],
|
||||
['http://127.0.0.1:15672/#/queues', 'http://127.0.0.1:15672/#/queues'],
|
||||
['http://[::1]:9000/admin', 'http://[::1]:9000/admin'],
|
||||
['https://localhost:8443/', 'https://localhost:8443/'],
|
||||
])('allows %s', (declared, href) => {
|
||||
expect(accountMenuLinkHref(declared)).toBe(href)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['plain http to another host', 'http://mail.example.com/'],
|
||||
['http to a name that only starts like this machine', 'http://localhost.example.com/'],
|
||||
['http to an address that only starts like this machine', 'http://127.0.0.1.example.com/'],
|
||||
['http to another loopback spelling', 'http://127.0.0.2/'],
|
||||
['http to a private address', 'http://192.168.1.10/'],
|
||||
['a user name and password', 'https://admin:secret@id.example.com/'],
|
||||
['a user name alone', 'https://admin@id.example.com/'],
|
||||
['credentials on this machine', 'http://admin:secret@localhost:8025/'],
|
||||
['a script', 'javascript:alert(1)'],
|
||||
['a script with odd spelling', ' JaVaScRiPt:alert(1)'],
|
||||
['a data URL', 'data:text/html,<script>alert(1)</script>'],
|
||||
['a file', 'file:///etc/passwd'],
|
||||
['another scheme', 'ftp://files.example.com/'],
|
||||
['a relative path', '/app/person'],
|
||||
['a protocol-relative URL', '//example.com/'],
|
||||
['a bare host', 'example.com'],
|
||||
['an empty string', ''],
|
||||
['blank space', ' '],
|
||||
['a number', 8025],
|
||||
['nothing', undefined],
|
||||
['an object', { href: 'https://example.com/' }],
|
||||
])('refuses %s', (_what, declared) => {
|
||||
expect(accountMenuLinkHref(declared)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('accountMenuLinkGroups', () => {
|
||||
it('reads a declared group: label, links in order, and well-formed icon names', () => {
|
||||
const groups = accountMenuLinkGroups(instance({
|
||||
localTools: links(
|
||||
{ label: 'Mail inbox', url: 'http://localhost:8025/', icon: 'mail' },
|
||||
{ label: ' Identity provider ', url: 'https://id.example.com/admin/' },
|
||||
{ label: 'Message broker', url: 'http://127.0.0.1:15672/', icon: '<svg onload=alert(1)>' },
|
||||
),
|
||||
}))
|
||||
expect(groups).toEqual([{
|
||||
name: 'localTools',
|
||||
label: 'Local tools',
|
||||
links: [
|
||||
{ label: 'Mail inbox', href: 'http://localhost:8025/', icon: 'mail' },
|
||||
{ label: 'Identity provider', href: 'https://id.example.com/admin/' },
|
||||
{ label: 'Message broker', href: 'http://127.0.0.1:15672/' },
|
||||
],
|
||||
}])
|
||||
})
|
||||
|
||||
it('is empty when the application declares nothing, and before metadata loads', () => {
|
||||
expect(accountMenuLinkGroups(undefined)).toEqual([])
|
||||
expect(accountMenuLinkGroups({ widgets: {} })).toEqual([])
|
||||
expect(accountMenuLinkGroups(instance({ chart: { type: 'chart', defaultValues: { links: [{ label: 'x', url: 'https://example.com/' }] } } }))).toEqual([])
|
||||
})
|
||||
|
||||
it('drops every link that is not a label and an allowed URL, and keeps the rest', () => {
|
||||
const [group] = accountMenuLinkGroups(instance({
|
||||
tools: links(
|
||||
{ label: 'Good', url: 'https://example.com/' },
|
||||
{ label: 'Plain http', url: 'http://example.com/' },
|
||||
{ label: 'Script', url: 'javascript:alert(1)' },
|
||||
{ label: 'Credentials', url: 'https://user:pw@example.com/' },
|
||||
{ label: '', url: 'https://example.com/' },
|
||||
{ label: ' ', url: 'https://example.com/' },
|
||||
{ url: 'https://example.com/' },
|
||||
{ label: 'No address' },
|
||||
{ label: { text: 'Object' }, url: 'https://example.com/' },
|
||||
'https://example.com/',
|
||||
null,
|
||||
['Array', 'https://example.com/'],
|
||||
{ label: 'Also good', url: 'http://[::1]:3000/' },
|
||||
),
|
||||
}))
|
||||
expect(group.links.map((link) => link.label)).toEqual(['Good', 'Also good'])
|
||||
})
|
||||
|
||||
it('shows no group that is left without links, is hidden by permission, or is malformed', () => {
|
||||
expect(accountMenuLinkGroups(instance({
|
||||
empty: links(),
|
||||
allBad: links({ label: 'Script', url: 'javascript:alert(1)' }),
|
||||
denied: { ...links({ label: 'Good', url: 'https://example.com/' }), hasPermission: false },
|
||||
notAList: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, defaultValues: { links: { label: 'Good', url: 'https://example.com/' } } },
|
||||
aString: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, defaultValues: { links: '[{"label":"Good","url":"https://example.com/"}]' } },
|
||||
noValues: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE },
|
||||
}))).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps several groups in metadata order, names a group without a label, and caps a long one', () => {
|
||||
const many = Array.from({ length: ACCOUNT_MENU_LINKS_MAX + 5 }, (_, index) => ({ label: `Tool ${index + 1}`, url: `https://example.com/${index + 1}` }))
|
||||
const groups = accountMenuLinkGroups(instance({
|
||||
second: { ...links({ label: 'B', url: 'https://example.com/b' }), label: 'Second' },
|
||||
first: { ...links(...many), label: ' ' },
|
||||
}))
|
||||
expect(groups.map((group) => [group.name, group.label, group.links.length])).toEqual([['second', 'Second', 1], ['first', 'Links', ACCOUNT_MENU_LINKS_MAX]])
|
||||
expect(groups[1].links.at(-1)?.label).toBe(`Tool ${ACCOUNT_MENU_LINKS_MAX}`)
|
||||
})
|
||||
|
||||
it('shortens an overlong label instead of trusting it', () => {
|
||||
const [group] = accountMenuLinkGroups(instance({ tools: links({ label: 'x'.repeat(500), url: 'https://example.com/' }) }))
|
||||
expect(group.links[0].label).toHaveLength(80)
|
||||
})
|
||||
})
|
||||
@@ -1,141 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file account-menu-links — links an application declares for the account menu: a labelled
|
||||
* group of links to the tools that go with one environment (a mail capture inbox, an identity
|
||||
* provider's admin page, a message broker's console).
|
||||
*
|
||||
* The contract is a widget in the instance metadata, the same carrier the Tools shortcut uses,
|
||||
* because an application can declare a widget without any change to QQQ itself and the metadata
|
||||
* response already publishes a widget's `type`, `label`, `hasPermission` and `defaultValues`:
|
||||
*
|
||||
* ```json
|
||||
* "widgets": {
|
||||
* "localTools": {
|
||||
* "name": "localTools",
|
||||
* "label": "Local tools",
|
||||
* "type": "ACCOUNT_MENU_LINKS",
|
||||
* "hasPermission": true,
|
||||
* "defaultValues": {
|
||||
* "links": [
|
||||
* { "label": "Mail inbox", "url": "http://localhost:8025/", "icon": "mail" },
|
||||
* { "label": "Identity provider", "url": "https://id.example.com/admin/" }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Everything that arrives is untrusted: a link that is not exactly a label and a safe URL is
|
||||
* dropped, never repaired and never rendered.
|
||||
*/
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
|
||||
/** Widget `type` that declares a group of account menu links. */
|
||||
export const ACCOUNT_MENU_LINKS_WIDGET_TYPE = 'ACCOUNT_MENU_LINKS'
|
||||
|
||||
/** Most links one group shows; the menu is a menu, not a directory. */
|
||||
export const ACCOUNT_MENU_LINKS_MAX = 12
|
||||
|
||||
/** Longest label kept, in characters. */
|
||||
const LABEL_MAX = 80
|
||||
|
||||
/** A Material icon name, as the menu's other metadata icons use. */
|
||||
const ICON_NAME = /^[a-z0-9_]{1,40}$/
|
||||
|
||||
/** Hosts that are this machine. */
|
||||
const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]']
|
||||
|
||||
/** One link, ready to render. */
|
||||
export interface AccountMenuLink {
|
||||
/** Text of the menu item. */
|
||||
label: string
|
||||
/** The normalized, safe URL. */
|
||||
href: string
|
||||
/** Material icon name, when the application named a well-formed one. */
|
||||
icon?: string
|
||||
}
|
||||
|
||||
/** One labelled group of links. */
|
||||
export interface AccountMenuLinkGroup {
|
||||
/** The declaring widget's name (a stable key and CSS hook). */
|
||||
name: string
|
||||
/** The group's heading. */
|
||||
label: string
|
||||
/** Its links, in declared order; never empty. */
|
||||
links: AccountMenuLink[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The house rule for a link an application supplies: `https:` anywhere, or `http:` to this
|
||||
* machine (`localhost`, `127.0.0.1`, `[::1]`), absolute, and without credentials. Everything else
|
||||
* (`javascript:`, `data:`, plain `http:` to another host, a relative path, a URL with a user name
|
||||
* or password) is refused.
|
||||
*
|
||||
* @param value - The declared URL.
|
||||
* @returns The normalized URL, or undefined when it is not allowed.
|
||||
*/
|
||||
export function accountMenuLinkHref(value: unknown): string | undefined {
|
||||
if (typeof value !== 'string' || !value.trim()) return undefined
|
||||
try {
|
||||
const url = new URL(value.trim())
|
||||
const loopback = LOOPBACK_HOSTS.includes(url.hostname)
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return undefined
|
||||
if (url.username || url.password) return undefined
|
||||
return url.href
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads one declared link.
|
||||
*
|
||||
* @param value - An entry of `defaultValues.links`.
|
||||
* @returns The link, or undefined when it has no label or no allowed URL.
|
||||
*/
|
||||
function readLink(value: unknown): AccountMenuLink | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
|
||||
const { label, url, icon } = value as Record<string, unknown>
|
||||
const text = typeof label === 'string' ? label.trim().slice(0, LABEL_MAX) : ''
|
||||
const href = accountMenuLinkHref(url)
|
||||
if (!text || !href) return undefined
|
||||
return { label: text, href, ...(typeof icon === 'string' && ICON_NAME.test(icon) ? { icon } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The link groups an instance declares for the account menu: every widget of type
|
||||
* {@link ACCOUNT_MENU_LINKS_WIDGET_TYPE} the user may see, in metadata order, with the links
|
||||
* that pass {@link accountMenuLinkHref}. A group left without links is not a group.
|
||||
*
|
||||
* @param metadata - Permission-filtered instance metadata, when loaded.
|
||||
* @returns The groups; empty when the application declares none.
|
||||
*/
|
||||
export function accountMenuLinkGroups(metadata: Pick<QInstance, 'widgets'> | undefined): AccountMenuLinkGroup[] {
|
||||
const groups: AccountMenuLinkGroup[] = []
|
||||
for (const [name, widget] of Object.entries(metadata?.widgets ?? {})) {
|
||||
if (widget?.type !== ACCOUNT_MENU_LINKS_WIDGET_TYPE || widget.hasPermission === false) continue
|
||||
const declared = widget.defaultValues?.links
|
||||
if (!Array.isArray(declared)) continue
|
||||
const links = declared.flatMap((entry) => readLink(entry) ?? []).slice(0, ACCOUNT_MENU_LINKS_MAX)
|
||||
if (links.length === 0) continue
|
||||
const label = typeof widget.label === 'string' && widget.label.trim() ? widget.label.trim().slice(0, LABEL_MAX) : 'Links'
|
||||
groups.push({ name, label, links })
|
||||
}
|
||||
return groups
|
||||
}
|
||||
@@ -32,15 +32,8 @@ vi.mock('@/lib/hooks/use-container-width', () => ({
|
||||
useContainerWidth: () => [undefined, layout.width],
|
||||
}))
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn() } }))
|
||||
const navigation = vi.hoisted(() => ({ leaveTo: vi.fn() }))
|
||||
vi.mock('@/lib/utils/external-navigation', async (original) => ({
|
||||
...(await original<typeof import('@/lib/utils/external-navigation')>()),
|
||||
leaveTo: navigation.leaveTo,
|
||||
}))
|
||||
beforeEach(() => {
|
||||
layout.width = 500
|
||||
navigation.leaveTo.mockClear()
|
||||
vi.mocked(toast.success).mockClear()
|
||||
})
|
||||
const tokens = preferencesFixture.sections.find((section) => section.name === 'access-tokens')!
|
||||
function renderForm(section: PreferenceSection = structuredClone(tokens)) {
|
||||
@@ -394,36 +387,3 @@ it('shows each returned secret and restores focus to the returned row after ackn
|
||||
expect(screen.queryByDisplayValue('recovery-test-only')).not.toBeInTheDocument()
|
||||
persist.mockRestore()
|
||||
})
|
||||
|
||||
it('sends the browser to an address-only result and never shows the address', async () => {
|
||||
const authorize =
|
||||
'https://slack.com/oauth/v2/authorize?client_id=1.2&scope=&user_scope=chat%3Awrite&redirect_uri=https%3A%2F%2Fapp.example.test%2Fqqq%2Fhooks%2Fslack%2Foauth%2Fcallback&state=abc.def'
|
||||
const section = structuredClone(tokens)
|
||||
section.actions!.push({ name: 'connect', label: 'Connect service', scope: 'SECTION' })
|
||||
server.use(
|
||||
http.post('/qqq/v1/preferences/access-tokens/actions/connect', () =>
|
||||
HttpResponse.json({ section, message: authorize })
|
||||
)
|
||||
)
|
||||
renderForm(section)
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Connect service' }))
|
||||
await waitFor(() => expect(navigation.leaveTo).toHaveBeenCalledWith(authorize))
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
expect(screen.queryByText(/slack\.com/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('still shows a result that only mentions an address as a message', async () => {
|
||||
const section = structuredClone(tokens)
|
||||
section.actions!.push({ name: 'connect', label: 'Connect service', scope: 'SECTION' })
|
||||
server.use(
|
||||
http.post('/qqq/v1/preferences/access-tokens/actions/connect', () =>
|
||||
HttpResponse.json({ section, message: 'Connected. See https://example.test/help for more.' })
|
||||
)
|
||||
)
|
||||
renderForm(section)
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Connect service' }))
|
||||
await waitFor(() =>
|
||||
expect(toast.success).toHaveBeenCalledWith('Connected. See https://example.test/help for more.')
|
||||
)
|
||||
expect(navigation.leaveTo).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -32,7 +32,6 @@ import type {
|
||||
} from '@/types/preferences'
|
||||
import { runPreferenceAction } from '@/lib/api/preferences'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { continuationUrl, leaveTo } from '@/lib/utils/external-navigation'
|
||||
import { BUTTON_CLASS, buttonClass } from '@/components/ui/controls'
|
||||
import { MetadataIcon } from '@/components/layout/MetadataIcon'
|
||||
import { PreferenceField } from './PreferenceField'
|
||||
@@ -382,11 +381,7 @@ export function usePreferenceActions({
|
||||
showingSecrets.current = Boolean(result.secrets?.length)
|
||||
onSaved(result.section)
|
||||
setSelected(null)
|
||||
// An answer that is only an address (the consent page of a service being connected) is
|
||||
// where the browser goes next. It is never shown: nobody can use an address in a toast.
|
||||
const destination = continuationUrl(result.message)
|
||||
if (destination) leaveTo(destination)
|
||||
else if (result.message) toast.success(result.message)
|
||||
if (result.message) toast.success(result.message)
|
||||
setSecrets(result.secrets ?? [])
|
||||
} catch (error) {
|
||||
if (mounted.current) setErrors(preferenceMessages(error))
|
||||
|
||||
@@ -22,7 +22,7 @@ import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { axe } from 'jest-axe'
|
||||
import { server } from '@/mocks/node'
|
||||
import { ThemeProvider } from '@/lib/theme/theme-provider'
|
||||
import { PreferencesPage, sectionOutcome } from './PreferencesPage'
|
||||
import { PreferencesPage } from './PreferencesPage'
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
search: '',
|
||||
@@ -107,42 +107,3 @@ it('offers retry on errors and keeps local display settings accessible', async (
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Retry' }))
|
||||
await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('says once that a flow that returned to a section succeeded, and takes the outcome off the address', async () => {
|
||||
state.search = 'section=regional&result=connected'
|
||||
renderPage()
|
||||
await screen.findByRole('heading', { name: 'Regional settings' })
|
||||
const outcome = screen.getByText('Regional settings: connected.')
|
||||
expect(outcome).toHaveAttribute('role', 'status')
|
||||
expect(outcome).toHaveAttribute('data-qqq-id', 'preferences-section-outcome')
|
||||
expect(state.replace).toHaveBeenCalledWith('/app/preferences?section=regional', { scroll: false })
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: /Notifications What reaches/ }))
|
||||
expect(screen.queryByText('Regional settings: connected.')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the reason a flow that returned to a section failed', async () => {
|
||||
state.search = 'section=regional&error=authorization_denied'
|
||||
renderPage()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Regional settings: authorization denied.'
|
||||
)
|
||||
})
|
||||
|
||||
it('reads only fixed outcome codes from the address, never a sentence', () => {
|
||||
const read = (search: string) => sectionOutcome(new URLSearchParams(search))
|
||||
expect(read('section=slack&result=connected')).toEqual({
|
||||
section: 'slack',
|
||||
failed: false,
|
||||
words: 'connected',
|
||||
})
|
||||
expect(read('section=slack&error=sign_in_required&result=connected')).toEqual({
|
||||
section: 'slack',
|
||||
failed: true,
|
||||
words: 'sign in required',
|
||||
})
|
||||
expect(read('section=slack')).toBeNull()
|
||||
expect(read('result=connected')).toBeNull()
|
||||
expect(read('section=slack&error=Call+555-0100+now')).toBeNull()
|
||||
expect(read('section=slack&error=%3Cb%3Ex%3C%2Fb%3E')).toBeNull()
|
||||
expect(read(`section=slack&error=${'a_'.repeat(20)}a`)).toBeNull()
|
||||
})
|
||||
@@ -17,14 +17,13 @@
|
||||
/** @file Preferences route content, with device display settings and server-owned sections. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getPreferences } from '@/lib/api/preferences'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { useQContext } from '@/lib/context/q-context'
|
||||
import { useMediaQuery } from '@/lib/hooks/use-media-query'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { BUTTON_CLASS } from '@/components/ui/controls'
|
||||
import { MetadataIcon } from '@/components/layout/MetadataIcon'
|
||||
import { DisplayPreferencesPanel } from '@/components/layout/DisplayPreferencesPanel'
|
||||
@@ -44,30 +43,6 @@ export function PreferencesSkeleton() {
|
||||
)
|
||||
}
|
||||
|
||||
/** What a flow that left the dashboard reports when it returns to a section. */
|
||||
export interface SectionOutcome {
|
||||
section: string
|
||||
failed: boolean
|
||||
/** The provider's outcome code as words: `authorization_denied` reads "authorization denied". */
|
||||
words: string
|
||||
}
|
||||
|
||||
/** Reads the outcome a flow that left the dashboard (a consent page of a connected service)
|
||||
* puts on the address when it returns: `?section=<name>&result=<code>` when it succeeded,
|
||||
* `&error=<code>` when it did not. The code is one of the provider's fixed lowercase names
|
||||
* (`connected`, `authorization_denied`). It is shown as words after the section's own label;
|
||||
* anything else on the address is ignored, so a link cannot put its own sentence on the page.
|
||||
* @param params - The page's query string.
|
||||
* @returns The outcome, or `null` when the address reports none.
|
||||
*/
|
||||
export function sectionOutcome(params: URLSearchParams): SectionOutcome | null {
|
||||
const section = params.get('section')
|
||||
const error = params.get('error')
|
||||
const code = error ?? params.get('result')
|
||||
if (!section || !code || !/^[a-z]+(?:_[a-z]+){0,7}$/.test(code)) return null
|
||||
return { section, failed: error !== null, words: code.replace(/_/g, ' ') }
|
||||
}
|
||||
|
||||
/** Every registered section and a client-only Display section, selected through the URL.
|
||||
* @returns Preferences navigation and selected section.
|
||||
*/
|
||||
@@ -84,13 +59,6 @@ export function PreferencesPage() {
|
||||
})
|
||||
// A client-only key cannot collide with the backend's [a-z] section names.
|
||||
const requested = params.get('section')
|
||||
const [outcome, setOutcome] = useState(() => sectionOutcome(params))
|
||||
const reported = params.has('result') || params.has('error')
|
||||
// An outcome is reported once: off the address it goes, so a reload does not repeat it.
|
||||
useEffect(() => {
|
||||
if (reported && requested)
|
||||
router.replace(`/app/preferences?section=${encodeURIComponent(requested)}`, { scroll: false })
|
||||
}, [reported, requested, router])
|
||||
const selected =
|
||||
requested === 'display' && !query.data?.sections.some((section) => section.name === 'display')
|
||||
? '__display'
|
||||
@@ -105,15 +73,13 @@ export function PreferencesPage() {
|
||||
...(query.data?.sections ?? []),
|
||||
]
|
||||
const section = query.data?.sections.find((section) => section.name === selected)
|
||||
const navigate = (name: string) => {
|
||||
setOutcome(null)
|
||||
const navigate = (name: string) =>
|
||||
router.replace(
|
||||
name === '__display'
|
||||
? '/app/preferences'
|
||||
: `/app/preferences?section=${encodeURIComponent(name)}`,
|
||||
{ scroll: false }
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-7xl space-y-6" data-qqq-id="preferences-page">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Preferences</h1>
|
||||
@@ -193,20 +159,6 @@ export function PreferencesPage() {
|
||||
<PreferencesSkeleton />
|
||||
) : section ? (
|
||||
<>
|
||||
{outcome?.section === section.name && (
|
||||
<p
|
||||
role={outcome.failed ? 'alert' : 'status'}
|
||||
className={cn(
|
||||
'rounded-md border p-3 text-sm',
|
||||
outcome.failed
|
||||
? 'border-destructive text-destructive'
|
||||
: 'border-border bg-muted text-foreground'
|
||||
)}
|
||||
data-qqq-id="preferences-section-outcome"
|
||||
>
|
||||
{`${section.label}: ${outcome.words}.`}
|
||||
</p>
|
||||
)}
|
||||
<PreferenceSectionForm key={section.name} section={section} />
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DeliveredFileActions } from './DeliveredFileActions'
|
||||
import * as delivery from '@/lib/api/attachment-download'
|
||||
|
||||
vi.mock('@/lib/api/attachment-download', () => ({ fetchTrackedAttachment: vi.fn(), safeAttachmentPreviewBlob: vi.fn(), saveAttachmentDownload: vi.fn() }))
|
||||
vi.mock('./FilePreviewLightbox', () => ({ FilePreviewLightbox: ({ items, onClose }: { items: { url: string }[]; onClose: () => void }) =>
|
||||
<div role="dialog"><span>{items[0].url}</span><button onClick={onClose}>Close preview</button></div> }))
|
||||
const URL_VALUE = 'https://api.example/credential-bound-transfer'
|
||||
|
||||
describe('metadata authenticated delivery', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('URL', Object.assign(class extends URL {}, { createObjectURL: vi.fn(() => 'blob:verified'), revokeObjectURL: vi.fn() }))
|
||||
vi.mocked(delivery.fetchTrackedAttachment).mockResolvedValue(new Blob(['verified']))
|
||||
vi.mocked(delivery.safeAttachmentPreviewBlob).mockResolvedValue(new Blob(['%PDF-1.7'], { type: 'application/pdf' }))
|
||||
vi.mocked(delivery.saveAttachmentDownload).mockResolvedValue()
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('never renders an authenticated capability in href/src and verifies only on request', async () => {
|
||||
const result = render(<DeliveredFileActions url={URL_VALUE} fileName="Packing.pdf" allowPreview dataQqqId="delivery" />)
|
||||
expect(delivery.fetchTrackedAttachment).not.toHaveBeenCalled()
|
||||
expect(result.container.querySelector('a, img, iframe')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview file' }))
|
||||
await screen.findByRole('dialog')
|
||||
expect(delivery.fetchTrackedAttachment).toHaveBeenCalledWith(URL_VALUE, expect.any(AbortSignal))
|
||||
expect(delivery.safeAttachmentPreviewBlob).toHaveBeenCalledWith(expect.any(Blob))
|
||||
expect(screen.getByRole('dialog')).toHaveTextContent('blob:verified')
|
||||
expect(result.container.innerHTML).not.toContain(URL_VALUE)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close preview' }))
|
||||
await waitFor(() => expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:verified'))
|
||||
})
|
||||
|
||||
it('shows receipt refusal and never opens a preview', async () => {
|
||||
vi.mocked(delivery.fetchTrackedAttachment).mockRejectedValue(new Error('No durable receipt'))
|
||||
render(<DeliveredFileActions url={URL_VALUE} fileName="Packing.pdf" allowPreview dataQqqId="delivery" />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview file' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('No durable receipt')
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves through the shared receipt gate and does not invent a plain link fallback', async () => {
|
||||
vi.mocked(delivery.saveAttachmentDownload).mockRejectedValue(new Error('Access revoked'))
|
||||
const result = render(<DeliveredFileActions url={URL_VALUE} fileName="Label.zpl" allowPreview={false} dataQqqId="delivery" />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Download file' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Access revoked')
|
||||
expect(delivery.saveAttachmentDownload).toHaveBeenCalledWith({ url: URL_VALUE, delivery: 'AUTHENTICATED_FETCH' }, 'Label.zpl', expect.any(AbortSignal))
|
||||
expect(result.container.querySelector('a')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Preview file' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not allocate a blob when its view unmounts during verification', async () => {
|
||||
let finish!: (blob: Blob) => void
|
||||
vi.mocked(delivery.fetchTrackedAttachment).mockReturnValue(new Promise((resolve) => { finish = resolve }))
|
||||
const result = render(<DeliveredFileActions url={URL_VALUE} fileName="Packing.pdf" allowPreview dataQqqId="delivery" />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview file' }))
|
||||
const signal = vi.mocked(delivery.fetchTrackedAttachment).mock.calls[0][1]
|
||||
result.unmount(); finish(new Blob(['verified']))
|
||||
await waitFor(() => expect(signal?.aborted).toBe(true))
|
||||
expect(delivery.safeAttachmentPreviewBlob).not.toHaveBeenCalled()
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,42 +0,0 @@
|
||||
/* Copyright 2026 QRun.IO, Inc. Licensed under the Apache License, Version 2.0. */
|
||||
import React from 'react'
|
||||
import { Blob as NodeBlob } from 'node:buffer'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { DeliveredFileActions } from './DeliveredFileActions'
|
||||
|
||||
vi.mock('@/lib/api/client', () => ({ default: { get: vi.fn(), getInstance: () => ({ defaults: { baseURL: 'https://api.example/qqq/v1' } }) } }))
|
||||
vi.mock('./FilePreviewLightbox', () => ({ FilePreviewLightbox: () => <div role="dialog" /> }))
|
||||
const url = 'https://api.example/qqq/v1/qbit/record-files/files/12/downloads/10000000-0000-0000-0000-000000000001'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
vi.stubGlobal('Blob', NodeBlob)
|
||||
vi.stubGlobal('URL', Object.assign(class extends URL {}, { createObjectURL: vi.fn(), revokeObjectURL: vi.fn() }))
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it.each(['unmount', 'source change'])('aborts an actual deferred receipt on %s without creating a preview', async (change) => {
|
||||
let receiptSignal: AbortSignal | undefined
|
||||
let rejectReceipt!: (error: Error) => void
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce(new Blob(['%PDF-1.7\nfixture'])).mockImplementationOnce((_route, options) => {
|
||||
receiptSignal = options?.signal as AbortSignal
|
||||
return new Promise((_resolve, reject) => {
|
||||
rejectReceipt = reject
|
||||
receiptSignal?.addEventListener('abort', () => reject(new DOMException('Cancelled', 'AbortError')), { once: true })
|
||||
})
|
||||
})
|
||||
const view = render(<DeliveredFileActions url={url} fileName="packing.pdf" allowPreview dataQqqId="delivery" />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview file' }))
|
||||
await waitFor(() => expect(apiClient.get).toHaveBeenCalledTimes(2))
|
||||
expect(vi.mocked(apiClient.get).mock.calls[1][0]).toMatch(/\/receipt$/)
|
||||
expect(receiptSignal?.aborted).toBe(false)
|
||||
if (change === 'unmount') view.unmount()
|
||||
else view.rerender(<DeliveredFileActions url={url.replace('/12/', '/13/')} fileName="other.pdf" allowPreview dataQqqId="delivery" />)
|
||||
await waitFor(() => expect(receiptSignal?.aborted).toBe(true))
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
rejectReceipt(new Error('Late response cannot revive the preview'))
|
||||
})
|
||||
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Receipt-gated actions for metadata-declared authenticated file delivery. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { fetchTrackedAttachment, safeAttachmentPreviewBlob, saveAttachmentDownload } from '@/lib/api/attachment-download'
|
||||
import { getErrorMessage } from '@/lib/utils/error-utils'
|
||||
import { kindOfMimeType, type FilePreviewItem } from '@/lib/utils/file-preview'
|
||||
import { FilePreviewLightbox } from './FilePreviewLightbox'
|
||||
|
||||
/** Props supplied by generic FILE_DOWNLOAD field metadata. */
|
||||
interface Props {
|
||||
url: string
|
||||
fileName: string
|
||||
allowPreview: boolean
|
||||
dataQqqId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated URLs are never href/src values. Only verified inert blobs can preview.
|
||||
* @param props - Current authorized delivery and display-only name.
|
||||
* @returns Explicit download/preview controls and any visible audit failure.
|
||||
*/
|
||||
export function DeliveredFileActions({ url, fileName, allowPreview, dataQqqId }: Props) {
|
||||
const [pending, setPending] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [preview, setPreview] = useState<FilePreviewItem>()
|
||||
const alive = useRef(true)
|
||||
const activeOperation = useRef<AbortController | undefined>(undefined)
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
setPreview(undefined); setPending(false); setError(undefined)
|
||||
return () => { alive.current = false; activeOperation.current?.abort() }
|
||||
}, [url])
|
||||
useEffect(() => () => { if (preview) URL.revokeObjectURL(preview.url) }, [preview])
|
||||
|
||||
/** Download always goes through the existing authenticated receipt verifier.
|
||||
* @param signal - Current operation lifetime, including source changes/unmount.
|
||||
*/
|
||||
async function download(signal: AbortSignal) {
|
||||
await saveAttachmentDownload({ url, delivery: 'AUTHENTICATED_FETCH' }, fileName, signal)
|
||||
}
|
||||
|
||||
/** Load an authorized bounded body, then restrict preview to verified raster/PDF.
|
||||
* @param signal - Current operation lifetime, including source changes/unmount.
|
||||
*/
|
||||
async function openPreview(signal: AbortSignal) {
|
||||
const original = await fetchTrackedAttachment(url, signal)
|
||||
signal.throwIfAborted()
|
||||
const blob = await safeAttachmentPreviewBlob(original)
|
||||
signal.throwIfAborted()
|
||||
if (!alive.current) return
|
||||
setPreview({ url: URL.createObjectURL(blob), fileName, mimeType: blob.type, kind: kindOfMimeType(blob.type),
|
||||
alt: fileName, sizeBytes: blob.size, previewable: true, thumbnailSize: 160 })
|
||||
}
|
||||
|
||||
/** Keep all failures visible; an audit failure never becomes an ordinary link.
|
||||
* @param action - Receipt-gated operation selected by the user.
|
||||
*/
|
||||
async function perform(action: (signal: AbortSignal) => Promise<void>) {
|
||||
activeOperation.current?.abort()
|
||||
const controller = new AbortController()
|
||||
activeOperation.current = controller
|
||||
setPending(true); setError(undefined)
|
||||
try { await action(controller.signal) }
|
||||
catch (failure) {
|
||||
if (alive.current && activeOperation.current === controller && !controller.signal.aborted) setError(getErrorMessage(failure))
|
||||
throw failure
|
||||
} finally {
|
||||
if (activeOperation.current === controller) {
|
||||
activeOperation.current = undefined
|
||||
if (alive.current) setPending(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return <span className="inline-flex flex-wrap items-center gap-2" data-qqq-id={dataQqqId}>
|
||||
<span>{fileName}</span>
|
||||
<button type="button" className="text-link underline disabled:opacity-50 pointer-coarse:inline-flex pointer-coarse:min-h-11 pointer-coarse:items-center" disabled={pending}
|
||||
data-qqq-id={dataQqqId + '-download'} onClick={() => { void perform(download).catch(() => {}) }}>Download file</button>
|
||||
{allowPreview && <button type="button" className="text-link underline disabled:opacity-50 pointer-coarse:inline-flex pointer-coarse:min-h-11 pointer-coarse:items-center" disabled={pending}
|
||||
data-qqq-id={dataQqqId + '-preview'} onClick={() => { void perform(openPreview).catch(() => {}) }}>Preview file</button>}
|
||||
{pending && <span role="status">Verifying file delivery…</span>}
|
||||
{error && <span role="alert" className="text-destructive">{error}</span>}
|
||||
{preview && <FilePreviewLightbox items={[preview]} index={0} onIndexChange={() => {}} onClose={() => setPreview(undefined)} onDownload={() => perform(download)} />}
|
||||
</span>
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
@@ -29,8 +29,6 @@ import { FileThumbnail } from './FileThumbnail'
|
||||
import { FilePreviewLightbox } from './FilePreviewLightbox'
|
||||
import type { FilePreviewItem } from '@/lib/utils/file-preview'
|
||||
|
||||
vi.mock('./PdfPreview', () => ({ PdfPreview: ({ url }: { url: string }) => <div data-qqq-id="file-preview-pdf" data-source={url} /> }))
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
|
||||
function field(name: string, values: Record<string, unknown> = {}, extra: Partial<QFieldMetaData> = {}): QFieldMetaData {
|
||||
@@ -141,9 +139,7 @@ describe('FilePreviewGallery', () => {
|
||||
await user.keyboard('{ArrowRight}')
|
||||
expect(within(dialog).getByRole('heading', { name: 'two.pdf' })).toBeInTheDocument()
|
||||
expect(dialog).toHaveAttribute('data-preview-kind', 'pdf')
|
||||
await waitFor(() => expect(document.querySelector('[data-qqq-id="file-preview-pdf"]')).toHaveAttribute('data-source', '/qqq/v1/table/media/2/blob/two.pdf'))
|
||||
expect(document.querySelector('iframe')).toBeNull()
|
||||
expect(document.querySelector('[data-qqq-id="file-preview-open"]')).toBeNull()
|
||||
expect(document.querySelector('[data-qqq-id="file-preview-pdf"]')).toHaveAttribute('src', '/qqq/v1/table/media/2/blob/two.pdf')
|
||||
|
||||
await user.keyboard('{End}')
|
||||
expect(within(dialog).getByText('3 of 3')).toBeInTheDocument()
|
||||
@@ -186,21 +182,6 @@ describe('FilePreviewGallery', () => {
|
||||
})
|
||||
|
||||
describe('FilePreviewLightbox', () => {
|
||||
it('uses the authorized callback and never falls back to its preview URL on failure', async () => {
|
||||
let reject!: (reason: Error) => void
|
||||
const download = vi.fn(() => new Promise<void>((_resolve, rejectPromise) => { reject = rejectPromise }))
|
||||
const file = item()
|
||||
render(<FilePreviewLightbox items={[file]} index={0} onIndexChange={() => undefined} onClose={() => undefined} onDownload={download} />)
|
||||
const button = screen.getByRole('button', { name: 'Download a.png' })
|
||||
fireEvent.click(button)
|
||||
expect(download).toHaveBeenCalledWith(file)
|
||||
expect(button).toBeDisabled()
|
||||
expect(button).not.toHaveAttribute('href')
|
||||
await act(async () => reject(new Error('Audit unavailable')))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Could not authorize this download')
|
||||
await waitFor(() => expect(button).not.toBeDisabled())
|
||||
expect(button).not.toHaveAttribute('href')
|
||||
})
|
||||
function show(items: FilePreviewItem[], index = 0) {
|
||||
const onIndexChange = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
@@ -267,13 +248,13 @@ describe('FilePreviewLightbox', () => {
|
||||
it('does not frame a PDF from another origin', () => {
|
||||
show([item({ kind: 'pdf', mimeType: 'application/pdf', fileName: 'c.pdf', url: 'https://elsewhere.example/c.pdf' })])
|
||||
expect(document.querySelector('[data-qqq-id="file-preview-pdf"]')).toBeNull()
|
||||
expect(screen.getByText(/trusted file preview source/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/opens in a new tab instead/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('frames only backend file paths, not other pages of this origin', () => {
|
||||
show([item({ kind: 'pdf', mimeType: 'application/pdf', fileName: 'd.pdf', url: '/app/media/1' })])
|
||||
expect(document.querySelector('[data-qqq-id="file-preview-pdf"]')).toBeNull()
|
||||
expect(screen.getByText(/trusted file preview source/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/not a file served by the application/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('plays video and audio, falling back when the player cannot load them', () => {
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { lazy, Suspense, useCallback, useEffect, useState } from 'react'
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import * as Dialog from '@radix-ui/react-dialog'
|
||||
import { ChevronLeft, ChevronRight, Download, ExternalLink, Maximize2, X, ZoomIn, ZoomOut } from 'lucide-react'
|
||||
|
||||
@@ -31,12 +31,9 @@ import type { FilePreviewItem } from '@/lib/utils/file-preview'
|
||||
import { apiUrl } from '@/lib/api/client'
|
||||
import { attachmentUrl } from '@/lib/utils/adornment-utils'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { formatBytes } from '@/lib/utils/file-preview'
|
||||
import { formatBytes, isBackendFileUrl, isSameOrigin } from '@/lib/utils/file-preview'
|
||||
import { useRestoreFocus } from '@/lib/hooks/use-restore-focus'
|
||||
import { FileKindIcon } from './FileKindIcon'
|
||||
import { pdfPreviewSource } from '@/lib/api/pdf-preview'
|
||||
|
||||
const PdfPreview = lazy(() => import('./PdfPreview').then((module) => ({ default: module.PdfPreview })))
|
||||
|
||||
/** Zoom steps of an image preview (1 = fit to the window). */
|
||||
export const ZOOM_STEPS = [1, 1.5, 2, 3, 4]
|
||||
@@ -51,8 +48,6 @@ export interface FilePreviewLightboxProps {
|
||||
onIndexChange: (index: number) => void
|
||||
/** Called when the preview closes. */
|
||||
onClose: () => void
|
||||
/** Authorizes a fresh download; when supplied, the preview URL is never used to download. */
|
||||
onDownload?: (item: FilePreviewItem) => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,7 +58,7 @@ export interface FilePreviewLightboxProps {
|
||||
* @param props - See {@link FilePreviewLightboxProps}.
|
||||
* @returns The dialog.
|
||||
*/
|
||||
export function FilePreviewLightbox({ items, index, onIndexChange, onClose, onDownload }: FilePreviewLightboxProps) {
|
||||
export function FilePreviewLightbox({ items, index, onIndexChange, onClose }: FilePreviewLightboxProps) {
|
||||
const restoreFocus = useRestoreFocus(true)
|
||||
const item = items[Math.min(Math.max(index, 0), items.length - 1)]
|
||||
const count = items.length
|
||||
@@ -161,7 +156,7 @@ export function FilePreviewLightbox({ items, index, onIndexChange, onClose, onDo
|
||||
<ToolbarButton label="Zoom in" onClick={() => zoomBy(1)} disabled={zoom >= ZOOM_STEPS[ZOOM_STEPS.length - 1]} id="zoom-in"><ZoomIn className="h-4 w-4" aria-hidden="true" /></ToolbarButton>
|
||||
</>
|
||||
)}
|
||||
<FileActions key={item.url} item={item} onDownload={onDownload} />
|
||||
<FileActions item={item} />
|
||||
<Dialog.Close asChild>
|
||||
<button type="button" aria-label="Close preview" data-qqq-id="file-preview-close"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
@@ -251,10 +246,15 @@ function PreviewStage({ item, zoom, failed, onFailed, onNaturalSize, onToggleZoo
|
||||
}
|
||||
|
||||
if (item.kind === 'pdf') {
|
||||
try { pdfPreviewSource(item.url) } catch {
|
||||
return <Unavailable item={item} reason="This PDF is not available through a trusted file preview source." />
|
||||
// frames are limited to the dashboard's own origin by its Content-Security-Policy, and within
|
||||
// it to backend file paths, so a stored URL cannot frame another page of the dashboard
|
||||
if (!isSameOrigin(item.url)) {
|
||||
return <Unavailable item={item} reason="This PDF is on another site, so it opens in a new tab instead of here." />
|
||||
}
|
||||
return <Suspense fallback={<p role="status" className="p-4">Loading PDF viewer…</p>}><PdfPreview key={item.url} url={item.url} fileName={item.fileName} /></Suspense>
|
||||
if (!isBackendFileUrl(item.url)) {
|
||||
return <Unavailable item={item} reason="This PDF is not a file served by the application, so it opens in a new tab instead of here." />
|
||||
}
|
||||
return <iframe src={item.url} title={item.fileName} className="absolute inset-0 h-full w-full border-0 bg-white" data-qqq-id="file-preview-pdf" />
|
||||
}
|
||||
|
||||
if (item.kind === 'video') {
|
||||
@@ -297,9 +297,7 @@ function Unavailable({ item, reason }: { item: FilePreviewItem; reason: string }
|
||||
* @param props - The item.
|
||||
* @returns The links.
|
||||
*/
|
||||
function FileActions({ item, onDownload }: { item: FilePreviewItem; onDownload?: (item: FilePreviewItem) => Promise<void> }) {
|
||||
const [pending, setPending] = useState(false)
|
||||
const [error, setError] = useState(false)
|
||||
function FileActions({ item }: { item: FilePreviewItem }) {
|
||||
if (!item.url) return null
|
||||
// backend field downloads honour ?download=1; other URLs rely on the download attribute (same origin)
|
||||
const backendFile = item.url.startsWith(apiUrl('/table/'))
|
||||
@@ -307,32 +305,14 @@ function FileActions({ item, onDownload }: { item: FilePreviewItem; onDownload?:
|
||||
const linkClass = 'inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'
|
||||
return (
|
||||
<>
|
||||
{item.kind !== 'pdf' && <a href={item.url} target="_blank" rel="noopener noreferrer" className={linkClass} title="Open original" data-qqq-id="file-preview-open">
|
||||
<a href={item.url} target="_blank" rel="noopener noreferrer" className={linkClass} title="Open original" data-qqq-id="file-preview-open">
|
||||
<ExternalLink className="h-4 w-4" aria-hidden="true" />
|
||||
<span className="sr-only">Open original (opens in a new tab)</span>
|
||||
</a>}
|
||||
{onDownload ? (
|
||||
<button type="button" disabled={pending} aria-busy={pending} className={cn(linkClass, 'disabled:opacity-50')}
|
||||
title="Download" data-qqq-id="file-preview-download"
|
||||
onClick={async () => {
|
||||
setPending(true)
|
||||
setError(false)
|
||||
try {
|
||||
await onDownload(item)
|
||||
} catch {
|
||||
setError(true)
|
||||
} finally {
|
||||
setPending(false)
|
||||
}
|
||||
}}>
|
||||
<Download className="h-4 w-4" aria-hidden="true" />
|
||||
<span className="sr-only">{pending ? 'Preparing download' : `Download ${item.fileName}`}</span>
|
||||
</button>
|
||||
) : <a href={downloadHref} download={item.fileName} className={linkClass} title="Download" data-qqq-id="file-preview-download">
|
||||
</a>
|
||||
<a href={downloadHref} download={item.fileName} className={linkClass} title="Download" data-qqq-id="file-preview-download">
|
||||
<Download className="h-4 w-4" aria-hidden="true" />
|
||||
<span className="sr-only">Download {item.fileName}</span>
|
||||
</a>}
|
||||
{error && <p role="alert" className="max-w-xs text-xs text-destructive">Could not authorize this download. Please try again.</p>}
|
||||
</a>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, afterEach, expect, it, vi } from 'vitest'
|
||||
import { PdfPreview } from './PdfPreview'
|
||||
const mocks = vi.hoisted(() => ({ load: vi.fn(), getDocument: vi.fn(), create: vi.fn(), terminate: vi.fn(), destroy: vi.fn(), render: vi.fn(), cancel: vi.fn(), reader: vi.fn(), cleanup: vi.fn() }))
|
||||
vi.mock('@/lib/api/pdf-preview', () => ({ loadPdfPreviewBytes: mocks.load, PDF_PAGE_LIMIT: 1000, PDF_PIXEL_LIMIT: 8_000_000 }))
|
||||
vi.mock('pdfjs-dist', () => ({ PDFWorker: { create: mocks.create }, getDocument: mocks.getDocument }))
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('Worker', class { terminate = mocks.terminate })
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as CanvasRenderingContext2D)
|
||||
mocks.load.mockResolvedValue(new Uint8Array([1]))
|
||||
mocks.destroy.mockResolvedValue(undefined)
|
||||
mocks.render.mockReturnValue({ promise: Promise.resolve(), cancel: mocks.cancel })
|
||||
mocks.reader.mockImplementation(() => {
|
||||
let read = false
|
||||
return { read: async () => read ? { done: true } : (read = true, { done: false, value: { items: [{ str: '<script>inert page text</script>' }] } }), cancel: async () => {}, releaseLock: () => {} }
|
||||
})
|
||||
mocks.getDocument.mockReturnValue({ destroy: mocks.destroy, promise: Promise.resolve({ numPages: 2, getPage: async () => ({
|
||||
getViewport: ({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale }),
|
||||
render: mocks.render, cleanup: mocks.cleanup, streamTextContent: () => ({ getReader: mocks.reader }),
|
||||
}) }) })
|
||||
})
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
|
||||
it('renders pixels and inert text with explicit worker/data-only policy, then cancels on close', async () => {
|
||||
const user = userEvent.setup()
|
||||
const view = render(<PdfPreview url="blob:http://localhost/fixture" fileName="Packing slip.pdf" />)
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled())
|
||||
expect(mocks.getDocument).toHaveBeenCalledWith(expect.objectContaining({ data: expect.any(Uint8Array), useWorkerFetch: false, useWasm: false, enableXfa: false, maxImageSize: 8_000_000 }))
|
||||
expect(mocks.getDocument.mock.calls[0][0].url).toBeUndefined()
|
||||
expect(mocks.render).toHaveBeenCalledWith(expect.objectContaining({ annotationMode: 0 }))
|
||||
await waitFor(() => expect(mocks.cleanup).toHaveBeenCalledTimes(1))
|
||||
expect(document.querySelector('iframe,object,embed,script')).toBeNull()
|
||||
await waitFor(() => expect(screen.getByText('<script>inert page text</script>')).toBeInTheDocument())
|
||||
await user.click(screen.getByRole('button', { name: 'Next page' }))
|
||||
await waitFor(() => expect(screen.getByRole('img')).toHaveAccessibleName('Packing slip.pdf, page 2'))
|
||||
view.unmount()
|
||||
expect(mocks.terminate).toHaveBeenCalled()
|
||||
expect(mocks.destroy).toHaveBeenCalled()
|
||||
})
|
||||
it('starts the packaged worker from a .js URL, because hosts serve .mjs as application/octet-stream and module workers refuse it', async () => {
|
||||
const urls: string[] = []
|
||||
vi.stubGlobal('Worker', class { terminate = mocks.terminate; constructor(url: string) { urls.push(url) } })
|
||||
render(<PdfPreview url="blob:http://localhost/fixture" fileName="Packing slip.pdf" />)
|
||||
await waitFor(() => expect(urls).toHaveLength(1))
|
||||
expect(urls[0]).toMatch(/^\/pdf-generated\/pdf-[\d.]+\.worker\.js$/)
|
||||
})
|
||||
it('rejects page counts outside the bound without rendering', async () => {
|
||||
mocks.getDocument.mockReturnValue({ destroy: mocks.destroy, promise: Promise.resolve({ numPages: 1001 }) })
|
||||
render(<PdfPreview url="blob:http://localhost/fixture" fileName="Huge.pdf" />)
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('preview limits')
|
||||
expect(mocks.render).not.toHaveBeenCalled()
|
||||
expect(mocks.terminate).toHaveBeenCalled()
|
||||
})
|
||||
it('stops before starting a parser when closed during input loading', async () => {
|
||||
let resolve!: (bytes: Uint8Array) => void
|
||||
mocks.load.mockImplementation(() => new Promise<Uint8Array>((done) => { resolve = done }))
|
||||
const view = render(<PdfPreview url="blob:http://localhost/fixture" fileName="Slow.pdf" />)
|
||||
view.unmount(); resolve(new Uint8Array([1]))
|
||||
await new Promise((done) => setTimeout(done, 0))
|
||||
expect(mocks.getDocument).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('bounds streamed text before materializing a full page string', async () => {
|
||||
const reader = { read: vi.fn().mockResolvedValue({ done: false, value: { items: [{ str: 'x'.repeat(200_000) }] } }), cancel: vi.fn().mockResolvedValue(undefined), releaseLock: vi.fn() }
|
||||
mocks.reader.mockReturnValue(reader)
|
||||
render(<PdfPreview url="blob:http://localhost/fixture" fileName="Text.pdf" />)
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled())
|
||||
expect(reader.read).toHaveBeenCalledTimes(1)
|
||||
expect(reader.cancel).toHaveBeenCalled()
|
||||
expect(document.querySelector('details p')?.textContent?.length).toBe(100_000)
|
||||
})
|
||||
it('keeps navigation busy during text transfer and cancels that transfer on close', async () => {
|
||||
let finish!: (value: { done: boolean }) => void
|
||||
const reader = { read: vi.fn(() => new Promise<{ done: boolean }>((resolve) => { finish = resolve })), cancel: vi.fn(async () => { finish({ done: true }) }), releaseLock: vi.fn() }
|
||||
mocks.reader.mockReturnValue(reader)
|
||||
const view = render(<PdfPreview url="blob:http://localhost/fixture" fileName="Text.pdf" />)
|
||||
await waitFor(() => expect(reader.read).toHaveBeenCalled())
|
||||
expect(screen.getByRole('button', { name: 'Next page' })).toBeDisabled()
|
||||
view.unmount()
|
||||
await waitFor(() => expect(reader.cancel).toHaveBeenCalled())
|
||||
expect(mocks.terminate).toHaveBeenCalled()
|
||||
})
|
||||
@@ -1,148 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Canvas-only PDF pages with a real parser worker, bounded resources and no document actions. */
|
||||
'use client'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { PDFDocumentProxy, PDFDocumentLoadingTask, PDFPageProxy, RenderTask } from 'pdfjs-dist'
|
||||
import { loadPdfPreviewBytes, PDF_PAGE_LIMIT, PDF_PIXEL_LIMIT } from '@/lib/api/pdf-preview'
|
||||
|
||||
/** No document-selected auxiliary URL is fetched by the main thread. */
|
||||
class NoExternalPdfData {
|
||||
/** Reject an auxiliary request instead of resolving any document-selected URL.
|
||||
* @returns A rejected resource request.
|
||||
*/
|
||||
async fetch(): Promise<Uint8Array> { throw new Error('External PDF resources are disabled') }
|
||||
}
|
||||
|
||||
/** Render a PDF as pixels/text only; the browser never navigates to the uploaded content.
|
||||
* @param props - Authorized source URL and accessible document name.
|
||||
* @returns Bounded page controls, canvas and optional plain text.
|
||||
*/
|
||||
export function PdfPreview({ url, fileName }: { url: string; fileName: string }) {
|
||||
const canvas = useRef<HTMLCanvasElement>(null)
|
||||
const [document, setDocument] = useState<PDFDocumentProxy | null>(null)
|
||||
const [page, setPage] = useState(1)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [error, setError] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [text, setText] = useState('')
|
||||
const workerRef = useRef<Worker | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const abort = new AbortController()
|
||||
let task: PDFDocumentLoadingTask | undefined
|
||||
let worker: Worker | undefined
|
||||
let disposed = false
|
||||
setDocument(null); setPage(1); setError(false); setBusy(true)
|
||||
const timeout = setTimeout(() => { abort.abort(); worker?.terminate(); if (!disposed) { setError(true); setBusy(false) } }, 30_000)
|
||||
void (async () => {
|
||||
const bytes = await loadPdfPreviewBytes(url, abort.signal)
|
||||
const pdf = await import('pdfjs-dist')
|
||||
abort.signal.throwIfAborted()
|
||||
// Supplying a real port avoids PDF.js's main-thread fake-worker fallback.
|
||||
worker = new Worker('/pdf-generated/pdf-6.4.299.worker.js', { type: 'module', name: 'qqq-pdf-preview' })
|
||||
workerRef.current = worker
|
||||
const parser = pdf.PDFWorker.create({ port: worker })
|
||||
task = pdf.getDocument({ data: bytes, worker: parser, enableXfa: false,
|
||||
useWorkerFetch: false, useWasm: false, BinaryDataFactory: NoExternalPdfData,
|
||||
disableAutoFetch: true, disableRange: true, disableStream: true,
|
||||
maxImageSize: PDF_PIXEL_LIMIT, canvasMaxAreaInBytes: PDF_PIXEL_LIMIT * 4,
|
||||
disableFontFace: true, useSystemFonts: true, stopAtErrors: true, verbosity: 0,
|
||||
})
|
||||
const loaded = await task.promise
|
||||
if (loaded.numPages < 1 || loaded.numPages > PDF_PAGE_LIMIT) throw new Error('PDF page limit exceeded')
|
||||
if (!disposed && !abort.signal.aborted) setDocument(loaded)
|
||||
})().catch(() => { if (!disposed) { setError(true); setBusy(false); worker?.terminate() } }).finally(() => clearTimeout(timeout))
|
||||
return () => {
|
||||
disposed = true; abort.abort(); clearTimeout(timeout)
|
||||
worker?.terminate(); workerRef.current = null
|
||||
void task?.destroy().catch(() => {})
|
||||
}
|
||||
}, [url])
|
||||
|
||||
useEffect(() => {
|
||||
if (!document || !canvas.current || error) return
|
||||
let disposed = false
|
||||
let render: RenderTask | undefined
|
||||
let loadedPage: PDFPageProxy | undefined
|
||||
let cancelText: (() => void) | undefined
|
||||
setBusy(true); setText('')
|
||||
const target = canvas.current
|
||||
const timeout = setTimeout(() => { render?.cancel(); cancelText?.(); workerRef.current?.terminate(); if (!disposed) { setError(true); setBusy(false) } }, 15_000)
|
||||
void (async () => {
|
||||
const pdfPage = await document.getPage(page)
|
||||
loadedPage = pdfPage
|
||||
if (disposed) return
|
||||
const natural = pdfPage.getViewport({ scale: 1 })
|
||||
if (!Number.isFinite(natural.width * natural.height) || natural.width <= 0 || natural.height <= 0) throw new Error('Invalid page size')
|
||||
const desired = Math.min(2, window.devicePixelRatio || 1) * zoom * Math.min(1.5, 1000 / natural.width)
|
||||
const scale = Math.min(desired, 8192 / natural.width, 8192 / natural.height, Math.sqrt(PDF_PIXEL_LIMIT / (natural.width * natural.height)))
|
||||
const viewport = pdfPage.getViewport({ scale })
|
||||
target.width = Math.max(1, Math.floor(viewport.width)); target.height = Math.max(1, Math.floor(viewport.height))
|
||||
const context = target.getContext('2d', { alpha: false })
|
||||
if (!context) throw new Error('Canvas unavailable')
|
||||
// No annotation, form, action, link, HTML or scripting layer is created.
|
||||
render = pdfPage.render({ canvas: target, canvasContext: context, viewport, annotationMode: 0 })
|
||||
await render.promise
|
||||
if (disposed) return
|
||||
const reader = pdfPage.streamTextContent().getReader()
|
||||
cancelText = () => { void reader.cancel().catch(() => {}) }
|
||||
const parts: string[] = []
|
||||
let characters = 0
|
||||
let items = 0
|
||||
try {
|
||||
while (!disposed && characters < 100_000 && items < 10_000) {
|
||||
const chunk = await reader.read()
|
||||
if (chunk.done || disposed) break
|
||||
for (const item of chunk.value.items) {
|
||||
if (++items > 10_000 || characters >= 100_000) break
|
||||
if ('str' in item) {
|
||||
const part = item.str.slice(0, 100_000 - characters)
|
||||
parts.push(part); characters += part.length + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {})
|
||||
reader.releaseLock()
|
||||
}
|
||||
if (!disposed) { setText(parts.join(' ')); setBusy(false) }
|
||||
})().catch(() => { if (!disposed) { setError(true); setBusy(false) } }).finally(() => {
|
||||
clearTimeout(timeout)
|
||||
// PDF.js defers cleanup if a cancelled render still has pending work.
|
||||
loadedPage?.cleanup()
|
||||
})
|
||||
return () => { disposed = true; clearTimeout(timeout); render?.cancel(); cancelText?.() }
|
||||
}, [document, page, zoom, error])
|
||||
|
||||
const button = 'min-h-11 rounded border border-border px-3 disabled:opacity-50 focus-visible:ring-2 focus-visible:ring-ring'
|
||||
return <section className="absolute inset-0 flex flex-col" aria-label={'PDF preview: ' + fileName} data-qqq-id="file-preview-pdf">
|
||||
<div className="flex flex-wrap items-center gap-2 border-b border-border bg-card p-2" role="toolbar" aria-label="PDF page controls">
|
||||
<button type="button" className={button} disabled={!document || busy || error || page <= 1} onClick={() => setPage(page - 1)} data-qqq-id="pdf-previous">Previous page</button>
|
||||
<span role="status" aria-live="polite">{document ? 'Page ' + page + ' of ' + document.numPages : 'Loading PDF'}</span>
|
||||
<button type="button" className={button} disabled={!document || busy || error || page >= document.numPages} onClick={() => setPage(page + 1)} data-qqq-id="pdf-next">Next page</button>
|
||||
<button type="button" className={button} disabled={!document || busy || error || zoom <= 0.5} onClick={() => setZoom(zoom - 0.25)} data-qqq-id="pdf-zoom-out">Zoom out</button>
|
||||
<button type="button" className={button} disabled={!document || busy || error || zoom >= 2} onClick={() => setZoom(zoom + 0.25)} data-qqq-id="pdf-zoom-in">Zoom in</button>
|
||||
</div>
|
||||
{error ? <p role="alert" className="p-4">This PDF could not be safely previewed within the preview limits. Use Download to retain the original.</p>
|
||||
: <div className="min-h-0 flex-1 overflow-auto p-3" aria-busy={busy}>
|
||||
{busy && <p role="status">Rendering PDF page…</p>}
|
||||
<canvas ref={canvas} className="mx-auto max-w-full bg-white" role="img" aria-label={fileName + ', page ' + page} />
|
||||
<details className="mt-3 rounded border border-border bg-card p-3"><summary className="cursor-pointer" data-qqq-id="pdf-page-text">Page text</summary><p className="whitespace-pre-wrap">{text || 'No extractable text on this page.'}</p></details>
|
||||
</div>}
|
||||
</section>
|
||||
}
|
||||
@@ -56,10 +56,9 @@ export function HtmlComponent({ index }: HtmlComponentProps) {
|
||||
const raw = values[`${step.name}.html`]
|
||||
const html = useMemo(() => (typeof raw === 'string' && raw ? sanitizeProcessHtml(raw) : ''), [raw])
|
||||
if (!html) return null
|
||||
// links read as links: without it they inherit the text color and have no underline
|
||||
return (
|
||||
<div
|
||||
className="prose prose-sm max-w-none text-foreground [&_a]:text-link [&_a]:underline"
|
||||
className="prose prose-sm max-w-none text-foreground"
|
||||
data-qqq-id={`process-html-${index}`}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { QFieldMetaData, QFrontendStepMetaData, QProcessMetaData } from '@/types'
|
||||
import { processRecords } from '@/lib/api/processes'
|
||||
import { ProcessStepScreen } from './ProcessStepScreen'
|
||||
|
||||
vi.mock('@/lib/api/processes', async (original) => ({ ...await original<typeof import('@/lib/api/processes')>(), processRecords: vi.fn() }))
|
||||
const step: QFrontendStepMetaData = {
|
||||
name: 'order', label: 'Order files', components: [{ type: 'RECORD_LIST', values: { orderFieldName: 'orderedIds', identityFieldName: 'id' } }],
|
||||
recordListFields: [{ name: 'name', label: 'File', type: 'STRING', isRequired: false, isEditable: false, isHeavy: false, isHidden: false, adornments: [] } as QFieldMetaData],
|
||||
}
|
||||
const result: QFrontendStepMetaData = { name: 'done', label: 'Done', components: [] }
|
||||
const process: QProcessMetaData = { name: 'order', label: 'Order', tableName: '', isHidden: false, iconName: '', hasPermission: true, stepFlow: 'LINEAR', minInputRecords: 1, frontendSteps: [step, result] }
|
||||
/** Render the real process screen and collect submitted contributions.
|
||||
* @returns Submit spy.
|
||||
*/
|
||||
function mount() {
|
||||
const submit = vi.fn()
|
||||
render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<ProcessStepScreen processName="order" processMetaData={process} processUUID="run" step={step} steps={process.frontendSteps} values={{}}
|
||||
backStep={null} isWorking={false} onSubmit={submit} onBack={vi.fn()} onCancel={vi.fn()} onReturn={vi.fn()} />
|
||||
</QueryClientProvider>)
|
||||
return submit
|
||||
}
|
||||
beforeEach(() => { vi.resetAllMocks() })
|
||||
it('moves rows with keyboard controls and submits the complete identity order automatically', async () => {
|
||||
vi.mocked(processRecords).mockResolvedValue({ totalRecords: 2, records: [
|
||||
{ tableName: 'items', values: { id: 11, name: 'Front photo' } }, { tableName: 'items', values: { id: 22, name: 'BOL scan' } },
|
||||
] })
|
||||
const submit = mount()
|
||||
const user = userEvent.setup()
|
||||
const down = await screen.findByRole('button', { name: 'Move Front photo down' })
|
||||
expect(screen.getByRole('button', { name: 'Move Front photo up' })).toBeDisabled()
|
||||
down.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
expect(screen.getAllByRole('listitem')[0]).toHaveTextContent('BOL scan')
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Moved to position 2 of 2')
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
await user.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() => expect(submit).toHaveBeenCalledWith({ orderedIds: '22,11' }, undefined))
|
||||
})
|
||||
it('blocks submit when the complete identity set cannot be loaded', async () => {
|
||||
vi.mocked(processRecords).mockResolvedValue({ totalRecords: 2, records: [{ tableName: 'items', values: { id: 1, name: 'First' } }, { tableName: 'items', values: { id: 1, name: 'Duplicate' } }] })
|
||||
const submit = mount()
|
||||
await screen.findByRole('alert')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
expect(submit).not.toHaveBeenCalled()
|
||||
})
|
||||
it('loads all bounded pages before enabling ordering and never silently drops missing members', async () => {
|
||||
vi.mocked(processRecords).mockResolvedValueOnce({ totalRecords: 2, records: [{ tableName: 'items', values: { id: 1, name: 'First' } }] })
|
||||
.mockResolvedValueOnce({ totalRecords: 2, records: [] })
|
||||
const submit = mount()
|
||||
await screen.findByRole('alert')
|
||||
expect(processRecords).toHaveBeenCalledTimes(2)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
expect(submit).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/** @file Optional native record-list ordering, with bounded complete-set loading. */
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { QFrontendComponent, QRecord } from '@/types'
|
||||
import { processRecords } from '@/lib/api/processes'
|
||||
import { isRestricted } from '@/lib/utils/secured-data'
|
||||
import { recordCellText } from './RecordListComponent'
|
||||
import { useProcessStep, useSubmitContributor } from './ProcessStepContext'
|
||||
|
||||
/** Render a metadata-enabled ordering list; ordinary record lists stay unchanged.
|
||||
* @param props - Component metadata and index.
|
||||
* @returns Accessible up/down controls and submit contribution.
|
||||
*/
|
||||
export function OrderedRecordListComponent({ component, index }: { component: QFrontendComponent; index: number }) {
|
||||
const { step, processName, processUUID, tableVariant, isWorking } = useProcessStep()
|
||||
const [ordered, setOrdered] = useState<{ scope: string; records: QRecord[] } | null>(null)
|
||||
const [announcement, setAnnouncement] = useState('')
|
||||
const orderField = component.values?.orderFieldName
|
||||
const identityField = component.values?.identityFieldName
|
||||
const valid = typeof orderField === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(orderField) &&
|
||||
typeof identityField === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(identityField)
|
||||
const scope = JSON.stringify([processName, processUUID, step.name, tableVariant, identityField])
|
||||
const fields = (step.recordListFields ?? []).filter((field) => !field.isHidden && !isRestricted(field))
|
||||
const query = useQuery({
|
||||
queryKey: ['qqq', 'processOrderRecords', processName, processUUID, step.name, tableVariant, identityField],
|
||||
enabled: valid && Boolean(processUUID), retry: false, staleTime: Infinity, refetchOnWindowFocus: false,
|
||||
queryFn: async ({ signal }) => {
|
||||
const records: QRecord[] = []
|
||||
let total = 1
|
||||
while (records.length < total) {
|
||||
signal.throwIfAborted()
|
||||
const page = await processRecords(processName, processUUID!, records.length, 100, tableVariant)
|
||||
signal.throwIfAborted()
|
||||
if (!Number.isInteger(page.totalRecords) || page.totalRecords < 1 || page.totalRecords > 5000 ||
|
||||
(records.length > 0 && page.totalRecords !== total) || page.records.length === 0 || page.records.length > 100) {
|
||||
throw new Error('The complete ordering list is unavailable or exceeds 5,000 records.')
|
||||
}
|
||||
total = page.totalRecords
|
||||
records.push(...page.records)
|
||||
}
|
||||
const ids = records.map((record) => record.values?.[identityField as string])
|
||||
if (records.length !== total || ids.some((id) => typeof id !== 'number' || !Number.isSafeInteger(id) || id < 1) || new Set(ids).size !== total) {
|
||||
throw new Error('The ordering list contains invalid or duplicate identities.')
|
||||
}
|
||||
return records
|
||||
},
|
||||
})
|
||||
const records = ordered?.scope === scope ? ordered.records : query.data ?? []
|
||||
const ready = valid && query.isSuccess && records.length > 0 && !isWorking
|
||||
useSubmitContributor('record-order-' + index, () => ({
|
||||
maySubmit: ready,
|
||||
values: ready ? { [orderField as string]: records.map((record) => record.values?.[identityField as string]).join(',') } : undefined,
|
||||
}))
|
||||
/** Move exactly one row, preserving its stable identity and keyboard focus.
|
||||
* @param position - Current row position.
|
||||
* @param direction - Adjacent movement.
|
||||
* @returns Nothing.
|
||||
*/
|
||||
const move = (position: number, direction: -1 | 1): void => {
|
||||
const next = [...records]
|
||||
const target = position + direction
|
||||
if (!ready || target < 0 || target >= next.length) return
|
||||
;[next[position], next[target]] = [next[target], next[position]]
|
||||
setOrdered({ scope, records: next })
|
||||
setAnnouncement('Moved to position ' + (target + 1) + ' of ' + next.length + '.')
|
||||
}
|
||||
if (!valid) return <p role="alert">This ordering control is not configured correctly.</p>
|
||||
if (query.isError) return <div role="alert"><p>{query.error.message}</p><button type="button" data-qqq-id="record-order-retry" onClick={() => { setOrdered(null); void query.refetch() }}>Retry loading</button></div>
|
||||
if (!query.isSuccess) return <p role="status">Loading the complete list for ordering…</p>
|
||||
return <section aria-label="Record order" data-qqq-id="record-order">
|
||||
<p className="text-sm text-muted-foreground">Use Move up and Move down to set the order, then submit.</p>
|
||||
<p role="status" className="sr-only">{announcement}</p>
|
||||
<ol className="space-y-2">
|
||||
{records.map((record, position) => {
|
||||
const label = fields.map((field) => recordCellText(record, field)).filter((value) => value !== '—').join(' — ') || 'Record'
|
||||
return <li key={String(record.values?.[identityField as string])} className="flex flex-wrap items-center gap-3 rounded border p-3">
|
||||
<span className="min-w-0 flex-1 break-words">{position + 1}. {label}</span>
|
||||
<button type="button" className="min-h-11 rounded border px-3" disabled={!ready || position === 0} aria-label={'Move ' + label + ' up'} data-qqq-id="record-order-up" onClick={() => move(position, -1)}>Move up</button>
|
||||
<button type="button" className="min-h-11 rounded border px-3" disabled={!ready || position === records.length - 1} aria-label={'Move ' + label + ' down'} data-qqq-id="record-order-down" onClick={() => move(position, 1)}>Move down</button>
|
||||
</li>
|
||||
})}
|
||||
</ol>
|
||||
</section>
|
||||
}
|
||||
@@ -36,7 +36,6 @@ import { HelpTextComponent } from './HelpTextComponent'
|
||||
import { HtmlComponent } from './HtmlComponent'
|
||||
import { ProcessSummaryResultsComponent } from './ProcessSummaryResultsComponent'
|
||||
import { RecordListComponent } from './RecordListComponent'
|
||||
import { OrderedRecordListComponent } from './OrderedRecordListComponent'
|
||||
import { ValidationReviewComponent } from './ValidationReviewComponent'
|
||||
import { ViewFormComponent } from './ViewFormComponent'
|
||||
import { WidgetComponent } from './WidgetComponent'
|
||||
@@ -58,9 +57,7 @@ export function ProcessComponent({ component, index }: ProcessComponentProps) {
|
||||
case 'HELP_TEXT': return <HelpTextComponent component={component} index={index} />
|
||||
case 'EDIT_FORM': return <EditFormComponent component={component} index={index} />
|
||||
case 'VIEW_FORM': return <ViewFormComponent index={index} />
|
||||
case 'RECORD_LIST': return component.values?.orderFieldName !== undefined
|
||||
? <OrderedRecordListComponent key={index} component={component} index={index} />
|
||||
: <RecordListComponent index={index} />
|
||||
case 'RECORD_LIST': return <RecordListComponent index={index} />
|
||||
case 'VALIDATION_REVIEW_SCREEN': return <ValidationReviewComponent index={index} />
|
||||
case 'PROCESS_SUMMARY_RESULTS': return <ProcessSummaryResultsComponent index={index} />
|
||||
case 'DOWNLOAD_FORM': return <DownloadFormComponent index={index} />
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { QFieldMetaData } from '@/types'
|
||||
import { ViewFormComponent } from './ViewFormComponent'
|
||||
import { useProcessStep } from './ProcessStepContext'
|
||||
|
||||
vi.mock('./ProcessStepContext', () => ({ useProcessStep: vi.fn() }))
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
|
||||
function field(name: string, extra: Partial<QFieldMetaData> = {}): QFieldMetaData {
|
||||
return { name, label: name, type: 'STRING', isRequired: false, isEditable: false, isHeavy: false, isHidden: false, adornments: [], ...extra }
|
||||
}
|
||||
|
||||
function show(fields: QFieldMetaData[], values: Record<string, unknown>) {
|
||||
vi.mocked(useProcessStep).mockReturnValue({ step: { viewFields: fields }, values, processName: 'nativeAction' } as unknown as ReturnType<typeof useProcessStep>)
|
||||
return render(<QueryClientProvider client={new QueryClient()}><ViewFormComponent index={0} /></QueryClientProvider>)
|
||||
}
|
||||
|
||||
describe('native process result adornments', () => {
|
||||
it('opens actual record links and hides absent navigation fields', () => {
|
||||
show([field('request', { adornments: [{ type: 'LINK', values: { toRecordFromTable: 'request' } }] }),
|
||||
field('absent', { adornments: [{ type: 'LINK', values: { toRecordFromTable: 'other' } }] }), field('state')], { request: 42, state: 'RETAINED' })
|
||||
expect(screen.getByRole('link', { name: '42' })).toHaveAttribute('href', '/app/request/42')
|
||||
expect(screen.queryByText('absent:')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('RETAINED')).toBeVisible()
|
||||
})
|
||||
|
||||
it('uses hidden companion metadata without showing capability URLs as links', () => {
|
||||
const result = show([field('file', { adornments: [{ type: 'LINK', values: { toRecordFromTableField: 'table' } }] }),
|
||||
field('table', { isHidden: true }), field('url', { adornments: [{ type: 'FILE_DOWNLOAD', values: { deliveryModeField: 'mode', fileNameField: 'name' } }] }),
|
||||
field('mode', { isHidden: true }), field('name', { isHidden: true })],
|
||||
{ file: '7', table: 'retained', url: 'https://api.example/private-transfer', mode: 'AUTHENTICATED_FETCH', name: 'Packing.pdf' })
|
||||
expect(screen.getByRole('link', { name: '7' })).toHaveAttribute('href', '/app/retained/7')
|
||||
expect(screen.getByRole('button', { name: 'Download file' })).toBeEnabled()
|
||||
expect(result.container.innerHTML).not.toContain('https://api.example/private-transfer')
|
||||
expect(screen.queryByText('mode:')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not downgrade an unknown or missing delivery mode to a link', () => {
|
||||
const result = show([field('url', { adornments: [{ type: 'FILE_DOWNLOAD', values: { deliveryModeField: 'mode' } }, { type: 'FILE_PREVIEW' }] }),
|
||||
field('mode', { isHidden: true })], { url: 'https://api.example/private-transfer', mode: 'UNKNOWN' })
|
||||
expect(result.container.querySelector('a, img, iframe, button')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -29,7 +29,6 @@ import { fetchProcessPossibleValues } from '@/lib/api/possible-values'
|
||||
|
||||
import { useProcessStep } from './ProcessStepContext'
|
||||
import { formatProcessValue } from './process-values'
|
||||
import { FieldValue } from '@/components/records/FieldValue'
|
||||
|
||||
/** Props for {@link ViewFormComponent}. */
|
||||
export interface ViewFormComponentProps {
|
||||
@@ -49,7 +48,6 @@ interface ViewFieldScope {
|
||||
* @returns The rendered line.
|
||||
*/
|
||||
function ViewField({ field, value, scope: { processName, values } }: { field: QFieldMetaData; value: unknown; scope: ViewFieldScope }) {
|
||||
const { instance, tableMetaData } = useProcessStep()
|
||||
const hasValue = value !== null && value !== undefined && value !== ''
|
||||
const { data: label } = useQuery({
|
||||
queryKey: ['qqq', 'processViewValueLabel', processName, field.name, String(value), values],
|
||||
@@ -60,8 +58,6 @@ function ViewField({ field, value, scope: { processName, values } }: { field: QF
|
||||
const text = formatProcessValue(field, value, label ?? undefined)
|
||||
const isError = field.adornments?.some((adornment) => adornment.type === 'ERROR')
|
||||
|
||||
if (!hasValue && field.adornments?.some((adornment) => ['LINK', 'FILE_DOWNLOAD', 'FILE_PREVIEW', 'CODE_EDITOR'].includes(adornment.type))) return null
|
||||
|
||||
if (isError) {
|
||||
if (!text) return null
|
||||
return (
|
||||
@@ -71,10 +67,7 @@ function ViewField({ field, value, scope: { processName, values } }: { field: QF
|
||||
return (
|
||||
<div className="flex flex-wrap gap-x-2 py-1 text-sm" data-qqq-id={`process-view-field-${field.name}`}>
|
||||
<span className="font-semibold text-foreground">{field.label}:</span>
|
||||
<div className="min-w-0 text-foreground" data-qqq-id={`process-view-value-${field.name}`}>{field.adornments?.length || (field.possibleValueSourceName && instance?.tables?.[field.possibleValueSourceName])
|
||||
? <FieldValue field={field} record={{ tableName: tableMetaData?.name ?? '', values,
|
||||
displayValues: label ? { [field.name]: label } : undefined }} allTables={instance?.tables} tableMetaData={tableMetaData} />
|
||||
: text || <span className="text-muted-foreground">—</span>}</div>
|
||||
<span className="text-foreground" data-qqq-id={`process-view-value-${field.name}`}>{text || <span className="text-muted-foreground">—</span>}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ function NamedWidget({ widget, seeded, index }: { widget: QWidgetMetaData; seede
|
||||
produced.current = type === 'childRecordList' ? { frontendRecords: frontendRecordsJson(data) } : { ...(produced.current ?? {}), ...data }
|
||||
}, [type])
|
||||
|
||||
useSubmitContributor(`widget-${index}-${widget.name}`, () => ({ maySubmit: type !== 'AUTHENTIK_ACCESS_EDITOR' || produced.current?.__accessEditorReady === true, values: produced.current ?? undefined }))
|
||||
useSubmitContributor(`widget-${index}-${widget.name}`, () => ({ maySubmit: true, values: produced.current ?? undefined }))
|
||||
|
||||
return (
|
||||
<div data-qqq-id={`process-widget-${widget.name}`}>
|
||||
|
||||
@@ -205,24 +205,6 @@ describe('ProcessSummaryLines', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('HTML component', () => {
|
||||
it('shows a link the backend put on the last screen as a link that opens in this tab', () => {
|
||||
const address = 'https://slack.com/oauth/v2/authorize?client_id=1.2&scope=&user_scope=chat%3Awrite&state=abc.def'
|
||||
const step: QFrontendStepMetaData = { name: 'result', label: 'Continue to Slack', components: [{ type: 'HTML' }] }
|
||||
renderStep(step, {
|
||||
noMoreSteps: true,
|
||||
'result.html': `<p>Slack will ask you to approve the connection.</p><p><a href="${address.replace(/&/g, '&')}" style="display:inline-block;padding:8px 16px;background:#4A154B;color:#ffffff">Continue to Slack</a></p><p>This link expires in 10 minutes.</p>`,
|
||||
})
|
||||
const link = screen.getByRole('link', { name: 'Continue to Slack' })
|
||||
expect(link).toHaveAttribute('href', address)
|
||||
expect(link).not.toHaveAttribute('target')
|
||||
expect(link.getAttribute('style')).toContain('background')
|
||||
expect(link.closest('[data-qqq-id="process-html-0"]')).toHaveClass('[&_a]:text-link', '[&_a]:underline')
|
||||
expect(screen.getByText('This link expires in 10 minutes.')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Return' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('process helpers', () => {
|
||||
it('sanitizes HTML but keeps CSV and text template downloads', () => {
|
||||
const html = sanitizeProcessHtml('<a href="data:text/csv;base64,QQ==" download="t.csv">t</a><a href="data:text/html,<b>x</b>">h</a><img src="x" onerror="alert(1)"><script>alert(1)</script>')
|
||||
|
||||
@@ -95,20 +95,6 @@ function instanceWith(...widgets: QWidgetMetaData[]): QInstance {
|
||||
describe('process screens: fields and chrome (#725)', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('submits TypeScript source unchanged through a native EDIT_FORM CODE_EDITOR field', async () => {
|
||||
const source = ' export async function main(): Promise<string> {\n return "日本語";\n}\n\n'
|
||||
const step: QFrontendStepMetaData = {
|
||||
name: 'source', label: 'Source', components: [{ type: 'EDIT_FORM' }],
|
||||
formFields: [field('source', 'TypeScript source', {
|
||||
type: 'TEXT', adornments: [{ type: 'CODE_EDITOR', values: { languageMode: 'typescript' } }],
|
||||
})],
|
||||
}
|
||||
const { onSubmit } = renderStep(step, { source: '// initial\n' })
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'TypeScript source' }), { target: { value: source } })
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith({ source }, undefined))
|
||||
})
|
||||
|
||||
it('adds inputFieldList fields to a screen with an edit form, searching their source, and submits them', async () => {
|
||||
const user = userEvent.setup()
|
||||
const step: QFrontendStepMetaData = { name: 'input', label: 'Input', components: [{ type: 'EDIT_FORM' }], formFields: [field('note', 'Note')] }
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import type { QTableMetaData } from '@/types'
|
||||
import { useRecordQuery } from '@/lib/hooks/use-record-query'
|
||||
import { authorizationFilteredPagination, paginationSourceTables } from '@/lib/utils/query-pagination'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
import { server } from '@/mocks/node'
|
||||
import { RecordQueryContent } from './RecordQueryContent'
|
||||
|
||||
let client: QueryClient
|
||||
let table: QTableMetaData
|
||||
let sources: Record<string, QTableMetaData>
|
||||
|
||||
function Screen() {
|
||||
const rq = useRecordQuery({ tableName: table.name, tableMetaData: table, allTables: { [table.name]: table } })
|
||||
return <RecordQueryContent
|
||||
allTables={sources}
|
||||
tableName={table.name} tableMetaData={table} viewMode="card" activeFilterCount={0}
|
||||
{...rq.data} {...rq.pagination} {...rq.columns}
|
||||
sortOrder={rq.filter.sortOrder} onSortChange={rq.filter.setSort}
|
||||
onResetFilter={rq.filter.resetFilter} quickSearchTerm={rq.filter.quickSearchTerm}
|
||||
rowSelection={rq.selection.rowSelection} onRowSelectionChange={rq.selection.setRowSelection}
|
||||
onColumnWidthChange={rq.columns.setColumnWidth} density={rq.density}
|
||||
onPageChange={rq.pagination.setPage} onPageSizeChange={rq.pagination.setPageSize}
|
||||
/>
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
table = { ...qInstance.tables.person, capabilities: ['TABLE_QUERY', 'TABLE_COUNT'], supplementalMetaData: {
|
||||
queryPagination: { authorizationFiltered: true },
|
||||
} }
|
||||
sources = { archive: { ...qInstance.tables.person, name: 'record_files_archive_source', label: 'Retained Source Archives', readPermission: true, isHidden: false,
|
||||
supplementalMetaData: { queryPagination: { sourceBrowser: true } } } }
|
||||
vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => { cleanup(); client.clear(); vi.restoreAllMocks() })
|
||||
|
||||
it('requests one later page after an empty authorized page, permits back navigation, and never counts', async () => {
|
||||
const offsets: number[] = []
|
||||
let countCalls = 0
|
||||
let revoked = false
|
||||
server.use(
|
||||
http.post('*/qqq/v1/table/person/query', async ({ request }) => {
|
||||
const body = await request.json() as { filter: { skip?: number; limit: number } }
|
||||
const skip = body.filter.skip ?? 0
|
||||
offsets.push(skip)
|
||||
expect(body.filter.limit).toBe(50)
|
||||
return HttpResponse.json({ records: skip === 50 && !revoked ? [{ tableName: 'person', recordLabel: 'Visible later', values: { id: 99, firstName: 'Visible later' } }] : [] })
|
||||
}),
|
||||
http.post('*/qqq/v1/table/person/count', () => { countCalls++; return HttpResponse.json({ count: 999 }) }),
|
||||
)
|
||||
render(<QueryClientProvider client={client}><Screen /></QueryClientProvider>)
|
||||
expect(await screen.findByText('No authorized records on this page')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled()
|
||||
expect(screen.getByText('0 visible records on page 1')).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'Retained Source Archives' })).toHaveAttribute('href', '/app/record_files_archive_source')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
|
||||
await waitFor(() => expect(screen.getByText('1 visible records on page 2')).toBeInTheDocument())
|
||||
expect(offsets).toEqual([0, 50])
|
||||
expect(countCalls).toBe(0)
|
||||
revoked = true
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Previous page' }))
|
||||
await waitFor(() => expect(screen.getByText('0 visible records on page 1')).toBeInTheDocument())
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled())
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
|
||||
await waitFor(() => expect(screen.getByText('0 visible records on page 2')).toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled()
|
||||
expect(countCalls).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves ordinary empty tables and rejects a truthy string opt-in', async () => {
|
||||
table = { ...table, supplementalMetaData: { queryPagination: { authorizationFiltered: 'true' } } }
|
||||
server.use(http.post('*/qqq/v1/table/person/query', () => HttpResponse.json({ records: [] })),
|
||||
http.post('*/qqq/v1/table/person/count', () => HttpResponse.json({ count: 0 })))
|
||||
render(<QueryClientProvider client={client}><Screen /></QueryClientProvider>)
|
||||
expect(await screen.findByText('No records found')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Next page' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/Completeness is unknown/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not turn malformed navigation metadata into arbitrary links', () => {
|
||||
sources.denied = { ...sources.archive, name: 'denied', readPermission: false }
|
||||
sources.hidden = { ...sources.archive, name: 'hidden', isHidden: true }
|
||||
sources.bad = { ...sources.archive, name: '../secret' }
|
||||
sources.missing = { ...sources.archive, name: undefined } as unknown as QTableMetaData
|
||||
sources.nullName = { ...sources.archive, name: null } as unknown as QTableMetaData
|
||||
sources.truthyRead = { ...sources.archive, readPermission: 'true' } as unknown as QTableMetaData
|
||||
sources.truthySource = { ...sources.archive, supplementalMetaData: { queryPagination: { sourceBrowser: 'true' } } }
|
||||
expect(paginationSourceTables(sources)).toEqual([sources.archive])
|
||||
expect(authorizationFilteredPagination(undefined)).toBe(false)
|
||||
})
|
||||
@@ -31,8 +31,6 @@ import { PAGE_SIZE_OPTIONS, type PageSize } from '@/lib/hooks/use-record-query'
|
||||
* Props for the Pagination component.
|
||||
*/
|
||||
interface PaginationProps {
|
||||
/** Parent authorization filters pages after selection, so completeness is unknown. */
|
||||
authorizationFiltered?: boolean
|
||||
/** Current 1-based page number. */
|
||||
pageNum: number
|
||||
/** Number of records displayed per page (constrained to the PageSize union type). */
|
||||
@@ -68,7 +66,6 @@ interface PaginationProps {
|
||||
* @returns The rendered pagination controls.
|
||||
*/
|
||||
export function Pagination({
|
||||
authorizationFiltered = false,
|
||||
pageNum,
|
||||
pageSize,
|
||||
totalCount,
|
||||
@@ -124,9 +121,7 @@ export function Pagination({
|
||||
{/* Left: record count summary */}
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
|
||||
<span aria-live="polite" aria-atomic="true" data-qqq-id="pagination-summary">
|
||||
{authorizationFiltered ? (
|
||||
`${pageRowCount.toLocaleString()} visible records on page ${pageNum.toLocaleString()}`
|
||||
) : isCounting && !uncounted ? (
|
||||
{isCounting && !uncounted ? (
|
||||
'Counting...'
|
||||
) : shown === 0 ? (
|
||||
'No records'
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// The sort a record list opens with: the one its table declares
|
||||
// (`supplementalMetaData.nextUi.defaultSort`), unless the person has a sort of their own (in the
|
||||
// address, in a saved view, or remembered by the browser), and primary key descending otherwise.
|
||||
|
||||
import { act, render, renderHook, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { QFilterOrderBy, QTableMetaData } from '@/types'
|
||||
import type { QueryRecordsRequest } from '@/lib/api/tables'
|
||||
import { QContextProvider } from '@/lib/context/q-context'
|
||||
import { useRecordQuery } from '@/lib/hooks/use-record-query'
|
||||
import { emptyFilter, serializeFilter } from '@/lib/utils/filter-utils'
|
||||
import { defaultColumnVisibility } from '@/lib/utils/query-columns'
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
import { server } from '@/mocks/node'
|
||||
import { RecordQuery } from './RecordQuery'
|
||||
|
||||
let search = ''
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
|
||||
usePathname: () => '/app/person',
|
||||
useSearchParams: () => new URLSearchParams(search),
|
||||
}))
|
||||
|
||||
const NEWEST_FIRST: QFilterOrderBy[] = [{ fieldName: 'modifyDate', isAscending: false }]
|
||||
const PRIMARY_KEY_DESCENDING: QFilterOrderBy[] = [{ fieldName: 'id', isAscending: false }]
|
||||
|
||||
/**
|
||||
* The people table, declaring a default sort unless told otherwise.
|
||||
*
|
||||
* @param defaultSort - The declared sort; `null` for a table that declares none.
|
||||
* @returns Table metadata and the table registry.
|
||||
*/
|
||||
function tables(defaultSort: unknown = NEWEST_FIRST) {
|
||||
const allTables = structuredClone(qInstance.tables)
|
||||
if (defaultSort !== null) allTables.person.supplementalMetaData = { nextUi: { defaultSort } }
|
||||
return { tableName: 'person', tableMetaData: allTables.person as QTableMetaData, allTables }
|
||||
}
|
||||
|
||||
function wrapper({ children }: { children: React.ReactNode }) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return <QueryClientProvider client={client}><QContextProvider>{children}</QContextProvider></QueryClientProvider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Records what the list asks the server for.
|
||||
*
|
||||
* @returns The sort of the latest query request.
|
||||
*/
|
||||
function captureSort() {
|
||||
const sorts: (QFilterOrderBy[] | undefined)[] = []
|
||||
server.use(http.post('/qqq/v1/table/person/:action', async ({ request, params }) => {
|
||||
const body = await request.json() as QueryRecordsRequest
|
||||
if (params.action === 'query') sorts.push(body.filter.orderBys)
|
||||
return HttpResponse.json(params.action === 'query' ? { records: [{ tableName: 'person', recordLabel: 'Alice', values: { id: 1, firstName: 'Alice' } }] } : { count: 1 })
|
||||
}))
|
||||
return () => sorts.at(-1)
|
||||
}
|
||||
|
||||
/** The sort the address carries, if any. */
|
||||
const addressSort = () => {
|
||||
const encoded = new URLSearchParams(window.location.search).get('filter')
|
||||
return encoded ? (JSON.parse(atob(encoded)) as { orderBys?: QFilterOrderBy[] }).orderBys : undefined
|
||||
}
|
||||
|
||||
describe('record list default sort', () => {
|
||||
beforeEach(() => {
|
||||
search = ''
|
||||
localStorage.clear()
|
||||
window.history.replaceState(null, '', '/app/person')
|
||||
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('opens with the sort the table declares, without putting it in the address', async () => {
|
||||
const lastSort = captureSort()
|
||||
render(<RecordQuery {...tables()} />, { wrapper })
|
||||
expect((await screen.findAllByText('Alice'))[0]).toBeVisible()
|
||||
expect(lastSort()).toEqual(NEWEST_FIRST)
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Toggle advanced filter panel' }))
|
||||
expect(screen.getByRole('combobox', { name: 'Sort field' })).toHaveValue('modifyDate')
|
||||
// a default is not a choice: nothing to share in the address, nothing to save or reset
|
||||
expect(addressSort()).toBeUndefined()
|
||||
expect(screen.queryByRole('button', { name: 'Reset All Changes' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens by primary key descending when the table declares nothing, or nothing usable', async () => {
|
||||
for (const declared of [null, [], [{ fieldName: 'noSuchField', isAscending: false }], 'modifyDate']) {
|
||||
const lastSort = captureSort()
|
||||
const view = render(<RecordQuery {...tables(declared)} />, { wrapper })
|
||||
expect((await screen.findAllByText('Alice'))[0]).toBeVisible()
|
||||
expect(lastSort()).toEqual(PRIMARY_KEY_DESCENDING)
|
||||
expect(addressSort()).toBeUndefined()
|
||||
view.unmount()
|
||||
localStorage.clear()
|
||||
}
|
||||
})
|
||||
|
||||
it('a sort in the address wins over the declared one', async () => {
|
||||
const mine = [{ fieldName: 'lastName', isAscending: true }]
|
||||
search = new URLSearchParams({ filter: serializeFilter({ criteria: [], booleanOperator: 'AND', orderBys: mine }) }).toString()
|
||||
const lastSort = captureSort()
|
||||
render(<RecordQuery {...tables()} />, { wrapper })
|
||||
expect((await screen.findAllByText('Alice'))[0]).toBeVisible()
|
||||
expect(lastSort()).toEqual(mine)
|
||||
})
|
||||
|
||||
it("a person's own sort is kept, remembered for the next visit, and Reset returns to the declared one", async () => {
|
||||
const user = userEvent.setup()
|
||||
const lastSort = captureSort()
|
||||
const first = render(<RecordQuery {...tables()} />, { wrapper })
|
||||
expect((await screen.findAllByText('Alice'))[0]).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'Toggle advanced filter panel' }))
|
||||
const mode = within(screen.getByRole('group', { name: 'Filter mode' }))
|
||||
await user.selectOptions(mode.getByRole('combobox', { name: 'Sort field' }), 'lastName')
|
||||
await waitFor(() => expect(lastSort()).toEqual([{ fieldName: 'lastName', isAscending: false }]))
|
||||
// now it is a choice: it is in the address, and it can be reset
|
||||
await waitFor(() => expect(addressSort()).toEqual([{ fieldName: 'lastName', isAscending: false }]))
|
||||
expect(screen.getByRole('button', { name: 'Reset All Changes' })).toBeInTheDocument()
|
||||
|
||||
// the next visit (no sort in the address) opens with the remembered sort, not the declared one
|
||||
first.unmount()
|
||||
window.history.replaceState(null, '', '/app/person')
|
||||
render(<RecordQuery {...tables()} />, { wrapper })
|
||||
expect((await screen.findAllByText('Alice'))[0]).toBeVisible()
|
||||
await waitFor(() => expect(lastSort()).toEqual([{ fieldName: 'lastName', isAscending: false }]))
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Reset All Changes' }))
|
||||
await waitFor(() => expect(lastSort()).toEqual(NEWEST_FIRST))
|
||||
await waitFor(() => expect(addressSort()).toBeUndefined())
|
||||
expect(screen.queryByRole('button', { name: 'Reset All Changes' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("a saved view's sort wins, when the view is opened and when it is applied later", () => {
|
||||
const { tableMetaData, allTables } = tables()
|
||||
const viewSort = [{ fieldName: 'firstName', isAscending: true }]
|
||||
const view = {
|
||||
userFilter: emptyFilter(50), sortOrder: viewSort, columnVisibility: defaultColumnVisibility(tableMetaData),
|
||||
columnOrder: [], columnWidths: {}, pageSize: 50, filterMode: 'basic' as const,
|
||||
}
|
||||
const opened = renderHook(() => useRecordQuery({ tableName: 'person', tableMetaData, allTables, initialView: view, paused: true }), { wrapper })
|
||||
expect(opened.result.current.filter.sortOrder).toEqual(viewSort)
|
||||
expect(opened.result.current.filter.defaultSort).toEqual(NEWEST_FIRST)
|
||||
|
||||
const applied = renderHook(() => useRecordQuery({ tableName: 'person', tableMetaData, allTables, paused: true }), { wrapper })
|
||||
expect(applied.result.current.filter.sortOrder).toEqual(NEWEST_FIRST)
|
||||
act(() => applied.result.current.applyView(view))
|
||||
expect(applied.result.current.filter.sortOrder).toEqual(viewSort)
|
||||
// clearing a sort returns to the declared default, not to the primary key
|
||||
act(() => applied.result.current.filter.setSort([]))
|
||||
expect(applied.result.current.filter.sortOrder).toEqual(NEWEST_FIRST)
|
||||
})
|
||||
|
||||
it('keeps the same default sort when metadata is loaded again with the same declaration', () => {
|
||||
const { tableMetaData, allTables } = tables()
|
||||
const hook = renderHook(({ table }) => useRecordQuery({ tableName: 'person', tableMetaData: table, allTables, paused: true }), { wrapper, initialProps: { table: tableMetaData } })
|
||||
const before = hook.result.current.filter.defaultSort
|
||||
hook.rerender({ table: structuredClone(tableMetaData) })
|
||||
expect(hook.result.current.filter.defaultSort).toBe(before)
|
||||
})
|
||||
})
|
||||
@@ -1,167 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Every sub-view of the record list (the explore views and the saved analysis viewer) must leave
|
||||
// a way back to the list it was opened from: its own back control, the table's breadcrumb and the
|
||||
// browser's Back button. The tests walk the registry, so a view added to it without a way back,
|
||||
// or one that loses the list's filter or page, fails here.
|
||||
|
||||
import { act, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { qInstance } from '@/mocks/fixtures/q-instance'
|
||||
import { server } from '@/mocks/node'
|
||||
import { QContextProvider } from '@/lib/context/q-context'
|
||||
import { EXPLORE_LABELS, EXPLORE_VIEWS } from '@/lib/utils/data-analysis-explore'
|
||||
import { serializeFilter } from '@/lib/utils/filter-utils'
|
||||
import { listSearch, TABLE_SUB_VIEWS, type TableSubView } from '@/lib/utils/table-sub-views'
|
||||
import Breadcrumbs from '@/components/layout/Breadcrumbs'
|
||||
import { relationshipCapabilities } from '../../../tests/fixtures/data-analysis-compare'
|
||||
import { RecordQuery } from './RecordQuery'
|
||||
|
||||
vi.mock('next/navigation', async () => (await import('../../../tests/helpers/history-navigation')).historyNavigation)
|
||||
vi.mock('@/lib/api/data-analysis', async (original) => ({
|
||||
...(await original<typeof import('@/lib/api/data-analysis')>()),
|
||||
getCapabilities: vi.fn(async () => relationshipCapabilities),
|
||||
listSavedAnalyses: vi.fn(async () => ({ analyses: [] })),
|
||||
runSavedAnalysis: vi.fn(() => new Promise(() => undefined)),
|
||||
}))
|
||||
|
||||
const LIST = '[data-qqq-id="record-query-person"]'
|
||||
const criteria = [{ fieldName: 'firstName', operator: 'EQUALS' as const, values: ['Alice'] }]
|
||||
const orderBys = [{ fieldName: 'firstName', isAscending: true }]
|
||||
const filter = serializeFilter({ criteria, booleanOperator: 'AND', orderBys })
|
||||
/** The list as the person left it: page 2 of a filtered, sorted, searched query. */
|
||||
const listAddress = `/app/person?${new URLSearchParams({ page: '2', pageSize: '25', filter, q: 'ali' })}`
|
||||
|
||||
/**
|
||||
* The page: the header's breadcrumb and the record list, on one address.
|
||||
*
|
||||
* @returns Both.
|
||||
*/
|
||||
function Page() {
|
||||
const tables = structuredClone(qInstance.tables)
|
||||
return (
|
||||
<>
|
||||
<Breadcrumbs pathToLabelMap={{ '/app/person': tables.person.label }} />
|
||||
<RecordQuery tableName="person" tableMetaData={tables.person} allTables={tables} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function renderAt(address: string) {
|
||||
// a new entry, so no test starts with another test's Forward entries
|
||||
window.history.pushState(null, '', address)
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(<QueryClientProvider client={client}><QContextProvider><Page /></QContextProvider></QueryClientProvider>)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the address says about the list.
|
||||
*
|
||||
* @returns Its page, page size, search, and the filter with its sort.
|
||||
*/
|
||||
function listState() {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const encoded = params.get('filter')
|
||||
const decoded = encoded ? JSON.parse(atob(encoded)) as { criteria?: unknown; orderBys?: unknown } : {}
|
||||
return { path: window.location.pathname, page: params.get('page'), pageSize: params.get('pageSize'), q: params.get('q'), criteria: decoded.criteria, orderBys: decoded.orderBys, view: params.get('view') }
|
||||
}
|
||||
const asLeft = { path: '/app/person', page: '2', pageSize: '25', q: 'ali', view: null, criteria, orderBys }
|
||||
|
||||
const viewAddress = (view: TableSubView) => `${listAddress}&view=${view.name}${view.name === 'saved' ? '&saved=7' : ''}`
|
||||
const backControl = (view: TableSubView) => document.querySelector<HTMLElement>(`[data-qqq-id="${view.backId}"]`)
|
||||
const listShown = () => waitFor(() => expect(document.querySelector(LIST)).toBeInTheDocument())
|
||||
const viewShown = (view: TableSubView) => waitFor(() => expect(backControl(view)).toBeInTheDocument(), { timeout: 5000 })
|
||||
|
||||
describe('RecordQuery sub-views leave a way back', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
|
||||
server.use(
|
||||
http.post('/qqq/v1/table/person/:action', ({ params }) =>
|
||||
HttpResponse.json(params.action === 'query' ? { records: [{ tableName: 'person', recordLabel: 'Alice', values: { id: 1, firstName: 'Alice' } }] } : { count: 30 })),
|
||||
http.get('/qqq/v1/table/data_analysis_saved/:id', () => HttpResponse.json({ error: 'not found' }, { status: 404 })),
|
||||
)
|
||||
})
|
||||
|
||||
it.each(Object.values(TABLE_SUB_VIEWS))('a link to $name opens it; its back control and the breadcrumb return to the list as it was', async (view) => {
|
||||
const user = userEvent.setup()
|
||||
renderAt(viewAddress(view))
|
||||
await viewShown(view)
|
||||
expect(document.querySelector(LIST)).not.toBeInTheDocument()
|
||||
|
||||
// The breadcrumb names the view, and the table is a link to the list behind it
|
||||
expect(screen.getByText(view.label, { selector: '[aria-current="page"]' })).toBeInTheDocument()
|
||||
const crumb = screen.getByRole('link', { name: 'People' })
|
||||
expect(crumb).toHaveAttribute('href', `/app/person${listSearch(window.location.search)}`)
|
||||
expect(new URLSearchParams(crumb.getAttribute('href')!.split('?')[1]).get('page')).toBe('2')
|
||||
|
||||
// Its own control
|
||||
expect(backControl(view)).toHaveAccessibleName('Back to records')
|
||||
await user.click(backControl(view)!)
|
||||
await listShown()
|
||||
expect(backControl(view)).not.toBeInTheDocument()
|
||||
expect(screen.getByText('People', { selector: '[aria-current="page"]' })).toBeInTheDocument()
|
||||
await waitFor(() => expect(listState()).toEqual(asLeft))
|
||||
|
||||
// Following the breadcrumb link from the view gives the same list
|
||||
act(() => window.history.pushState(null, '', viewAddress(view)))
|
||||
await viewShown(view)
|
||||
const href = screen.getByRole('link', { name: 'People' }).getAttribute('href')!
|
||||
act(() => window.history.pushState(null, '', href))
|
||||
await listShown()
|
||||
await waitFor(() => expect(listState()).toEqual(asLeft))
|
||||
})
|
||||
|
||||
it.each(EXPLORE_VIEWS.map((name) => TABLE_SUB_VIEWS[name]))('$name opened from the list: browser Back, then its back control, return to the list as it was', async (view) => {
|
||||
const user = userEvent.setup()
|
||||
renderAt(listAddress)
|
||||
await listShown()
|
||||
await waitFor(() => expect(listState()).toEqual(asLeft))
|
||||
const entries = window.history.length
|
||||
|
||||
const open = async () => {
|
||||
await user.click(await screen.findByRole('button', { name: 'Explore' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: EXPLORE_LABELS[view.name as keyof typeof EXPLORE_LABELS] }))
|
||||
await viewShown(view)
|
||||
}
|
||||
|
||||
// Browser Back
|
||||
await open()
|
||||
expect(window.history.length).toBe(entries + 1)
|
||||
expect(listState().view).toBe(view.name)
|
||||
act(() => window.history.back())
|
||||
await listShown()
|
||||
await waitFor(() => expect(listState()).toEqual(asLeft))
|
||||
// the list does not rewrite the address after the step back (that would drop the page)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
expect(listState()).toEqual(asLeft)
|
||||
|
||||
// The view's own control is one step back too: the view stays one Forward away
|
||||
await open()
|
||||
await user.click(backControl(view)!)
|
||||
await listShown()
|
||||
await waitFor(() => expect(listState()).toEqual(asLeft))
|
||||
expect(window.history.length).toBe(entries + 1)
|
||||
act(() => window.history.forward())
|
||||
await viewShown(view)
|
||||
expect(listState().view).toBe(view.name)
|
||||
})
|
||||
})
|
||||
@@ -211,20 +211,19 @@ describe('RecordQuery joined read permissions', () => {
|
||||
render(<RecordQuery {...options} />, { wrapper: createWrapper() })
|
||||
expect(await screen.findByText('Alice')).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'Toggle advanced filter panel' }))
|
||||
const filterMode = within(screen.getByRole('group', { name: 'Filter mode' }))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'First Name' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Filter value for First Name' }), 'Bob')
|
||||
await user.click(screen.getByRole('button', { name: 'Apply quick filter' }))
|
||||
await waitFor(() => expect(requests.at(-1)?.body.filter.criteria?.length).toBe(1))
|
||||
await user.selectOptions(filterMode.getByRole('combobox', { name: 'Sort field' }), 'lastName')
|
||||
await user.click(filterMode.getByRole('button', { name: 'Clear all filters' }))
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Sort field' }), 'lastName')
|
||||
await user.click(screen.getByRole('button', { name: 'Clear all filters' }))
|
||||
expect(screen.getByRole('alertdialog')).toBeVisible()
|
||||
await user.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Cancel' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(requests.at(-1)?.body.filter.criteria?.length).toBe(1)
|
||||
|
||||
await user.click(filterMode.getByRole('button', { name: 'Clear all filters' }))
|
||||
await user.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Clear filters' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Clear all filters' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Clear filters' }))
|
||||
await waitFor(() => expect(requests.filter(({ action }) => action === 'query').at(-1)?.body.filter.criteria?.length).toBe(0))
|
||||
expect(requests.filter(({ action }) => action === 'query').at(-1)?.body.filter.orderBys).toEqual([{ fieldName: 'lastName', isAscending: false }])
|
||||
})
|
||||
@@ -239,12 +238,11 @@ describe('RecordQuery joined read permissions', () => {
|
||||
render(<RecordQuery {...options} />, { wrapper: createWrapper() })
|
||||
expect(await screen.findByText('Alice')).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'Toggle advanced filter panel' }))
|
||||
const filterMode = within(screen.getByRole('group', { name: 'Filter mode' }))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'First Name' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Filter value for First Name' }), 'Bob')
|
||||
await user.click(screen.getByRole('button', { name: 'Apply quick filter' }))
|
||||
await user.click(filterMode.getByRole('button', { name: 'Advanced' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Advanced' }))
|
||||
expect(screen.queryByLabelText('Advanced filter preview')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Clear all filters' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Clear all' })).toBeVisible()
|
||||
|
||||
@@ -26,7 +26,7 @@ import { canSortField } from '@/lib/utils/secured-data'
|
||||
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
|
||||
import Link from 'next/link'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
|
||||
import { X, ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
@@ -39,9 +39,9 @@ import { getCapabilities } from '@/lib/api/data-analysis'
|
||||
import type { PageSize } from '@/lib/hooks/use-record-query'
|
||||
|
||||
import { QUERY_SCREEN_HELP_ROLES } from '@/lib/utils/help-utils'
|
||||
import { encodeExplore, type RelationshipView, type ExploreLayout } from '@/lib/utils/data-analysis-explore'
|
||||
import { listSearch, tableSubView, TABLE_SUB_VIEW_PARAM, type TableSubViewName } from '@/lib/utils/table-sub-views'
|
||||
import { encodeExplore, EXPLORE_VIEWS, type RelationshipView, type ExploreLayout } from '@/lib/utils/data-analysis-explore'
|
||||
import { encodePivot, type PivotLayout } from '@/lib/utils/data-analysis-pivot'
|
||||
import { deserializeFilter } from '@/lib/utils/filter-utils'
|
||||
import { queryRecords, type TableVariant } from '@/lib/api/tables'
|
||||
import { useRecordQuery, hasCapability } from '@/lib/hooks/use-record-query'
|
||||
import { useSavedViews, useSavedView } from '@/lib/hooks/use-saved-views'
|
||||
@@ -122,7 +122,6 @@ interface RecordQueryProps {
|
||||
export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, allTables, processes, metaData, savedViewId }: RecordQueryProps) {
|
||||
const tableMetaData = useMemo(() => withReadableExposedJoins(sourceTableMetaData, allTables), [sourceTableMetaData, allTables])
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const fromPath = searchParams.get('from')
|
||||
const fromLabel = searchParams.get('fromLabel')
|
||||
@@ -325,59 +324,36 @@ export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, all
|
||||
const openAnalysis = (field?: { name: string; label: string }) => setAnalysis({ field, filter: rq.filter.baseFilter, returnFocus: field ? document.querySelector<HTMLElement>(`[data-qqq-id="grid-column-menu-${CSS.escape(field.name)}"]`) : document.activeElement instanceof HTMLElement ? document.activeElement : null })
|
||||
const closeAnalysis = () => { const target = analysis?.returnFocus; setAnalysis(null); requestAnimationFrame(() => target?.focus()) }
|
||||
const canAnalyze = capabilities.data?.canAnalyze === true
|
||||
// Sub-views (the explore views and the saved analysis viewer) are states of this route, named by
|
||||
// the query string. `table-sub-views` is their registry: a view opens only through it, so the
|
||||
// breadcrumb knows every one of them.
|
||||
const subView = tableSubView(searchParams)
|
||||
const pivotOpen = subView?.name === 'pivot'
|
||||
const relationshipView = subView && subView.name !== 'pivot' && subView.name !== 'saved' ? subView.name as RelationshipView : undefined
|
||||
const { restoreFromUrl } = rq
|
||||
// Browser Back and Forward between the list and a sub-view (or two states of the list) change the
|
||||
// address without remounting this page: take the filter, sort, quick search and page from it, so
|
||||
// the list is the one that address names. A step to another page is not this page's to follow.
|
||||
const pivotOpen = searchParams.get('view') === 'pivot'
|
||||
const relationshipView = EXPLORE_VIEWS.find(v => v !== 'pivot' && v === searchParams.get('view')) as RelationshipView | undefined
|
||||
const explorerOpen = pivotOpen || Boolean(relationshipView)
|
||||
const { setUserFilter: restorePivotFilter, setQuickSearch: restorePivotSearch } = rq.filter
|
||||
useEffect(() => {
|
||||
const samePath = (a: string, b: string) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '')
|
||||
const restore = () => {
|
||||
if (!samePath(window.location.pathname, pathname)) return
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
restoreFromUrl(window.location.search)
|
||||
if (!explorerOpen && !EXPLORE_VIEWS.some(v => v === params.get('view'))) return
|
||||
restorePivotFilter(deserializeFilter(params.get('filter') ?? '', rq.viewState.pageSize))
|
||||
restorePivotSearch(params.get('q') ?? '')
|
||||
setLocalSearchTerm(params.get('q') ?? '')
|
||||
}
|
||||
window.addEventListener('popstate', restore)
|
||||
return () => window.removeEventListener('popstate', restore)
|
||||
}, [pathname, restoreFromUrl])
|
||||
// The list address a sub-view was opened from, while that list is the previous history entry.
|
||||
const openedFromRef = useRef<string | null>(null)
|
||||
// Opens a sub-view, or updates the open one's layout, in the address (a new history entry only
|
||||
// when a view opens, so Back returns to the list and a re-run does not pile up entries).
|
||||
const openSubView = (view: TableSubViewName, layout?: string) => {
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.set(TABLE_SUB_VIEW_PARAM, view)
|
||||
if (layout !== undefined) url.searchParams.set(view, layout)
|
||||
if (subView) window.history.replaceState(null, '', url)
|
||||
else {
|
||||
openedFromRef.current = `${window.location.pathname}${window.location.search}`
|
||||
window.history.pushState(null, '', url)
|
||||
}
|
||||
}
|
||||
// Returns to the list, with whatever filter, sort and page the address now carries. When that is
|
||||
// still the list this view was opened from, it is one step back in history, so the view stays
|
||||
// one Forward away and Back does not meet the same list twice; otherwise (a deep link, or a
|
||||
// drill changed the filter) the list replaces the view in place.
|
||||
const closeSubView = () => {
|
||||
const list = `${window.location.pathname}${listSearch(window.location.search)}`
|
||||
const openedFrom = openedFromRef.current
|
||||
openedFromRef.current = null
|
||||
if (openedFrom === list) window.history.back()
|
||||
else window.history.replaceState(null, '', `${list}${window.location.hash}`)
|
||||
}
|
||||
}, [explorerOpen, restorePivotFilter, restorePivotSearch, rq.viewState.pageSize])
|
||||
const updatePivotUrl = (open: boolean, request?: PivotLayout) => {
|
||||
if (open) openSubView('pivot', request ? encodePivot(request) : undefined)
|
||||
else closeSubView()
|
||||
const url = new URL(window.location.href)
|
||||
if (open) url.searchParams.set('view', 'pivot')
|
||||
else { url.searchParams.delete('view'); url.searchParams.delete('pivot') }
|
||||
if (request) url.searchParams.set('pivot', encodePivot(request))
|
||||
if (open && !pivotOpen) window.history.pushState(null, '', url)
|
||||
else window.history.replaceState(null, '', url)
|
||||
}
|
||||
const updateExploreUrl = (view?: RelationshipView, layout?: ExploreLayout) => {
|
||||
if (view) openSubView(view, layout ? encodeExplore(view, layout) : undefined)
|
||||
else closeSubView()
|
||||
const url = new URL(window.location.href)
|
||||
if (view) url.searchParams.set('view', view)
|
||||
else { url.searchParams.delete('view'); EXPLORE_VIEWS.forEach(v => url.searchParams.delete(v)) }
|
||||
if (view && layout) url.searchParams.set(view, encodeExplore(view, layout))
|
||||
if (view && !explorerOpen) window.history.pushState(null, '', url)
|
||||
else window.history.replaceState(null, '', url)
|
||||
}
|
||||
// A drill on this table applies its filter here: this page reads the URL only on mount.
|
||||
const applyAnalysisDrill = (drill: DataAnalysisDrillV1) => {
|
||||
@@ -632,8 +608,13 @@ export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, all
|
||||
</>
|
||||
)
|
||||
|
||||
if (subView?.name === 'saved') {
|
||||
const closeSaved = closeSubView
|
||||
if (searchParams.get('view') === 'saved') {
|
||||
const closeSaved = () => {
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.delete('view')
|
||||
url.searchParams.delete('saved')
|
||||
window.history.replaceState(null, '', url)
|
||||
}
|
||||
return <AnalysisDrillContext.Provider value={drill => {
|
||||
if (!applyAnalysisDrill(drill)) return false
|
||||
closeSaved()
|
||||
@@ -895,7 +876,6 @@ export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, all
|
||||
</div>
|
||||
) : (
|
||||
<RecordQueryContent
|
||||
allTables={allTables}
|
||||
tableName={tableName}
|
||||
tableMetaData={tableMetaData}
|
||||
viewMode={viewMode}
|
||||
|
||||
@@ -22,8 +22,6 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { authorizationFilteredPagination, paginationSourceTables } from '@/lib/utils/query-pagination'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
@@ -53,8 +51,6 @@ export interface RecordQueryContentProps {
|
||||
tableName: string
|
||||
/** Full table metadata from the QQQ backend. */
|
||||
tableMetaData: QTableMetaData
|
||||
/** Current authorized metadata, used only for source navigation hints. */
|
||||
allTables?: Record<string, QTableMetaData>
|
||||
/** Currently active view mode (grid or card). */
|
||||
viewMode: ViewMode
|
||||
/** Number of active filter criteria (used by the empty-state clear action). */
|
||||
@@ -143,7 +139,6 @@ export interface RecordQueryContentProps {
|
||||
export function RecordQueryContent({
|
||||
tableName,
|
||||
tableMetaData,
|
||||
allTables = {},
|
||||
viewMode,
|
||||
activeFilterCount,
|
||||
records,
|
||||
@@ -179,25 +174,11 @@ export function RecordQueryContent({
|
||||
}: RecordQueryContentProps) {
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const pagePolicy = authorizationFilteredPagination(tableMetaData)
|
||||
const sourceTables = paginationSourceTables(allTables)
|
||||
// Material's grid alert can be closed; a new error shows again
|
||||
const [dismissedError, setDismissedError] = useState<Error | null>(null)
|
||||
|
||||
return (
|
||||
<>
|
||||
{pagePolicy && (
|
||||
<div className="rounded border border-border p-3 text-sm text-muted-foreground" data-qqq-id="query-page-completeness">
|
||||
<p>Completeness is unknown. Each page shows only records you can access. Later pages may contain records even when this page is empty. Next requests one page and remains available because the end cannot be determined.</p>
|
||||
{sourceTables.length > 0 && (
|
||||
<p className="mt-2">To narrow by source, choose a record and open its Files tab:{' '}
|
||||
{sourceTables.map((source) => (
|
||||
<Link key={source.name} href={`/app/${encodeURIComponent(source.name)}/`} className="mr-3 inline-flex min-h-[44px] items-center underline">{source.label || source.name}</Link>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* ============================================================
|
||||
Error state
|
||||
============================================================ */}
|
||||
@@ -254,7 +235,7 @@ export function RecordQueryContent({
|
||||
{/* ============================================================
|
||||
Data Grid / Card View
|
||||
============================================================ */}
|
||||
{(isLoading || records.length > 0 || (pagePolicy && !isError)) && (
|
||||
{(isLoading || records.length > 0) && (
|
||||
<ErrorBoundary className="rounded-xl" resetLabel="Reset saved query and reload" onReset={() => {
|
||||
clearStoredQueryState(tableName)
|
||||
if (window.location.pathname.includes('/savedView/')) router.replace(`/app/${encodeURIComponent(tableName)}/`)
|
||||
@@ -310,7 +291,6 @@ export function RecordQueryContent({
|
||||
|
||||
{/* Pagination */}
|
||||
<Pagination
|
||||
authorizationFiltered={pagePolicy}
|
||||
pageNum={pageNum}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
@@ -341,7 +321,6 @@ export function RecordQueryContent({
|
||||
* @returns EmptyState title, description and width.
|
||||
*/
|
||||
export function emptyStateText(tableMetaData: QTableMetaData, filtered: boolean): { title: string; description: string; wideDescription?: boolean } {
|
||||
if (authorizationFilteredPagination(tableMetaData)) return { title: 'No authorized records on this page', description: 'Later pages may contain records. Use Next or narrow your search to a source record.' }
|
||||
const help = filtered ? undefined : selectSlotHelp(tableMetaData.helpContents, 'help', QUERY_SCREEN_HELP_ROLES)
|
||||
const text = help ? helpPlainText(help) : ''
|
||||
if (!text) return { title: 'No records found', description: 'Try adjusting your filters or search term.' }
|
||||
|
||||
@@ -42,7 +42,6 @@ import type { Density } from '@/lib/hooks/use-record-query'
|
||||
import type { TableVariant } from '@/lib/api/tables'
|
||||
import type { ColumnPins } from '@/lib/utils/query-columns'
|
||||
import { MATERIAL_BUTTON_VARIANTS } from '@/lib/utils/qqq-id'
|
||||
import { EXPLORE_LABELS, EXPLORE_VIEWS } from '@/lib/utils/data-analysis-explore'
|
||||
|
||||
import { LazyFavoriteToggle } from '@/components/collaboration/LazyFavoriteToggle'
|
||||
import { GotoRecordButton } from '@/components/records/GotoRecordDialog'
|
||||
@@ -190,7 +189,7 @@ export interface RecordQueryToolbarProps {
|
||||
/** Opens table analysis when capabilities permit it. */
|
||||
onAnalyzeTable?: () => void
|
||||
/** Opens an explorer under the table's analysis capability. */
|
||||
onExplore?: (view: (typeof EXPLORE_VIEWS)[number]) => void
|
||||
onExplore?: (view: 'pivot' | 'compare' | 'correlation' | 'crosstab' | 'shift') => void
|
||||
/** The backend table name used in API calls and URL routing. */
|
||||
tableName: string
|
||||
/** Full table metadata from the QQQ backend. */
|
||||
@@ -468,9 +467,9 @@ export function RecordQueryToolbar({
|
||||
</DropdownMenuPrimitive.Trigger>
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content align="start" sideOffset={4} className="z-[200] min-w-44 rounded border border-border bg-popover p-1 text-popover-foreground shadow-md">
|
||||
{EXPLORE_VIEWS.map(view => (
|
||||
{(['pivot', 'compare', 'correlation', 'crosstab', 'shift'] as const).map(view => (
|
||||
<DropdownMenuPrimitive.Item key={view} onSelect={() => onExplore(view)} className="cursor-pointer rounded px-3 py-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground" data-qqq-id={`explore-${view}`}>
|
||||
{EXPLORE_LABELS[view]}
|
||||
{view === 'shift' ? 'Shift over time' : view[0].toUpperCase() + view.slice(1)}
|
||||
</DropdownMenuPrimitive.Item>
|
||||
))}
|
||||
</DropdownMenuPrimitive.Content>
|
||||
|
||||
@@ -331,7 +331,7 @@ describe('AssociatedScriptViewer', () => {
|
||||
await user.type(input, 'Ada')
|
||||
await user.click(byQqqId(`button-test-script-${FIELD}`)!)
|
||||
|
||||
expect(testScript).toHaveBeenCalledWith({ scriptId: 101, files: { 'Script.js': "return 'Hello, friend';" }, inputValues: { name: 'Ada' } }, { signal: expect.any(AbortSignal) })
|
||||
expect(testScript).toHaveBeenCalledWith({ scriptId: 101, files: { 'Script.js': "return 'Hello, friend';" }, inputValues: { name: 'Ada' } })
|
||||
const output = byQqqId(`script-test-output-${FIELD}`)!
|
||||
await waitFor(() => expect(byQqqId(`script-test-output-${FIELD}-greeting`)).toHaveTextContent('Greeting: Hello, Ada! (22 characters)'))
|
||||
expect(within(output).queryByRole('alert')).toBeNull()
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { axe } from 'jest-axe'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
|
||||
import type { QAuditRecord, QTableMetaData } from '@/types'
|
||||
import { useAuditRecords } from '@/lib/hooks/use-audit-records'
|
||||
@@ -56,89 +55,3 @@ describe('AuditHistoryDialog', () => {
|
||||
expect(vi.mocked(useAuditRecords)).toHaveBeenLastCalledWith(expect.objectContaining({ isSortAscending: false }))
|
||||
})
|
||||
})
|
||||
describe('AuditHistoryDialog layout', () => {
|
||||
const LONG_ID = 'a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086'
|
||||
const history = (state: Partial<ReturnType<typeof useAuditRecords>>) =>
|
||||
vi.mocked(useAuditRecords).mockReturnValue({ auditRecords: [], total: null, isLoading: false, isError: false, error: null, refetch: vi.fn(), ...state } as unknown as ReturnType<typeof useAuditRecords>)
|
||||
const open = (recordLabel = LONG_ID, primaryKey: string | number = LONG_ID) =>
|
||||
render(<AuditHistoryDialog open onOpenChange={vi.fn()} source="process" tableMetaData={tableMetaData} primaryKey={primaryKey} recordLabel={recordLabel} />)
|
||||
|
||||
it('keeps a 64 character identifier inside the header: it may shrink and wrap, the controls may not', () => {
|
||||
open()
|
||||
const dialog = screen.getByRole('dialog', { name: `Audit for Record Lab: ${LONG_ID}` })
|
||||
const header = dialog.querySelector('[data-qqq-id="audit-history-header"]')!
|
||||
const title = screen.getByRole('heading', { level: 2 })
|
||||
const controls = header.querySelector('[data-qqq-id="audit-history-controls"]')!
|
||||
|
||||
// the heading's column is allowed to be narrower than its text, and the text breaks anywhere
|
||||
expect(header).toHaveClass('grid', 'grid-cols-[minmax(0,1fr)_auto]')
|
||||
expect(title).toHaveClass('min-w-0', '[overflow-wrap:anywhere]', 'line-clamp-3')
|
||||
// cut text stays available: in the title attribute and in the dialog's name
|
||||
expect(title).toHaveAttribute('title', `Audit for Record Lab: ${LONG_ID}`)
|
||||
expect(title).toHaveTextContent(LONG_ID)
|
||||
// every control is in the header, in the column that keeps its size
|
||||
expect(controls).toHaveClass('shrink-0')
|
||||
expect(controls.parentElement).toBe(header)
|
||||
for (const name of ['Copy record ID', 'Sort by time ascending (oldest to newest)', 'Sort by time descending (newest to oldest)', 'Close audit history']) {
|
||||
expect(within(controls as HTMLElement).getByRole('button', { name })).toBeInTheDocument()
|
||||
}
|
||||
})
|
||||
|
||||
it('copies the full identifier, and names what it copies', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
||||
open()
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Copy record ID' })) })
|
||||
expect(writeText).toHaveBeenCalledWith(LONG_ID)
|
||||
expect(screen.getByRole('button', { name: 'Copy record ID: copied' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the copy button for a label that is not the record ID', () => {
|
||||
open('Alice Johnson', 7)
|
||||
expect(screen.getByRole('button', { name: 'Copy record label' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an empty history as one block: icon and sentence together, no list and no band below', async () => {
|
||||
history({ auditRecords: [] })
|
||||
open()
|
||||
const dialog = screen.getByRole('dialog')
|
||||
const status = screen.getByRole('status')
|
||||
expect(status).toHaveTextContent('No audits were found for this record.')
|
||||
expect(status).toHaveAttribute('data-empty', 'true')
|
||||
expect(status).toHaveClass('flex', 'flex-col', 'items-center', 'text-center')
|
||||
// the icon belongs to the sentence, and is the only one outside the header
|
||||
expect(status.querySelectorAll('svg')).toHaveLength(1)
|
||||
expect(status.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(status).not.toHaveClass('border-b')
|
||||
// header and status are the whole dialog
|
||||
expect(dialog.children).toHaveLength(2)
|
||||
expect(dialog.lastElementChild).toBe(status)
|
||||
expect(screen.queryByRole('list', { name: 'Audits' })).not.toBeInTheDocument()
|
||||
expect(await axe(dialog)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it('shows loading and an error as a line, without the empty-state icon or an empty body', () => {
|
||||
history({ isLoading: true })
|
||||
const { unmount } = open()
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Loading audits...')
|
||||
expect(screen.getByRole('status').querySelector('svg')).toBeNull()
|
||||
expect(screen.getByRole('dialog').children).toHaveLength(2)
|
||||
unmount()
|
||||
|
||||
history({ isError: true, error: new Error('boom') })
|
||||
open()
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Error loading audits')
|
||||
expect(screen.getByRole('alert').querySelector('svg')).toBeNull()
|
||||
expect(screen.getByRole('dialog').children).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps the count line above the list when there are audits', () => {
|
||||
history({ auditRecords: records, total: null })
|
||||
open('Record 7', 7)
|
||||
const status = screen.getByRole('status')
|
||||
expect(status).toHaveTextContent('Showing all 3 audits for this record')
|
||||
expect(status).toHaveClass('border-b')
|
||||
expect(status.querySelector('svg')).toBeNull()
|
||||
expect(screen.getByRole('list', { name: 'Audits' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog'
|
||||
import { ArrowDown, ArrowUp, Check, Copy, History, X } from 'lucide-react'
|
||||
import { ArrowDown, ArrowUp, History, X } from 'lucide-react'
|
||||
|
||||
import type { QAuditRecord, QTableMetaData } from '@/types'
|
||||
import type { AuditSource } from '@/lib/api/audits'
|
||||
@@ -127,21 +127,11 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
|
||||
const { auditRecords, total, isLoading, isError, error } = useAuditRecords({ capabilities: tableMetaData.clientCapabilities,
|
||||
source, tableName: tableMetaData.name, primaryKey, enabled: open && sortReady, isSortAscending,
|
||||
})
|
||||
const [copied, setCopied] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!copied) return
|
||||
const timer = setTimeout(() => setCopied(false), 2000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [copied])
|
||||
|
||||
let status: string
|
||||
if (isLoading) status = 'Loading audits...'
|
||||
else if (isError) status = getErrorStatusCode(error) === 403 ? 'You do not have permission to view audits' : 'Error loading audits'
|
||||
else status = countSentence(auditRecords.length, total)
|
||||
const isEmpty = !isLoading && !isError && auditRecords.length === 0
|
||||
const heading = `Audit for ${tableMetaData.label}: ${recordLabel}`
|
||||
// what the copy button copies is what the heading may have cut short
|
||||
const copyLabel = recordLabel === String(primaryKey) ? 'Copy record ID' : 'Copy record label'
|
||||
|
||||
return (
|
||||
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
||||
@@ -162,23 +152,10 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
|
||||
'rounded-xl border border-border bg-card shadow-lg focus:outline-none'
|
||||
)}
|
||||
>
|
||||
{/* The heading takes the space the controls leave (`minmax(0,1fr)` lets it shrink below its
|
||||
text), so a long record identifier wraps inside the card, at any character, instead of
|
||||
pushing the sort and close buttons out of it. Past three lines it is cut with an
|
||||
ellipsis; the whole text stays in its `title`, in the dialog's accessible name, and on
|
||||
the copy button. */}
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 border-b border-border px-4 py-4 sm:gap-x-3 sm:px-6" data-qqq-id="audit-history-header">
|
||||
<DialogPrimitive.Title title={heading} data-qqq-id="audit-history-title"
|
||||
className="line-clamp-3 min-w-0 pt-1 text-lg font-semibold leading-snug tracking-tight text-foreground [overflow-wrap:anywhere]">
|
||||
{heading}
|
||||
<div className="flex items-center justify-between gap-3 border-b border-border px-6 py-4">
|
||||
<DialogPrimitive.Title className="text-lg font-semibold tracking-tight text-foreground">
|
||||
Audit for {tableMetaData.label}: {recordLabel}
|
||||
</DialogPrimitive.Title>
|
||||
<div className="flex shrink-0 items-center gap-1" data-qqq-id="audit-history-controls">
|
||||
<button type="button" aria-label={copied ? `${copyLabel}: copied` : copyLabel} title={copyLabel}
|
||||
onClick={() => { void navigator.clipboard?.writeText(recordLabel).then(() => setCopied(true), () => setCopied(false)) }}
|
||||
data-qqq-id="button-audit-copy-record"
|
||||
className="rounded-lg p-2 text-muted-foreground hover:bg-accent hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring">
|
||||
{copied ? <Check className="h-4 w-4 text-green-600 dark:text-green-400" aria-hidden="true" /> : <Copy className="h-4 w-4" aria-hidden="true" />}
|
||||
</button>
|
||||
<div className="flex shrink-0 items-center gap-1" role="group" aria-label="Audit sort order">
|
||||
<button type="button" aria-label="Sort by time ascending (oldest to newest)" aria-pressed={isSortAscending}
|
||||
onClick={() => { setSortAscending(true); localStorage.setItem('audit.sortDirection', 'true') }}
|
||||
@@ -200,21 +177,17 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
</DialogPrimitive.Close>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* One status element for every state (the dialog is described by it). With audits it is a
|
||||
line above the list. With none it is the whole body: a small icon and the sentence as
|
||||
one centered block, with no list and no empty band under it. */}
|
||||
<p id="audit-history-status" role={isError ? 'alert' : 'status'} data-qqq-id="audit-history-status"
|
||||
data-empty={isEmpty ? 'true' : undefined}
|
||||
className={cn('px-4 text-sm sm:px-6', isError ? 'text-destructive' : 'text-muted-foreground',
|
||||
isEmpty ? 'flex flex-col items-center gap-2 py-8 text-center' : 'py-3', auditRecords.length > 0 && 'border-b border-border')}>
|
||||
{isEmpty && <History className="h-6 w-6 text-muted-foreground/60" aria-hidden="true" />}
|
||||
className={cn('border-b border-border px-6 py-3 text-sm', isError ? 'text-destructive' : 'text-muted-foreground')}>
|
||||
{status}
|
||||
</p>
|
||||
|
||||
{auditRecords.length > 0 && <div className="flex-1 overflow-y-auto px-4 py-4 sm:px-6">
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
{!isLoading && !isError && auditRecords.length === 0 && (
|
||||
<History className="mx-auto h-10 w-10 text-muted-foreground/30" aria-hidden="true" />
|
||||
)}
|
||||
<ol aria-label="Audits">
|
||||
{groupAuditsByDate(auditRecords).map((group) => (
|
||||
<li key={`${localAuditDate(group[0].timestamp)}-${group[0].id}`}>
|
||||
@@ -224,7 +197,7 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>}
|
||||
</div>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
|
||||
@@ -15,14 +15,11 @@
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { FieldAdornment, QFieldMetaData, QRecord, QWidgetMetaData } from '@/types'
|
||||
import { FieldValue } from './FieldValue'
|
||||
import * as attachmentDelivery from '@/lib/api/attachment-download'
|
||||
|
||||
vi.mock('@/lib/api/attachment-download', () => ({ fetchTrackedAttachment: vi.fn(), safeAttachmentPreviewBlob: vi.fn(), saveAttachmentDownload: vi.fn() }))
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
|
||||
@@ -82,40 +79,6 @@ describe('FieldValue adornments use the backend value keys', () => {
|
||||
expect(document.querySelector('[data-qqq-id="field-value-doc-download"]')).toHaveAttribute('href', '/qqq/v1/table/lab/1/doc/a.txt?download=1')
|
||||
})
|
||||
|
||||
it.each(['preview', 'download'] as const)('uses the verified delivery gate for native attachment %s metadata', async (kind) => {
|
||||
const url = 'https://api.example/qqq/v1/qbit/record-files/files/7/downloads/00000000-0000-4000-8000-000000000001'
|
||||
const name = `${kind}Url`
|
||||
const adornments: FieldAdornment[] = [{ type: 'FILE_DOWNLOAD', values: { fileNameField: 'fileName', deliveryModeField: `${kind}Delivery`, ...(kind === 'download' ? { downloadUrlDynamic: true } : {}) } }]
|
||||
if (kind === 'preview') adornments.push({ type: 'FILE_PREVIEW', values: { fileNameField: 'fileName', mimeTypeField: 'contentType', sizeBytesField: 'sizeBytes', thumbnailMaxSize: 48 } })
|
||||
vi.mocked(attachmentDelivery.fetchTrackedAttachment).mockRejectedValue(new Error('Receipt unavailable'))
|
||||
vi.mocked(attachmentDelivery.saveAttachmentDownload).mockRejectedValue(new Error('Current access revoked'))
|
||||
const value = show(field(name, adornments), { [name]: url, [`${kind}Delivery`]: 'AUTHENTICATED_FETCH', fileName: 'Retained.pdf', contentType: 'application/pdf', sizeBytes: 13 },
|
||||
kind === 'download' ? { downloadUrl: 'Retained.pdf', 'downloadUrl:downloadUrlDynamic': url } : {})
|
||||
expect(value.querySelector('a,img,iframe')).toBeNull()
|
||||
expect(value.innerHTML).not.toContain(url)
|
||||
if (kind === 'preview') {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview file' }))
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Receipt unavailable'))
|
||||
expect(attachmentDelivery.fetchTrackedAttachment).toHaveBeenCalledWith(url, expect.any(AbortSignal))
|
||||
expect(value.querySelector('a,img,iframe')).toBeNull()
|
||||
} else {
|
||||
expect(screen.queryByRole('button', { name: 'Preview file' })).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Download file' }))
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Current access revoked'))
|
||||
expect(attachmentDelivery.saveAttachmentDownload).toHaveBeenCalledWith({ url, delivery: 'AUTHENTICATED_FETCH' }, 'Retained.pdf', expect.any(AbortSignal))
|
||||
expect(value.querySelector('a')).toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps native signed downloads compatible and refuses a missing declared delivery mode', () => {
|
||||
const nativeField = field('downloadUrl', [{ type: 'FILE_DOWNLOAD', values: { fileNameField: 'fileName', deliveryModeField: 'downloadDelivery', downloadUrlDynamic: true } }])
|
||||
const url = 'https://storage.example/immutable'
|
||||
const value = show(nativeField, { downloadUrl: url, fileName: 'Original.pdf', downloadDelivery: 'SIGNED_URL' }, { 'downloadUrl:downloadUrlDynamic': url })
|
||||
expect(value.querySelector('a')).toHaveAttribute('href', url)
|
||||
const missing = show(field('missingUrl', [{ type: 'FILE_DOWNLOAD', values: { deliveryModeField: 'missingDelivery' } }]), { missingUrl: url })
|
||||
expect(missing.querySelector('a,button,img,iframe')).toBeNull()
|
||||
})
|
||||
|
||||
it('reveals REVEAL values on request', () => {
|
||||
const secret = show(field('token', [{ type: 'REVEAL' }], { label: 'Token' }), { token: 'abc' })
|
||||
expect(secret).toHaveTextContent('••••••••')
|
||||
|
||||
@@ -47,7 +47,6 @@ import { HighlightedCode } from '@/components/scripts/HighlightedCode'
|
||||
import { SeededWidget } from '@/components/widgets/ConnectedWidget'
|
||||
import { DateTimeText } from '@/components/ui/DateTimeText'
|
||||
import { FileThumbnail } from '@/components/preview/FileThumbnail'
|
||||
import { DeliveredFileActions } from '@/components/preview/DeliveredFileActions'
|
||||
import { RecordHoverCard } from './RecordHoverCard'
|
||||
|
||||
/**
|
||||
@@ -160,13 +159,6 @@ function FieldValueContent({ field, record, allTables, navigateFrom, widgetMetaD
|
||||
)
|
||||
}
|
||||
|
||||
const deliveryAdornment = findAdornment(field, 'FILE_DOWNLOAD')
|
||||
if (deliveryAdornment?.values?.deliveryModeField !== undefined) {
|
||||
const delivery = fileDownload(field, record)
|
||||
if (!delivery) return <EmptyValue fieldName={field.name} className={className} />
|
||||
if (delivery.delivery === 'AUTHENTICATED_FETCH') return <DeliveredFileActions key={delivery.url} url={delivery.url} fileName={delivery.fileName}
|
||||
allowPreview={!!findAdornment(field, 'FILE_PREVIEW')} dataQqqId={dataQqqId} />
|
||||
}
|
||||
const preview = filePreview(field, record, storedRecordVariantJson(tableMetaData ?? allTables?.[record.tableName]))
|
||||
if (preview) {
|
||||
return <FileThumbnail field={field} record={record} item={preview} size={thumbnailSize} showName={thumbnailSize !== undefined}
|
||||
|
||||
@@ -567,11 +567,8 @@ function RecordViewContent({
|
||||
)
|
||||
const viewId = `record-view-${tableMetaData.name}`
|
||||
// the record's FILE_PREVIEW values, in section order, form the preview gallery of the page
|
||||
const previewFields = [...new Set(orderedSections.flatMap((section) => section.fieldNames ?? []))]
|
||||
.map((name) => recordSectionField(tableMetaData, allTables, name))
|
||||
.filter((field): field is QFieldMetaData => Boolean(field && !field.isHidden))
|
||||
// Delivery-aware fields use their own verified transfer controls, never a raw gallery URL.
|
||||
.filter((field) => !field.adornments?.some((adornment) => adornment.type === 'FILE_DOWNLOAD' && adornment.values?.deliveryModeField !== undefined))
|
||||
const previewFields = [...new Set((tableMetaData.sections ?? []).flatMap((section) => section.fieldNames ?? []))]
|
||||
.map((name) => tableMetaData.fields[name]).filter((field): field is QFieldMetaData => Boolean(field))
|
||||
const materialViewId = `record-view-${sanitizeQqqId(tableMetaData.name)}`
|
||||
|
||||
return (
|
||||
|
||||
@@ -38,18 +38,6 @@ const record = { tableName: 'lab', values: { id: 1, title: 'Visible title' } } a
|
||||
afterEach(() => window.localStorage.clear())
|
||||
|
||||
describe('RecordViewSection widget headings', () => {
|
||||
it('renders native virtual values while excluding hidden and absent fields', () => {
|
||||
const metadata = { ...table, virtualFields: {
|
||||
previewUrl: { name: 'previewUrl', label: 'Preview', type: 'STRING', isHidden: false },
|
||||
hiddenUrl: { name: 'hiddenUrl', label: 'Hidden', type: 'STRING', isHidden: true },
|
||||
} } as unknown as QTableMetaData
|
||||
const section = { name: 'file', label: 'File', fieldNames: ['previewUrl', 'hiddenUrl', 'absent'], isHidden: false } as QTableSection
|
||||
render(<RecordViewSection section={section} tableMetaData={metadata} record={{ ...record, values: { previewUrl: 'visible virtual value', hiddenUrl: 'must stay hidden' } }} />)
|
||||
expect(screen.getByText('visible virtual value')).toBeVisible()
|
||||
expect(screen.queryByText('must stay hidden')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('undefined')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('leaves the heading to the widget card when the card has the same label', () => {
|
||||
const section = { name: 'progress', label: 'Live Progress', fieldNames: [], widgetName: 'progressWidget', isHidden: false } as QTableSection
|
||||
const widget = { name: 'progressWidget', label: 'Live Progress', hasPermission: true } as QWidgetMetaData
|
||||
|
||||
@@ -39,7 +39,7 @@ import React, { useCallback, useLayoutEffect, useRef, useState, useSyncExternalS
|
||||
|
||||
import type { CodeLanguage } from '@/lib/utils/code-highlight'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { findCodeCompletions, type CodeCompletion, type CodeCompletionMatch } from '@/lib/utils/code-completions'
|
||||
import { findCodeCompletions, type CodeCompletionMatch } from '@/lib/utils/code-completions'
|
||||
import { HighlightedCode } from './HighlightedCode'
|
||||
|
||||
/** The text a Tab inserts. */
|
||||
@@ -101,8 +101,6 @@ export interface CodeEditorProps {
|
||||
language: CodeLanguage
|
||||
/** Enable local code suggestions for script files. */
|
||||
autocomplete?: boolean
|
||||
/** Runtime-specific helper suggestions; omitted for the existing trusted API. */
|
||||
apiCompletions?: readonly CodeCompletion[]
|
||||
/** Read-only: selectable and focusable, never edited, never captures Tab. */
|
||||
readOnly?: boolean
|
||||
/** Visible rows. Defaults to 12. */
|
||||
@@ -165,7 +163,6 @@ export function CodeEditor({
|
||||
language,
|
||||
readOnly = false,
|
||||
autocomplete = false,
|
||||
apiCompletions,
|
||||
rows = 12,
|
||||
ariaLabel,
|
||||
describedBy,
|
||||
@@ -203,7 +200,7 @@ export function CodeEditor({
|
||||
setCompletion(null)
|
||||
return
|
||||
}
|
||||
const match = findCodeCompletions(textarea.value, textarea.selectionStart, language, explicit, apiCompletions)
|
||||
const match = findCodeCompletions(textarea.value, textarea.selectionStart, language, explicit)
|
||||
if (!match) { setCompletion(null); return }
|
||||
const before = textarea.value.slice(0, textarea.selectionStart).split('\n')
|
||||
const metrics = metricsRef.current?.getBoundingClientRect()
|
||||
|
||||
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user