Compare commits

..
Author SHA1 Message Date
james.maesandClaude Fable 5.2 5694671227 feat(query): a table can declare the sort its record list opens with
maven / build (push) Successful in 11m7s
build / maven (push) Successful in 11m7s
The record list fixed its initial sort at primary key descending
(use-record-query) and read no default from the table metadata, so an
application could not make a list open newest first by a date field.

QQQ core serves no table-level default sort or default view (checked at
4.1.0-RC.32: the table metadata has built-in views only for record ownership,
and no order-by). It does publish a table's supplemental metadata, where this
frontend already reads a hint object, supplementalMetaData.nextUi, for
defaultColumns. The contract is one more key in that object:

  "supplementalMetaData": { "nextUi": { "defaultSort": [
    { "fieldName": "receivedAt", "isAscending": false } ] } }

Each entry has the shape of a query filter order-by (QFilterOrderBy);
isAscending defaults to ascending. Entries naming an unknown field, a field
the user may not sort by, or with a non-boolean direction are ignored; with no
usable entry the default stays primary key descending.

The declared sort replaces the one default the hook already had, so every use
follows it: the list opens with it, the address omits it, New View and Reset
All Changes return to it, clearing a sort returns to it, and it is not an
unsaved change. A sort in the address, a saved view's sort, and the sort the
browser remembers for the table each win over it.

Documented in the README under "Default sort", including what an application
adds on the backend to fill the hint.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 03:43:12 -06:00
james.maes 787a227602 Merge pull request 'fix(preferences): an action that answers with an address opens it; a section says how a connection ended' (#214) from fix/process-link-and-preference-redirect into main
maven / build (push) Successful in 10m17s
build / maven (push) Successful in 10m17s
2026-11-11 12:38:10 +00:00
james.maesandClaude Fable 5.2 30f4f9d586 fix(preferences): an action that answers with an address opens it; a section says how a connection ended
maven / build (push) Successful in 5m2s
build / maven (push) Successful in 5m2s
A preference action that starts an OAuth connection (Connect Slack)
answers with the consent page's address in the action result's message,
because the UI API has no redirect field. The address was the text of a
success toast: long, not clickable and gone in seconds.

- A message that is nothing but one absolute https address is where the
  browser goes, in this tab, and is never shown (continuationUrl,
  leaveTo). A message that only mentions an address is still a message.
  Plain http, credentials in the address and other schemes are not
  followed.
- A flow that returns to /app/preferences?section=<name>&result=<code>
  or &error=<code> gets its outcome shown once above the section's form,
  as the section's label and the code as words ("Slack: connected.",
  "Slack: authorization denied."), as a status or an alert, and taken
  off the address. Only a fixed lowercase code is read, never a sentence.
- Links in an HTML process component use the link color and an
  underline; they looked like the text around them. A link's own inline
  style still wins.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 06:31:38 -06:00
james.maes 24bbe4a038 Merge pull request 'fix(errors): the error banner says what failed and no longer stacks' (#210) from fix/error-banner-names-cause into main
maven / build (push) Successful in 5m7s
build / maven (push) Successful in 5m7s
2026-11-11 00:58:17 +00:00
james.maes 8903f272c4 Merge pull request 'fix(header): the Ask button's activity dot and unread badge sit on its icon' (#213) from fix/ask-indicator-anchor into main
maven / build (push) Successful in 8m37s
build / maven (push) Successful in 8m37s
2026-11-11 00:58:15 +00:00
james.maesandClaude Fable 5.2 2345039911 fix(header): the Ask button's activity dot and unread badge sit on its icon
maven / build (push) Successful in 14m45s
build / maven (push) Successful in 14m44s
The dot shown while a reply is being written was positioned against the
button (absolute bottom-0 right-0). The button's box is its hit area: 10 px
of padding around the icon and, from 1440 px, the "Ask" label, with no
visible edge at rest. The dot therefore landed past the label and under its
baseline, detached from the icon; the unread badge landed over the end of
the label.

Header indicators are now positioned against the icon: HeaderIconAnchor is
a box exactly the size of the icon, with HEADER_BADGE_CLASS (top-right) and
HEADER_STATUS_DOT_CLASS (bottom-right). Ask, the bell and Jobs share it; on
the 40 px icon-only buttons the badge keeps its pixels (2 px inside the
button's top-right corner).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 18:40:45 -06:00
23 changed files with 933 additions and 49 deletions

No files matched your search

+35
View File
@@ -225,3 +225,38 @@ 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.
+7
View File
@@ -13,9 +13,16 @@
- 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.
- **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.
- **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 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.
+13 -11
View File
@@ -35,7 +35,7 @@ import { getAlertsInboxSummary } from '@/lib/api/alerts'
import { queryKeys } from '@/lib/query-client'
import type { AlertsInboxSummary } from '@/types/alerts'
import type { QInstance } from '@/types/metadata'
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
const AlertsBellPopover = lazy(() => import('./AlertsBellPopover'))
@@ -132,16 +132,18 @@ export function AlertsBell(_props: { metaData: QInstance | undefined }) {
aria-expanded={open}
data-qqq-id="button-notifications"
>
<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>
)}
<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>
</button>
<span className="sr-only" aria-live="polite" data-qqq-id="alerts-unread-announcer">{label}</span>
{open && (
@@ -198,7 +198,12 @@ 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')
expect(screen.getByText('2', { selector: '[data-qqq-id="alerts-unread-badge"]' })).toHaveClass('bg-destructive')
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(document.querySelector('[data-qqq-id="alerts-unread-announcer"]')).toHaveAttribute('aria-live', 'polite')
first.unmount()
@@ -0,0 +1,177 @@
/*
* 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,13 +25,14 @@ import React from 'react'
import { useQuery } from '@tanstack/react-query'
import { Sparkles } from 'lucide-react'
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HEADER_STATUS_DOT_CLASS, HeaderIconAnchor } 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. 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 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).
*
* @returns The button, or null when the assistant is unavailable.
*/
@@ -50,24 +51,23 @@ export function AssistantHeaderButton() {
event.currentTarget.focus({ preventScroll: true })
toggle()
}}
className={cn(HEADER_BUTTON_CLASS, 'gap-1.5')}
className={cn(HEADER_BUTTON_CLASS, 'gap-2')}
aria-label={label}
title="Ask the assistant (Ctrl+J or ⌘J)"
aria-pressed={open}
data-qqq-id="button-assistant"
>
<Sparkles className="h-5 w-5" aria-hidden="true" />
{/* 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>
<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>
)
}
@@ -106,6 +106,12 @@ 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()
+13 -11
View File
@@ -18,7 +18,7 @@
'use client'
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'
import { BriefcaseBusiness } from 'lucide-react'
import { HEADER_BUTTON_CLASS } from '@/components/layout/HeaderMenu'
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
import { useJobsInstalled, useMyJobs } from '@/lib/hooks/use-my-jobs'
import './jobs.css'
@@ -76,16 +76,18 @@ export function JobsHeaderButton() {
className="qqq-job-ring absolute inset-1 rounded-full border border-primary"
/>
)}
<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>
)}
<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>
</button>
<span aria-live="polite" className="sr-only" data-qqq-id="jobs-announcer">
{announcement}
+28
View File
@@ -33,6 +33,34 @@ 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',
@@ -32,8 +32,15 @@ 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)) {
@@ -387,3 +394,36 @@ 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,6 +32,7 @@ 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'
@@ -381,7 +382,11 @@ export function usePreferenceActions({
showingSecrets.current = Boolean(result.secrets?.length)
onSaved(result.section)
setSelected(null)
if (result.message) toast.success(result.message)
// 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)
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 } from './PreferencesPage'
import { PreferencesPage, sectionOutcome } from './PreferencesPage'
const state = vi.hoisted(() => ({
search: '',
@@ -107,3 +107,42 @@ 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()
})
+50 -2
View File
@@ -17,13 +17,14 @@
/** @file Preferences route content, with device display settings and server-owned sections. */
'use client'
import { useEffect } from 'react'
import { useEffect, useState } 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'
@@ -43,6 +44,30 @@ 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.
*/
@@ -59,6 +84,13 @@ 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'
@@ -73,13 +105,15 @@ export function PreferencesPage() {
...(query.data?.sections ?? []),
]
const section = query.data?.sections.find((section) => section.name === selected)
const navigate = (name: string) =>
const navigate = (name: string) => {
setOutcome(null)
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>
@@ -159,6 +193,20 @@ 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} />
</>
) : (
+2 -1
View File
@@ -56,9 +56,10 @@ 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"
className="prose prose-sm max-w-none text-foreground [&_a]:text-link [&_a]:underline"
data-qqq-id={`process-html-${index}`}
dangerouslySetInnerHTML={{ __html: html }}
/>
@@ -205,6 +205,24 @@ 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, '&amp;')}" 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>')
@@ -0,0 +1,180 @@
/*
* 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)
})
})
+8 -3
View File
@@ -56,6 +56,7 @@ import { isColumnVisible, type ViewState } from '@/lib/utils/saved-view-utils'
import { getDefaultQuickFilterFieldNames, reconcileBasicMode } from '@/lib/utils/quick-filter-utils'
import { defaultColumnVisibility, hasCapability, withReadableExposedJoins, type ColumnPins } from '@/lib/utils/query-columns'
import { DENSITY_STORAGE_KEY, readLegacyColumnState } from '@/lib/utils/query-view-storage'
import { tableDefaultSort } from '@/lib/utils/query-default-sort'
import { useLocalStorage } from '@/lib/hooks/use-local-storage'
import { useColumnConfig } from '@/lib/hooks/use-column-config'
import { DEFAULT_PAGE_SIZE, PAGE_SIZE_OPTIONS } from '@/lib/constants'
@@ -320,9 +321,13 @@ export function useRecordQuery({
const [storedDensity, setDensity] = useLocalStorage<Density>(DENSITY_STORAGE_KEY, 'standard')
const density: Density = (['compact', 'standard', 'comfortable'] as const).includes(storedDensity) ? storedDensity : 'standard'
const primaryKey = tableMetaData?.primaryKeyField
/** Material's default sort: primary key, descending. */
const defaultSort = useMemo<QFilterOrderBy[]>(() => (primaryKey ? [{ fieldName: primaryKey, isAscending: false }] : []), [primaryKey])
/**
* The sort the list opens with and resets to: the one the table's metadata declares
* (`supplementalMetaData.nextUi.defaultSort`), else Material's default, primary key descending.
* Keyed by its content, so reloaded metadata that declares the same sort changes nothing.
*/
const defaultSortKey = JSON.stringify(tableDefaultSort(tableMetaData))
const defaultSort = useMemo<QFilterOrderBy[]>(() => JSON.parse(defaultSortKey) as QFilterOrderBy[], [defaultSortKey])
/** Quick filters every user sees in basic mode (Material defaultQuickFilterFieldNames, else T1 fields). */
const defaultQuickFilterFieldNames = useMemo(() => (tableMetaData ? getDefaultQuickFilterFieldNames(tableMetaData) : []), [tableMetaData])
const filterModeKey = `qqq-${tableName}-filter-mode`
+43
View File
@@ -0,0 +1,43 @@
/*
* 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 { expect, it } from 'vitest'
import { continuationUrl } from './external-navigation'
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'
it('recognizes an answer that is only an absolute https address, and returns it unchanged', () => {
expect(continuationUrl(AUTHORIZE)).toBe(AUTHORIZE)
expect(continuationUrl(` ${AUTHORIZE}\n`)).toBe(AUTHORIZE)
})
it.each([
['an ordinary message', 'Slack disconnected.'],
['a sentence that contains an address', `Open ${AUTHORIZE}`],
['two addresses', `${AUTHORIZE} ${AUTHORIZE}`],
['plain http', 'http://slack.com/oauth/v2/authorize'],
['a script address', 'javascript:alert(1)'],
['a data address', 'data:text/html,<p>x</p>'],
['a protocol-relative address', '//slack.com/oauth'],
['a local path', '/app/preferences'],
['credentials in the address', 'https://user:secret@slack.com/oauth'],
['no host', 'https://'],
['an empty answer', ''],
['no answer', undefined],
])('leaves %s as a message', (_name, text) => {
expect(continuationUrl(text)).toBeNull()
})
+49
View File
@@ -0,0 +1,49 @@
/*
* 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 external-navigation — leaving the dashboard for another site, such as the consent
* page of a service the user is connecting. An address is something to go to, never text to
* show: a backend answer that is only an address is recognized here and opened.
*/
/**
* The address a backend answer names when the answer is nothing but one absolute `https:`
* address: no other words, no whitespace, no credentials in it. A sentence that merely
* contains an address is an ordinary message and is not matched.
*
* @param text - The backend's answer (an action result message, for example).
* @returns The address exactly as sent, or `null` when the answer is anything else.
*/
export function continuationUrl(text: string | null | undefined): string | null {
const address = text?.trim()
if (!address || /\s/.test(address) || !/^https:\/\//i.test(address)) return null
try {
const url = new URL(address)
return url.protocol === 'https:' && url.hostname && !url.username && !url.password ? address : null
} catch {
return null
}
}
/**
* Sends the browser to another site in this tab, so the site can return the user here.
*
* @param url - An absolute address (see {@link continuationUrl}).
*/
export function leaveTo(url: string): void {
window.location.assign(url)
}
+112
View File
@@ -0,0 +1,112 @@
/*
* 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 { QTableMetaData } from '@/types'
import { qInstance } from '@/mocks/fixtures/q-instance'
import { declaredDefaultSort, tableDefaultSort } from './query-default-sort'
const PRIMARY_KEY_DESCENDING = [{ fieldName: 'id', isAscending: false }]
/**
* The people table with a Next UI hint.
*
* @param nextUi - The hint object.
* @param legacy - Put it under the legacy `supplementalTableMetaData` key.
* @returns Table metadata.
*/
function person(nextUi?: unknown, legacy = false): QTableMetaData {
const table = structuredClone(qInstance.tables.person)
if (nextUi !== undefined) table[legacy ? 'supplementalTableMetaData' : 'supplementalMetaData'] = { nextUi } as Record<string, unknown>
return table
}
describe('tableDefaultSort', () => {
it('is primary key descending for a table that declares nothing', () => {
expect(tableDefaultSort(person())).toEqual(PRIMARY_KEY_DESCENDING)
expect(tableDefaultSort(person({ defaultColumns: ['id', 'firstName'] }))).toEqual(PRIMARY_KEY_DESCENDING)
expect(declaredDefaultSort(person())).toEqual([])
})
it('is empty before metadata loads and for a table without a primary key', () => {
expect(tableDefaultSort(undefined)).toEqual([])
expect(tableDefaultSort({ ...person(), primaryKeyField: '' })).toEqual([])
})
it('honours a declared sort, in order, with ascending as the direction when none is given', () => {
expect(tableDefaultSort(person({ defaultSort: [{ fieldName: 'modifyDate', isAscending: false }] }))).toEqual([{ fieldName: 'modifyDate', isAscending: false }])
expect(tableDefaultSort(person({ defaultSort: [{ fieldName: 'lastName' }, { fieldName: 'firstName', isAscending: true }, { fieldName: 'id', isAscending: false }] }))).toEqual([
{ fieldName: 'lastName', isAscending: true },
{ fieldName: 'firstName', isAscending: true },
{ fieldName: 'id', isAscending: false },
])
})
it('reads the legacy supplemental key, and prefers the current one', () => {
expect(tableDefaultSort(person({ defaultSort: [{ fieldName: 'lastName', isAscending: true }] }, true))).toEqual([{ fieldName: 'lastName', isAscending: true }])
const both = person({ defaultSort: [{ fieldName: 'firstName', isAscending: true }] })
both.supplementalTableMetaData = { nextUi: { defaultSort: [{ fieldName: 'lastName', isAscending: true }] } }
expect(tableDefaultSort(both)).toEqual([{ fieldName: 'firstName', isAscending: true }])
})
it('accepts a field of an exposed join', () => {
const table = person()
const join = table.exposedJoins?.find((candidate) => Object.keys(candidate.joinTable?.fields ?? {}).length > 0)
const fieldName = `${join?.joinTable?.name}.${Object.keys(join?.joinTable?.fields ?? {})[0]}`
expect(join).toBeTruthy()
table.supplementalMetaData = { nextUi: { defaultSort: [{ fieldName, isAscending: false }] } }
expect(tableDefaultSort(table)).toEqual([{ fieldName, isAscending: false }])
})
it('drops entries it cannot use and keeps the rest', () => {
const table = person({
defaultSort: [
{ fieldName: 'noSuchField', isAscending: false },
{ fieldName: 'lastName', isAscending: 'yes' },
{ isAscending: false },
'modifyDate',
null,
['modifyDate', false],
{ fieldName: 'modifyDate', isAscending: false },
{ fieldName: 'modifyDate', isAscending: true },
{ fieldName: 'noSuchJoin.name', isAscending: true },
],
})
expect(tableDefaultSort(table)).toEqual([{ fieldName: 'modifyDate', isAscending: false }])
})
it('does not sort by a field the user may not sort by', () => {
const table = person({ defaultSort: [{ fieldName: 'email', isAscending: true }, { fieldName: 'lastName', isAscending: true }] })
table.fields.email = { ...table.fields.email, isSortable: false }
expect(tableDefaultSort(table)).toEqual([{ fieldName: 'lastName', isAscending: true }])
})
it.each([
['an empty list', []],
['a single object', { fieldName: 'modifyDate', isAscending: false }],
['a string', 'modifyDate'],
['null', null],
['only unusable entries', [{ fieldName: 'noSuchField' }, { fieldName: 'lastName', isAscending: 1 }]],
])('falls back to primary key descending for %s', (_what, defaultSort) => {
expect(tableDefaultSort(person({ defaultSort }))).toEqual(PRIMARY_KEY_DESCENDING)
})
it('falls back when the hint itself is not an object', () => {
expect(tableDefaultSort(person('newest'))).toEqual(PRIMARY_KEY_DESCENDING)
expect(tableDefaultSort(person(null))).toEqual(PRIMARY_KEY_DESCENDING)
})
})
+77
View File
@@ -0,0 +1,77 @@
/*
* 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 query-default-sort — the sort a table's record list opens with.
*
* A table can declare it, beside its default columns, in the Next UI hint of its supplemental
* metadata:
*
* ```json
* "supplementalMetaData": { "nextUi": { "defaultSort": [{ "fieldName": "receivedAt", "isAscending": false }] } }
* ```
*
* Each entry has the shape of an order-by in a query filter (`QFilterOrderBy`). Without a usable
* declaration the list sorts by primary key, descending, as it always has.
*/
import type { QFilterOrderBy, QTableMetaData } from '@/types'
import { resolveField } from './filter-utils'
import { canSortField } from './secured-data'
/**
* The sort a table's metadata declares for its record list, validated: an entry is kept when its
* `fieldName` names a field of the table (or of an exposed join, as `joinTable.field`) that the
* user may sort by, and its `isAscending` is a boolean or absent (ascending, as for an order-by).
* A field named twice counts once. Anything else is dropped.
*
* @param table - Table metadata.
* @returns The declared order-bys that can be used; empty when the table declares none.
*/
export function declaredDefaultSort(table: QTableMetaData): QFilterOrderBy[] {
const hint = (table.supplementalMetaData?.nextUi ?? table.supplementalTableMetaData?.nextUi) as { defaultSort?: unknown } | null | undefined
const declared = hint && typeof hint === 'object' ? hint.defaultSort : undefined
if (!Array.isArray(declared)) return []
const orderBys: QFilterOrderBy[] = []
for (const entry of declared) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
const { fieldName, isAscending } = entry as Record<string, unknown>
if (typeof fieldName !== 'string' || (isAscending !== undefined && typeof isAscending !== 'boolean')) continue
if (orderBys.some((orderBy) => orderBy.fieldName === fieldName)) continue
const field = resolveField(table, fieldName)?.field
if (!field || !canSortField(field)) continue
orderBys.push({ fieldName, isAscending: isAscending ?? true })
}
return orderBys
}
/**
* The sort a table's record list opens with, and returns to on a reset: the one the table
* declares, else its primary key, descending (Material's default).
*
* A person's own choice always comes first: a sort in the address, the sort of a saved view, or
* the sort the browser remembers for the table is used instead of this one.
*
* @param table - Table metadata, when loaded.
* @returns The default order-bys; empty only for a table without a primary key.
*/
export function tableDefaultSort(table: QTableMetaData | undefined): QFilterOrderBy[] {
if (!table) return []
const declared = declaredDefaultSort(table)
if (declared.length > 0) return declared
return table.primaryKeyField ? [{ fieldName: table.primaryKeyField, isAscending: false }] : []
}
+3 -3
View File
@@ -27,6 +27,7 @@ import type { QFieldMetaData, QFilterCriteria, QFilterOrderBy, QQueryFilter, QTa
import { formatDateTime } from './datetime-utils'
import { normalizeFilter, isCriterionComplete, emptyFilter, isFilterExpression, describeExpression, resolveField } from './filter-utils'
import { arrangePinnedColumns, effectivePins, getQueryColumns, orderColumns, type ColumnPin, type ColumnPins } from './query-columns'
import { tableDefaultSort } from './query-default-sort'
/** One column entry in a saved view (Material `QQueryColumns.Column`). */
export interface SavedViewColumn {
@@ -634,9 +635,8 @@ export function reconcileView(table: QTableMetaData, view: RecordQueryView): Rec
removedFields.add(orderBy.fieldName)
return false
})
if (savedOrderBys.length > 0 && orderBys.length === 0 && table.primaryKeyField) {
orderBys.push({ fieldName: table.primaryKeyField, isAscending: false })
}
// a view whose every sort field is gone falls back to the table's default sort
if (savedOrderBys.length > 0 && orderBys.length === 0) orderBys.push(...tableDefaultSort(table))
const quickFilterFieldNames = (view.quickFilterFieldNames ?? []).filter((name) => {
if (exists(name)) return true
removedFields.add(name)
+5
View File
@@ -91,6 +91,11 @@ export interface PreferenceSecret {
/** Only section is safe to retain in the preferences cache. */
export interface PreferenceActionResponse {
section: PreferenceSection
/**
* The outcome, shown once. The UI API has no redirect field, so a message that is nothing but
* one absolute `https:` address is where the browser goes next (an OAuth consent page) and is
* never shown; see `continuationUrl`.
*/
message?: string
secrets?: PreferenceSecret[]
focusRowKey?: string