AI-native design editor. Open-source Figma alternative.
feat: show Cloud console lists as paged, searchable tables with loading states (#1526)
Danila Poyarkov07056aab7fc7
diff --git a/bun.lock b/bun.lockindex eaeef6e65..f80d90253 100644--- a/bun.lock+++ b/bun.lock@@ -48,6 +48,7 @@"@smithy/fetch-http-handler": "^5.8.0","@stream-markdown/code": "2.0.0-beta.5","@tailwindcss/vite": "^4.3.3",+ "@tanstack/vue-table": "^9.3.1","@tauri-apps/api": "^2.12.1","@tauri-apps/plugin-clipboard-manager": "^2.4.1","@tauri-apps/plugin-dialog": "^2.8.1",@@ -2279,8 +2280,14 @@"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],+ "@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q=="],++ "@tanstack/table-core": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="],+"@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-BfEvehNpOT75r5Ksc5xW6NZuXujTfb7nlSEyVu4XHG3gdxNg1KqXruWbDewXOUaUYIo4oRbSfkjIajz4MAT8tA=="],+ "@tanstack/vue-table": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.11.2", "@tanstack/table-core": "9.3.1" }, "peerDependencies": { "vue": ">=3.2" } }, "sha512-7z7nS4UP91rLZ01suGxQBT611ogfBrs7/E+lsKeYS9XdHSRUAzclFvQ4B10F0bC/Q8BrzgXiNH3QzumK7b0Tow=="],+"@tanstack/vue-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.17.8" }, "peerDependencies": { "vue": "^2.7.0 || ^3.0.0" } }, "sha512-gKpExv4RbB9luVG+SucTXoqPZv/gzu/Yvz6BNO+8kpNxJ2x+I/ulryzl5W9BRciahZGp5Tls3Dp5XP1ztVGbMw=="],"@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ=="],diff --git a/changes/1526/changed.md b/changes/1526/changed.mdnew file mode 100644index 000000000..920bff33e--- /dev/null+++ b/changes/1526/changed.md@@ -0,0 +1 @@+- A Cloud server's console lists people, access requests, email, and activity as tables with labelled columns, and each one is searched, filtered with a count per filter, and paged: requests by name or email, email by recipient and delivery, activity by who acted or whom it was about. Access requests name the administrator who decided them, and each row keeps one action at hand with the rest in its "…" menu. Pages show placeholders while they first load and keep their rows while they load again, and the section row on a narrow screen scrolls with a chevron instead of a scrollbar.diff --git a/package.json b/package.jsonindex 75c141177..dfd307d5f 100644--- a/package.json+++ b/package.json@@ -163,6 +163,7 @@"@smithy/fetch-http-handler": "^5.8.0","@stream-markdown/code": "2.0.0-beta.5","@tailwindcss/vite": "^4.3.3",+ "@tanstack/vue-table": "^9.3.1","@tauri-apps/api": "^2.12.1","@tauri-apps/plugin-clipboard-manager": "^2.4.1","@tauri-apps/plugin-dialog": "^2.8.1",diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex 195cfdf27..a3a1dfa1e 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -16,6 +16,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- Renaming a table that shipped migrations query gives them a type under the name they ran with, so their SQL stays the same (`LegacyAuthSchemaDatabase` in `src/server/db/migrations/helpers.ts`).- `user.image` only ever holds an address this server serves; a picture from anywhere else is copied into `user_picture` or dropped, never linked (`src/server/pictures/service.ts`, `tests/integration/server/pictures/routes.test.ts`).- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).+- An admin list takes `search`, `filter`, `limit`, and `offset` through `listQuery` and answers with its rows, `total`, and per-filter `counts`; it declares its filters once as `ListFilters`, which count in one query and page with the same condition (`src/admin/list.ts`, `tests/integration/admin/lists.test.ts`).- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).- A revision's images live in `revision_image`; code that makes a revision from another copies them with `copyRevisionImages`, and a storage object a `workspace_image` holds is never unreferenced (`src/server/documents/images.ts`, `tests/integration/server/documents/images.test.ts`).- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).diff --git a/packages/cloud/src/admin/api/routes.ts b/packages/cloud/src/admin/api/routes.tsindex 2c45fe0ba..7bb222ca5 100644--- a/packages/cloud/src/admin/api/routes.ts+++ b/packages/cloud/src/admin/api/routes.ts@@ -11,7 +11,11 @@ import {parseUserRoleMutation} from '#cloud/admin/schema'import type { AdminUserService } from '#cloud/admin/users/service'-import { cloudAdminUserFilterSchema } from '#cloud/contract'+import {+ cloudAdminAuditFilterSchema,+ cloudAdminEmailFilterSchema,+ cloudAdminUserFilterSchema+} from '#cloud/contract'import type { CloudAPIEnvironment } from '#cloud/server/api'import type { CloudAuthAdapter } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'@@ -21,21 +25,25 @@ import { Hono, type Context } from 'hono'import { NoResultError, type Kysely } from 'kysely'import * as v from 'valibot'-/** A count from the query string; anything but digits is a bad request, not a NaN query. */-const countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber()))-const parseEnrollmentQuery = (input: unknown) =>- v.parse(v.object({ status: v.optional(enrollmentStatusSchema) }), input)-const parseUserQuery = (input: unknown) =>- v.parse(- v.object({- search: v.optional(v.string()),- filter: v.optional(cloudAdminUserFilterSchema),- limit: countSchema,- offset: countSchema- }),- input- )-const parseLimitQuery = (input: unknown) => v.parse(v.object({ limit: countSchema }), input)+/**+ * A count from the query string; anything but digits, or a number too large to be exact, is a bad+ * request rather than a NaN or out-of-range query.+ */+const countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber(), v.safeInteger()))+/** What an admin list reads from its query string: a search, one of `filters`, and a page. */+function listQuery<const Filter extends string>(filters: v.PicklistSchema<Filter[], undefined>) {+ const schema = v.object({+ search: v.optional(v.string()),+ filter: v.optional(filters),+ limit: countSchema,+ offset: countSchema+ })+ return (input: unknown) => v.parse(schema, input)+}+const parseEnrollmentQuery = listQuery(enrollmentStatusSchema)+const parseUserQuery = listQuery(cloudAdminUserFilterSchema)+const parseEmailQuery = listQuery(cloudAdminEmailFilterSchema)+const parseAuditQuery = listQuery(cloudAdminAuditFilterSchema)/** Accounts are named by UUID; anything else names no one, rather than failing the query. */const accountIdSchema = v.pipe(v.string(), v.uuid())@@ -113,9 +121,7 @@ export function createCloudAdminRoutes(throw error}).get('/enrollments', validatedQuery(parseEnrollmentQuery), async (context) =>- context.json({- enrollments: await services.enrollment.list(context.req.valid('query').status)- })+ context.json(await services.enrollment.list(context.req.valid('query')))).post('/enrollments/:id/approve', validatedJSON(parseEnrollmentReview), async (context) =>context.json({@@ -200,19 +206,15 @@ export function createCloudAdminRoutes()return context.json({ ok: true as const })})- .get('/email', validatedQuery(parseLimitQuery), async (context) =>- context.json({- messages: await services.email.list(context.req.valid('query').limit ?? 100)- })+ .get('/email', validatedQuery(parseEmailQuery), async (context) =>+ context.json(await services.email.list(context.req.valid('query')))).post('/email/:id/regenerate', async (context) => {await services.email.regenerate(context.get('actor').userId, context.req.param('id'))return context.json({ ok: true as const })})- .get('/audit', validatedQuery(parseLimitQuery), async (context) =>- context.json({- events: await services.audit.list(context.req.valid('query').limit ?? 100)- })+ .get('/audit', validatedQuery(parseAuditQuery), async (context) =>+ context.json(await services.audit.list(context.req.valid('query')))).get('/operations', async (context) => context.json(await services.operations.summary()))}diff --git a/packages/cloud/src/admin/audit/service.ts b/packages/cloud/src/admin/audit/service.tsindex def73dd22..d93cfe04c 100644--- a/packages/cloud/src/admin/audit/service.ts+++ b/packages/cloud/src/admin/audit/service.ts@@ -1,21 +1,91 @@-import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'+import {+ containsPattern,+ countEachFilter,+ listSearch,+ listWindow,+ type AdminListQuery,+ type ListFilters+} from '#cloud/admin/list'+import { isUUID } from '#cloud/admin/schema'+import { cloudAdminAuditFilterSchema, type CloudAdminAuditFilter } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'-import { clamp, uniq } from 'es-toolkit'-import type { Kysely } from 'kysely'-import * as v from 'valibot'+import { uniq } from 'es-toolkit'+import type { ExpressionBuilder, Kysely } from 'kysely'-const uuidSchema = v.pipe(v.string(), v.uuid())-const isUUID = (value: string) => v.is(uuidSchema, value)+/** Events by what they are about; every event is under `all`. */+const FILTERS: ListFilters<CloudAdminAuditFilter, 'adminAuditEvent'> = {+ all: (expression) => expression.lit(true),+ accounts: (expression) => expression('adminAuditEvent.subjectType', '=', 'user'),+ requests: (expression) => expression('adminAuditEvent.subjectType', '=', 'enrollment'),+ email: (expression) => expression('adminAuditEvent.subjectType', '=', 'transactional-email')+}++type AuditExpression = ExpressionBuilder<CloudDatabase, 'adminAuditEvent'>++/** Events whose actor, or the account or request they are about, has `pattern` in a name or email. */+function searchCondition(pattern: string) {+ return (expression: AuditExpression) => {+ const account = (column: 'adminAuditEvent.actorUserId' | 'adminAuditEvent.subjectId') =>+ expression.exists(+ expression+ .selectFrom('user')+ .select('user.id')+ .where((inner) => inner(inner.cast('user.id', 'text'), '=', inner.ref(column)))+ .where((inner) =>+ inner.or([inner('user.name', 'ilike', pattern), inner('user.email', 'ilike', pattern)])+ )+ )+ return expression.or([+ account('adminAuditEvent.actorUserId'),+ expression.and([+ expression('adminAuditEvent.subjectType', '=', 'user'),+ account('adminAuditEvent.subjectId')+ ]),+ expression.and([+ expression('adminAuditEvent.subjectType', '=', 'enrollment'),+ expression.exists(+ expression+ .selectFrom('enrollment')+ .select('enrollment.id')+ .where((inner) =>+ inner(+ inner.cast('enrollment.id', 'text'),+ '=',+ inner.ref('adminAuditEvent.subjectId')+ )+ )+ .where((inner) =>+ inner.or([+ inner('enrollment.name', 'ilike', pattern),+ inner('enrollment.emailNormalized', 'ilike', pattern)+ ])+ )+ )+ ])+ ])+ }+}export function createAdminAuditService(database: Kysely<CloudDatabase>) {return {- /** The newest events, each with its actor's and subject's names while the server knows them. */- async list(limit = 100) {- const events = await database- .selectFrom('adminAuditEvent')+ /**+ * A page of events, newest first, each with its actor's and subject's names while the server+ * knows them, and how many match the search under each filter.+ */+ async list(query: AdminListQuery<CloudAdminAuditFilter> = {}) {+ const search = listSearch(query)+ const filter = query.filter ?? 'all'+ const { limit, offset } = listWindow(query)+ let searched = database.selectFrom('adminAuditEvent')+ if (search) searched = searched.where(searchCondition(containsPattern(search)))+ const counts = await countEachFilter(searched, cloudAdminAuditFilterSchema.options, FILTERS)+ const events = await searched+ .where(FILTERS[filter]).selectAll().orderBy('createdAt', 'desc')- .limit(clamp(limit, 1, ADMIN_LIST_MAXIMUM))+ .orderBy('id', 'desc')+ .limit(limit)+ .offset(offset).execute()// Accounts and requests are named by UUID; anything else is not looked up.const userIds = uniq(@@ -45,7 +115,7 @@ export function createAdminAuditService(database: Kysely<CloudDatabase>) {enrollment.name ?? enrollment.emailNormalized]))- return events.map((event) => ({+ const rows = events.map((event) => ({id: event.id,actor: { id: event.actorUserId, name: names.get(event.actorUserId) ?? null },action: event.action,@@ -60,6 +130,7 @@ export function createAdminAuditService(database: Kysely<CloudDatabase>) {metadata: event.metadata,createdAt: event.createdAt}))+ return { events: rows, total: counts[filter], counts }}}}diff --git a/packages/cloud/src/admin/email/service.ts b/packages/cloud/src/admin/email/service.tsindex 864cf635a..180d37341 100644--- a/packages/cloud/src/admin/email/service.ts+++ b/packages/cloud/src/admin/email/service.ts@@ -1,9 +1,16 @@import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'import { AdminDomainError } from '#cloud/admin/errors'-import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'+import {+ containsPattern,+ countEachFilter,+ listSearch,+ listWindow,+ type AdminListQuery,+ type ListFilters+} from '#cloud/admin/list'+import { cloudAdminEmailFilterSchema, type CloudAdminEmailFilter } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'import type { TransactionalEmailService } from '#cloud/server/email'-import { clamp } from 'es-toolkit'import type { Kysely } from 'kysely'/** The enrollment status each message describes; a message is resent only while it still holds. */@@ -14,15 +21,32 @@ const ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {'enrollment-revoked': 'revoked'}+/** Messages by how their delivery went; every message is under `all`. */+const FILTERS: ListFilters<CloudAdminEmailFilter, 'transactionalEmail'> = {+ all: (expression) => expression.lit(true),+ sent: (expression) => expression('status', '=', 'accepted'),+ waiting: (expression) => expression('status', 'in', ['pending', 'sending']),+ failed: (expression) => expression('status', '=', 'failed')+}+export function createAdminEmailService(database: Kysely<CloudDatabase>,email?: TransactionalEmailService,links: { publicURL: string } = { publicURL: '' }) {return {- async list(limit = 100) {- const rows = await database- .selectFrom('transactionalEmail')+ /** A page of messages, newest first, with how many match the search under each filter. */+ async list(query: AdminListQuery<CloudAdminEmailFilter> = {}) {+ const search = listSearch(query)+ const filter = query.filter ?? 'all'+ const { limit, offset } = listWindow(query)+ let searched = database.selectFrom('transactionalEmail')+ if (search) {+ searched = searched.where('recipientEmailNormalized', 'ilike', containsPattern(search))+ }+ const counts = await countEachFilter(searched, cloudAdminEmailFilterSchema.options, FILTERS)+ const rows = await searched+ .where(FILTERS[filter]).select(['id','kind',@@ -37,9 +61,18 @@ export function createAdminEmailService('acceptedAt']).orderBy('createdAt', 'desc')- .limit(clamp(limit, 1, ADMIN_LIST_MAXIMUM))+ .orderBy('id', 'desc')+ .limit(limit)+ .offset(offset).execute()- return rows.map((row) => ({ ...row, regeneratable: row.kind.startsWith('enrollment-') }))+ return {+ messages: rows.map((row) => ({+ ...row,+ regeneratable: row.kind.startsWith('enrollment-')+ })),+ total: counts[filter],+ counts+ }},async regenerate(actorId: string, messageId: string): Promise<void> {if (!email)diff --git a/packages/cloud/src/admin/enrollment/service.ts b/packages/cloud/src/admin/enrollment/service.tsindex 330f8be8a..57a53d805 100644--- a/packages/cloud/src/admin/enrollment/service.ts+++ b/packages/cloud/src/admin/enrollment/service.ts@@ -1,5 +1,16 @@import { AdminDomainError } from '#cloud/admin/errors'+import {+ containsPattern,+ countEachFilter,+ listSearch,+ listWindow,+ type AdminListQuery,+ type ListFilters+} from '#cloud/admin/list'+import { isUUID } from '#cloud/admin/schema'+import { enrollmentStatusSchema } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'+import { compact, uniq } from 'es-toolkit'import type { Kysely } from 'kysely'import {@@ -22,6 +33,7 @@ export type EnrollmentRecord = {requestedAt: stringreviewedAt: string | nullreviewedBy: string | null+ reviewerName?: string | nullreviewNote: string | nullapprovedUserId: string | nullrequestRevision: number@@ -48,6 +60,14 @@ const ALLOWED_TRANSITIONS: Record<EnrollmentStatus, ReadonlySet<EnrollmentStatusrevoked: new Set(['pending', 'approved'])}+/** Requests by their status; each is in exactly one. */+const FILTERS: ListFilters<EnrollmentStatus, 'enrollment'> = {+ pending: (expression) => expression('status', '=', 'pending'),+ approved: (expression) => expression('status', '=', 'approved'),+ rejected: (expression) => expression('status', '=', 'rejected'),+ revoked: (expression) => expression('status', '=', 'revoked')+}+function dateString(value: Date | string | null): string | null {return value ? new Date(value).toISOString() : null}@@ -136,10 +156,45 @@ export function createEnrollmentService(async isApproved(email: string): Promise<boolean> {return (await statusForEmail(email)) === 'approved'},- async list(status?: EnrollmentStatus): Promise<EnrollmentRecord[]> {- let query = database.selectFrom('enrollment').selectAll()- if (status) query = query.where('status', '=', status)- return (await query.orderBy('requestedAt', 'desc').execute()).map(enrollmentRecord)+ /** A page of requests in one status, newest first, with how many match the search in each. */+ async list(query: AdminListQuery<EnrollmentStatus> = {}) {+ const search = listSearch(query)+ const status = query.filter ?? 'pending'+ const { limit, offset } = listWindow(query)+ let searched = database.selectFrom('enrollment')+ if (search) {+ const pattern = containsPattern(search)+ searched = searched.where((expression) =>+ expression.or([+ expression('name', 'ilike', pattern),+ expression('emailNormalized', 'ilike', pattern)+ ])+ )+ }+ const counts = await countEachFilter(searched, enrollmentStatusSchema.options, FILTERS)+ const rows = await searched+ .where(FILTERS[status])+ .selectAll()+ .orderBy('requestedAt', 'desc')+ .orderBy('id', 'desc')+ .limit(limit)+ .offset(offset)+ .execute()+ // Reviewers are named by account ID; anything else names no one.+ const reviewerIds = uniq(compact(rows.map((row) => row.reviewedBy))).filter(isUUID)+ const reviewers = reviewerIds.length+ ? await database+ .selectFrom('user')+ .select(['id', 'name'])+ .where('id', 'in', reviewerIds)+ .execute()+ : []+ const names = new Map(reviewers.map((reviewer) => [reviewer.id, reviewer.name]))+ const enrollments = rows.map((row) => ({+ ...enrollmentRecord(row),+ reviewerName: row.reviewedBy ? (names.get(row.reviewedBy) ?? null) : null+ }))+ return { enrollments, total: counts[status], counts }},async review(actorId: string,diff --git a/packages/cloud/src/admin/list.ts b/packages/cloud/src/admin/list.tsnew file mode 100644index 000000000..ac55ca485--- /dev/null+++ b/packages/cloud/src/admin/list.ts@@ -0,0 +1,61 @@+import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'+import type { CloudDatabase } from '#cloud/server/db'+import { clamp, zipObject } from 'es-toolkit'+import type { Expression, ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'++/** The rows an admin list returns when the request does not say. */+export const ADMIN_PAGE_SIZE = 50++/** What every admin list takes: words to search for, one of its filters, and a page. */+export type AdminListQuery<Filter extends string> = {+ search?: string+ filter?: Filter+ limit?: number+ offset?: number+}++/** A `like` pattern that finds `search` anywhere, matching `%`, `_`, and `\` literally. */+export function containsPattern(search: string): string {+ return `%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`+}++/** The search words, or undefined when there are none. */+export function listSearch(query: AdminListQuery<string>): string | undefined {+ return query.search?.trim() || undefined+}++/** The page a query asks for, kept within what one request may return. */+export function listWindow(query: AdminListQuery<string>) {+ return {+ limit: clamp(query.limit ?? ADMIN_PAGE_SIZE, 1, ADMIN_LIST_MAXIMUM),+ offset: Math.max(0, query.offset ?? 0)+ }+}++/** A list's filters, each the condition its rows meet; the same one counts them and pages them. */+export type ListFilters<Filter extends string, Table extends keyof CloudDatabase> = Record<+ Filter,+ (expression: ExpressionBuilder<CloudDatabase, Table>) => Expression<SqlBool>+>++/**+ * How many of `searched`'s rows meet each filter, in one query: each count is an aggregate with a+ * `filter (where …)` clause rather than a query of its own.+ */+export async function countEachFilter<Filter extends string, Table extends keyof CloudDatabase>(+ searched: SelectQueryBuilder<CloudDatabase, Table, object>,+ names: readonly Filter[],+ filters: ListFilters<Filter, Table>+): Promise<Record<Filter, number>> {+ // Kysely names each column after its filter but cannot type a generic name, so the row is read+ // as counts by name.+ const row: Record<string, unknown> = await searched+ .select((expression) =>+ names.map((name) => expression.fn.countAll<number>().filterWhere(filters[name]).as(name))+ )+ .executeTakeFirstOrThrow()+ return zipObject(+ names,+ names.map((name) => Number(row[name]))+ )+}diff --git a/packages/cloud/src/admin/schema.ts b/packages/cloud/src/admin/schema.tsindex ee1481101..6638015d0 100644--- a/packages/cloud/src/admin/schema.ts+++ b/packages/cloud/src/admin/schema.ts@@ -1,5 +1,9 @@import * as v from 'valibot'+const uuidSchema = v.pipe(v.string(), v.uuid())+/** Accounts and access requests are named by UUID; anything else names no row. */+export const isUUID = (value: string) => v.is(uuidSchema, value)+/** The most rows one admin list request returns. */export const ADMIN_LIST_MAXIMUM = 500diff --git a/packages/cloud/src/admin/users/service.ts b/packages/cloud/src/admin/users/service.tsindex daa3fafbe..8b0e841a1 100644--- a/packages/cloud/src/admin/users/service.ts+++ b/packages/cloud/src/admin/users/service.ts@@ -1,6 +1,18 @@import { AdminDomainError } from '#cloud/admin/errors'-import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'-import type { CloudAdminUser, CloudAdminUserDetail, CloudAdminUserFilter } from '#cloud/contract'+import {+ containsPattern,+ countEachFilter,+ listSearch,+ listWindow,+ type AdminListQuery,+ type ListFilters+} from '#cloud/admin/list'+import {+ cloudAdminUserFilterSchema,+ type CloudAdminUser,+ type CloudAdminUserDetail,+ type CloudAdminUserFilter+} from '#cloud/contract'import {createSignInActivity,type AuthenticationEmailService,@@ -9,19 +21,17 @@ import {import type { CloudDatabase } from '#cloud/server/db'import type { UserPictureService } from '#cloud/server/pictures'import { dateString } from '#cloud/server/sharing/contracts'-import { clamp, countBy, keyBy } from 'es-toolkit'+import { countBy, keyBy } from 'es-toolkit'import type { ExpressionBuilder, Kysely } from 'kysely'/** The sign-ins a person's page lists. */const DETAIL_SIGN_INS = 20-const FILTERS = ['all', 'administrators', 'suspended', 'without-two-step'] as const-type UserExpression = ExpressionBuilder<CloudDatabase, 'user'>/** A search for part of a name or email, matched literally and without case. */function searchCondition(search: string) {- const pattern = `%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`+ const pattern = containsPattern(search)return (expression: UserExpression) =>expression.or([expression('user.email', 'ilike', pattern),@@ -29,34 +39,26 @@ function searchCondition(search: string) {])}-function filterCondition(filter: CloudAdminUserFilter) {- return (expression: UserExpression) => {- if (filter === 'administrators') return expression('user.role', '=', 'admin')- if (filter === 'suspended') return expression('user.banned', '=', true)- if (filter === 'without-two-step') {- return expression.and([- // Better Auth leaves the flag unset on accounts that never turned it on.- expression('user.twoFactorEnabled', 'is not', true),- expression.not(- expression.exists(- expression- .selectFrom('passkey')- .select('passkey.id')- .whereRef('passkey.userId', '=', 'user.id')- )+const FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {+ all: (expression) => expression.lit(true),+ administrators: (expression) => expression('user.role', '=', 'admin'),+ suspended: (expression) => expression('user.banned', '=', true),+ 'without-two-step': (expression) =>+ expression.and([+ // Better Auth leaves the flag unset on accounts that never turned it on.+ expression('user.twoFactorEnabled', 'is not', true),+ expression.not(+ expression.exists(+ expression+ .selectFrom('passkey')+ .select('passkey.id')+ .whereRef('passkey.userId', '=', 'user.id'))- ])- }- return expression.lit(true)- }+ )+ ])}-export type AdminUserQuery = {- search?: string- filter?: CloudAdminUserFilter- limit?: number- offset?: number-}+export type AdminUserQuery = AdminListQuery<CloudAdminUserFilter>type UserRow = {id: string@@ -187,40 +189,21 @@ export function createAdminUserService(return {/** A page of accounts in sign-up order, with how many match the search under each filter. */async list(query: AdminUserQuery = {}) {- const search = query.search?.trim()+ const search = listSearch(query)const filter = query.filter ?? 'all'- const matching = (target: CloudAdminUserFilter) => {- let selection = database.selectFrom('user').where(filterCondition(target))- if (search) selection = selection.where(searchCondition(search))- return selection- }- const counts = await Promise.all(- FILTERS.map(async (target) => {- const row = await matching(target)- .select(({ fn }) => fn.countAll<number>().as('count'))- .executeTakeFirstOrThrow()- return Number(row.count)- })- )- const [all = 0, administrators = 0, suspended = 0, withoutTwoStep = 0] = counts- const countsByFilter = {- all,- administrators,- suspended,- 'without-two-step': withoutTwoStep- }- const rows = await matching(filter)+ const { limit, offset } = listWindow(query)+ let searched = database.selectFrom('user')+ if (search) searched = searched.where(searchCondition(search))+ const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)+ const rows = await searched+ .where(FILTERS[filter]).select(userColumns).orderBy('user.createdAt').orderBy('user.id')- .limit(clamp(query.limit ?? 50, 1, ADMIN_LIST_MAXIMUM))- .offset(Math.max(0, query.offset ?? 0))+ .limit(limit)+ .offset(offset).execute()- return {- users: await accountSummaries(rows),- total: countsByFilter[filter],- counts: countsByFilter- }+ return { users: await accountSummaries(rows), total: counts[filter], counts }},/** Everything an administrator reads about one account; null when there is none. */diff --git a/packages/cloud/src/client/portal/administration.ts b/packages/cloud/src/client/portal/administration.tsindex 8fcd0584b..c938e6114 100644--- a/packages/cloud/src/client/portal/administration.ts+++ b/packages/cloud/src/client/portal/administration.ts@@ -8,14 +8,33 @@ import {cloudAdminUsersResponseSchema,enrollmentReviewResponseSchema,enrollmentsResponseSchema,+ type CloudAdminAuditFilter,+ type CloudAdminEmailFilter,type CloudAdminUserFilter,- type enrollmentStatusSchema+ type EnrollmentStatus} from '#cloud/contract'-import type * as v from 'valibot'import type { CloudCall, PortalRouteClients } from './request'-type EnrollmentStatus = v.InferOutput<typeof enrollmentStatusSchema>+/** A page of an admin list: words to search for, one of its filters, and where the page starts. */+export type AdminListRequest<Filter extends string> = {+ search?: string+ filter?: Filter+ limit?: number+ offset?: number+}++/** The query string for `request`; an empty search asks for everything. */+function listQuery<Filter extends string>(request: AdminListRequest<Filter>) {+ return {+ query: {+ search: request.search || undefined,+ filter: request.filter,+ limit: request.limit,+ offset: request.offset+ }+ }+}export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRouteClients) {return {@@ -26,9 +45,9 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRsignal)},- enrollments(status?: EnrollmentStatus, signal?: AbortSignal) {+ enrollments(request: AdminListRequest<EnrollmentStatus>, signal?: AbortSignal) {return call(- (options) => admin.enrollments.$get({ query: { status } }, options),+ (options) => admin.enrollments.$get(listQuery(request), options),enrollmentsResponseSchema,signal)@@ -46,23 +65,9 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRsignal)},- users(- query: { search?: string; filter?: CloudAdminUserFilter; limit?: number; offset?: number },- signal?: AbortSignal- ) {+ users(request: AdminListRequest<CloudAdminUserFilter>, signal?: AbortSignal) {return call(- (options) =>- admin.users.$get(- {- query: {- search: query.search || undefined,- filter: query.filter,- limit: query.limit,- offset: query.offset- }- },- options- ),+ (options) => admin.users.$get(listQuery(request), options),cloudAdminUsersResponseSchema,signal)@@ -93,9 +98,9 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRsignal)},- email(signal?: AbortSignal) {+ email(request: AdminListRequest<CloudAdminEmailFilter>, signal?: AbortSignal) {return call(- (options) => admin.email.$get({ query: {} }, options),+ (options) => admin.email.$get(listQuery(request), options),adminEmailResponseSchema,signal)@@ -107,9 +112,9 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRsignal)},- audit(signal?: AbortSignal) {+ audit(request: AdminListRequest<CloudAdminAuditFilter>, signal?: AbortSignal) {return call(- (options) => admin.audit.$get({ query: {} }, options),+ (options) => admin.audit.$get(listQuery(request), options),adminAuditResponseSchema,signal)diff --git a/packages/cloud/src/contract/admin/index.ts b/packages/cloud/src/contract/admin/index.tsindex 848e19230..ac04e8b06 100644--- a/packages/cloud/src/contract/admin/index.ts+++ b/packages/cloud/src/contract/admin/index.ts@@ -1,3 +1,4 @@+import { zipObject } from 'es-toolkit'import * as v from 'valibot'import {@@ -10,6 +11,23 @@ import { workspaceRoleSchema } from '../workspaces'const timestampSchema = v.pipe(v.string(), v.isoTimestamp())const nullableTimestampSchema = v.nullable(timestampSchema)+const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))++/**+ * What every admin list answers besides its rows: how many rows match the search and filter+ * across every page, and how many match the search under each filter.+ */+function listTotals<const Filter extends string>(filters: readonly Filter[]) {+ return {+ total: countSchema,+ counts: v.object(+ zipObject(+ filters,+ filters.map(() => countSchema)+ )+ )+ }+}export const adminErrorCodeSchema = v.picklist(['bad_request',@@ -38,18 +56,21 @@ export const enrollmentSchema = v.object({requestedAt: timestampSchema,reviewedAt: nullableTimestampSchema,reviewedBy: v.nullable(v.string()),+ /** The reviewer's name, in lists, while the server still knows them. */+ reviewerName: v.optional(v.nullable(v.string())),reviewNote: v.nullable(v.string()),approvedUserId: v.nullable(v.string()),requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))})-export const enrollmentsResponseSchema = v.object({ enrollments: v.array(enrollmentSchema) })+export const enrollmentsResponseSchema = v.object({+ enrollments: v.array(enrollmentSchema),+ ...listTotals(enrollmentStatusSchema.options)+})export const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema })export const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })-const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))-export const cloudAdminUserSchema = v.object({...cloudPersonSchema.entries,role: v.optional(v.string()),@@ -72,15 +93,7 @@ export const cloudAdminUserFilterSchema = v.picklist([])export const cloudAdminUsersResponseSchema = v.object({users: v.array(cloudAdminUserSchema),- /** How many accounts match the search and filter, across every page. */- total: countSchema,- /** How many accounts match the search under each filter. */- counts: v.object({- all: countSchema,- administrators: countSchema,- suspended: countSchema,- 'without-two-step': countSchema- })+ ...listTotals(cloudAdminUserFilterSchema.options)})export const cloudAdminUserDetailSchema = v.object({@@ -120,8 +133,11 @@ export const transactionalEmailAdminSchema = v.object({acceptedAt: nullableTimestampSchema,regeneratable: v.boolean()})+/** Which messages a list of email shows, by how their delivery went. */+export const cloudAdminEmailFilterSchema = v.picklist(['all', 'sent', 'waiting', 'failed'])export const adminEmailResponseSchema = v.object({- messages: v.array(transactionalEmailAdminSchema)+ messages: v.array(transactionalEmailAdminSchema),+ ...listTotals(cloudAdminEmailFilterSchema.options)})/** Who or what an event names; `name` is null once the server no longer knows it. */@@ -136,7 +152,12 @@ export const adminAuditEventSchema = v.object({metadata: v.unknown(),createdAt: timestampSchema})-export const adminAuditResponseSchema = v.object({ events: v.array(adminAuditEventSchema) })+/** Which events a list of activity shows, by what they are about. */+export const cloudAdminAuditFilterSchema = v.picklist(['all', 'accounts', 'requests', 'email'])+export const adminAuditResponseSchema = v.object({+ events: v.array(adminAuditEventSchema),+ ...listTotals(cloudAdminAuditFilterSchema.options)+})export const adminOperationsResponseSchema = v.object({deployment: v.picklist(['official', 'self-hosted']),@@ -156,6 +177,9 @@ export type Enrollment = v.InferOutput<typeof enrollmentSchema>export type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>export type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>export type CloudAdminUserFilter = v.InferOutput<typeof cloudAdminUserFilterSchema>+export type CloudAdminEmailFilter = v.InferOutput<typeof cloudAdminEmailFilterSchema>+export type CloudAdminAuditFilter = v.InferOutput<typeof cloudAdminAuditFilterSchema>+export type EnrollmentStatus = v.InferOutput<typeof enrollmentStatusSchema>export type CloudAdminUsers = v.InferOutput<typeof cloudAdminUsersResponseSchema>export type CloudAdminUserDetail = v.InferOutput<typeof cloudAdminUserDetailSchema>export type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>diff --git a/packages/cloud/tests/client/portal/client.test.ts b/packages/cloud/tests/client/portal/client.test.tsindex a9b7e7e25..acb027a84 100644--- a/packages/cloud/tests/client/portal/client.test.ts+++ b/packages/cloud/tests/client/portal/client.test.ts@@ -104,11 +104,11 @@ describe('Cloud portal client', () => {}])requests.length = 0- await client.enrollments('pending').catch(() => undefined)+ await client.enrollments({ filter: 'pending' }).catch(() => undefined)await client.users({ search: 'ada' }).catch(() => undefined)await client.accountStatus().catch(() => undefined)expect(requests.map((request) => request.url)).toEqual([- 'https://cloud.example.com/api/admin/enrollments?status=pending',+ 'https://cloud.example.com/api/admin/enrollments?filter=pending','https://cloud.example.com/api/admin/users?search=ada','https://cloud.example.com/api/account/status'])diff --git a/packages/cloud/tests/integration/admin/enrollment/service.test.ts b/packages/cloud/tests/integration/admin/enrollment/service.test.tsindex 463daa69d..9fb1879f6 100644--- a/packages/cloud/tests/integration/admin/enrollment/service.test.ts+++ b/packages/cloud/tests/integration/admin/enrollment/service.test.ts@@ -14,7 +14,7 @@ describe('Cloud enrollment integration', () => {const enrollment = createEnrollmentService(runtime.database)await enrollment.request({ email: '[email protected]', name: 'Person', reason: 'Design' })await enrollment.request({ email: '[email protected]', name: 'Duplicate' })- const [pending] = await enrollment.list('pending')+ const [pending] = (await enrollment.list({ filter: 'pending' })).enrollmentsexpect(pending).toMatchObject({email: '[email protected]',name: 'Person',@@ -67,7 +67,7 @@ describe('Cloud enrollment integration', () => {})await enrollment.request({ email: '[email protected]', name: 'Person', reason: 'Design' })- let [record] = await enrollment.list()+ let [record] = (await enrollment.list()).enrollmentsif (!record) throw new Error('Expected enrollment')expect(record.requestRevision).toBe(1)expect(@@ -81,7 +81,7 @@ describe('Cloud enrollment integration', () => {'Enrollment cannot transition')await enrollment.request({ email: '[email protected]', reason: 'Try again' })- ;[record] = await enrollment.list()+ ;[record] = (await enrollment.list()).enrollmentsexpect(record).toMatchObject({ status: 'pending', requestRevision: 2, reason: 'Try again' })if (!record) throw new Error('Expected reopened enrollment')await enrollment.review('admin-user', record.id, 'approved', {})diff --git a/packages/cloud/tests/integration/admin/lists.test.ts b/packages/cloud/tests/integration/admin/lists.test.tsnew file mode 100644index 000000000..c0cd5f746--- /dev/null+++ b/packages/cloud/tests/integration/admin/lists.test.ts@@ -0,0 +1,135 @@+import { describe, expect, test } from 'bun:test'++import { createCloudTestDatabase } from '#cloud-tests/helpers/database'+import {+ createAdminAuditService,+ createAdminEmailService,+ createEnrollmentService+} from '#cloud/server'++const ADMIN_ID = '11111111-1111-4111-8111-111111111111'+const ADA_ID = '22222222-2222-4222-8222-222222222222'++describe('admin lists', () => {+ test('search, filter, and page access requests, counting each status', async () => {+ const runtime = await createCloudTestDatabase()+ try {+ const enrollment = createEnrollmentService(runtime.database)+ for (const name of ['Ada', 'Grace', 'Alan', 'Ada Two']) {+ await enrollment.request({ email: `${name.replace(' ', '.')}@example.com`, name })+ }+ const [first] = (await enrollment.list({ search: 'grace' })).enrollments+ if (!first) throw new Error('Expected a request from Grace')+ await runtime.database+ .insertInto('user')+ .values({ id: ADMIN_ID, name: 'Admin', email: '[email protected]', emailVerified: true })+ .execute()+ await enrollment.review(ADMIN_ID, first.id, 'approved', {})+ const [approved] = (await enrollment.list({ filter: 'approved' })).enrollments+ expect(approved).toMatchObject({ name: 'Grace', reviewedBy: ADMIN_ID, reviewerName: 'Admin' })++ const ada = await enrollment.list({ search: 'ADA' })+ expect(ada.enrollments.map((request) => request.name).sort()).toEqual(['Ada', 'Ada Two'])+ expect(ada.counts).toEqual({ pending: 2, approved: 0, rejected: 0, revoked: 0 })++ const page = await enrollment.list({ limit: 2, offset: 2 })+ expect(page.enrollments).toHaveLength(1)+ expect(page.total).toBe(3)+ expect(page.counts).toEqual({ pending: 3, approved: 1, rejected: 0, revoked: 0 })++ // `%` and `_` are searched for as they are, not as patterns.+ expect((await enrollment.list({ search: '%' })).total).toBe(0)+ } finally {+ await runtime.close()+ }+ })++ test('search and filter email by recipient and delivery', async () => {+ const runtime = await createCloudTestDatabase()+ try {+ const sent = new Date('2026-10-01T10:00:00Z')+ const message = (+ index: number,+ recipient: string,+ status: 'accepted' | 'failed' | 'pending'+ ) => ({+ id: crypto.randomUUID(),+ idempotencyKey: `list-test/${index}`,+ kind: 'email-verification' as const,+ recipientEmailNormalized: recipient,+ payloadEncrypted: null,+ status,+ nextAttemptAt: sent,+ createdAt: new Date(sent.getTime() + index * 1000),+ updatedAt: sent+ })+ await runtime.database+ .insertInto('transactionalEmail')+ .values([+ message(1, '[email protected]', 'accepted'),+ message(2, '[email protected]', 'failed'),+ message(3, '[email protected]', 'pending')+ ])+ .execute()+ const email = createAdminEmailService(runtime.database)++ const all = await email.list()+ expect(all.messages.map((row) => row.status)).toEqual(['pending', 'failed', 'accepted'])+ expect(all.counts).toEqual({ all: 3, sent: 1, waiting: 1, failed: 1 })++ const ada = await email.list({ search: 'ada', filter: 'sent' })+ expect(ada.messages.map((row) => row.recipientEmailNormalized)).toEqual(['[email protected]'])+ expect(ada.total).toBe(1)+ expect(ada.counts).toEqual({ all: 2, sent: 1, waiting: 1, failed: 0 })+ } finally {+ await runtime.close()+ }+ })++ test('search activity by the names of who acted and whom it was about', async () => {+ const runtime = await createCloudTestDatabase()+ try {+ await runtime.database+ .insertInto('user')+ .values([+ { id: ADMIN_ID, name: 'Admin', email: '[email protected]', emailVerified: true },+ { id: ADA_ID, name: 'Ada Lovelace', email: '[email protected]', emailVerified: true }+ ])+ .execute()+ const at = new Date('2026-10-01T10:00:00Z')+ const event = (index: number, action: string, subjectType: string, subjectId: string) => ({+ id: crypto.randomUUID(),+ actorUserId: ADMIN_ID,+ action,+ subjectType,+ subjectId,+ metadata: {},+ createdAt: new Date(at.getTime() + index * 1000)+ })+ await runtime.database+ .insertInto('adminAuditEvent')+ .values([+ event(1, 'user.banned', 'user', ADA_ID),+ event(2, 'email.regenerated', 'transactional-email', crypto.randomUUID()),+ event(3, 'user.unbanned', 'user', ADA_ID)+ ])+ .execute()+ const audit = createAdminAuditService(runtime.database)++ const lovelace = await audit.list({ search: 'lovelace' })+ expect(lovelace.events.map((row) => row.action)).toEqual(['user.unbanned', 'user.banned'])+ expect(lovelace.counts).toEqual({ all: 2, accounts: 2, requests: 0, email: 0 })++ // Everything here was done by Admin, so searching for them finds every event.+ const admin = await audit.list({ search: 'admin@example', filter: 'email' })+ expect(admin.events.map((row) => row.action)).toEqual(['email.regenerated'])+ expect(admin.counts).toEqual({ all: 3, accounts: 2, requests: 0, email: 1 })++ const page = await audit.list({ limit: 1, offset: 1 })+ expect(page.events.map((row) => row.action)).toEqual(['email.regenerated'])+ expect(page.total).toBe(3)+ } finally {+ await runtime.close()+ }+ })+})diff --git a/packages/cloud/tests/integration/admin/users/service.test.ts b/packages/cloud/tests/integration/admin/users/service.test.tsindex b768863e8..f8b31ea57 100644--- a/packages/cloud/tests/integration/admin/users/service.test.ts+++ b/packages/cloud/tests/integration/admin/users/service.test.ts@@ -325,7 +325,7 @@ describe('deployment admin user safety', () => {.execute()expect(factors).toEqual([])expect(notices).toEqual(['[email protected]:reset-by-administrator'])- const events = await createAdminAuditService(runtime.database).list()+ const { events } = await createAdminAuditService(runtime.database).list()expect(events).toEqual([expect.objectContaining({action: 'user.two-step-reset',@@ -382,7 +382,7 @@ describe('deployment admin user safety', () => {expect(user.image).toBeNull()const kept = await runtime.database.selectFrom('userPicture').select('userId').execute()expect(kept).toEqual([])- expect(await createAdminAuditService(runtime.database).list()).toEqual([+ expect((await createAdminAuditService(runtime.database).list()).events).toEqual([expect.objectContaining({action: 'user.picture-removed',subject: { type: 'user', id: USER_ID, name: 'Pictured' }diff --git a/packages/cloud/tests/integration/server/app.test.ts b/packages/cloud/tests/integration/server/app.test.tsindex 721268491..14bb4a95b 100644--- a/packages/cloud/tests/integration/server/app.test.ts+++ b/packages/cloud/tests/integration/server/app.test.ts@@ -245,7 +245,9 @@ describe('createCloudApp', () => {'/api/admin/audit?limit=many','/api/admin/email?limit=-1','/api/admin/users?offset=1.5',- '/api/admin/enrollments?status=sideways'+ '/api/admin/users?offset=99999999999999999999',+ '/api/admin/enrollments?filter=sideways',+ '/api/admin/email?filter=bounced']) {const response = await adminApp.request(path)expect(response.status).toBe(400)diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 21cf617fb..b9cd28bd2 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -206,9 +206,16 @@ pending request that a deployment administrator approves or rejects; approval caDeployment administrators are separate from workspace administrators, and startup never grantseither role: the first operator is approved and promoted through the `admin` command.-The console's People list pages through accounts in sign-up order, searched by name or email and-filtered to administrators, suspended accounts, or accounts without two-step sign-in, with a count-for each filter. A person's page shows how they sign in, their workspaces, sessions, and recent+The console's lists are tables the server pages, searches, and filters: each admin list endpoint+takes `search`, `filter`, `limit`, and `offset` and answers with its rows, the `total` matching, and+how many match the search under each filter (`src/admin/list.ts`). A list declares its filters once, as conditions on its table; one query counts them all with `count(*) filter (where …)`, and the page uses the same condition. People lists accounts in sign-up+order, searched by name or email and filtered to administrators, suspended accounts, or accounts+without two-step sign-in; access requests are searched by name or email in each status; email by+recipient and delivery; activity by the names of who acted and whom it was about, and by what it+was about. In the portal, `usePortalList` (`src/app/cloud-portal/list.ts`) holds a list's search,+filter, and page and builds its TanStack Table; `PortalTable` draws the toolbar, the shared+`AppDataTable`, and the pages, and each list only defines its columns, which render their cells with the components in `src/components/cloud-portal/table/`. A row has at most one inline+action, such as Approve; the rest are in its “…” menu. A person's page shows how they sign in, their workspaces, sessions, and recentsign-ins. Administrators make and remove administrators, sign people out everywhere, suspendwith a reason the activity log keeps, and reset a locked-out person's two-step sign-in, whichremoves their authenticator app, recovery codes, and passkeys, and take down a person's picture.diff --git a/packages/vue/src/i18n/locales/de/cloud/portal.json b/packages/vue/src/i18n/locales/de/cloud/portal.jsonindex c9f44c77f..e131c9e90 100644--- a/packages/vue/src/i18n/locales/de/cloud/portal.json+++ b/packages/vue/src/i18n/locales/de/cloud/portal.json@@ -250,6 +250,39 @@"nextPage": "Nächste Seite","noPeopleFound": "Keine Treffer","noPeopleFoundDescription": "Versuche einen anderen Namen, eine andere E-Mail-Adresse oder einen anderen Filter.",+ "member": "Mitglied",+ "searchRequests": "Anfragen suchen…",+ "searchEmail": "Nach Empfänger suchen…",+ "searchActivity": "Nach Name oder E-Mail-Adresse suchen…",+ "filterAll": "Alle",+ "filterAccounts": "Konten",+ "filterRequests": "Anfragen",+ "filterEmail": "E-Mail",+ "noEmailFound": "Keine passenden E-Mails",+ "noEmailFoundDescription": "Vom Server gesendete E-Mails erscheinen hier. Versuche einen anderen Empfänger oder Filter.",+ "noActivityFound": "Keine passende Aktivität",+ "noActivityFoundDescription": "Hier erscheint, was Administratoren tun. Versuche einen anderen Namen, eine andere E-Mail-Adresse oder einen anderen Filter.",+ "columnPerson": "Nutzer",+ "columnRole": "Rolle",+ "columnWorkspaces": "Arbeitsbereiche",+ "columnWorkspace": "Arbeitsbereich",+ "columnMembers": "Mitglieder",+ "columnLastActive": "Zuletzt aktiv",+ "columnJoined": "Beigetreten",+ "columnActions": "Aktionen",+ "columnReason": "Grund",+ "columnRequested": "Angefragt",+ "columnDecision": "Entscheidung",+ "columnMessage": "Nachricht",+ "columnRecipient": "Empfänger",+ "columnStatus": "Status",+ "columnWhen": "Wann",+ "columnAdministrator": "Admin",+ "columnAction": "Aktion",+ "columnSubject": "Betrifft",+ "columnDevice": "Gerät",+ "columnAddress": "IP-Adresse",+ "columnSignedIn": "Angemeldet","suspendedReason": "Gesperrt: {reason}","suspendHeading": "{name} sperren?","suspendDescription": "Die Person wird überall abgemeldet und kann sich erst wieder anmelden, wenn du das Konto entsperrst. Ihre Dateien bleiben erhalten.",diff --git a/packages/vue/src/i18n/locales/es/cloud/portal.json b/packages/vue/src/i18n/locales/es/cloud/portal.jsonindex cab163d17..1fcb3e1b9 100644--- a/packages/vue/src/i18n/locales/es/cloud/portal.json+++ b/packages/vue/src/i18n/locales/es/cloud/portal.json@@ -250,6 +250,39 @@"nextPage": "Página siguiente","noPeopleFound": "Nadie coincide","noPeopleFoundDescription": "Prueba con otro nombre o correo, o con otro filtro.",+ "member": "Miembro",+ "searchRequests": "Buscar solicitudes…",+ "searchEmail": "Buscar por destinatario…",+ "searchActivity": "Buscar por nombre o correo…",+ "filterAll": "Todos",+ "filterAccounts": "Cuentas",+ "filterRequests": "Solicitudes",+ "filterEmail": "Correo",+ "noEmailFound": "Ningún correo coincide",+ "noEmailFoundDescription": "Los correos que envía el servidor aparecen aquí. Prueba con otro destinatario o filtro.",+ "noActivityFound": "Ninguna actividad coincide",+ "noActivityFoundDescription": "Lo que hacen los administradores aparece aquí. Prueba con otro nombre o correo, o con otro filtro.",+ "columnPerson": "Persona",+ "columnRole": "Rol",+ "columnWorkspaces": "Espacios de trabajo",+ "columnWorkspace": "Espacio de trabajo",+ "columnMembers": "Miembros",+ "columnLastActive": "Última actividad",+ "columnJoined": "Se unió",+ "columnActions": "Acciones",+ "columnReason": "Motivo",+ "columnRequested": "Solicitada",+ "columnDecision": "Decisión",+ "columnMessage": "Mensaje",+ "columnRecipient": "Destinatario",+ "columnStatus": "Estado",+ "columnWhen": "Cuándo",+ "columnAdministrator": "Administrador",+ "columnAction": "Acción",+ "columnSubject": "Sobre",+ "columnDevice": "Dispositivo",+ "columnAddress": "Dirección IP",+ "columnSignedIn": "Inicio de sesión","suspendedReason": "Suspendida: {reason}","suspendHeading": "¿Suspender a {name}?","suspendDescription": "Se cerrarán todas sus sesiones y no podrá iniciar sesión hasta que restaures la cuenta. Sus archivos se conservan.",diff --git a/packages/vue/src/i18n/locales/fr/cloud/portal.json b/packages/vue/src/i18n/locales/fr/cloud/portal.jsonindex 9b04d3ccd..c2aee8627 100644--- a/packages/vue/src/i18n/locales/fr/cloud/portal.json+++ b/packages/vue/src/i18n/locales/fr/cloud/portal.json@@ -250,6 +250,39 @@"nextPage": "Page suivante","noPeopleFound": "Aucun résultat","noPeopleFoundDescription": "Essayez un autre nom ou e-mail, ou un autre filtre.",+ "member": "Membre",+ "searchRequests": "Rechercher des demandes…",+ "searchEmail": "Rechercher par destinataire…",+ "searchActivity": "Rechercher par nom ou e-mail…",+ "filterAll": "Tous",+ "filterAccounts": "Comptes",+ "filterRequests": "Demandes",+ "filterEmail": "E-mail",+ "noEmailFound": "Aucun e-mail ne correspond",+ "noEmailFoundDescription": "Les e-mails envoyés par le serveur s’affichent ici. Essayez un autre destinataire ou un autre filtre.",+ "noActivityFound": "Aucune activité ne correspond",+ "noActivityFoundDescription": "Les actions des administrateurs s’affichent ici. Essayez un autre nom ou e-mail, ou un autre filtre.",+ "columnPerson": "Personne",+ "columnRole": "Rôle",+ "columnWorkspaces": "Espaces de travail",+ "columnWorkspace": "Espace de travail",+ "columnMembers": "Membres",+ "columnLastActive": "Dernière activité",+ "columnJoined": "Inscription",+ "columnActions": "Actions",+ "columnReason": "Motif",+ "columnRequested": "Demandée le",+ "columnDecision": "Décision",+ "columnMessage": "Message",+ "columnRecipient": "Destinataire",+ "columnStatus": "Statut",+ "columnWhen": "Quand",+ "columnAdministrator": "Administrateur",+ "columnAction": "Action",+ "columnSubject": "Concerne",+ "columnDevice": "Appareil",+ "columnAddress": "Adresse IP",+ "columnSignedIn": "Connexion","suspendedReason": "Suspendu : {reason}","suspendHeading": "Suspendre {name} ?","suspendDescription": "Cette personne est déconnectée partout et ne pourra plus se connecter tant que vous n’aurez pas rétabli le compte. Ses fichiers sont conservés.",diff --git a/packages/vue/src/i18n/locales/it/cloud/portal.json b/packages/vue/src/i18n/locales/it/cloud/portal.jsonindex ba9abe1d4..f3035a6ca 100644--- a/packages/vue/src/i18n/locales/it/cloud/portal.json+++ b/packages/vue/src/i18n/locales/it/cloud/portal.json@@ -250,6 +250,39 @@"nextPage": "Pagina successiva","noPeopleFound": "Nessuna corrispondenza","noPeopleFoundDescription": "Prova un altro nome o un’altra email, oppure un altro filtro.",+ "member": "Membro",+ "searchRequests": "Cerca richieste…",+ "searchEmail": "Cerca per destinatario…",+ "searchActivity": "Cerca per nome o email…",+ "filterAll": "Tutti",+ "filterAccounts": "Account",+ "filterRequests": "Richieste",+ "filterEmail": "Email",+ "noEmailFound": "Nessuna email corrisponde",+ "noEmailFoundDescription": "Le email inviate dal server compaiono qui. Prova un altro destinatario o un altro filtro.",+ "noActivityFound": "Nessuna attività corrisponde",+ "noActivityFoundDescription": "Le azioni degli amministratori compaiono qui. Prova un altro nome o un’altra email, oppure un altro filtro.",+ "columnPerson": "Persona",+ "columnRole": "Ruolo",+ "columnWorkspaces": "Aree di lavoro",+ "columnWorkspace": "Area di lavoro",+ "columnMembers": "Membri",+ "columnLastActive": "Ultima attività",+ "columnJoined": "Iscrizione",+ "columnActions": "Azioni",+ "columnReason": "Motivo",+ "columnRequested": "Richiesta",+ "columnDecision": "Decisione",+ "columnMessage": "Messaggio",+ "columnRecipient": "Destinatario",+ "columnStatus": "Stato",+ "columnWhen": "Quando",+ "columnAdministrator": "Amministratore",+ "columnAction": "Azione",+ "columnSubject": "Riguarda",+ "columnDevice": "Dispositivo",+ "columnAddress": "Indirizzo IP",+ "columnSignedIn": "Accesso","suspendedReason": "Sospeso: {reason}","suspendHeading": "Sospendere {name}?","suspendDescription": "Viene disconnesso ovunque e non può accedere finché non ripristini l’account. I suoi file restano.",diff --git a/packages/vue/src/i18n/locales/ja/cloud/portal.json b/packages/vue/src/i18n/locales/ja/cloud/portal.jsonindex c5eeb79ff..586e63bdc 100644--- a/packages/vue/src/i18n/locales/ja/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ja/cloud/portal.json@@ -248,6 +248,39 @@"nextPage": "次のページ","noPeopleFound": "該当するユーザーはいません","noPeopleFoundDescription": "別の名前やメールアドレス、または別のフィルターをお試しください。",+ "member": "メンバー",+ "searchRequests": "リクエストを検索…",+ "searchEmail": "宛先で検索…",+ "searchActivity": "名前またはメールアドレスで検索…",+ "filterAll": "すべて",+ "filterAccounts": "アカウント",+ "filterRequests": "リクエスト",+ "filterEmail": "メール",+ "noEmailFound": "一致するメールはありません",+ "noEmailFoundDescription": "サーバーが送信したメールがここに表示されます。別の宛先またはフィルターをお試しください。",+ "noActivityFound": "一致するアクティビティはありません",+ "noActivityFoundDescription": "管理者の操作がここに表示されます。別の名前やメールアドレス、または別のフィルターをお試しください。",+ "columnPerson": "ユーザー",+ "columnRole": "ロール",+ "columnWorkspaces": "ワークスペース",+ "columnWorkspace": "ワークスペース",+ "columnMembers": "メンバー",+ "columnLastActive": "最終アクティブ",+ "columnJoined": "参加日",+ "columnActions": "操作",+ "columnReason": "理由",+ "columnRequested": "リクエスト日時",+ "columnDecision": "判断",+ "columnMessage": "メッセージ",+ "columnRecipient": "宛先",+ "columnStatus": "ステータス",+ "columnWhen": "日時",+ "columnAdministrator": "管理者",+ "columnAction": "操作",+ "columnSubject": "対象",+ "columnDevice": "デバイス",+ "columnAddress": "IP アドレス",+ "columnSignedIn": "サインイン日時","suspendedReason": "停止中:{reason}","suspendHeading": "{name}を停止しますか?","suspendDescription": "すべての場所からサインアウトされ、アカウントを復元するまでサインインできません。ファイルは残ります。",diff --git a/packages/vue/src/i18n/locales/pl/cloud/portal.json b/packages/vue/src/i18n/locales/pl/cloud/portal.jsonindex ea9dead92..c013113c6 100644--- a/packages/vue/src/i18n/locales/pl/cloud/portal.json+++ b/packages/vue/src/i18n/locales/pl/cloud/portal.json@@ -252,6 +252,39 @@"nextPage": "Następna strona","noPeopleFound": "Nikt nie pasuje","noPeopleFoundDescription": "Spróbuj innego imienia, adresu e-mail lub innego filtra.",+ "member": "Członek",+ "searchRequests": "Szukaj próśb…",+ "searchEmail": "Szukaj według odbiorcy…",+ "searchActivity": "Szukaj według nazwy lub adresu e-mail…",+ "filterAll": "Wszystko",+ "filterAccounts": "Konta",+ "filterRequests": "Prośby",+ "filterEmail": "E-mail",+ "noEmailFound": "Brak pasujących e-maili",+ "noEmailFoundDescription": "E-maile wysyłane przez serwer pojawiają się tutaj. Spróbuj innego odbiorcy lub filtra.",+ "noActivityFound": "Brak pasującej aktywności",+ "noActivityFoundDescription": "Działania administratorów pojawiają się tutaj. Spróbuj innego imienia, adresu e-mail lub innego filtra.",+ "columnPerson": "Użytkownik",+ "columnRole": "Rola",+ "columnWorkspaces": "Obszary robocze",+ "columnWorkspace": "Obszar roboczy",+ "columnMembers": "Członkowie",+ "columnLastActive": "Ostatnia aktywność",+ "columnJoined": "Dołączył(a)",+ "columnActions": "Akcje",+ "columnReason": "Powód",+ "columnRequested": "Zgłoszono",+ "columnDecision": "Decyzja",+ "columnMessage": "Wiadomość",+ "columnRecipient": "Odbiorca",+ "columnStatus": "Status",+ "columnWhen": "Kiedy",+ "columnAdministrator": "Admin",+ "columnAction": "Działanie",+ "columnSubject": "Dotyczy",+ "columnDevice": "Urządzenie",+ "columnAddress": "Adres IP",+ "columnSignedIn": "Zalogowano","suspendedReason": "Zawieszono: {reason}","suspendHeading": "Zawiesić konto: {name}?","suspendDescription": "Ta osoba zostanie wylogowana ze wszystkich urządzeń i nie zaloguje się, dopóki nie przywrócisz konta. Jej pliki zostaną.",diff --git a/packages/vue/src/i18n/locales/ru/cloud/portal.json b/packages/vue/src/i18n/locales/ru/cloud/portal.jsonindex d60d9a0f8..e7e48ac1d 100644--- a/packages/vue/src/i18n/locales/ru/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ru/cloud/portal.json@@ -252,6 +252,39 @@"nextPage": "Следующая страница","noPeopleFound": "Никого не найдено","noPeopleFoundDescription": "Попробуйте другое имя, почту или фильтр.",+ "member": "Участник",+ "searchRequests": "Поиск запросов…",+ "searchEmail": "Поиск по получателю…",+ "searchActivity": "Поиск по имени или почте…",+ "filterAll": "Все",+ "filterAccounts": "Аккаунты",+ "filterRequests": "Запросы",+ "filterEmail": "Почта",+ "noEmailFound": "Нет подходящих писем",+ "noEmailFoundDescription": "Здесь появляются письма, которые отправляет сервер. Попробуйте другого получателя или фильтр.",+ "noActivityFound": "Нет подходящих действий",+ "noActivityFoundDescription": "Здесь появляется то, что делают администраторы. Попробуйте другое имя, почту или фильтр.",+ "columnPerson": "Пользователь",+ "columnRole": "Роль",+ "columnWorkspaces": "Рабочие пространства",+ "columnWorkspace": "Рабочее пространство",+ "columnMembers": "Участники",+ "columnLastActive": "Последняя активность",+ "columnJoined": "Регистрация",+ "columnActions": "Действия",+ "columnReason": "Причина",+ "columnRequested": "Запрошено",+ "columnDecision": "Решение",+ "columnMessage": "Письмо",+ "columnRecipient": "Получатель",+ "columnStatus": "Статус",+ "columnWhen": "Когда",+ "columnAdministrator": "Администратор",+ "columnAction": "Действие",+ "columnSubject": "Объект",+ "columnDevice": "Устройство",+ "columnAddress": "IP-адрес",+ "columnSignedIn": "Вход","suspendedReason": "Заблокирован: {reason}","suspendHeading": "Заблокировать {name}?","suspendDescription": "Человек выйдет на всех устройствах и не сможет войти, пока вы не восстановите аккаунт. Его файлы сохранятся.",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.jsonindex 69c594523..2d26d783a 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json@@ -248,6 +248,39 @@"nextPage": "下一页","noPeopleFound": "没有匹配的人","noPeopleFoundDescription": "请尝试其他名字、邮箱或筛选条件。",+ "member": "成员",+ "searchRequests": "搜索请求…",+ "searchEmail": "按收件人搜索…",+ "searchActivity": "按姓名或邮箱搜索…",+ "filterAll": "全部",+ "filterAccounts": "账号",+ "filterRequests": "请求",+ "filterEmail": "邮件",+ "noEmailFound": "没有匹配的邮件",+ "noEmailFoundDescription": "服务器发送的邮件会显示在这里。请尝试其他收件人或筛选条件。",+ "noActivityFound": "没有匹配的活动",+ "noActivityFoundDescription": "管理员的操作会显示在这里。请尝试其他名字、邮箱或筛选条件。",+ "columnPerson": "用户",+ "columnRole": "角色",+ "columnWorkspaces": "工作区",+ "columnWorkspace": "工作区",+ "columnMembers": "成员",+ "columnLastActive": "最近活跃",+ "columnJoined": "加入时间",+ "columnActions": "操作",+ "columnReason": "原因",+ "columnRequested": "请求时间",+ "columnDecision": "决定",+ "columnMessage": "消息",+ "columnRecipient": "收件人",+ "columnStatus": "状态",+ "columnWhen": "时间",+ "columnAdministrator": "管理员",+ "columnAction": "操作",+ "columnSubject": "对象",+ "columnDevice": "设备",+ "columnAddress": "IP 地址",+ "columnSignedIn": "登录时间","suspendedReason": "已停用:{reason}","suspendHeading": "停用 {name}?","suspendDescription": "对方会在所有设备上退出登录,并且在你恢复账号之前无法登录。其文件会保留。",diff --git a/packages/vue/src/i18n/messages/cloud/portal.ts b/packages/vue/src/i18n/messages/cloud/portal.tsindex d0ee69b4f..851582876 100644--- a/packages/vue/src/i18n/messages/cloud/portal.ts+++ b/packages/vue/src/i18n/messages/cloud/portal.ts@@ -290,6 +290,40 @@ export const cloudPortalMessageDefaults = {nextPage: 'Next page',noPeopleFound: 'No one matches',noPeopleFoundDescription: 'Try another name or email, or another filter.',+ member: 'Member',+ searchRequests: 'Search requests…',+ searchEmail: 'Search by recipient…',+ searchActivity: 'Search by name or email…',+ filterAll: 'All',+ filterAccounts: 'Accounts',+ filterRequests: 'Requests',+ filterEmail: 'Email',+ noEmailFound: 'No email matches',+ noEmailFoundDescription: 'Email the server sends shows here. Try another recipient or filter.',+ noActivityFound: 'No activity matches',+ noActivityFoundDescription:+ 'What administrators do shows here. Try another name or email, or another filter.',+ columnPerson: 'Person',+ columnRole: 'Role',+ columnWorkspaces: 'Workspaces',+ columnWorkspace: 'Workspace',+ columnMembers: 'Members',+ columnLastActive: 'Last active',+ columnJoined: 'Joined',+ columnActions: 'Actions',+ columnReason: 'Reason',+ columnRequested: 'Requested',+ columnDecision: 'Decision',+ columnMessage: 'Message',+ columnRecipient: 'Recipient',+ columnStatus: 'Status',+ columnWhen: 'When',+ columnAdministrator: 'Administrator',+ columnAction: 'Action',+ columnSubject: 'About',+ columnDevice: 'Device',+ columnAddress: 'IP address',+ columnSignedIn: 'Signed in',suspendedReason: params('Suspended: {reason}'),suspendHeading: params('Suspend {name}?'),suspendDescription:diff --git a/src/AGENTS.md b/src/AGENTS.mdindex af0169fd3..78a92558b 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -57,7 +57,7 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and## UI-`src/components/ui/**` is generic, store-free design-system code grouped by family: `{button,input,select,toggle,dialog,panel,binding,feedback,overlay,menu,paint}/`. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under `src/theme/`; feature themes stay separate. Use explicit imports without old-path forwarding shims.+`src/components/ui/**` is generic, store-free design-system code grouped by family: `{binding,button,collapsible,date,dialog,feedback,input,list,menu,overlay,paint,panel,select,table,tabs,toggle}/`. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under `src/theme/`; feature themes stay separate. Use explicit imports without old-path forwarding shims.### Building blocks@@ -67,7 +67,8 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and- Colors are the `--color-*` tokens in `src/theme/tokens.css`, each defined for both themes; statuses use one family each: `error` and `warning` have a text color, a `-bg` tint, and a `-border`, `success` a text color; `error-fill` and `success-fill` are solid, and `warning-action` colors buttons on the warning tint. Name the token's utility (`text-warning`), not `[var(--color-warning)]` or a default palette color (`open-pencil/no-unknown-tailwind-classes`).- Bind visual state through semantic `data-*` attributes. Steiger rejects template-time `use*UI()`, visual-state utility branches, and raw SVG app icons.- `Tip`, not native `title`; Lucide/Iconify components, not raw SVG or Unicode icons; `e.code`, not `e.key`, for modified shortcuts.-- App dialogs compose the Reka-backed components under `src/components/ui/dialog/` and the typed theme in `src/theme/dialog.ts`. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs.+- A theme file default-exports a plain slots object; the component side wraps it with `tv` once and derives its `UI` type with `ComponentUI` (`src/components/ui/table/ui.ts`). A family of parts keeps one theme in `src/theme/<family>/index.ts`, wraps it in `ui.ts` as `<family>` and `use<Family>UI`, and exports its parts from `index.ts`; a single component keeps `src/theme/<family>/<component>.ts` and a wrapper of the same name (`src/components/ui/feedback/toast.ts`). Compose parts as components; slots carry content, not data that a part could render itself.+- App dialogs compose the Reka-backed components under `src/components/ui/dialog/` and the typed theme in `src/theme/dialog/index.ts`. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs.- SDK property primitives, binding fields, commands, and i18n: `packages/vue/AGENTS.md`.### Layout@@ -89,6 +90,8 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and### Feedback and forms- `AppAlert` (`src/components/ui/feedback/AppAlert.vue`, theme `src/theme/feedback/alert.ts`) for persistent contextual errors, warnings, recovery guidance, and informative results, with translated `heading`/`description` and an `actions` slot. Do not hand-roll alert markup or colored error paragraphs. Alerts announce changes without taking keyboard focus.+- Rows under labelled columns are a TanStack Table drawn by `AppDataTable` from the table parts (`src/components/ui/table/`): each column renders its own cell, plain values through `accessor` and anything richer as a cell component through `h()`, with widths or container-width hiding in its `meta`; do not hand-roll `<ul>` rows with aligned spans or pass cells through slots. Portal lists the server pages go through `usePortalList` and `PortalTable` (`src/components/cloud-portal/console/PortalPeople.vue`).+- Content that is loading shows `AppSkeleton` placeholders in its own shape, which fade in after a moment so fast answers replace nothing; a refresh keeps what was shown, and an empty state appears only once a load finished with nothing in it (`src/components/ui/table/AppTablePlaceholder.vue`, `src/components/cloud-portal/layout/PortalPageSkeleton.vue`).- The toast service is for transient confirmations without a visible control to carry them, such as a copy from a menu or shortcut, or an action completed after its view closes. A copy button confirms in place instead: a leading copy icon that turns into a check and the label `common.copied` (`src/components/ui/input/AppCopyField.vue`). Never show a toast and an alert for the same event; partial saves and actionable failures must not disappear in a toast.- Field validation stays inline in the shared field component with `aria-invalid`, error text before hints, and first-invalid-field focus.- Ordinary labels such as Running/Stopped remain status text or badges. Destructive confirmation belongs in the shared confirmation dialog.diff --git a/src/app/cloud-portal/list.ts b/src/app/cloud-portal/list.tsnew file mode 100644index 000000000..738b461e7--- /dev/null+++ b/src/app/cloud-portal/list.ts@@ -0,0 +1,150 @@+import {+ functionalUpdate,+ rowPaginationFeature,+ tableFeatures,+ useTable,+ type ColumnDef,+ type PaginationState,+ type RowData,+ type Updater+} from '@tanstack/vue-table'+import { refDebounced } from '@vueuse/core'+import { computed, ref, shallowRef, toValue, watch, type MaybeRefOrGetter } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import type { TableColumnMeta } from '@/components/ui/table/columns'++import { usePortalLoad } from './state'++/** The rows a console list shows at a time. */+export const PORTAL_PAGE_SIZE = 50+/** How long typing pauses before a search asks the server. */+const SEARCH_DELAY_MS = 250++/** What console tables can do: the server pages them, and columns carry their own classes. */+export const portalTableFeatures = tableFeatures({+ rowPaginationFeature,+ // A type-only slot: TanStack reads the columns' `meta` type from it.+ columnMeta: {} as TableColumnMeta+})+export type PortalTableFeatures = typeof portalTableFeatures+export type PortalColumn<Row extends RowData> = ColumnDef<PortalTableFeatures, Row>++/** What a console list asks the server for: words to search for, a filter, and a page. */+export type PortalListRequest<Filter extends string> = {+ search?: string+ filter: Filter+ limit: number+ offset: number+}++/** A console table of rows the page already holds, such as an account's sessions. */+export function usePortalRows<Row extends RowData>(+ rows: MaybeRefOrGetter<Row[]>,+ options: { rowId: (row: Row) => string; columns: PortalColumn<Row>[] }+) {+ return useTable({+ features: portalTableFeatures,+ columns: options.columns,+ data: computed(() => toValue(rows)),+ getRowId: options.rowId+ })+}++/** A page of a console list, as the server answers it. */+export type PortalListPage<Filter extends string, Row> = {+ rows: Row[]+ /** How many rows match the search and filter, across every page. */+ total: number+ /** How many rows match the search under each filter. */+ counts: Record<Filter, number>+}++/**+ * A console list the server searches, filters, and pages: what the person types, which filter is+ * on, and the page shown, loaded again whenever one changes. A new search or filter starts from+ * the first page, and a change that empties the last page steps back to the one before.+ */+export function usePortalList<Filter extends string, Row extends RowData>(options: {+ filter: Filter+ load: (request: PortalListRequest<Filter>) => Promise<PortalListPage<Filter, Row>>+ rowId: (row: Row) => string+ columns: PortalColumn<Row>[]+}) {+ const messages = useCloudPortalMessages()+ const query = ref('')+ const search = refDebounced(query, SEARCH_DELAY_MS)+ const filter = shallowRef<Filter>(options.filter)+ const pagination = ref<PaginationState>({ pageIndex: 0, pageSize: PORTAL_PAGE_SIZE })+ const offset = computed(() => pagination.value.pageIndex * pagination.value.pageSize)++ // Each page keeps the offset it was asked for, so the range describes the rows on screen, not+ // a page still on its way.+ const list = usePortalLoad(async () => {+ const request = {+ search: search.value.trim() || undefined,+ filter: filter.value,+ limit: pagination.value.pageSize,+ offset: offset.value+ }+ return { ...(await options.load(request)), offset: request.offset }+ }, null)+ const shownOffset = computed(() => list.data.value?.offset ?? 0)+ // After a failed load the last page belongs to another search or filter, so none is shown.+ const rows = computed(() => (list.error.value ? [] : (list.data.value?.rows ?? [])))+ const total = computed(() => list.data.value?.total ?? 0)+ const counts = computed(() => list.data.value?.counts ?? null)++ const table = useTable({+ features: portalTableFeatures,+ columns: options.columns,+ data: rows,+ rowCount: total,+ manualPagination: true,+ getRowId: options.rowId,+ state: computed(() => ({ pagination: pagination.value })),+ onPaginationChange: (next: Updater<PaginationState>) => {+ pagination.value = functionalUpdate(next, pagination.value)+ }+ })++ watch([search, filter], () => {+ if (pagination.value.pageIndex === 0) void list.reload()+ else pagination.value = { ...pagination.value, pageIndex: 0 }+ })+ watch(+ () => pagination.value.pageIndex,+ () => void list.reload()+ )+ watch(total, (count) => {+ const { pageIndex, pageSize } = pagination.value+ if (pageIndex > 0 && pageIndex * pageSize >= count) {+ pagination.value = { pageSize, pageIndex: Math.max(0, Math.ceil(count / pageSize) - 1) }+ }+ })++ return {+ table,+ query,+ filter,+ total,+ counts,+ loading: list.loading,+ status: list.status,+ error: list.error,+ reload: list.reload,+ /** Which rows the page shows, such as “51–100 of 230”. */+ range: computed(() =>+ messages.value.pageRange({+ from: Math.min(shownOffset.value + 1, total.value),+ to: Math.min(shownOffset.value + rows.value.length, total.value),+ total: total.value+ })+ )+ }+}++export type PortalList<Filter extends string, Row extends RowData> = ReturnType<+ typeof usePortalList<Filter, Row>+>diff --git a/src/app/cloud-portal/state.ts b/src/app/cloud-portal/state.tsindex 135c33bd4..57c164506 100644--- a/src/app/cloud-portal/state.ts+++ b/src/app/cloud-portal/state.ts@@ -1,21 +1,53 @@import { noop, useAsyncState } from '@vueuse/core'-import { computed, shallowRef } from 'vue'+import { computed, getCurrentInstance, onActivated, shallowRef } from 'vue'import { usePortalFailureMessages } from './failure'+/**+ * Where a load stands: nothing to show yet, the last value shown while a newer one loads, or done.+ * A failure is `failed` before anything loaded and `ready` with an error after, since the page+ * then still has something to show.+ */+export type PortalLoadStatus = 'loading' | 'failed' | 'refreshing' | 'ready'+/*** Something the page reads from the server. A newer load replaces an older one still running,* a failure is kept in words until the next load starts, and the last good value stays shown.+ * A page the console keeps alive loads again when it comes back, showing what it had meanwhile.*/export function usePortalLoad<T>(load: () => Promise<T>, initial: T) {const failures = usePortalFailureMessages()- const { state, isLoading, error, execute } = useAsyncState(load, initial, {- resetOnExecute: false,- onError: noop+ // `useAsyncState` resets its own `isReady` on every run, so whether anything ever loaded is kept+ // here: it tells a first load, with nothing to show, from a refresh. Only the newest request+ // counts, as for the value: an older one that succeeds after a newer one failed shows nothing.+ const loaded = shallowRef(false)+ let latest = 0+ const { state, isLoading, error, execute } = useAsyncState(+ async () => {+ const request = ++latest+ const value = await load()+ if (request === latest) loaded.value = true+ return value+ },+ initial,+ { resetOnExecute: false, onError: noop }+ )+ const status = computed<PortalLoadStatus>(() => {+ if (loaded.value) return isLoading.value ? 'refreshing' : 'ready'+ return isLoading.value ? 'loading' : 'failed'})+ // `onActivated` also runs when the page first appears, which has just started its own load.+ let shown = false+ if (getCurrentInstance()) {+ onActivated(() => {+ if (shown) void execute()+ shown = true+ })+ }return {data: state,loading: isLoading,+ status,error: computed(() => (error.value === undefined ? null : failures.api(error.value))),reload: async () => {await execute()diff --git a/src/components/TabBar.vue b/src/components/TabBar.vueindex 3f2677c92..0999a6421 100644--- a/src/components/TabBar.vue+++ b/src/components/TabBar.vue@@ -8,7 +8,7 @@ import { useI18n } from '@open-pencil/vue/i18n'import { animationsEnabled } from '@/app/shell/motion'import { useTabsStore, createTab } from '@/app/tabs'import PreparationIndicator from '@/components/preparation/tab/Indicator.vue'-import { useScrollOverflow } from '@/components/shell/useScrollOverflow'+import { useScrollOverflow } from '@/components/ui/list/useScrollOverflow'import Tip from '@/components/ui/overlay/Tip.vue'import tabBarTheme from '@/theme/tab-bar'@@ -19,7 +19,12 @@ const tabBarStyles = tv(tabBarTheme)const baseStyles = tabBarStyles()const scroller = useTemplateRef<HTMLElement>('scroller')-const { overflowing, overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(scroller)+const { overflowing, overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(+ scroller,+ {+ smooth: animationsEnabled+ }+)// Keep the active tab in view when it opens, when another one is chosen, and when the row starts// or stops overflowing, since the chevron that appears then narrows the visible row. Scrollingdiff --git a/src/components/cloud-portal/account/PortalSessions.vue b/src/components/cloud-portal/account/PortalSessions.vueindex 2baabeff3..e92b1d8f3 100644--- a/src/components/cloud-portal/account/PortalSessions.vue+++ b/src/components/cloud-portal/account/PortalSessions.vue@@ -1,17 +1,21 @@<script setup lang="ts">-import { compact } from 'es-toolkit'-import { computed, ref } from 'vue'+import { createColumnHelper } from '@tanstack/vue-table'+import { computed, h, ref, type Component } from 'vue'+import IconAppWindow from '~icons/lucide/app-window'+import IconGlobe from '~icons/lucide/globe'+import IconLogIn from '~icons/lucide/log-in'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import { usePortalDeviceLabels } from '@/app/cloud-portal/devices'+import { usePortalRows, type PortalTableFeatures } from '@/app/cloud-portal/list'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'-import AppBadge from '@/components/ui/feedback/AppBadge.vue'import { useHeldContent } from '@/components/ui/overlay/held'-import { portalList } from '@/theme/cloud-portal/list'+import AppDataTable from '@/components/ui/table/AppDataTable.vue'+import PortalTextCell from '../table/PortalTextCell.vue'import type { PortalDevice, PortalSession, PortalSignIn } from '../types'/**@@ -23,17 +27,19 @@ const {sessions,signIns,manage = false,- busy = false+ busy = false,+ loading = false} = defineProps<{sessions: PortalSession[]signIns: PortalSignIn[]/** The person's own sessions, which they can sign out. */manage?: booleanbusy?: boolean+ /** `first` before anything has loaded, `refresh` while it loads again. */+ loading?: 'first' | 'refresh' | false}>()const emit = defineEmits<{ revoke: [sessionId: string]; revokeOthers: [] }>()-const ui = portalList()const messages = useCloudPortalMessages()const labels = usePortalDeviceLabels()const others = computed(() => sessions.filter((session) => !session.current))@@ -56,10 +62,82 @@ const confirmation = computed(() => {}})-const detail = (parts: (string | null)[]) => compact(parts).join(' · ')const signedInWith = (device: PortalDevice) =>device.method ? messages.value.signedInWith({ method: labels.method(device.method) }) : null+const address = {+ header: () => messages.value.columnAddress,+ meta: { class: 'hidden w-36 whitespace-nowrap text-muted tabular-nums @xl/table:table-cell' }+}+/** A device a session or sign-in came from, with how it signed in under it. */+function device(entry: PortalDevice, icon: Component, current = false) {+ return h(PortalTextCell, {+ icon,+ text: labels.device(entry),+ strong: true,+ badge: current ? messages.value.thisSession : null,+ detail: signedInWith(entry)+ })+}++const sessionColumn = createColumnHelper<PortalTableFeatures, PortalSession>()+const sessionTable = usePortalRows(() => sessions, {+ rowId: (session) => session.id,+ columns: sessionColumn.columns([+ sessionColumn.display({+ id: 'device',+ header: () => messages.value.columnDevice,+ cell: ({ row: { original: session } }) =>+ device(session, session.method === 'desktop' ? IconAppWindow : IconGlobe, session.current)+ }),+ sessionColumn.accessor('ipAddress', { id: 'address', ...address }),+ sessionColumn.accessor('signedInOn', {+ header: () => messages.value.columnSignedIn,+ meta: { class: 'hidden w-32 whitespace-nowrap text-muted @2xl/table:table-cell' }+ }),+ sessionColumn.accessor('lastActive', {+ header: () => messages.value.columnLastActive,+ meta: { class: 'w-32 whitespace-nowrap text-muted' }+ }),+ sessionColumn.display({+ id: 'actions',+ header: () => messages.value.columnActions,+ meta: { class: 'w-px text-right', actions: true },+ cell: ({ row: { original: session } }) =>+ session.current+ ? null+ : h(+ AppButton,+ {+ size: 'sm',+ variant: 'ghost',+ disabled: busy,+ onClick: () => {+ confirming.value = { kind: 'one', session }+ }+ },+ () => messages.value.signOut+ )+ })+ ])+})+const signInColumn = createColumnHelper<PortalTableFeatures, PortalSignIn>()+const signInTable = usePortalRows(() => signIns, {+ rowId: (signIn) => signIn.id,+ columns: signInColumn.columns([+ signInColumn.display({+ id: 'device',+ header: () => messages.value.columnDevice,+ cell: ({ row: { original: signIn } }) => device(signIn, IconLogIn)+ }),+ signInColumn.accessor('ipAddress', { id: 'address', ...address }),+ signInColumn.accessor('when', {+ header: () => messages.value.columnWhen,+ meta: { class: 'w-44 whitespace-nowrap text-muted' }+ })+ ])+})+function confirm() {const pending = confirming.valueconfirming.value = null@@ -83,61 +161,32 @@ function confirm() {{{ messages.signOutOtherSessions }}</AppButton></template>- <ul v-if="sessions.length" :class="ui.list()">- <li v-for="session in sessions" :key="session.id" :class="ui.row()">- <icon-lucide-app-window- v-if="session.method === 'desktop'"- class="size-4 shrink-0 text-muted"- />- <icon-lucide-globe v-else class="size-4 shrink-0 text-muted" />- <div :class="ui.body()">- <p :class="ui.title()">- {{ labels.device(session) }}- <AppBadge v-if="session.current">{{ messages.thisSession }}</AppBadge>- </p>- <p :class="ui.detail()">- {{- detail([- messages.lastActive({ when: session.lastActive }),- session.ipAddress,- messages.signedInOn({ date: session.signedInOn }),- signedInWith(session)- ])- }}- </p>- </div>- <AppButton- v-if="manage && !session.current"- size="sm"- variant="ghost"- :disabled="busy"- @click="confirming = { kind: 'one', session }"- >- {{ messages.signOut }}- </AppButton>- </li>- </ul>- <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">- {{ messages.noSessions }}- </p>+ <AppDataTable+ :table="sessionTable"+ :label="messages.activeSessions"+ :loading="loading"+ :loading-label="messages.loading"+ :hidden="manage ? [] : ['actions']"+ >+ <template #empty>+ <p class="text-center text-xs text-muted">{{ messages.noSessions }}</p>+ </template>+ </AppDataTable></SettingsSection><SettingsSection><template #title>{{ messages.recentSignIns }}</template><template v-if="manage" #description>{{ messages.recentSignInsDescription }}</template>- <ul v-if="signIns.length" :class="ui.list()">- <li v-for="signIn in signIns" :key="signIn.id" :class="ui.row()">- <icon-lucide-log-in class="size-4 shrink-0 text-muted" />- <div :class="ui.body()">- <p :class="ui.title()">{{ labels.device(signIn) }}</p>- <p :class="ui.detail()">{{ detail([signIn.ipAddress, signedInWith(signIn)]) }}</p>- </div>- <span :class="ui.meta()">{{ signIn.when }}</span>- </li>- </ul>- <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">- {{ messages.noSignIns }}- </p>+ <AppDataTable+ :table="signInTable"+ :label="messages.recentSignIns"+ :loading="loading"+ :loading-label="messages.loading"+ >+ <template #empty>+ <p class="text-center text-xs text-muted">{{ messages.noSignIns }}</p>+ </template>+ </AppDataTable></SettingsSection><AppConfirmationDialogdiff --git a/src/components/cloud-portal/console/CloudPortalConsole.stories.ts b/src/components/cloud-portal/console/CloudPortalConsole.stories.tsindex a39df6d44..d60af8228 100644--- a/src/components/cloud-portal/console/CloudPortalConsole.stories.ts+++ b/src/components/cloud-portal/console/CloudPortalConsole.stories.ts@@ -1,5 +1,4 @@import type { Meta, StoryObj } from '@storybook/vue3-vite'-import { ref } from 'vue'import PortalAccountSecurity from '../account/PortalAccountSecurity.vue'import PortalProfile from '../account/PortalProfile.vue'@@ -8,6 +7,8 @@ import PortalConsoleLayout from '../layout/PortalConsoleLayout.vue'import { PORTAL_SECTION_ICONS } from '../layout/sections'import type {AccessRequest,+ PortalActivityEntry,+ PortalEmail,PortalPerson,PortalPersonDetail,PortalSection,@@ -117,7 +118,90 @@ const people: PortalPerson[] = [workspaceCount: 0}]-const counts = { all: 24, administrators: 2, suspended: 1, 'without-two-step': 9 }+/** A console list's server for a story: every page holds `rows`, and each filter `counts`. */+const serve =+ <Filter extends string, Row>(rows: Row[], counts: Record<Filter, number>) =>+ () =>+ Promise.resolve({ rows, total: rows.length, counts })+const loadPeople = serve(people, {+ all: 24,+ administrators: 2,+ suspended: 1,+ 'without-two-step': 9+})+const loadRequests = serve(requests, { pending: 3, approved: 18, rejected: 2, revoked: 1 })+const loadNoRequests = serve<AccessRequest['status'], AccessRequest>([], {+ pending: 0,+ approved: 18,+ rejected: 2,+ revoked: 1+})+const emails: PortalEmail[] = [+ {+ id: 'e1',+ kind: 'document-invitation',+ recipient: '[email protected]',+ status: 'failed',+ attempts: 5,+ when: 'Oct 25, 2026, 10:42 AM',+ error: 'Mailbox unavailable'+ },+ {+ id: 'e2',+ kind: 'email-verification',+ recipient: '[email protected]',+ status: 'sent',+ attempts: 1,+ when: 'Oct 25, 2026, 9:15 AM',+ error: null+ },+ {+ id: 'e4',+ kind: 'new-sign-in',+ recipient: '[email protected]',+ status: 'sent',+ attempts: 1,+ when: 'Oct 25, 2026, 8:51 AM',+ error: null+ },+ {+ id: 'e3',+ kind: 'enrollment-approved',+ recipient: '[email protected]',+ status: 'waiting',+ attempts: 2,+ when: 'Oct 24, 2026, 6:20 PM',+ error: null+ }+]+const loadEmails = serve(emails, { all: 4, sent: 2, waiting: 1, failed: 1 })+const entries: PortalActivityEntry[] = [+ {+ id: 'a1',+ actor: { id: 'user-ana', name: 'Ana Duarte' },+ action: 'enrollment.approved',+ target: '[email protected]',+ reason: null,+ when: 'Oct 24, 2026, 3:10 PM'+ },+ {+ id: 'a2',+ actor: { id: 'user-ben', name: 'Ben Ortiz' },+ action: 'user.banned',+ target: 'Tom Weber',+ reason: 'Shared files outside the studio',+ when: 'Oct 21, 2026, 11:02 AM'+ },+ {+ id: 'a3',+ actor: { id: 'user-ana', name: 'Ana Duarte' },+ action: 'user.admin-granted',+ target: 'Ben Ortiz',+ reason: null,+ when: 'Sep 28, 2026, 9:30 AM'+ }+]+const loadActivity = serve(entries, { all: 3, accounts: 2, requests: 1, email: 0 })const sessions: PortalSession[] = [{id: 's1',@@ -226,14 +310,14 @@ const story = (setup: () => ({account,sections,- requests,- people,- counts,sessions,signIns,person,- filter: ref('pending'),- peopleFilter: ref('all'),+ loadPeople,+ loadRequests,+ loadNoRequests,+ loadEmails,+ loadActivity,...extra}),template: `@@ -290,39 +374,30 @@ export const AccessRequests = story('requests','Access requests','People asking to join. Approving lets them sign in; each gets an email either way.',- `<PortalAccessRequests v-model:filter="filter" :requests="requests" />`+ `<PortalAccessRequests :load="loadRequests" />`)export const NoAccessRequests = story('requests','Access requests','People asking to join. Approving lets them sign in; each gets an email either way.',- `<PortalAccessRequests v-model:filter="filter" :requests="[]" />`+ `<PortalAccessRequests :load="loadNoRequests" />`)export const People = story('people','People','24 accounts on this server.',- `<PortalPeople v-model:filter="peopleFilter" :people="people" :counts="counts" :page-size="4" />`+ `<PortalPeople :load="loadPeople" />`)export const Person = story('people', 'People', '', `<PortalPerson :detail="person" />`)export const EmailDelivery = story('email','Email delivery','Invitations, sign-in links, and access decisions the server sends.',- `<PortalEmailDelivery :emails="[- { id: 'e1', kind: 'document-invitation', recipient: '[email protected]', status: 'failed', attempts: 5, when: '10:42', error: 'Mailbox unavailable' },- { id: 'e2', kind: 'email-verification', recipient: '[email protected]', status: 'sent', attempts: 1, when: '09:15' },- { id: 'e4', kind: 'new-sign-in', recipient: '[email protected]', status: 'sent', attempts: 1, when: '08:51' },- { id: 'e3', kind: 'enrollment-approved', recipient: '[email protected]', status: 'sent', attempts: 1, when: 'Yesterday' }- ]" />`+ `<PortalEmailDelivery :load="loadEmails" />`)export const Activity = story('activity','Activity','What administrators did on this server.',- `<PortalActivity :entries="[- { id: 'a1', actor: { id: 'user-ana', name: 'Ana Duarte' }, action: 'enrollment.approved', target: '[email protected]', when: 'Yesterday' },- { id: 'a2', actor: { id: 'user-ben', name: 'Ben Ortiz' }, action: 'user.banned', target: 'Tom Weber', reason: 'Shared files outside the studio', when: 'Oct 21, 2026, 11:02 AM' },- { id: 'a3', actor: { id: 'user-ana', name: 'Ana Duarte' }, action: 'user.admin-granted', target: 'Ben Ortiz', when: 'Sep 28' }- ]" />`+ `<PortalActivity :load="loadActivity" />`)diff --git a/src/components/cloud-portal/console/PortalAccessRequests.vue b/src/components/cloud-portal/console/PortalAccessRequests.vueindex ac66c4319..a7053a5a6 100644--- a/src/components/cloud-portal/console/PortalAccessRequests.vue+++ b/src/components/cloud-portal/console/PortalAccessRequests.vue@@ -1,58 +1,113 @@<script setup lang="ts">-import { computed, ref } from 'vue'+import { createColumnHelper } from '@tanstack/vue-table'+import { computed, h, ref } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'-import AccountAvatar from '@/components/presence/AccountAvatar.vue'-import AppButton from '@/components/ui/button/AppButton.vue'+import {+ usePortalList,+ type PortalListPage,+ type PortalListRequest,+ type PortalTableFeatures+} from '@/app/cloud-portal/list'import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'-import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import AppTextarea from '@/components/ui/input/AppTextarea.vue'import { useHeldContent } from '@/components/ui/overlay/held'-import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'import { portalForm } from '@/theme/cloud-portal/form'-import { portalList } from '@/theme/cloud-portal/list'+import PortalIdentityCell from '../table/PortalIdentityCell.vue'+import PortalRequestActions from '../table/PortalRequestActions.vue'+import PortalTable from '../table/PortalTable.vue'+import PortalTextCell from '../table/PortalTextCell.vue'import type { AccessRequest, AccessRequestStatus } from '../types'/** People asking to join a server that reviews new accounts, and the decisions made so far. */-const { requests, busy = null } = defineProps<{- requests: AccessRequest[]+const { load, busy = null } = defineProps<{+ load: (+ request: PortalListRequest<AccessRequestStatus>+ ) => Promise<PortalListPage<AccessRequestStatus, AccessRequest>>/** The request a decision is being saved for. */busy?: string | null}>()-const filter = defineModel<AccessRequestStatus>('filter', { default: 'pending' })const emit = defineEmits<{approve: [id: string]reject: [id: string, note?: string]revoke: [id: string, note?: string]}>()-const ui = portalList()const form = portalForm()const messages = useCloudPortalMessages()-const tones = {- pending: 'warning',- approved: 'success',- rejected: 'neutral',- revoked: 'error'-} as const+const name = (request: AccessRequest) => request.name ?? request.emailconst labels = computed(() => ({pending: messages.value.statusWaiting,approved: messages.value.statusApproved,rejected: messages.value.statusDeclined,revoked: messages.value.statusRemoved}))-function detail(request: AccessRequest) {- const asked = messages.value.asked({ date: request.requestedOn })- if (!request.reviewedBy || request.status === 'pending') return asked- const decision = labels.value[request.status]- const reviewed = `${asked} · ${messages.value.reviewedBy({ decision, name: request.reviewedBy })}`- return request.note- ? `${reviewed} · ${messages.value.noteDetail({ note: request.note })}`- : reviewed-}+const column = createColumnHelper<PortalTableFeatures, AccessRequest>()+const requests = usePortalList<AccessRequestStatus, AccessRequest>({+ filter: 'pending',+ load: (request) => load(request),+ rowId: (request) => request.id,+ columns: column.columns([+ column.display({+ id: 'person',+ header: () => messages.value.columnPerson,+ cell: ({ row: { original: request } }) =>+ h(PortalIdentityCell, {+ id: request.email,+ name: name(request),+ detail: request.name ? request.email : null+ })+ }),+ column.display({+ id: 'reason',+ header: () => messages.value.columnReason,+ meta: { class: 'hidden w-2/5 @2xl/table:table-cell' },+ cell: ({ row: { original: request } }) => h(PortalTextCell, { quote: request.reason })+ }),+ column.accessor('requestedOn', {+ header: () => messages.value.columnRequested,+ meta: { class: 'hidden w-28 whitespace-nowrap text-muted @xl/table:table-cell' }+ }),+ column.display({+ id: 'decision',+ header: () => messages.value.columnDecision,+ meta: { class: 'hidden @3xl/table:table-cell' },+ cell: ({ row: { original: request } }) =>+ h(PortalTextCell, {+ text: request.reviewedBy+ ? messages.value.reviewedBy({+ decision: labels.value[request.status],+ name: request.reviewedBy+ })+ : null,+ detail: request.note ? messages.value.noteDetail({ note: request.note }) : null+ })+ }),+ column.display({+ id: 'actions',+ header: () => messages.value.columnActions,+ meta: { class: 'w-px whitespace-nowrap text-right', actions: true },+ cell: ({ row: { original: request } }) =>+ h(PortalRequestActions, {+ request,+ busy: busy === request.id,+ onApprove: () => emit('approve', request.id),+ onAsk: (kind: 'reject' | 'revoke') => ask(kind, request)+ })+ })+ ])+})+const filters = computed(() => [+ { value: 'pending' as const, label: messages.value.filterWaiting },+ { value: 'approved' as const, label: messages.value.filterApproved },+ { value: 'rejected' as const, label: messages.value.filterDeclined },+ { value: 'revoked' as const, label: messages.value.filterRemoved }+])+// Waiting requests have no decision yet.+const hidden = computed(() => (requests.filter.value === 'pending' ? ['decision'] : []))/** Declining or taking access away is asked once more, with a note for the other administrators. */const confirming = ref<{ kind: 'reject' | 'revoke'; request: AccessRequest } | null>(null)const note = ref('')@@ -61,15 +116,14 @@ const confirmation = computed(() => {const pending = confirmingShown.valueif (!pending) return nullconst words = messages.value- const name = pending.request.name ?? pending.request.emailreturn pending.kind === 'reject'? {- heading: words.declineHeading({ name }),+ heading: words.declineHeading({ name: name(pending.request) }),description: words.declineDescription,confirm: words.decline}: {- heading: words.removeAccessHeading({ name }),+ heading: words.removeAccessHeading({ name: name(pending.request) }),description: words.removeAccessDescription,confirm: words.removeAccess}@@ -86,96 +140,37 @@ function confirm() {if (pending.kind === 'reject') emit('reject', pending.request.id, written)else emit('revoke', pending.request.id, written)}++defineExpose({ reload: requests.reload })</script><template>- <div class="flex flex-col gap-3">- <div :class="ui.toolbar()">- <SegmentedControl- v-model="filter"- required- :label="messages.accessRequests"- :options="[- { value: 'pending', label: messages.filterWaiting },- { value: 'approved', label: messages.filterApproved },- { value: 'rejected', label: messages.filterDeclined },- { value: 'revoked', label: messages.filterRemoved }- ]"- />+ <PortalTable+ :list="requests"+ :label="messages.accessRequests"+ :search-label="messages.searchRequests"+ :filters="filters"+ :hidden="hidden"+ :empty-label="+ requests.filter.value === 'pending' ? messages.noOneWaiting : messages.nothingHere+ "+ :empty-description="messages.requestsEmptyDescription"+ >+ <template #icon><icon-lucide-inbox class="size-5" /></template>+ </PortalTable>+ <AppConfirmationDialog+ :open="confirming !== null"+ tone="danger"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="messages.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ @update:open="(open) => !open && (confirming = null)"+ @confirm="confirm"+ >+ <div :class="[form.field(), 'mt-3']">+ <label for="portal-review-note" :class="form.label()">{{ messages.reviewNote }}</label>+ <AppTextarea id="portal-review-note" v-model="note" :rows="2" maxlength="1000" /></div>- <ul v-if="requests.length" :class="ui.list()">- <li v-for="request in requests" :key="request.id" :class="ui.row()">- <AccountAvatar :id="request.email" :name="request.name ?? request.email" size="md" />- <div :class="ui.body()">- <p :class="ui.title()">- {{ request.name ?? request.email }}- <span v-if="request.name" class="font-normal text-muted">{{ request.email }}</span>- </p>- <p v-if="request.reason" :class="ui.quote()">“{{ request.reason }}”</p>- <p :class="ui.detail()">{{ detail(request) }}</p>- </div>- <span- v-if="request.status !== 'pending'"- :class="ui.status()"- :data-tone="tones[request.status]"- >- {{ labels[request.status] }}- </span>- <div :class="ui.actions()">- <template v-if="request.status === 'pending'">- <AppButton- size="sm"- variant="ghost"- :disabled="busy === request.id"- @click="ask('reject', request)"- >- {{ messages.decline }}- </AppButton>- <AppButton- size="sm"- color="primary"- variant="solid"- :loading="busy === request.id"- @click="emit('approve', request.id)"- >- {{ messages.approve }}- </AppButton>- </template>- <AppButton- v-else-if="request.status === 'approved'"- size="sm"- variant="ghost"- :loading="busy === request.id"- @click="ask('revoke', request)"- >- {{ messages.removeAccess }}- </AppButton>- </div>- </li>- </ul>- <AppPlaceholder- v-else- size="page"- :label="filter === 'pending' ? messages.noOneWaiting : messages.nothingHere"- :description="messages.requestsEmptyDescription"- :ui="{ root: 'rounded-lg border border-dashed border-border' }"- >- <template #icon><icon-lucide-inbox class="size-5" /></template>- </AppPlaceholder>- <AppConfirmationDialog- :open="confirming !== null"- tone="danger"- :heading="confirmation?.heading ?? ''"- :description="confirmation?.description"- :cancel-label="messages.cancel"- :confirm-label="confirmation?.confirm ?? ''"- @update:open="(open) => !open && (confirming = null)"- @confirm="confirm"- >- <div :class="[form.field(), 'mt-3']">- <label for="portal-review-note" :class="form.label()">{{ messages.reviewNote }}</label>- <AppTextarea id="portal-review-note" v-model="note" :rows="2" maxlength="1000" />- </div>- </AppConfirmationDialog>- </div>+ </AppConfirmationDialog></template>diff --git a/src/components/cloud-portal/console/PortalActivity.vue b/src/components/cloud-portal/console/PortalActivity.vueindex 0824eacf4..a48bb66ce 100644--- a/src/components/cloud-portal/console/PortalActivity.vue+++ b/src/components/cloud-portal/console/PortalActivity.vue@@ -1,16 +1,29 @@<script setup lang="ts">-import { computed } from 'vue'+import { createColumnHelper } from '@tanstack/vue-table'+import { computed, h } from 'vue'+import type { CloudAdminAuditFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'-import AccountAvatar from '@/components/presence/AccountAvatar.vue'-import { portalList } from '@/theme/cloud-portal/list'+import {+ usePortalList,+ type PortalListPage,+ type PortalListRequest,+ type PortalTableFeatures+} from '@/app/cloud-portal/list'+import PortalIdentityCell from '../table/PortalIdentityCell.vue'+import PortalTable from '../table/PortalTable.vue'+import PortalTextCell from '../table/PortalTextCell.vue'import type { PortalActivityEntry } from '../types'/** What administrators did on the server, newest first. */-const { entries } = defineProps<{ entries: PortalActivityEntry[] }>()-const ui = portalList()+const { load } = defineProps<{+ load: (+ request: PortalListRequest<CloudAdminAuditFilter>+ ) => Promise<PortalListPage<CloudAdminAuditFilter, PortalActivityEntry>>+}>()+const messages = useCloudPortalMessages()const actions = computed<Record<string, string>>(() => ({'enrollment.approved': messages.value.activityApproved,@@ -25,23 +38,58 @@ const actions = computed<Record<string, string>>(() => ({'user.two-step-reset': messages.value.activityTwoStepReset,'user.picture-removed': messages.value.activityPictureRemoved}))++const column = createColumnHelper<PortalTableFeatures, PortalActivityEntry>()+const activity = usePortalList<CloudAdminAuditFilter, PortalActivityEntry>({+ filter: 'all',+ load: (request) => load(request),+ rowId: (entry) => entry.id,+ columns: column.columns([+ column.display({+ id: 'administrator',+ header: () => messages.value.columnAdministrator,+ meta: { class: 'w-1/4' },+ cell: ({ row: { original: entry } }) =>+ h(PortalIdentityCell, { id: entry.actor.id, name: entry.actor.name, size: 'sm' })+ }),+ column.display({+ id: 'action',+ header: () => messages.value.columnAction,+ // What it was about has its own column once the table is wide enough.+ cell: ({ row: { original: entry } }) =>+ h(PortalTextCell, {+ text: actions.value[entry.action] ?? messages.value.activityChanged,+ narrowDetail: entry.target,+ detail: entry.reason ? messages.value.activityReason({ reason: entry.reason }) : null+ })+ }),+ column.accessor('target', {+ header: () => messages.value.columnSubject,+ meta: { class: 'hidden w-1/4 @xl/table:table-cell' }+ }),+ column.accessor('when', {+ header: () => messages.value.columnWhen,+ meta: { class: 'hidden w-44 whitespace-nowrap text-muted @2xl/table:table-cell' }+ })+ ])+})+const filters = computed(() => [+ { value: 'all' as const, label: messages.value.filterAll },+ { value: 'accounts' as const, label: messages.value.filterAccounts },+ { value: 'requests' as const, label: messages.value.filterRequests },+ { value: 'email' as const, label: messages.value.filterEmail }+])</script><template>- <ul :class="ui.list()">- <li v-for="entry in entries" :key="entry.id" :class="ui.row()">- <AccountAvatar :id="entry.actor.id" :name="entry.actor.name" />- <div :class="ui.body()">- <p class="text-xs text-muted">- <span class="font-medium text-surface">{{ entry.actor.name }}</span>- {{ actions[entry.action] ?? messages.activityChanged }}- <span class="text-surface">{{ entry.target }}</span>- </p>- <p v-if="entry.reason" :class="ui.detail()">- {{ messages.activityReason({ reason: entry.reason }) }}- </p>- </div>- <span :class="ui.meta()">{{ entry.when }}</span>- </li>- </ul>+ <PortalTable+ :list="activity"+ :label="messages.activity"+ :search-label="messages.searchActivity"+ :filters="filters"+ :empty-label="messages.noActivityFound"+ :empty-description="messages.noActivityFoundDescription"+ >+ <template #icon><icon-lucide-history class="size-5" /></template>+ </PortalTable></template>diff --git a/src/components/cloud-portal/console/PortalEmailDelivery.vue b/src/components/cloud-portal/console/PortalEmailDelivery.vueindex 89997b5f5..ac5dc8bd5 100644--- a/src/components/cloud-portal/console/PortalEmailDelivery.vue+++ b/src/components/cloud-portal/console/PortalEmailDelivery.vue@@ -1,18 +1,33 @@<script setup lang="ts">-import { computed } from 'vue'+import { createColumnHelper } from '@tanstack/vue-table'+import { computed, h } from 'vue'+import type { CloudAdminEmailFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'+import {+ usePortalList,+ type PortalListPage,+ type PortalListRequest,+ type PortalTableFeatures+} from '@/app/cloud-portal/list'import AppButton from '@/components/ui/button/AppButton.vue'-import { portalList } from '@/theme/cloud-portal/list'+import PortalStatusCell from '../table/PortalStatusCell.vue'+import PortalTable from '../table/PortalTable.vue'+import PortalTextCell from '../table/PortalTextCell.vue'import type { PortalEmail } from '../types'/** Email the server sends, such as invitations and sign-in links, and whether it went out. */-const { emails, busy = null } = defineProps<{ emails: PortalEmail[]; busy?: string | null }>()+const { load, busy = null } = defineProps<{+ load: (+ request: PortalListRequest<CloudAdminEmailFilter>+ ) => Promise<PortalListPage<CloudAdminEmailFilter, PortalEmail>>+ /** The message being sent again. */+ busy?: string | null+}>()const emit = defineEmits<{ retry: [id: string] }>()-const ui = portalList()const messages = useCloudPortalMessages()const tones = {sent: 'success',@@ -41,36 +56,86 @@ const kindLabels = computed<Record<string, string>>(() => ({'new-sign-in': messages.value.emailKindNewSignIn,'two-step-changed': messages.value.emailKindTwoStepChanged}))-function detail(email: PortalEmail) {- const to = messages.value.emailTo({ recipient: email.recipient })- if (email.error) return `${to} · ${email.error}`- return email.attempts > 1 ? `${to} · ${messages.value.attempts(email.attempts)}` : to+/** What went wrong, or how many tries it took. */+function delivery(email: PortalEmail) {+ if (email.error) return email.error+ return email.attempts > 1 ? messages.value.attempts(email.attempts) : null}++const column = createColumnHelper<PortalTableFeatures, PortalEmail>()+const emails = usePortalList<CloudAdminEmailFilter, PortalEmail>({+ filter: 'all',+ load: (request) => load(request),+ rowId: (email) => email.id,+ columns: column.columns([+ column.display({+ id: 'message',+ header: () => messages.value.columnMessage,+ // The recipient has its own column once the table is wide enough.+ cell: ({ row: { original: email } }) =>+ h(PortalTextCell, {+ text: kindLabels.value[email.kind] ?? messages.value.emailKindOther,+ strong: true,+ narrowDetail: email.recipient+ })+ }),+ column.accessor('recipient', {+ header: () => messages.value.columnRecipient,+ meta: { class: 'hidden text-muted @xl/table:table-cell' }+ }),+ column.display({+ id: 'status',+ header: () => messages.value.columnStatus,+ meta: { class: 'w-32' },+ cell: ({ row: { original: email } }) =>+ h(PortalStatusCell, {+ statuses: [{ label: statusLabels.value[email.status], tone: tones[email.status] }],+ detail: delivery(email)+ })+ }),+ column.accessor('when', {+ header: () => messages.value.columnWhen,+ meta: { class: 'hidden w-44 whitespace-nowrap text-muted @2xl/table:table-cell' }+ }),+ column.display({+ id: 'actions',+ header: () => messages.value.columnActions,+ meta: { class: 'w-px text-right', actions: true },+ cell: ({ row: { original: email } }) =>+ email.status === 'failed'+ ? h(+ AppButton,+ {+ size: 'sm',+ variant: 'outline',+ loading: busy === email.id,+ onClick: () => emit('retry', email.id)+ },+ () => messages.value.retry+ )+ : null+ })+ ])+})+const filters = computed(() => [+ { value: 'all' as const, label: messages.value.filterAll },+ { value: 'sent' as const, label: messages.value.emailSent },+ { value: 'waiting' as const, label: messages.value.emailWaiting },+ { value: 'failed' as const, label: messages.value.emailFailed }+])++defineExpose({ reload: emails.reload })</script><template>- <ul :class="ui.list()">- <li v-for="email in emails" :key="email.id" :class="ui.row()">- <icon-lucide-mail class="size-4 shrink-0 text-muted" />- <div :class="ui.body()">- <p :class="ui.title()">{{ kindLabels[email.kind] ?? messages.emailKindOther }}</p>- <p :class="ui.detail()">{{ detail(email) }}</p>- </div>- <span :class="ui.status()" :data-tone="tones[email.status]">- {{ statusLabels[email.status] }}- </span>- <span :class="ui.meta()">{{ email.when }}</span>- <div :class="[ui.actions(), 'w-16 justify-end']">- <AppButton- v-if="email.status === 'failed'"- size="sm"- variant="outline"- :loading="busy === email.id"- @click="emit('retry', email.id)"- >- {{ messages.retry }}- </AppButton>- </div>- </li>- </ul>+ <PortalTable+ :list="emails"+ :label="messages.emailDelivery"+ :search-label="messages.searchEmail"+ :filters="filters"+ :empty-label="messages.noEmailFound"+ :empty-description="messages.noEmailFoundDescription"+ >+ <template #icon><icon-lucide-mail class="size-5" /></template>+ </PortalTable></template>diff --git a/src/components/cloud-portal/console/PortalPeople.vue b/src/components/cloud-portal/console/PortalPeople.vueindex ca821a485..47007b8a4 100644--- a/src/components/cloud-portal/console/PortalPeople.vue+++ b/src/components/cloud-portal/console/PortalPeople.vue@@ -1,16 +1,21 @@<script setup lang="ts">-import { computed } from 'vue'+import { createColumnHelper } from '@tanstack/vue-table'+import { compact } from 'es-toolkit'+import { computed, h } from 'vue'import type { CloudAdminUserFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'-import AccountAvatar from '@/components/presence/AccountAvatar.vue'-import IconButton from '@/components/ui/button/IconButton.vue'-import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'-import AppInput from '@/components/ui/input/AppInput.vue'-import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'-import { portalList } from '@/theme/cloud-portal/list'+import {+ usePortalList,+ type PortalListPage,+ type PortalListRequest,+ type PortalTableFeatures+} from '@/app/cloud-portal/list'+import PortalIdentityCell from '../table/PortalIdentityCell.vue'+import PortalStatusCell from '../table/PortalStatusCell.vue'+import PortalTable from '../table/PortalTable.vue'import type { PortalPerson, PortalPersonAction } from '../types'import PortalPersonActions from './PortalPersonActions.vue'@@ -18,154 +23,109 @@ import PortalPersonActions from './PortalPersonActions.vue'* Everyone with an account on the server, a page at a time: filtered by what they are, searched* by name or email, each with what an administrator can do about them.*/-const {- people,- counts,- offset = 0,- pageSize = 50,- busy = false-} = defineProps<{- people: PortalPerson[]- /** How many accounts match the search under each filter. */- counts: Record<CloudAdminUserFilter, number>- offset?: number- pageSize?: number+const { load, busy = false } = defineProps<{+ load: (+ request: PortalListRequest<CloudAdminUserFilter>+ ) => Promise<PortalListPage<CloudAdminUserFilter, PortalPerson>>busy?: boolean}>()-const query = defineModel<string>('query', { default: '' })-const filter = defineModel<CloudAdminUserFilter>('filter', { default: 'all' })const emit = defineEmits<{act: [person: PortalPerson, action: PortalPersonAction, reason?: string]open: [personId: string]- page: [offset: number]}>()-const ui = portalList()const messages = useCloudPortalMessages()-const total = computed(() => counts[filter.value])++/** What an account is on the server, as badges; an ordinary account has none. */+function standing(person: PortalPerson) {+ const words = messages.value+ return compact([+ person.admin && { label: words.administrator, tone: 'neutral' as const },+ person.suspended && { label: words.suspended, tone: 'error' as const },+ !person.suspended &&+ person.admin &&+ !person.twoStep && { label: words.twoStepOff, tone: 'warning' as const }+ ])+}++const column = createColumnHelper<PortalTableFeatures, PortalPerson>()+const people = usePortalList<CloudAdminUserFilter, PortalPerson>({+ filter: 'all',+ load: (request) => load(request),+ rowId: (person) => person.id,+ columns: column.columns([+ column.display({+ id: 'person',+ header: () => messages.value.columnPerson,+ cell: ({ row: { original: person } }) =>+ h(PortalIdentityCell, {+ id: person.id,+ name: person.name,+ detail: person.email,+ image: person.image,+ you: person.you,+ link: true,+ onOpen: () => emit('open', person.id)+ })+ }),+ column.display({+ id: 'role',+ header: () => messages.value.columnRole,+ meta: { class: 'hidden max-w-56 @md/table:table-cell' },+ // The badge says the account is suspended; the line under it says why.+ cell: ({ row: { original: person } }) =>+ h(PortalStatusCell, {+ statuses: standing(person),+ fallback: messages.value.member,+ detail: person.suspendedReason+ })+ }),+ column.accessor('workspaceCount', {+ header: () => messages.value.columnWorkspaces,+ meta: { class: 'hidden w-24 text-right tabular-nums @2xl/table:table-cell' }+ }),+ column.accessor((person) => person.lastActive ?? messages.value.notSignedIn, {+ id: 'lastActive',+ header: () => messages.value.columnLastActive,+ meta: { class: 'hidden w-32 whitespace-nowrap text-muted @xl/table:table-cell' }+ }),+ column.accessor('joinedOn', {+ header: () => messages.value.columnJoined,+ meta: { class: 'hidden w-28 whitespace-nowrap text-muted @3xl/table:table-cell' }+ }),+ column.display({+ id: 'actions',+ header: () => messages.value.columnActions,+ meta: { class: 'w-px text-right', actions: true },+ cell: ({ row: { original: person } }) =>+ h(PortalPersonActions, {+ person,+ disabled: busy,+ onAct: (action: PortalPersonAction, reason?: string) =>+ emit('act', person, action, reason)+ })+ })+ ])+})const filters = computed(() => [- { value: 'all', label: messages.value.filterEveryone },- { value: 'administrators', label: messages.value.filterAdministrators },- { value: 'suspended', label: messages.value.filterSuspended },- { value: 'without-two-step', label: messages.value.filterWithoutTwoStep }+ { value: 'all' as const, label: messages.value.filterEveryone },+ { value: 'administrators' as const, label: messages.value.filterAdministrators },+ { value: 'suspended' as const, label: messages.value.filterSuspended },+ { value: 'without-two-step' as const, label: messages.value.filterWithoutTwoStep }])-const isFilter = (value: string): value is CloudAdminUserFilter =>- filters.value.some((option) => option.value === value)-const filterValue = computed({- get: () => filter.value,- set: (value: string) => {- if (isFilter(value)) filter.value = value- }-})-const range = computed(() =>- messages.value.pageRange({- from: Math.min(offset + 1, total.value),- to: Math.min(offset + people.length, total.value),- total: total.value- })-)++defineExpose({ reload: people.reload })</script><template>- <div class="flex flex-col gap-3">- <div :class="ui.toolbar()">- <AppInput- v-model="query"- type="search"- density="compact"- :placeholder="messages.searchPeople"- :aria-label="messages.searchPeople"- class="w-64"- >- <template #leading><icon-lucide-search class="size-3.5" /></template>- </AppInput>- <SegmentedControl v-model="filterValue" required :label="messages.people" :options="filters">- <template #option="{ option }">- {{ option.label }}- <span class="text-muted tabular-nums">- {{ isFilter(option.value) ? counts[option.value] : '' }}- </span>- </template>- </SegmentedControl>- </div>- <ul v-if="people.length" :class="ui.list()">- <li v-for="person in people" :key="person.id" :class="ui.row()">- <AccountAvatar :id="person.id" :name="person.name" :image="person.image" size="md" />- <button- type="button"- :class="[- ui.body(),- 'rounded text-left focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:outline-none'- ]"- @click="emit('open', person.id)"- >- <span :class="ui.title()">- <span class="truncate">{{ person.name }}</span>- <span v-if="person.you" class="shrink-0 font-normal text-muted">{{- messages.you- }}</span>- </span>- <span :class="[ui.detail(), 'block']">- {{ person.email }}- <template v-if="person.suspendedReason">- · {{ messages.suspendedReason({ reason: person.suspendedReason }) }}- </template>- </span>- </button>- <span v-if="person.admin" :class="ui.status()" data-tone="neutral">- {{ messages.administrator }}- </span>- <span v-if="person.suspended" :class="ui.status()" data-tone="error">- {{ messages.suspended }}- </span>- <span v-else-if="person.admin && !person.twoStep" :class="ui.status()" data-tone="warning">- {{ messages.twoStepOff }}- </span>- <span :class="[ui.meta(), 'w-24 text-right']">- {{ messages.workspaceCount(person.workspaceCount) }}- </span>- <span :class="[ui.meta(), 'w-28 text-right']">- {{- person.lastActive- ? messages.lastActive({ when: person.lastActive })- : messages.notSignedIn- }}- </span>- <span :class="[ui.meta(), 'w-32 text-right']">- {{ messages.joined({ date: person.joinedOn }) }}- </span>- <PortalPersonActions- :person="person"- :disabled="busy"- @act="(action, reason) => emit('act', person, action, reason)"- />- </li>- </ul>- <AppPlaceholder- v-else- size="compact"- :fill="false"- :label="messages.noPeopleFound"- :description="messages.noPeopleFoundDescription"- >- <template #icon><icon-lucide-users class="size-5" /></template>- </AppPlaceholder>- <div v-if="total > pageSize" class="flex items-center justify-end gap-1 text-[11px] text-muted">- <span class="tabular-nums">{{ range }}</span>- <IconButton- :label="messages.previousPage"- :disabled="offset === 0"- @click="emit('page', Math.max(0, offset - pageSize))"- >- <icon-lucide-chevron-left class="size-3.5" />- </IconButton>- <IconButton- :label="messages.nextPage"- :disabled="offset + people.length >= total"- @click="emit('page', offset + pageSize)"- >- <icon-lucide-chevron-right class="size-3.5" />- </IconButton>- </div>- </div>+ <PortalTable+ :list="people"+ :label="messages.people"+ :search-label="messages.searchPeople"+ :filters="filters"+ :empty-label="messages.noPeopleFound"+ :empty-description="messages.noPeopleFoundDescription"+ >+ <template #icon><icon-lucide-users class="size-5" /></template>+ </PortalTable></template>diff --git a/src/components/cloud-portal/console/PortalPerson.vue b/src/components/cloud-portal/console/PortalPerson.vueindex 33be72e01..5e608bce4 100644--- a/src/components/cloud-portal/console/PortalPerson.vue+++ b/src/components/cloud-portal/console/PortalPerson.vue@@ -1,18 +1,24 @@<script setup lang="ts">+import { createColumnHelper } from '@tanstack/vue-table'import { compact } from 'es-toolkit'-import { computed } from 'vue'+import { computed, h } from 'vue'+import IconLayers from '~icons/lucide/layers'import type { WorkspaceRole } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'+import { usePortalRows, type PortalTableFeatures } from '@/app/cloud-portal/list'import AccountAvatar from '@/components/presence/AccountAvatar.vue'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'-import { portalList } from '@/theme/cloud-portal/list'+import AppDataTable from '@/components/ui/table/AppDataTable.vue'+import { portalTable } from '@/theme/cloud-portal/table'import PortalSessions from '../account/PortalSessions.vue'+import PortalStatusCell from '../table/PortalStatusCell.vue'+import PortalTextCell from '../table/PortalTextCell.vue'import type { PortalPersonAction, PortalPersonDetail } from '../types'import PortalPersonActions from './PortalPersonActions.vue'@@ -23,7 +29,7 @@ import PortalPersonActions from './PortalPersonActions.vue'const { detail, busy = false } = defineProps<{ detail: PortalPersonDetail; busy?: boolean }>()const emit = defineEmits<{ act: [action: PortalPersonAction, reason?: string]; back: [] }>()-const ui = portalList()+const ui = portalTable()const messages = useCloudPortalMessages()const person = computed(() => detail.person)@@ -52,6 +58,30 @@ const roleLabel = (role: WorkspaceRole) =>editor: messages.value.workspaceRoleEditor,viewer: messages.value.workspaceRoleViewer})[role]++const column = createColumnHelper<PortalTableFeatures, PortalPersonDetail['workspaces'][number]>()+const workspaces = usePortalRows(() => detail.workspaces, {+ rowId: (workspace) => workspace.id,+ columns: column.columns([+ column.display({+ id: 'workspace',+ header: () => messages.value.columnWorkspace,+ cell: ({ row: { original: workspace } }) =>+ h(PortalTextCell, { icon: IconLayers, text: workspace.name, strong: true })+ }),+ column.display({+ id: 'role',+ header: () => messages.value.columnRole,+ meta: { class: 'w-32' },+ cell: ({ row: { original: workspace } }) =>+ h(PortalStatusCell, { statuses: [{ label: roleLabel(workspace.role), tone: 'neutral' }] })+ }),+ column.accessor('memberCount', {+ header: () => messages.value.columnMembers,+ meta: { class: 'w-24 text-right tabular-nums' }+ })+ ])+})</script><template>@@ -114,19 +144,11 @@ const roleLabel = (role: WorkspaceRole) =><SettingsSection><template #title>{{ messages.personWorkspaces }}</template>- <ul v-if="detail.workspaces.length" :class="ui.list()">- <li v-for="workspace in detail.workspaces" :key="workspace.id" :class="ui.row()">- <icon-lucide-layers class="size-4 shrink-0 text-muted" />- <div :class="ui.body()">- <p :class="ui.title()">{{ workspace.name }}</p>- <p :class="ui.detail()">{{ messages.workspaceMembers(workspace.memberCount) }}</p>- </div>- <span :class="ui.status()" data-tone="neutral">{{ roleLabel(workspace.role) }}</span>- </li>- </ul>- <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">- {{ messages.personWorkspacesEmpty }}- </p>+ <AppDataTable :table="workspaces" :label="messages.personWorkspaces">+ <template #empty>+ <p class="text-center text-xs text-muted">{{ messages.personWorkspacesEmpty }}</p>+ </template>+ </AppDataTable></SettingsSection><PortalSessions :sessions="detail.sessions" :sign-ins="detail.signIns" />diff --git a/src/components/cloud-portal/console/PortalPersonActions.vue b/src/components/cloud-portal/console/PortalPersonActions.vueindex 252cafa62..97817357a 100644--- a/src/components/cloud-portal/console/PortalPersonActions.vue+++ b/src/components/cloud-portal/console/PortalPersonActions.vue@@ -1,24 +1,15 @@<script setup lang="ts">-import {- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuPortal,- DropdownMenuRoot,- DropdownMenuSeparator,- DropdownMenuTrigger-} from 'reka-ui'+import { compact } from 'es-toolkit'import { computed, ref } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'-import AppButton from '@/components/ui/button/AppButton.vue'-import IconButton from '@/components/ui/button/IconButton.vue'import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'import AppTextarea from '@/components/ui/input/AppTextarea.vue'-import { menu } from '@/components/ui/menu/menu'import { useHeldContent } from '@/components/ui/overlay/held'import { portalForm } from '@/theme/cloud-portal/form'+import PortalRowMenu from '../table/PortalRowMenu.vue'import type { PortalPerson, PortalPersonAction } from '../types'/**@@ -38,7 +29,6 @@ const {const emit = defineEmits<{ act: [action: PortalPersonAction, reason?: string] }>()const messages = useCloudPortalMessages()-const menuUI = menu()const form = portalForm()const confirming = ref<PortalPersonAction | null>(null)const reason = ref('')@@ -99,6 +89,21 @@ const confirmation = computed(() => {return copy[action]})+const items = computed(() => {+ const words = messages.value+ return compact([+ person.admin+ ? { action: 'remove-admin' as const, label: words.removeAdministrator }+ : { action: 'make-admin' as const, label: words.makeAdministrator },+ { action: 'sign-out' as const, label: words.signOutEverywhere },+ person.twoStep && { action: 'reset-two-step' as const, label: words.resetTwoStep },+ person.image && { action: 'remove-picture' as const, label: words.removePersonPicture },+ person.suspended+ ? { action: 'restore' as const, label: words.restoreAccount, separated: true }+ : { action: 'suspend' as const, label: words.suspendAccount, separated: true }+ ])+})+function ask(action: PortalPersonAction) {reason.value = ''confirming.value = action@@ -114,65 +119,13 @@ function confirm() {</script><template>- <DropdownMenuRoot :modal="false">- <DropdownMenuTrigger as-child>- <IconButton- v-if="look === 'icon'"- :label="messages.actionsFor({ name: person.name })"- :disabled="disabled || person.you"- >- <icon-lucide-ellipsis class="size-3.5" />- </IconButton>- <AppButton- v-else- size="sm"- variant="outline"- :aria-label="messages.actionsFor({ name: person.name })"- :disabled="disabled || person.you"- >- <icon-lucide-ellipsis class="size-3.5" />- </AppButton>- </DropdownMenuTrigger>- <DropdownMenuPortal>- <DropdownMenuContent- side="bottom"- align="end"- :side-offset="4"- :class="[menuUI.content(), 'w-56']"- >- <DropdownMenuItem- :class="menuUI.item({ justify: 'start' })"- @select="ask(person.admin ? 'remove-admin' : 'make-admin')"- >- {{ person.admin ? messages.removeAdministrator : messages.makeAdministrator }}- </DropdownMenuItem>- <DropdownMenuItem :class="menuUI.item({ justify: 'start' })" @select="ask('sign-out')">- {{ messages.signOutEverywhere }}- </DropdownMenuItem>- <DropdownMenuItem- v-if="person.twoStep"- :class="menuUI.item({ justify: 'start' })"- @select="ask('reset-two-step')"- >- {{ messages.resetTwoStep }}- </DropdownMenuItem>- <DropdownMenuItem- v-if="person.image"- :class="menuUI.item({ justify: 'start' })"- @select="ask('remove-picture')"- >- {{ messages.removePersonPicture }}- </DropdownMenuItem>- <DropdownMenuSeparator :class="menuUI.separator()" />- <DropdownMenuItem- :class="menuUI.item({ justify: 'start' })"- @select="ask(person.suspended ? 'restore' : 'suspend')"- >- {{ person.suspended ? messages.restoreAccount : messages.suspendAccount }}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenuRoot>+ <PortalRowMenu+ :label="messages.actionsFor({ name: person.name })"+ :items="items"+ :look="look"+ :disabled="disabled || person.you"+ @select="ask"+ /><AppConfirmationDialog:open="confirming !== null":tone="confirmation?.tone"diff --git a/src/components/cloud-portal/layout/PortalConsoleLayout.vue b/src/components/cloud-portal/layout/PortalConsoleLayout.vueindex cbec963bf..f3e9f18a7 100644--- a/src/components/cloud-portal/layout/PortalConsoleLayout.vue+++ b/src/components/cloud-portal/layout/PortalConsoleLayout.vue@@ -1,11 +1,15 @@<script setup lang="ts">import { uniq } from 'es-toolkit'+import { useTemplateRef, watch } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import BrandMark from '@/components/brand/BrandMark.vue'import AccountAvatar from '@/components/presence/AccountAvatar.vue'import IconButton from '@/components/ui/button/IconButton.vue'+import AppSkeleton from '@/components/ui/feedback/AppSkeleton.vue'+import { skeleton } from '@/components/ui/feedback/skeleton'+import { useScrollOverflow } from '@/components/ui/list/useScrollOverflow'import { useAppButtonUI } from '@/theme/button/button'import { portalLayout } from '@/theme/cloud-portal/layout'import { sideList } from '@/theme/list/side-list'@@ -22,7 +26,8 @@ const { host, account, sections, active, heading, description } = defineProps<{sections: PortalSection[]active: stringheading: string- description?: string+ /** Null while it is still being counted, which keeps its line with a placeholder. */+ description?: string | null}>()const emit = defineEmits<{ select: [id: string]; signOut: [] }>()@@ -31,6 +36,21 @@ const messages = useCloudPortalMessages()const side = sideList()const groups = () => uniq(sections.map((section) => section.group))const editorLink = useAppButtonUI({ variant: 'outline', size: 'sm' })+const placeholders = skeleton()+const nav = useTemplateRef<HTMLElement>('nav')+const { overflowing, overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(nav)++// On a narrow page the sections are one row; keep the current one in view, as the editor's tab+// bar keeps its active tab, also once the row starts overflowing.+watch(+ [() => active, overflowing],+ () => {+ nav.value+ ?.querySelector('[aria-current="page"]')+ ?.scrollIntoView({ block: 'nearest', inline: 'nearest' })+ },+ { flush: 'post' }+)</script><template>@@ -51,33 +71,60 @@ const editorLink = useAppButtonUI({ variant: 'outline', size: 'sm' })</div></header><div :class="ui.console()">- <nav :class="side.root({ class: ui.nav() })" :aria-label="messages.productName">- <div v-for="group in groups()" :key="group" :class="side.group({ class: ui.navGroup() })">- <div :class="side.header({ class: ui.navHeader() })">- <span :class="side.title()">{{ group }}</span>- </div>- <div :class="side.items({ class: ui.navItems() })">- <button- v-for="section in sections.filter((candidate) => candidate.group === group)"- :key="section.id"- type="button"- :class="side.item({ class: ui.navItem() })"- :data-active="section.id === active"- :aria-current="section.id === active ? 'page' : undefined"- @click="emit('select', section.id)"- >- <component :is="section.icon" :class="side.icon()" />- <span :class="side.label()">{{ section.label }}</span>- <span v-if="section.count" :class="side.trailing()">{{ section.count }}</span>- </button>+ <div :class="ui.navFrame()">+ <nav+ ref="nav"+ :class="side.root({ class: ui.nav() })"+ :aria-label="messages.productName"+ :data-overflow-start="overflowStart || undefined"+ :data-overflow-end="overflowEnd || undefined"+ >+ <div v-for="group in groups()" :key="group" :class="side.group({ class: ui.navGroup() })">+ <div :class="side.header({ class: ui.navHeader() })">+ <span :class="side.title()">{{ group }}</span>+ </div>+ <div :class="side.items({ class: ui.navItems() })">+ <button+ v-for="section in sections.filter((candidate) => candidate.group === group)"+ :key="section.id"+ type="button"+ :class="side.item({ class: ui.navItem() })"+ :data-active="section.id === active"+ :aria-current="section.id === active ? 'page' : undefined"+ @click="emit('select', section.id)"+ >+ <component :is="section.icon" :class="side.icon()" />+ <span :class="side.label()">{{ section.label }}</span>+ <span v-if="section.count" :class="side.trailing()">{{ section.count }}</span>+ </button>+ </div></div>- </div>- </nav>+ </nav>+ <!-- Pointer affordance only: Tab already reaches every section and scrolls it into view. -->+ <button+ v-if="overflowStart || overflowEnd"+ type="button"+ tabindex="-1"+ aria-hidden="true"+ :class="ui.navScroll()"+ :data-start="!overflowEnd || undefined"+ @click="scrollTowardHidden"+ >+ <icon-lucide-chevron-right v-if="overflowEnd" class="size-3.5" />+ <icon-lucide-chevron-left v-else class="size-3.5" />+ </button>+ </div><main :class="ui.main()"><div :class="ui.mainInner()"><header><h1 :class="ui.pageTitle()">{{ heading }}</h1><p v-if="description" :class="ui.pageDescription()">{{ description }}</p>+ <p+ v-else-if="description === null"+ :class="[ui.pageDescription(), placeholders.group()]"+ >+ <AppSkeleton class="inline-block w-40 align-middle" />+ </p></header><slot /></div>diff --git a/src/components/cloud-portal/layout/PortalLoadAlert.vue b/src/components/cloud-portal/layout/PortalLoadAlert.vuenew file mode 100644index 000000000..cbafd54a5--- /dev/null+++ b/src/components/cloud-portal/layout/PortalLoadAlert.vue@@ -0,0 +1,21 @@+<script setup lang="ts">+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++/** Says a page could not read what it shows, with a way to read it again. */+const { error } = defineProps<{ error: string }>()+const emit = defineEmits<{ retry: [] }>()+const messages = useCloudPortalMessages()+</script>++<template>+ <AppAlert tone="error" :heading="messages.errorTitle" :description="error">+ <template #actions>+ <AppButton size="sm" variant="outline" @click="emit('retry')">+ {{ messages.tryAgain }}+ </AppButton>+ </template>+ </AppAlert>+</template>diff --git a/src/components/cloud-portal/layout/PortalPageSkeleton.vue b/src/components/cloud-portal/layout/PortalPageSkeleton.vuenew file mode 100644index 000000000..4a062c56c--- /dev/null+++ b/src/components/cloud-portal/layout/PortalPageSkeleton.vue@@ -0,0 +1,45 @@+<script setup lang="ts">+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import AppSkeleton from '@/components/ui/feedback/AppSkeleton.vue'+import { skeleton } from '@/components/ui/feedback/skeleton'++/**+ * A settings page before it loads, in its own shape: the person it is about when `avatar` is on,+ * then one group per entry of `groups` with that many rows, so the page fills in without moving.+ */+const { avatar = false, groups } = defineProps<{ avatar?: boolean; groups: readonly number[] }>()+const placeholders = skeleton()+const messages = useCloudPortalMessages()+</script>++<template>+ <!-- The bars are for the eye; the status says it to assistive technology. -->+ <span role="status" class="sr-only">{{ messages.loading }}</span>+ <div :class="[placeholders.group(), 'flex max-w-2xl flex-col gap-6']" aria-hidden="true">+ <div v-if="avatar" class="flex items-center gap-3">+ <AppSkeleton class="size-12 rounded-full" />+ <div class="flex flex-col gap-2">+ <AppSkeleton class="h-3 w-32" />+ <AppSkeleton class="w-44" />+ </div>+ </div>+ <div v-for="(rows, group) in groups" :key="group" class="flex flex-col gap-3">+ <AppSkeleton class="w-24" />+ <SettingsGroup>+ <div+ v-for="row in rows"+ :key="row"+ class="flex items-center justify-between gap-4 px-3 py-3"+ >+ <div class="flex flex-col gap-2">+ <AppSkeleton class="w-20" />+ <AppSkeleton class="w-40" />+ </div>+ <AppSkeleton class="h-7 w-24 rounded-md" />+ </div>+ </SettingsGroup>+ </div>+ </div>+</template>diff --git a/src/components/cloud-portal/sections/AdminActivitySection.vue b/src/components/cloud-portal/sections/AdminActivitySection.vueindex e28860d29..af951eb13 100644--- a/src/components/cloud-portal/sections/AdminActivitySection.vue+++ b/src/components/cloud-portal/sections/AdminActivitySection.vue@@ -1,15 +1,14 @@<script setup lang="ts">import * as v from 'valibot'+import type { CloudAdminAuditFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages, useI18n } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'-import { usePortalLoad } from '@/app/cloud-portal/state'+import type { PortalListRequest } from '@/app/cloud-portal/list'import { formatDate } from '@/app/i18n/date'-import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalActivity from '../console/PortalActivity.vue'-import type { PortalActivityEntry } from '../types'/** The reason an administrator gave, which the server keeps in the event's metadata. */const reasonSchema = v.object({ reason: v.string() })@@ -22,9 +21,9 @@ const portal = usePortal()const messages = useCloudPortalMessages()const { locale } = useI18n()-const { data: entries, error } = usePortalLoad(async (): Promise<PortalActivityEntry[]> => {- const { events } = await portal.api.audit()- return events.map((event) => ({+async function load(request: PortalListRequest<CloudAdminAuditFilter>) {+ const { events, total, counts } = await portal.api.audit(request)+ const rows = events.map((event) => ({id: event.id,actor: { id: event.actor.id, name: event.actor.name ?? messages.value.someoneElse },action: event.action,@@ -32,10 +31,10 @@ const { data: entries, error } = usePortalLoad(async (): Promise<PortalActivityEreason: eventReason(event.metadata),when: formatDate(event.createdAt, 'dateTime', locale.value)}))-}, [])+ return { rows, total, counts }+}</script><template>- <AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />- <PortalActivity v-else :entries="entries" />+ <PortalActivity :load="load" /></template>diff --git a/src/components/cloud-portal/sections/AdminEmailSection.vue b/src/components/cloud-portal/sections/AdminEmailSection.vueindex 4dc67a4c2..18980884b 100644--- a/src/components/cloud-portal/sections/AdminEmailSection.vue+++ b/src/components/cloud-portal/sections/AdminEmailSection.vue@@ -1,10 +1,12 @@<script setup lang="ts">-import { computed } from 'vue'+import { useTemplateRef } from 'vue'+import type { CloudAdminEmailFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages, useI18n } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'-import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import type { PortalListRequest } from '@/app/cloud-portal/list'+import { usePortalAction } from '@/app/cloud-portal/state'import { formatDate } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'@@ -14,6 +16,7 @@ import type { PortalEmail } from '../types'const portal = usePortal()const messages = useCloudPortalMessages()const { locale } = useI18n()+const emails = useTemplateRef('emails')function deliveryStatus(status: string): PortalEmail['status'] {if (status === 'accepted') return 'sent'@@ -22,13 +25,9 @@ function deliveryStatus(status: string): PortalEmail['status'] {return 'waiting'}-const {- data: emails,- error: loadError,- reload-} = usePortalLoad(async (): Promise<PortalEmail[]> => {- const { messages: rows } = await portal.api.email()- return rows.map((row) => ({+async function load(request: PortalListRequest<CloudAdminEmailFilter>) {+ const { messages: sent, total, counts } = await portal.api.email(request)+ const rows = sent.map((row) => ({id: row.id,kind: row.kind,recipient: row.recipientEmailNormalized,@@ -37,22 +36,22 @@ const {when: formatDate(row.nextAttemptAt, 'dateTime', locale.value),error: row.lastErrorCode}))-}, [])+ return { rows, total, counts }+}const {subject: busy,- error: retryError,+ error,run: retry} = usePortalAction(async (id: string) => {await portal.api.regenerateEmail(id)- await reload()+ await emails.value?.reload()})-const error = computed(() => retryError.value ?? loadError.value)</script><template><div class="flex flex-col gap-3"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />- <PortalEmailDelivery :emails="emails" :busy="busy" @retry="retry" />+ <PortalEmailDelivery ref="emails" :load="load" :busy="busy" @retry="retry" /></div></template>diff --git a/src/components/cloud-portal/sections/AdminOverviewSection.vue b/src/components/cloud-portal/sections/AdminOverviewSection.vueindex b252baa89..c27d50f80 100644--- a/src/components/cloud-portal/sections/AdminOverviewSection.vue+++ b/src/components/cloud-portal/sections/AdminOverviewSection.vue@@ -1,23 +1,30 @@<script setup lang="ts">-import { useCloudPortalMessages } from '@open-pencil/vue/i18n'-import { usePortal } from '@/app/cloud-portal/context'import { usePortalLoad } from '@/app/cloud-portal/state'-import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalStatus from '../console/PortalStatus.vue'+import PortalLoadAlert from '../layout/PortalLoadAlert.vue'+import PortalPageSkeleton from '../layout/PortalPageSkeleton.vue'import type { PortalServerStatus } from '../types'const emit = defineEmits<{ open: [section: 'requests' | 'email'] }>()const portal = usePortal()-const messages = useCloudPortalMessages()-const { data: status, error } = usePortalLoad<PortalServerStatus | null>(- () => portal.api.operations(),- null-)+const overview = usePortalLoad<PortalServerStatus | null>(() => portal.api.operations(), null)</script><template>- <AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />- <PortalStatus v-else-if="status" :status="status" @open="(section) => emit('open', section)" />+ <!-- A failed refresh says so above the status it last read, which stays. -->+ <div class="flex flex-col gap-4" :aria-busy="overview.loading.value || undefined">+ <PortalLoadAlert+ v-if="overview.error.value"+ :error="overview.error.value"+ @retry="overview.reload()"+ />+ <PortalStatus+ v-if="overview.data.value"+ :status="overview.data.value"+ @open="(section) => emit('open', section)"+ />+ <PortalPageSkeleton v-else-if="overview.status.value === 'loading'" :groups="[3, 3, 3]" />+ </div></template>diff --git a/src/components/cloud-portal/sections/AdminPeopleSection.vue b/src/components/cloud-portal/sections/AdminPeopleSection.vueindex 1fdb3104b..79014d3a0 100644--- a/src/components/cloud-portal/sections/AdminPeopleSection.vue+++ b/src/components/cloud-portal/sections/AdminPeopleSection.vue@@ -1,94 +1,51 @@<script setup lang="ts">-import { refDebounced } from '@vueuse/core'-import { computed, ref, watch } from 'vue'+import { computed, useTemplateRef } from 'vue'import type { CloudAdminUserFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'-import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import type { PortalListRequest } from '@/app/cloud-portal/list'+import { usePortalAction } from '@/app/cloud-portal/state'import { useDateFormat } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalPeople from '../console/PortalPeople.vue'import { personAction, portalPerson } from './people'-const PAGE_SIZE = 50-/** The accounts on this server, a page at a time, and what administrators do about them. */const emit = defineEmits<{ total: [count: number]; open: [personId: string] }>()const portal = usePortal()const messages = useCloudPortalMessages()const dates = useDateFormat()-const query = ref('')-const search = refDebounced(query, 250)-const filter = ref<CloudAdminUserFilter>('all')-const offset = ref(0)+const people = useTemplateRef('people')-const {- data: listing,- error: loadError,- loading,- reload-} = usePortalLoad(- () =>- portal.api.users({- search: search.value.trim() || undefined,- filter: filter.value,- limit: PAGE_SIZE,- offset: offset.value- }),- null-)-// After a failed load the last list belongs to another search or filter, so none is shown.-const people = computed(() =>- (loadError.value ? [] : (listing.value?.users ?? [])).map((user) =>- portalPerson(user, portal.account.value?.user.userId, dates)- )-)-const counts = computed(- () => listing.value?.counts ?? { all: 0, administrators: 0, suspended: 0, 'without-two-step': 0 }-)+async function load(request: PortalListRequest<CloudAdminUserFilter>) {+ const { users, total, counts } = await portal.api.users(request)+ // The page's own count is of every account, not of those a search finds.+ if (!request.search) emit('total', counts.all)+ const you = portal.account.value?.user.userId+ return { rows: users.map((user) => portalPerson(user, you, dates)), total, counts }+}const action = usePortalAction(async (change: () => Promise<unknown>) => {await change()- await reload()-})-const error = computed(() => action.error.value ?? loadError.value)--// A new search or filter starts again from the first page.-watch([search, filter], () => {- offset.value = 0- void reload()-})-watch(offset, () => void reload())-watch(listing, (current) => {- if (!current) return- emit('total', current.counts.all)- // A change that empties the last page, such as restoring its only person, steps back a page.- const total = current.counts[filter.value]- if (offset.value > 0 && offset.value >= total) {- offset.value = Math.max(0, Math.floor((total - 1) / PAGE_SIZE) * PAGE_SIZE)- }+ await people.value?.reload()})+const error = computed(() => action.error.value)</script><template><div class="flex flex-col gap-3"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><PortalPeople- v-model:query="query"- v-model:filter="filter"- :people="people"- :counts="counts"- :offset="offset"- :page-size="PAGE_SIZE"- :busy="action.busy.value || loading"+ ref="people"+ :load="load"+ :busy="action.busy.value"@act="(person, kind, reason) => action.run(() => personAction(portal.api, person, kind, reason))"@open="(id) => emit('open', id)"- @page="(next) => (offset = next)"/></div></template>diff --git a/src/components/cloud-portal/sections/AdminPersonSection.vue b/src/components/cloud-portal/sections/AdminPersonSection.vueindex 251b63f7a..5ec22a3cd 100644--- a/src/components/cloud-portal/sections/AdminPersonSection.vue+++ b/src/components/cloud-portal/sections/AdminPersonSection.vue@@ -12,6 +12,8 @@ import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import PortalPerson from '../console/PortalPerson.vue'+import PortalLoadAlert from '../layout/PortalLoadAlert.vue'+import PortalPageSkeleton from '../layout/PortalPageSkeleton.vue'import type { PortalPersonAction, PortalPersonDetail } from '../types'import { personAction, portalPerson } from './people'import { portalSession, portalSignIn } from './sessions'@@ -53,7 +55,7 @@ const action = usePortalAction(async (change: () => Promise<unknown>) => {await change()await loaded.reload()})-const error = computed(() => action.error.value ?? loaded.error.value)+const error = computed(() => action.error.value)function act(kind: PortalPersonAction, reason?: string) {const person = detail.value?.person@@ -67,7 +69,12 @@ watch(</script><template>- <div class="flex flex-col gap-4">+ <div class="flex flex-col gap-4" :aria-busy="loaded.loading.value || undefined">+ <PortalLoadAlert+ v-if="loaded.error.value"+ :error="loaded.error.value"+ @retry="loaded.reload()"+ /><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><AppPlaceholderv-if="loaded.data.value === 'missing'"@@ -90,5 +97,6 @@ watch(@act="act"@back="emit('back')"/>+ <PortalPageSkeleton v-else-if="loaded.status.value === 'loading'" avatar :groups="[5, 2]" /></div></template>diff --git a/src/components/cloud-portal/sections/AdminRequestsSection.vue b/src/components/cloud-portal/sections/AdminRequestsSection.vueindex ae0dac92b..314812a5a 100644--- a/src/components/cloud-portal/sections/AdminRequestsSection.vue+++ b/src/components/cloud-portal/sections/AdminRequestsSection.vue@@ -1,60 +1,57 @@<script setup lang="ts">-import { computed, ref, watch } from 'vue'+import { useTemplateRef } from 'vue'import { useCloudPortalMessages, useI18n } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'-import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import type { PortalListRequest } from '@/app/cloud-portal/list'+import { usePortalAction } from '@/app/cloud-portal/state'import { formatDate } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalAccessRequests from '../console/PortalAccessRequests.vue'-import type { AccessRequest, AccessRequestStatus } from '../types'+import type { AccessRequestStatus } from '../types'const emit = defineEmits<{ changed: [] }>()const portal = usePortal()const messages = useCloudPortalMessages()const { locale } = useI18n()-const filter = ref<AccessRequestStatus>('pending')+const requests = useTemplateRef('requests')-const {- data: requests,- error: loadError,- reload-} = usePortalLoad(async (): Promise<AccessRequest[]> => {- const { enrollments } = await portal.api.enrollments(filter.value)- return enrollments.map((enrollment) => ({+async function load(request: PortalListRequest<AccessRequestStatus>) {+ const { enrollments, total, counts } = await portal.api.enrollments(request)+ const rows = enrollments.map((enrollment) => ({id: enrollment.id,name: enrollment.name,email: enrollment.email,reason: enrollment.reason,requestedOn: formatDate(enrollment.requestedAt, 'date', locale.value),status: enrollment.status,- reviewedBy: enrollment.reviewedBy,+ reviewedBy: enrollment.reviewedBy+ ? (enrollment.reviewerName ?? messages.value.someoneElse)+ : null,note: enrollment.reviewNote}))-}, [])+ return { rows, total, counts }+}const {subject: busy,- error: reviewError,+ error,run: review} = usePortalAction(async (id: string, action: 'approve' | 'reject' | 'revoke', note?: string) => {await portal.api.reviewEnrollment(id, action, note)emit('changed')- await reload()+ await requests.value?.reload()})-const error = computed(() => reviewError.value ?? loadError.value)--watch(filter, () => void reload())</script><template><div class="flex flex-col gap-3"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><PortalAccessRequests- v-model:filter="filter"- :requests="requests"+ ref="requests"+ :load="load":busy="busy"@approve="(id) => review(id, 'approve')"@reject="(id, note) => review(id, 'reject', note)"diff --git a/src/components/cloud-portal/sections/ProfileSection.vue b/src/components/cloud-portal/sections/ProfileSection.vueindex 12dd6fb9e..076f58629 100644--- a/src/components/cloud-portal/sections/ProfileSection.vue+++ b/src/components/cloud-portal/sections/ProfileSection.vue@@ -14,12 +14,13 @@ import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'import { portalToast } from '@/app/cloud-portal/toast'import { useDateFormat } from '@/app/i18n/date'import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'-import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalFieldDialog from '../account/PortalFieldDialog.vue'import PortalPasswordDialog from '../account/PortalPasswordDialog.vue'import PortalPictureDialog from '../account/PortalPictureDialog.vue'import PortalProfile from '../account/PortalProfile.vue'+import PortalLoadAlert from '../layout/PortalLoadAlert.vue'+import PortalPageSkeleton from '../layout/PortalPageSkeleton.vue'/** The query the email confirmation link comes back with. */const EMAIL_CONFIRMED = 'email-confirmed'@@ -155,7 +156,6 @@ const confirmPassword = usePortalAction(async (password: string) => {const busy = computed(() =>- loaded.loading.value ||rename.busy.value ||savePicture.busy.value ||removePicture.busy.value ||@@ -178,12 +178,11 @@ onMounted(async () => {</script><template>- <div class="flex max-w-2xl flex-col gap-4">- <AppAlert+ <div class="flex max-w-2xl flex-col gap-4" :aria-busy="loaded.loading.value || undefined">+ <PortalLoadAlertv-if="loaded.error.value"- tone="error"- :heading="messages.errorTitle"- :description="loaded.error.value"+ :error="loaded.error.value"+ @retry="loaded.reload()"/><PortalProfilev-if="profile"@@ -195,6 +194,7 @@ onMounted(async () => {@choose-picture="choosePicture"@remove-picture="removeOpen = true"/>+ <PortalPageSkeleton v-else-if="loaded.status.value === 'loading'" avatar :groups="[2, 1]" /><AppConfirmationDialogv-model:open="removeOpen"tone="danger"diff --git a/src/components/cloud-portal/sections/SecuritySection.vue b/src/components/cloud-portal/sections/SecuritySection.vueindex 8a1f19e05..13d0818db 100644--- a/src/components/cloud-portal/sections/SecuritySection.vue+++ b/src/components/cloud-portal/sections/SecuritySection.vue@@ -16,6 +16,8 @@ import PortalAccountSecurity from '../account/PortalAccountSecurity.vue'import PortalAuthenticatorSetup from '../account/PortalAuthenticatorSetup.vue'import PortalPasswordDialog from '../account/PortalPasswordDialog.vue'import PortalRecoveryCodes from '../account/PortalRecoveryCodes.vue'+import PortalLoadAlert from '../layout/PortalLoadAlert.vue'+import PortalPageSkeleton from '../layout/PortalPageSkeleton.vue'import type { PortalSignInMethod } from '../types'/** The signed-in person's sign-in methods and second steps, with every change they can make. */@@ -128,11 +130,7 @@ const passwordAction = usePortalAction()const busy = computed(- () =>- security.loading.value ||- change.busy.value ||- passwordAction.busy.value ||- verifyAction.busy.value+ () => change.busy.value || passwordAction.busy.value || verifyAction.busy.value)const passwordError = computed(() => (passwordStep.value ? passwordAction.error.value : null))const passwordShown = useHeldContent(passwordStep)@@ -140,10 +138,7 @@ const passwordErrorShown = useHeldContent(passwordError, () => passwordStep.valuconst setupShown = useHeldContent(setupURI)const codesShown = useHeldContent(recoveryCodes)const error = computed(- () =>- change.error.value ??- (passwordStep.value ? null : passwordAction.error.value) ??- security.error.value+ () => change.error.value ?? (passwordStep.value ? null : passwordAction.error.value))function link(provider: PortalSignInMethod) {@@ -201,7 +196,12 @@ function addPasskey() {</script><template>- <div class="flex max-w-2xl flex-col gap-4">+ <div class="flex max-w-2xl flex-col gap-4" :aria-busy="security.loading.value || undefined">+ <PortalLoadAlert+ v-if="security.error.value"+ :error="security.error.value"+ @retry="security.reload()"+ /><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><PortalAccountSecurityv-if="methods && mfa"@@ -227,6 +227,7 @@ function addPasskey() {@add-passkey="addPasskey"@remove-passkey="(id) => change.run(() => portal.api.deletePasskey(id))"/>+ <PortalPageSkeleton v-else-if="security.status.value === 'loading'" :groups="[2, 2, 1]" /><PortalPasswordDialog:open="passwordStep !== null"diff --git a/src/components/cloud-portal/sections/SessionsSection.vue b/src/components/cloud-portal/sections/SessionsSection.vueindex 5fd56639a..dc260df54 100644--- a/src/components/cloud-portal/sections/SessionsSection.vue+++ b/src/components/cloud-portal/sections/SessionsSection.vue@@ -9,6 +9,7 @@ import { useDateFormat } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalSessions from '../account/PortalSessions.vue'+import PortalLoadAlert from '../layout/PortalLoadAlert.vue'import { portalSession, portalSignIn } from './sessions'/** Where the signed-in person's account is signed in, its recent sign-ins, and signing them out. */@@ -35,15 +36,26 @@ const change = usePortalAction(async (work: () => Promise<unknown>) => {await work()await activity.reload()})-const error = computed(() => change.error.value ?? activity.error.value)+const error = computed(() => change.error.value)+/** What the tables show while the server answers. */+const loading = computed(() => {+ if (activity.status.value === 'loading') return 'first'+ return activity.status.value === 'refreshing' ? 'refresh' : false+})</script><template><div class="flex flex-col gap-4">+ <PortalLoadAlert+ v-if="activity.error.value"+ :error="activity.error.value"+ @retry="activity.reload()"+ /><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><PortalSessions- v-if="activity.data.value"+ v-if="activity.status.value !== 'failed'"manage+ :loading="loading":sessions="sessions":sign-ins="signIns":busy="change.busy.value"diff --git a/src/components/cloud-portal/table/PortalIdentityCell.vue b/src/components/cloud-portal/table/PortalIdentityCell.vuenew file mode 100644index 000000000..e249d894c--- /dev/null+++ b/src/components/cloud-portal/table/PortalIdentityCell.vue@@ -0,0 +1,50 @@+<script setup lang="ts">+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+import { portalTable } from '@/theme/cloud-portal/table'++/**+ * Who a row is about: their picture, name, and a line under it such as their email. With `link`+ * the name opens their page.+ */+const {+ id,+ name,+ detail,+ image = null,+ you = false,+ size = 'md',+ link = false+} = defineProps<{+ id: string+ name: string+ detail?: string | null+ image?: string | null+ /** Marks the signed-in person's own row. */+ you?: boolean+ size?: 'sm' | 'md'+ link?: boolean+}>()+const emit = defineEmits<{ open: [] }>()+const ui = portalTable()+const messages = useCloudPortalMessages()+</script>++<template>+ <div class="flex min-w-0 items-center gap-3">+ <AccountAvatar :id="id" :name="name" :image="image" :size="size" />+ <component+ :is="link ? 'button' : 'div'"+ :type="link ? 'button' : undefined"+ class="min-w-0 rounded text-left focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:outline-none"+ @click="link && emit('open')"+ >+ <span :class="ui.title()">+ <span class="truncate">{{ name }}</span>+ <span v-if="you" class="shrink-0 font-normal text-muted">{{ messages.you }}</span>+ </span>+ <span v-if="detail" :class="[ui.detail(), 'block']">{{ detail }}</span>+ </component>+ </div>+</template>diff --git a/src/components/cloud-portal/table/PortalRequestActions.vue b/src/components/cloud-portal/table/PortalRequestActions.vuenew file mode 100644index 000000000..575c0066e--- /dev/null+++ b/src/components/cloud-portal/table/PortalRequestActions.vue@@ -0,0 +1,48 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AppButton from '@/components/ui/button/AppButton.vue'+import { portalTable } from '@/theme/cloud-portal/table'++import type { AccessRequest } from '../types'+import PortalRowMenu from './PortalRowMenu.vue'++/** What can be decided about an access request: approving it at hand, the rest in its menu. */+const { request, busy = false } = defineProps<{ request: AccessRequest; busy?: boolean }>()+const emit = defineEmits<{ approve: []; ask: [kind: 'reject' | 'revoke'] }>()++const ui = portalTable()+const messages = useCloudPortalMessages()+const items = computed(() => {+ if (request.status === 'pending')+ return [{ action: 'reject' as const, label: messages.value.decline }]+ if (request.status === 'approved') {+ return [{ action: 'revoke' as const, label: messages.value.removeAccess }]+ }+ return []+})+</script>++<template>+ <div :class="ui.actions()">+ <AppButton+ v-if="request.status === 'pending'"+ size="sm"+ color="primary"+ variant="solid"+ :loading="busy"+ @click="emit('approve')"+ >+ {{ messages.approve }}+ </AppButton>+ <PortalRowMenu+ v-if="items.length"+ :label="messages.actionsFor({ name: request.name ?? request.email })"+ :items="items"+ :disabled="busy"+ @select="(kind) => emit('ask', kind)"+ />+ </div>+</template>diff --git a/src/components/cloud-portal/table/PortalRowMenu.vue b/src/components/cloud-portal/table/PortalRowMenu.vuenew file mode 100644index 000000000..23354203e--- /dev/null+++ b/src/components/cloud-portal/table/PortalRowMenu.vue@@ -0,0 +1,72 @@+<script setup lang="ts" generic="Action extends string">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'++import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import { menu } from '@/components/ui/menu/menu'++/**+ * The “…” menu at the end of a console row, holding what can be done to it besides its one+ * inline action. An item with `separated` starts a group of its own.+ */+const {+ label,+ items,+ look = 'icon',+ disabled = false+} = defineProps<{+ /** Names the menu for the row, such as “Actions for Ada”. */+ label: string+ items: readonly { action: Action; label: string; separated?: boolean }[]+ /** An icon in a table row, or an outlined button on a page of its own. */+ look?: 'icon' | 'button'+ disabled?: boolean+}>()+const emit = defineEmits<{ select: [action: Action] }>()++const menuUI = menu()+</script>++<template>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton v-if="look === 'icon'" :label="label" :disabled="disabled || !items.length">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ <AppButton+ v-else+ size="sm"+ variant="outline"+ :aria-label="label"+ :disabled="disabled || !items.length"+ >+ <icon-lucide-ellipsis class="size-3.5" />+ </AppButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent+ side="bottom"+ align="end"+ :side-offset="4"+ :class="[menuUI.content(), 'w-56']"+ >+ <template v-for="item in items" :key="item.action">+ <DropdownMenuSeparator v-if="item.separated" :class="menuUI.separator()" />+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('select', item.action)"+ >+ {{ item.label }}+ </DropdownMenuItem>+ </template>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+</template>diff --git a/src/components/cloud-portal/table/PortalStatusCell.vue b/src/components/cloud-portal/table/PortalStatusCell.vuenew file mode 100644index 000000000..95e1ef3ff--- /dev/null+++ b/src/components/cloud-portal/table/PortalStatusCell.vue@@ -0,0 +1,31 @@+<script setup lang="ts">+import { portalTable } from '@/theme/cloud-portal/table'++/**+ * Where a row stands, as coloured badges, or `fallback` in plain words when no badge applies, with+ * a line under them such as why.+ */+const { statuses, fallback, detail } = defineProps<{+ statuses: readonly { label: string; tone: 'neutral' | 'success' | 'warning' | 'error' }[]+ fallback?: string+ detail?: string | null+}>()+const ui = portalTable()+</script>++<template>+ <div class="flex min-w-0 flex-col items-start gap-0.5">+ <div v-if="statuses.length" class="flex flex-wrap items-center gap-1">+ <span+ v-for="status in statuses"+ :key="status.label"+ :class="ui.status()"+ :data-tone="status.tone"+ >+ {{ status.label }}+ </span>+ </div>+ <span v-else-if="fallback" class="text-muted">{{ fallback }}</span>+ <span v-if="detail" :class="ui.detail()">{{ detail }}</span>+ </div>+</template>diff --git a/src/components/cloud-portal/table/PortalTable.vue b/src/components/cloud-portal/table/PortalTable.vuenew file mode 100644index 000000000..d4e710724--- /dev/null+++ b/src/components/cloud-portal/table/PortalTable.vue@@ -0,0 +1,131 @@+<script setup lang="ts" generic="Filter extends string, Row extends RowData">+import type { RowData } from '@tanstack/vue-table'+import { computed } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import type { PortalList } from '@/app/cloud-portal/list'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppSkeleton from '@/components/ui/feedback/AppSkeleton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import AppDataTable from '@/components/ui/table/AppDataTable.vue'+import AppTablePagination from '@/components/ui/table/AppTablePagination.vue'+import { portalTable } from '@/theme/cloud-portal/table'++import PortalLoadAlert from '../layout/PortalLoadAlert.vue'++/**+ * A console list the server searches, filters, and pages: a search box when `searchLabel` is+ * given, the filters with how many rows each holds, the table its columns draw, and the pages.+ */+const {+ list,+ label,+ searchLabel,+ filters = [],+ hidden = [],+ emptyLabel,+ emptyDescription+} = defineProps<{+ list: PortalList<Filter, Row>+ label: string+ searchLabel?: string+ filters?: { value: Filter; label: string }[]+ hidden?: readonly string[]+ emptyLabel: string+ emptyDescription?: string+}>()+defineSlots<{ icon?: () => unknown }>()++const ui = portalTable()+const messages = useCloudPortalMessages()+const { table, query, filter, counts, range, total, status, error, reload } = list+/** What the table shows while the server answers. */+const loading = computed(() => {+ if (status.value === 'loading') return 'first'+ return status.value === 'refreshing' ? 'refresh' : false+})+const filterOf = (value: string) => filters.find((option) => option.value === value)+const filterValue = computed({+ get: () => filter.value,+ set: (value: string) => {+ const option = filterOf(value)+ if (option) filter.value = option.value+ }+})+/** How many rows a filter holds, once the server has said. */+function countOf(value: string) {+ const option = filterOf(value)+ return option && counts.value ? counts.value[option.value] : null+}+</script>++<template>+ <div class="flex flex-col gap-3">+ <PortalLoadAlert v-if="error" :error="error" @retry="reload()" />+ <div v-if="searchLabel || filters.length" :class="ui.toolbar()">+ <!-- On a narrow page the filters scroll sideways rather than leave it. -->+ <div v-if="filters.length" class="max-w-full overflow-x-auto">+ <!-- As tall as the search field beside it, in the same type. -->+ <SegmentedControl+ v-model="filterValue"+ required+ :label="label"+ :options="filters"+ :ui="{ root: 'h-8', item: 'h-7 px-2.5 text-xs' }"+ >+ <template #option="{ option }">+ {{ option.label }}+ <span v-if="countOf(option.value) !== null" class="text-muted tabular-nums">+ {{ countOf(option.value) }}+ </span>+ <!-- Holds the count's place until the server has counted. -->+ <AppSkeleton v-else-if="status === 'loading'" class="w-3" />+ </template>+ </SegmentedControl>+ </div>+ <AppInput+ v-if="searchLabel"+ v-model="query"+ type="search"+ :placeholder="searchLabel"+ :aria-label="searchLabel"+ class="ml-auto w-64 max-w-full"+ >+ <template #leading><icon-lucide-search class="size-3.5" /></template>+ </AppInput>+ </div>+ <AppDataTable+ :table="table"+ :label="label"+ :hidden="hidden"+ :loading="loading"+ :loading-label="messages.loading"+ >+ <!-- A failed load says so above the table; it does not mean nothing matched. -->+ <template v-if="!error" #empty>+ <AppPlaceholder+ size="compact"+ :fill="false"+ :label="emptyLabel"+ :description="emptyDescription"+ >+ <template #icon><slot name="icon" /></template>+ </AppPlaceholder>+ </template>+ <!-- After a failed load the rows are gone, so the last range would no longer be true. -->+ <template v-if="total && !error" #footer>+ <AppTablePagination+ :range="range"+ :can-previous="table.getCanPreviousPage()"+ :can-next="table.getCanNextPage()"+ :previous-label="messages.previousPage"+ :next-label="messages.nextPage"+ @previous="table.previousPage()"+ @next="table.nextPage()"+ />+ </template>+ </AppDataTable>+ </div>+</template>diff --git a/src/components/cloud-portal/table/PortalTextCell.vue b/src/components/cloud-portal/table/PortalTextCell.vuenew file mode 100644index 000000000..2801bfa5b--- /dev/null+++ b/src/components/cloud-portal/table/PortalTextCell.vue@@ -0,0 +1,45 @@+<script setup lang="ts">+import type { Component } from 'vue'++import AppBadge from '@/components/ui/feedback/AppBadge.vue'+import { portalTable } from '@/theme/cloud-portal/table'++/**+ * A cell of words: a line of text, optionally strong, with an icon or badge beside it, a line under+ * it, and a quotation such as a reason someone gave. `narrowDetail` is a line only a narrow table+ * shows, for a column it hides.+ */+const {+ text,+ icon,+ strong = false,+ badge,+ detail,+ narrowDetail,+ quote+} = defineProps<{+ text?: string | null+ icon?: Component+ strong?: boolean+ badge?: string | null+ detail?: string | null+ narrowDetail?: string | null+ quote?: string | null+}>()+const ui = portalTable()+</script>++<template>+ <div class="flex min-w-0 items-center gap-3">+ <component :is="icon" v-if="icon" class="size-4 shrink-0 text-muted" />+ <div class="min-w-0">+ <p v-if="text" :class="strong ? ui.title() : 'truncate'">+ {{ text }}+ <AppBadge v-if="badge">{{ badge }}</AppBadge>+ </p>+ <p v-if="narrowDetail" :class="[ui.detail(), '@xl/table:hidden']">{{ narrowDetail }}</p>+ <p v-if="detail" :class="ui.detail()">{{ detail }}</p>+ <p v-if="quote" :class="ui.quote()">“{{ quote }}”</p>+ </div>+ </div>+</template>diff --git a/src/components/shell/AppMenu.vue b/src/components/shell/AppMenu.vueindex 61c62a4b6..c55a8e372 100644--- a/src/components/shell/AppMenu.vue+++ b/src/components/shell/AppMenu.vue@@ -37,11 +37,12 @@ import {updateMenuChecked} from '@/app/shell/menu/entry'import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'+import { animationsEnabled } from '@/app/shell/motion'import { resolvedAppTheme } from '@/app/shell/theme'import BrandMark from '@/components/brand/BrandMark.vue'import { CloudDocumentStatusHost } from '@/components/cloud/integration'-import { useScrollOverflow } from '@/components/shell/useScrollOverflow'import IconButton from '@/components/ui/button/IconButton.vue'+import { useScrollOverflow } from '@/components/ui/list/useScrollOverflow'import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'import { useMenuUI } from '@/components/ui/menu/menu'import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'@@ -65,7 +66,9 @@ const subMenuCls = useMenuUI({ content: 'min-w-44' })// A narrow panel clips the menubar; fade the clipped side and offer a chevron so it reads as scrollable.const menubar = useTemplateRef<HTMLElement>('menubar')-const { overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(menubar)+const { overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(menubar, {+ smooth: animationsEnabled+})</script><template>diff --git a/src/components/ui/feedback/AppSkeleton.vue b/src/components/ui/feedback/AppSkeleton.vuenew file mode 100644index 000000000..252c554b8--- /dev/null+++ b/src/components/ui/feedback/AppSkeleton.vue@@ -0,0 +1,14 @@+<script setup lang="ts">+import { skeleton } from './skeleton'++/**+ * One grey bar where text or a control will be once it loads; give it the width of what it stands+ * for. Placeholders are for the eye only, so assistive technology skips them.+ */+const { class: className } = defineProps<{ class?: string }>()+const styles = skeleton()+</script>++<template>+ <span :class="styles.bar({ class: className })" aria-hidden="true" />+</template>diff --git a/src/components/ui/feedback/skeleton.ts b/src/components/ui/feedback/skeleton.tsnew file mode 100644index 000000000..344a63d0d--- /dev/null+++ b/src/components/ui/feedback/skeleton.ts@@ -0,0 +1,5 @@+import { tv } from 'tailwind-variants'++import skeletonTheme from '@/theme/feedback/skeleton'++export const skeleton = tv(skeletonTheme)diff --git a/src/components/shell/useScrollOverflow.ts b/src/components/ui/list/useScrollOverflow.tssimilarity index 59%rename from src/components/shell/useScrollOverflow.tsrename to src/components/ui/list/useScrollOverflow.tsindex 92ffbd99a..41ee5f8f1 100644--- a/src/components/shell/useScrollOverflow.ts+++ b/src/components/ui/list/useScrollOverflow.ts@@ -1,16 +1,32 @@-import { useMutationObserver, useResizeObserver, useScroll } from '@vueuse/core'-import { computed, ref, type ShallowRef } from 'vue'+import {+ useMutationObserver,+ usePreferredReducedMotion,+ useResizeObserver,+ useScroll+} from '@vueuse/core'+import { computed, ref, toValue, type MaybeRefOrGetter, type ShallowRef } from 'vue'-import { animationsEnabled } from '@/app/shell/motion'+/** How close to an end counts as having reached it. */+const EDGE_TOLERANCE_PX = 8/*** Tracks which ends of a horizontally scrolling row hide content, for an edge fade and a chevron* that scrolls toward the hidden side. The row's first child is watched as well as the row, and* its items are watched as they come and go, so content that changes width without resizing a- * box (another language, a tab opened or closed while the row overflows) is remeasured.+ * box (another language, a tab opened or closed while the row overflows) is remeasured. The+ * chevron scrolls smoothly unless `smooth` says not to, which by default follows the system's+ * reduced-motion setting.*/-export function useScrollOverflow(scroller: Readonly<ShallowRef<HTMLElement | null>>) {- const { arrivedState, measure } = useScroll(scroller)+export function useScrollOverflow(+ scroller: Readonly<ShallowRef<HTMLElement | null>>,+ options: { smooth?: MaybeRefOrGetter<boolean> } = {}+) {+ const preferredMotion = usePreferredReducedMotion()+ const smooth = () => toValue(options.smooth) ?? preferredMotion.value !== 'reduce'+ // A row's own padding at either end is not hidden content.+ const { arrivedState, measure } = useScroll(scroller, {+ offset: { left: EDGE_TOLERANCE_PX, right: EDGE_TOLERANCE_PX }+ })/** Whether the row is wider than its box, from sizes alone, so scrolling never changes it. */const overflowing = ref(false)function remeasure() {@@ -35,7 +51,7 @@ export function useScrollOverflow(scroller: Readonly<ShallowRef<HTMLElement | nuif (!element) returnelement.scrollBy({left: overflowEnd.value ? element.clientWidth : -element.scrollWidth,- behavior: animationsEnabled.value ? 'smooth' : 'auto'+ behavior: smooth() ? 'smooth' : 'auto'})}diff --git a/src/components/ui/table/AppDataTable.stories.ts b/src/components/ui/table/AppDataTable.stories.tsnew file mode 100644index 000000000..66e4b7ca1--- /dev/null+++ b/src/components/ui/table/AppDataTable.stories.ts@@ -0,0 +1,77 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { createColumnHelper, tableFeatures, useTable } from '@tanstack/vue-table'+import { expect, within } from 'storybook/test'++import AppDataTable from './AppDataTable.vue'+import AppTablePagination from './AppTablePagination.vue'+import type { TableColumnMeta } from './columns'++type Layer = { id: string; name: string; kind: string; updated: string }++const features = tableFeatures({ columnMeta: {} as TableColumnMeta })+const column = createColumnHelper<typeof features, Layer>()+const columns = column.columns([+ column.accessor('name', { header: 'Name', meta: { class: 'font-medium' } }),+ column.accessor('kind', { header: 'Kind', meta: { class: 'w-28 text-muted' } }),+ column.accessor('updated', {+ header: 'Updated',+ meta: { class: 'hidden w-36 text-muted @xl/table:table-cell' }+ })+])+const layers: Layer[] = [+ { id: '1', name: 'Hero', kind: 'Frame', updated: 'Oct 24, 2026' },+ { id: '2', name: 'Primary button', kind: 'Component', updated: 'Oct 22, 2026' },+ { id: '3', name: 'Logo', kind: 'Vector', updated: 'Sep 30, 2026' }+]+const rowId = (layer: Layer) => layer.id++const meta = {+ title: 'Design System/Table/Data table',+ render: () => ({+ components: { AppDataTable, AppTablePagination },+ setup: () => ({ table: useTable({ features, columns, data: layers, getRowId: rowId }) }),+ template: `+ <div class="max-w-3xl p-4">+ <AppDataTable :table="table" label="Layers">+ <template #footer>+ <AppTablePagination range="1–3 of 3" :can-previous="false" :can-next="false" previous-label="Previous page" next-label="Next page" />+ </template>+ </AppDataTable>+ </div>`+ })+} satisfies Meta++export default meta+type Story = StoryObj<typeof meta>++export const Rows: Story = {+ play: async ({ canvasElement }) => {+ const page = within(canvasElement)+ await expect(page.getByRole('table', { name: 'Layers' })).toBeVisible()+ await expect(page.getAllByRole('row')).toHaveLength(4)+ }+}++export const Loading: Story = {+ render: () => ({+ components: { AppDataTable },+ setup: () => ({ table: useTable({ features, columns, data: [] }) }),+ template: `+ <div class="max-w-3xl p-4">+ <AppDataTable :table="table" label="Layers" loading="first" />+ </div>`+ })+}++export const Empty: Story = {+ render: () => ({+ components: { AppDataTable },+ setup: () => ({ table: useTable({ features, columns, data: [] }) }),+ template: `+ <div class="max-w-3xl p-4">+ <AppDataTable :table="table" label="Layers">+ <template #empty><p class="text-center text-xs text-muted">No layers yet.</p></template>+ </AppDataTable>+ </div>`+ })+}diff --git a/src/components/ui/table/AppDataTable.vue b/src/components/ui/table/AppDataTable.vuenew file mode 100644index 000000000..a632e6932--- /dev/null+++ b/src/components/ui/table/AppDataTable.vue@@ -0,0 +1,90 @@+<script setup lang="ts" generic="Features extends TableFeatures, Row extends RowData">+import { FlexRender, type RowData, type Table, type TableFeatures } from '@tanstack/vue-table'+import { computed } from 'vue'++import AppTable from './AppTable.vue'+import AppTableBody from './AppTableBody.vue'+import AppTableCell from './AppTableCell.vue'+import AppTableEmpty from './AppTableEmpty.vue'+import AppTableHead from './AppTableHead.vue'+import AppTableHeader from './AppTableHeader.vue'+import AppTablePlaceholder from './AppTablePlaceholder.vue'+import AppTableRow from './AppTableRow.vue'+import { tableColumnMeta } from './columns'++/**+ * A TanStack table drawn with the table parts: each column renders its own header and cells, and+ * its `meta` (`TableColumnMeta`) gives their classes; `hidden` leaves columns out. Before its first+ * rows load it shows placeholders in its columns, and while newer rows load it keeps the old ones.+ */+const {+ table,+ label,+ hidden = [],+ loading = false,+ loadingLabel+} = defineProps<{+ table: Table<Features, Row>+ /** What the table lists, for assistive technology. */+ label: string+ hidden?: readonly string[]+ loading?: 'first' | 'refresh' | false+ /** What assistive technology announces while the table loads, such as “Loading…”. */+ loadingLabel?: string+}>()+defineSlots<{ empty?: () => unknown; footer?: () => unknown }>()++const shown = (column: { id: string }) => !hidden.includes(column.id)+const headers = computed(() =>+ table.getHeaderGroups().map((group) => ({+ id: group.id,+ headers: group.headers.filter((header) => shown(header.column))+ }))+)+const rows = computed(() =>+ table.getRowModel().rows.map((row) => ({+ row,+ cells: row.getAllCells().filter((cell) => shown(cell.column))+ }))+)+const columns = computed(() =>+ (headers.value.at(-1)?.headers ?? []).map((header) => {+ const meta = tableColumnMeta(header.column.columnDef.meta)+ return { id: header.column.id, class: meta.class, actions: meta.actions }+ })+)+</script>++<template>+ <AppTable :label="label" :loading="loading" :loading-label="loadingLabel">+ <AppTableHeader>+ <AppTableRow v-for="group in headers" :key="group.id">+ <AppTableHead+ v-for="header in group.headers"+ :key="header.id"+ :colspan="header.colSpan"+ :label-hidden="tableColumnMeta(header.column.columnDef.meta).actions"+ :class="tableColumnMeta(header.column.columnDef.meta).class"+ >+ <FlexRender v-if="!header.isPlaceholder" :header="header" />+ </AppTableHead>+ </AppTableRow>+ </AppTableHeader>+ <AppTablePlaceholder v-if="loading === 'first'" :columns="columns" />+ <AppTableBody v-else :refreshing="loading === 'refresh'">+ <AppTableRow v-for="{ row, cells } in rows" :key="row.id">+ <AppTableCell+ v-for="cell in cells"+ :key="cell.id"+ :class="tableColumnMeta(cell.column.columnDef.meta).class"+ >+ <FlexRender :cell="cell" />+ </AppTableCell>+ </AppTableRow>+ <AppTableEmpty v-if="!rows.length && $slots.empty" :colspan="columns.length || 1">+ <slot name="empty" />+ </AppTableEmpty>+ </AppTableBody>+ <template v-if="$slots.footer" #footer><slot name="footer" /></template>+ </AppTable>+</template>diff --git a/src/components/ui/table/AppTable.vue b/src/components/ui/table/AppTable.vuenew file mode 100644index 000000000..1075fd8a4--- /dev/null+++ b/src/components/ui/table/AppTable.vue@@ -0,0 +1,50 @@+<script setup lang="ts">+import AppProgress from '@/components/ui/feedback/AppProgress.vue'+import { skeleton } from '@/components/ui/feedback/skeleton'++import { useTableUI, type TableUI } from './ui'++/**+ * The frame of a table: it scrolls sideways when its columns do not fit, holds a footer such as+ * the pages under the rows, and while newer rows load shows a pulsing bar along its top edge.+ */+const {+ label,+ loading = false,+ loadingLabel,+ ui+} = defineProps<{+ /** What the table lists, for assistive technology. */+ label: string+ /** `first` before any rows have loaded, `refresh` while newer rows replace the shown ones. */+ loading?: 'first' | 'refresh' | false+ /** What assistive technology announces while the table loads, such as “Loading…”. */+ loadingLabel?: string+ ui?: TableUI+}>()+const cls = useTableUI(ui)+const placeholders = skeleton()+</script>++<template>+ <div data-slot="table" :class="cls.root">+ <!-- The placeholders and the bar are for the eye; this says it to assistive technology, from+ outside the busy table so it is announced when loading starts. -->+ <span v-if="loadingLabel" role="status" class="sr-only">{{ loading ? loadingLabel : '' }}</span>+ <div+ v-if="loading === 'refresh'"+ :class="[cls.refresh, placeholders.group()]"+ aria-hidden="true"+ >+ <AppProgress :amount="{}" :ui="{ track: 'h-0.5 rounded-none bg-transparent' }" />+ </div>+ <div :class="cls.scroller">+ <table :class="cls.table" :aria-label="label" :aria-busy="loading ? true : undefined">+ <slot />+ </table>+ </div>+ <div v-if="$slots.footer" data-slot="table-footer" :class="cls.footer">+ <slot name="footer" />+ </div>+ </div>+</template>diff --git a/src/components/ui/table/AppTableBody.vue b/src/components/ui/table/AppTableBody.vuenew file mode 100644index 000000000..fa41d0c05--- /dev/null+++ b/src/components/ui/table/AppTableBody.vue@@ -0,0 +1,13 @@+<script setup lang="ts">+import { useTableUI, type TableUI } from './ui'++/** The rows; while newer ones load these stay, faded, so the table never jumps. */+const { refreshing = false, ui } = defineProps<{ refreshing?: boolean; ui?: TableUI }>()+const cls = useTableUI(ui)+</script>++<template>+ <tbody data-slot="table-body" :class="cls.body" :data-refreshing="refreshing || undefined">+ <slot />+ </tbody>+</template>diff --git a/src/components/ui/table/AppTableCell.vue b/src/components/ui/table/AppTableCell.vuenew file mode 100644index 000000000..6b6c83b1c--- /dev/null+++ b/src/components/ui/table/AppTableCell.vue@@ -0,0 +1,17 @@+<script setup lang="ts">+import { normalizeClass, type HTMLAttributes } from 'vue'++import { table } from './ui'++const { class: className, ui } = defineProps<{+ class?: HTMLAttributes['class']+ ui?: { cell?: string }+}>()+const cls = table()+</script>++<template>+ <td data-slot="table-cell" :class="cls.cell({ class: [ui?.cell, normalizeClass(className)] })">+ <slot />+ </td>+</template>diff --git a/src/components/ui/table/AppTableEmpty.vue b/src/components/ui/table/AppTableEmpty.vuenew file mode 100644index 000000000..990b6c82f--- /dev/null+++ b/src/components/ui/table/AppTableEmpty.vue@@ -0,0 +1,13 @@+<script setup lang="ts">+import { useTableUI, type TableUI } from './ui'++/** One row across every column, for what shows when there are no rows. */+const { colspan, ui } = defineProps<{ colspan: number; ui?: TableUI }>()+const cls = useTableUI(ui)+</script>++<template>+ <tr data-slot="table-empty">+ <td :colspan="colspan" :class="cls.empty"><slot /></td>+ </tr>+</template>diff --git a/src/components/ui/table/AppTableHead.vue b/src/components/ui/table/AppTableHead.vuenew file mode 100644index 000000000..499a9169e--- /dev/null+++ b/src/components/ui/table/AppTableHead.vue@@ -0,0 +1,30 @@+<script setup lang="ts">+import { normalizeClass, type HTMLAttributes } from 'vue'++import { table } from './ui'++/** A column's header; `labelHidden` keeps it for assistive technology only, as for row actions. */+const {+ colspan,+ labelHidden = false,+ class: className,+ ui+} = defineProps<{+ colspan?: number+ labelHidden?: boolean+ class?: HTMLAttributes['class']+ ui?: { head?: string }+}>()+const cls = table()+</script>++<template>+ <th+ data-slot="table-head"+ scope="col"+ :colspan="colspan"+ :class="cls.head({ class: [ui?.head, normalizeClass(className)] })"+ >+ <span :class="{ 'sr-only': labelHidden }"><slot /></span>+ </th>+</template>diff --git a/src/components/ui/table/AppTableHeader.vue b/src/components/ui/table/AppTableHeader.vuenew file mode 100644index 000000000..e093866c5--- /dev/null+++ b/src/components/ui/table/AppTableHeader.vue@@ -0,0 +1,12 @@+<script setup lang="ts">+import { useTableUI, type TableUI } from './ui'++const { ui } = defineProps<{ ui?: TableUI }>()+const cls = useTableUI(ui)+</script>++<template>+ <thead data-slot="table-header" :class="cls.header">+ <slot />+ </thead>+</template>diff --git a/src/components/ui/table/AppTablePagination.vue b/src/components/ui/table/AppTablePagination.vuenew file mode 100644index 000000000..1d6e8152d--- /dev/null+++ b/src/components/ui/table/AppTablePagination.vue@@ -0,0 +1,32 @@+<script setup lang="ts">+import IconButton from '@/components/ui/button/IconButton.vue'++import { useTableUI, type TableUI } from './ui'++/** Where a page sits among a table's rows, and the buttons to the pages either side. */+const { range, canPrevious, canNext, previousLabel, nextLabel, ui } = defineProps<{+ /** Which rows the page shows of how many, such as “51–100 of 230”. */+ range: string+ canPrevious: boolean+ canNext: boolean+ previousLabel: string+ nextLabel: string+ ui?: TableUI+}>()+const emit = defineEmits<{ previous: []; next: [] }>()+const cls = useTableUI(ui)+</script>++<template>+ <div data-slot="table-pagination" :class="cls.pagination">+ <span :class="cls.range">{{ range }}</span>+ <div :class="cls.pages">+ <IconButton :label="previousLabel" :disabled="!canPrevious" @click="emit('previous')">+ <icon-lucide-chevron-left class="size-3.5" />+ </IconButton>+ <IconButton :label="nextLabel" :disabled="!canNext" @click="emit('next')">+ <icon-lucide-chevron-right class="size-3.5" />+ </IconButton>+ </div>+ </div>+</template>diff --git a/src/components/ui/table/AppTablePlaceholder.vue b/src/components/ui/table/AppTablePlaceholder.vuenew file mode 100644index 000000000..00addc4d3--- /dev/null+++ b/src/components/ui/table/AppTablePlaceholder.vue@@ -0,0 +1,36 @@+<script setup lang="ts">+import AppSkeleton from '@/components/ui/feedback/AppSkeleton.vue'+import { skeleton } from '@/components/ui/feedback/skeleton'++import AppTableCell from './AppTableCell.vue'+import AppTableRow from './AppTableRow.vue'+import { useTableUI, type TableUI } from './ui'++/** How many rows of placeholders stand in for rows that have not loaded. */+const PLACEHOLDER_ROWS = 5++/**+ * Rows of grey bars in the table's own columns, before its first rows load; they fade in after a+ * moment so rows that arrive quickly replace nothing. The first column names a row, so it gets the+ * longer bar, and a column of actions gets none.+ */+const { columns, ui } = defineProps<{+ columns: readonly { id: string; class?: string; actions?: boolean }[]+ ui?: TableUI+}>()+const cls = useTableUI(ui)+const placeholders = skeleton()+</script>++<template>+ <tbody data-slot="table-placeholder" :class="[cls.body, placeholders.group()]">+ <AppTableRow v-for="row in PLACEHOLDER_ROWS" :key="row">+ <AppTableCell v-for="(column, index) in columns" :key="column.id" :class="column.class">+ <AppSkeleton+ v-if="!column.actions"+ :class="index === 0 ? 'w-40 max-w-full' : 'w-16 max-w-full'"+ />+ </AppTableCell>+ </AppTableRow>+ </tbody>+</template>diff --git a/src/components/ui/table/AppTableRow.vue b/src/components/ui/table/AppTableRow.vuenew file mode 100644index 000000000..f4d4ee114--- /dev/null+++ b/src/components/ui/table/AppTableRow.vue@@ -0,0 +1,12 @@+<script setup lang="ts">+import { useTableUI, type TableUI } from './ui'++const { ui } = defineProps<{ ui?: TableUI }>()+const cls = useTableUI(ui)+</script>++<template>+ <tr data-slot="table-row" :class="cls.row">+ <slot />+ </tr>+</template>diff --git a/src/components/ui/table/columns.ts b/src/components/ui/table/columns.tsnew file mode 100644index 000000000..6eadf3854--- /dev/null+++ b/src/components/ui/table/columns.ts@@ -0,0 +1,18 @@+/**+ * What a column says about its own look, in its TanStack `meta`: classes for its header and cells,+ * such as a width, an alignment, or hiding below a table width.+ */+export type TableColumnMeta = {+ class?: string+ /** A column of row actions: its header is read out but not shown, and it has no placeholder. */+ actions?: boolean+}++/** A column's meta as `TableColumnMeta`, whatever features its table was made with. */+export function tableColumnMeta(meta: unknown): TableColumnMeta {+ if (typeof meta !== 'object' || meta === null) return {}+ return {+ class: 'class' in meta && typeof meta.class === 'string' ? meta.class : undefined,+ actions: 'actions' in meta && meta.actions === true+ }+}diff --git a/src/components/ui/table/index.ts b/src/components/ui/table/index.tsnew file mode 100644index 000000000..da463aabc--- /dev/null+++ b/src/components/ui/table/index.ts@@ -0,0 +1,12 @@+export { default as AppDataTable } from './AppDataTable.vue'+export { default as AppTable } from './AppTable.vue'+export { default as AppTableBody } from './AppTableBody.vue'+export { default as AppTableCell } from './AppTableCell.vue'+export { default as AppTableEmpty } from './AppTableEmpty.vue'+export { default as AppTableHead } from './AppTableHead.vue'+export { default as AppTableHeader } from './AppTableHeader.vue'+export { default as AppTablePagination } from './AppTablePagination.vue'+export { default as AppTablePlaceholder } from './AppTablePlaceholder.vue'+export { default as AppTableRow } from './AppTableRow.vue'+export { tableColumnMeta, type TableColumnMeta } from './columns'+export { table, useTableUI, type TableUI } from './ui'diff --git a/src/components/ui/table/ui.ts b/src/components/ui/table/ui.tsnew file mode 100644index 000000000..6ce77d6f1--- /dev/null+++ b/src/components/ui/table/ui.ts@@ -0,0 +1,28 @@+import { tv } from 'tailwind-variants'++import type { ComponentUI } from '@/components/ui/types'+import tableTheme from '@/theme/table/index'++export const table = tv(tableTheme)++export type TableUI = ComponentUI<typeof tableTheme>++export function useTableUI(ui?: TableUI) {+ const cls = table()+ return {+ root: cls.root({ class: ui?.root }),+ scroller: cls.scroller({ class: ui?.scroller }),+ table: cls.table({ class: ui?.table }),+ header: cls.header({ class: ui?.header }),+ head: cls.head({ class: ui?.head }),+ body: cls.body({ class: ui?.body }),+ row: cls.row({ class: ui?.row }),+ cell: cls.cell({ class: ui?.cell }),+ empty: cls.empty({ class: ui?.empty }),+ refresh: cls.refresh({ class: ui?.refresh }),+ footer: cls.footer({ class: ui?.footer }),+ pagination: cls.pagination({ class: ui?.pagination }),+ range: cls.range({ class: ui?.range }),+ pages: cls.pages({ class: ui?.pages })+ }+}diff --git a/src/theme/cloud-portal/layout.ts b/src/theme/cloud-portal/layout.tsindex b7939e8fd..15fb7d5ee 100644--- a/src/theme/cloud-portal/layout.ts+++ b/src/theme/cloud-portal/layout.ts@@ -11,8 +11,14 @@ export const portalLayout = tv({barHost: 'truncate text-[11px] text-muted max-sm:hidden',barEnd: 'ml-auto flex items-center gap-2',console: 'flex min-h-0 flex-1 max-md:flex-col',- // Narrow screens turn the section list into one scrolling row above the page.- nav: 'max-md:h-auto max-md:w-full max-md:flex-row max-md:overflow-x-auto max-md:border-r-0 max-md:border-b max-md:p-1',+ // Narrow screens turn the section list into one row above the page that scrolls without a+ // scrollbar, fades where it hides sections, and has a chevron toward them, as the editor's+ // menu bar does.+ navFrame:+ 'flex shrink-0 bg-panel max-md:items-center max-md:border-b max-md:border-border max-md:pr-1',+ nav: 'scrollbar-none max-md:h-auto max-md:w-auto max-md:min-w-0 max-md:flex-1 max-md:flex-row max-md:overflow-x-auto max-md:border-r-0 max-md:p-1 data-overflow-end:mask-r-from-[calc(100%-2rem)] data-overflow-start:mask-l-from-[calc(100%-2rem)]',+ navScroll:+ 'flex h-6 w-5 shrink-0 cursor-pointer items-center justify-center rounded text-muted hover:bg-hover hover:text-surface data-start:order-first md:hidden',navGroup: 'max-md:flex-row max-md:items-center max-md:border-t-0 max-md:p-0',navHeader: 'max-md:hidden',navItems: 'max-md:flex-row',diff --git a/src/theme/cloud-portal/list.ts b/src/theme/cloud-portal/list.tsdeleted file mode 100644index c73d87424..000000000--- a/src/theme/cloud-portal/list.ts+++ /dev/null@@ -1,18 +0,0 @@-import { tv } from 'tailwind-variants'--/** Console lists, drawn like the home tab's list view. */-export const portalList = tv({- slots: {- toolbar: 'flex flex-wrap items-center gap-2',- list: 'overflow-hidden rounded-lg border border-border bg-panel',- row: 'flex min-h-14 items-center gap-3 border-b border-border px-4 py-2.5 last:border-b-0',- body: 'min-w-0 flex-1',- title: 'flex min-w-0 items-center gap-1.5 truncate text-xs font-medium text-surface',- detail: 'mt-0.5 truncate text-[11px] text-muted',- quote: 'mt-1 line-clamp-2 text-[11px] text-surface',- meta: 'hidden shrink-0 text-[11px] text-muted tabular-nums sm:block',- actions: 'flex shrink-0 items-center gap-1',- status:- 'shrink-0 rounded px-1.5 py-px text-[10px] font-medium data-[tone=neutral]:bg-panel-field data-[tone=neutral]:text-muted data-[tone=success]:bg-success/10 data-[tone=success]:text-success data-[tone=warning]:bg-warning-bg data-[tone=warning]:text-warning data-[tone=error]:bg-error-bg data-[tone=error]:text-error'- }-})diff --git a/src/theme/cloud-portal/table.ts b/src/theme/cloud-portal/table.tsnew file mode 100644index 000000000..39aba54c5--- /dev/null+++ b/src/theme/cloud-portal/table.ts@@ -0,0 +1,14 @@+import { tv } from 'tailwind-variants'++/** What console tables put in their cells and above them. */+export const portalTable = tv({+ slots: {+ toolbar: 'flex flex-wrap items-center gap-2',+ title: 'flex min-w-0 items-center gap-1.5 truncate text-xs font-medium text-surface',+ detail: 'mt-0.5 truncate text-[11px] text-muted',+ quote: 'line-clamp-2 text-[11px] text-surface',+ actions: 'flex items-center justify-end gap-1',+ status:+ 'inline-block shrink-0 rounded px-1.5 py-px text-[10px] font-medium whitespace-nowrap data-[tone=neutral]:bg-panel-field data-[tone=neutral]:text-muted data-[tone=success]:bg-success/10 data-[tone=success]:text-success data-[tone=warning]:bg-warning-bg data-[tone=warning]:text-warning data-[tone=error]:bg-error-bg data-[tone=error]:text-error'+ }+})diff --git a/src/theme/feedback/skeleton.ts b/src/theme/feedback/skeleton.tsnew file mode 100644index 000000000..3dd885d2a--- /dev/null+++ b/src/theme/feedback/skeleton.ts@@ -0,0 +1,15 @@+/**+ * Grey bars in the place of content that is still loading. A group of them fades in only after a+ * moment (`group`), so content that arrives quickly replaces nothing, and each bar pulses unless+ * motion is reduced.+ */+const skeletonTheme = {+ slots: {+ group:+ 'animate-in fade-in fill-mode-backwards delay-150 duration-200 motion-reduce:animate-none',+ bar: 'block h-2.5 animate-pulse rounded bg-panel-field motion-reduce:animate-none'+ }+} as const++export type SkeletonTheme = typeof skeletonTheme+export default skeletonThemediff --git a/src/theme/table/index.ts b/src/theme/table/index.tsnew file mode 100644index 000000000..602ead73f--- /dev/null+++ b/src/theme/table/index.ts@@ -0,0 +1,24 @@+/**+ * Rows under labelled columns. The frame is its own `table` container, so a column can hide below+ * a width of the space it is given (`@xl/table:table-cell`) rather than the window's.+ */+export default {+ slots: {+ root: '@container/table relative overflow-hidden rounded-lg border border-border bg-panel',+ scroller: 'overflow-x-auto',+ table: 'w-full border-collapse text-left text-xs text-surface',+ header: 'border-b border-border',+ head: 'h-8 px-3 align-middle text-[11px] font-medium whitespace-nowrap text-muted first:pl-4 last:pr-4',+ // While newer rows load the old ones stay, a little faded, so the table never jumps.+ body: 'transition-opacity duration-150 data-refreshing:opacity-60 motion-reduce:transition-none',+ row: 'border-b border-border transition-colors duration-100 last:border-b-0 hover:bg-hover/40 motion-reduce:transition-none',+ cell: 'h-12 px-3 py-2 align-middle first:pl-4 last:pr-4',+ empty: 'px-4 py-8',+ /** A bar that pulses along the top edge while newer rows load. */+ refresh: 'pointer-events-none absolute inset-x-0 top-0 z-10',+ footer: 'border-t border-border px-4 py-1.5',+ pagination: 'flex items-center justify-between gap-2 text-[11px] text-muted',+ range: 'tabular-nums',+ pages: 'flex items-center gap-0.5'+ }+} as constdiff --git a/src/views/cloud/ConsoleView.vue b/src/views/cloud/ConsoleView.vueindex 1de6166cb..b348a450f 100644--- a/src/views/cloud/ConsoleView.vue+++ b/src/views/cloud/ConsoleView.vue@@ -19,6 +19,8 @@ import SessionsSection from '@/components/cloud-portal/sections/SessionsSection.import type { PortalSection } from '@/components/cloud-portal/types'const ACCOUNT_SECTIONS = ['profile', 'security', 'sessions'] as const+/** Every section, and a few people's pages, stay loaded while others are shown. */+const SECTIONS_KEPT = 12const ADMIN_SECTIONS = ['overview', 'requests', 'people', 'email', 'activity'] as consttype AccountSectionId = (typeof ACCOUNT_SECTIONS)[number]type AdminSectionId = (typeof ADMIN_SECTIONS)[number]@@ -112,16 +114,17 @@ const sections = computed<PortalSection[]>(() => {const heading = computed(() => sections.value.find((section) => section.id === active.value)?.label ?? '')+// Null while the page's description waits on what it counts, so the layout keeps its line.const description = computed(() => {if (personId.value) return ''const value = messages.value- const descriptions: Record<SectionId, string> = {+ const descriptions: Record<SectionId, string | null> = {profile: value.profileDescription({ host: portal.host }),security: value.securityDescription({ host: portal.host }),sessions: value.sessionsDescription,overview: portal.host,requests: value.accessRequestsDescription,- people: peopleTotal.value === null ? '' : value.peopleDescription(peopleTotal.value),+ people: peopleTotal.value === null ? null : value.peopleDescription(peopleTotal.value),email: value.emailDeliveryDescription,activity: value.activityDescription}@@ -170,18 +173,26 @@ onMounted(() => void refreshWaiting())@select="select"@sign-out="signOut">- <ProfileSection v-if="active === 'profile'" />- <SecuritySection v-else-if="active === 'security'" />- <SessionsSection v-else-if="active === 'sessions'" />- <AdminOverviewSection v-else-if="active === 'overview'" @open="select" />- <AdminRequestsSection v-else-if="active === 'requests'" @changed="refreshWaiting" />- <AdminPersonSection v-else-if="personId" :user-id="personId" @back="select('people')" />- <AdminPeopleSection- v-else-if="active === 'people'"- @total="(count) => (peopleTotal = count)"- @open="openPerson"- />- <AdminEmailSection v-else-if="active === 'email'" />- <AdminActivitySection v-else />+ <!-- Sections keep what they loaded while another is shown, and load again on return. -->+ <KeepAlive :max="SECTIONS_KEPT">+ <ProfileSection v-if="active === 'profile'" />+ <SecuritySection v-else-if="active === 'security'" />+ <SessionsSection v-else-if="active === 'sessions'" />+ <AdminOverviewSection v-else-if="active === 'overview'" @open="select" />+ <AdminRequestsSection v-else-if="active === 'requests'" @changed="refreshWaiting" />+ <AdminPersonSection+ v-else-if="personId"+ :key="personId"+ :user-id="personId"+ @back="select('people')"+ />+ <AdminPeopleSection+ v-else-if="active === 'people'"+ @total="(count) => (peopleTotal = count)"+ @open="openPerson"+ />+ <AdminEmailSection v-else-if="active === 'email'" />+ <AdminActivitySection v-else />+ </KeepAlive></PortalConsoleLayout></template>diff --git a/tests/app/cloud-portal/state.test.ts b/tests/app/cloud-portal/state.test.tsnew file mode 100644index 000000000..8b2e2cf6b--- /dev/null+++ b/tests/app/cloud-portal/state.test.ts@@ -0,0 +1,101 @@+import { describe, expect, test } from 'bun:test'++import { effectScope, nextTick } from 'vue'++import { usePortalLoad } from '@/app/cloud-portal/state'++/** A load the test answers by hand, one request at a time. */+function pending() {+ let answer: (value: string) => void = () => undefined+ let refuse: (error: Error) => void = () => undefined+ const promise = new Promise<string>((resolve, reject) => {+ answer = resolve+ refuse = reject+ })+ return { promise, answer, refuse }+}++async function settle() {+ await nextTick()+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+}++describe('usePortalLoad', () => {+ test('tells a first load from a refresh, which keeps the value shown', async () => {+ const requests: ReturnType<typeof pending>[] = []+ const scope = effectScope(true)+ const load = scope.run(() =>+ usePortalLoad(() => {+ const request = pending()+ requests.push(request)+ return request.promise+ }, '')+ )+ if (!load) throw new Error('The load did not start')+ try {+ expect(load.status.value).toBe('loading')+ requests[0]?.answer('first')+ await settle()+ expect(load.status.value).toBe('ready')+ expect(load.data.value).toBe('first')++ const reloaded = load.reload()+ expect(load.status.value).toBe('refreshing')+ expect(load.data.value).toBe('first')+ requests[1]?.answer('second')+ await reloaded+ expect(load.status.value).toBe('ready')+ expect(load.data.value).toBe('second')++ // A failed refresh still has the last value to show.+ const failed = load.reload()+ requests[2]?.refuse(new Error('offline'))+ await failed+ expect(load.status.value).toBe('ready')+ expect(load.error.value).not.toBeNull()+ expect(load.data.value).toBe('second')+ } finally {+ scope.stop()+ }+ })++ test('counts only the newest request, as for its value', async () => {+ const requests: ReturnType<typeof pending>[] = []+ const scope = effectScope(true)+ const load = scope.run(() =>+ usePortalLoad(() => {+ const request = pending()+ requests.push(request)+ return request.promise+ }, '')+ )+ if (!load) throw new Error('The load did not start')+ try {+ // The page asks again before its first answer, which then arrives after the second failed.+ const again = load.reload()+ requests[1]?.refuse(new Error('offline'))+ await again+ requests[0]?.answer('stale')+ await settle()+ expect(load.status.value).toBe('failed')+ expect(load.data.value).toBe('')+ } finally {+ scope.stop()+ }+ })++ test('fails when nothing has loaded yet', async () => {+ const scope = effectScope(true)+ const load = scope.run(() => usePortalLoad(() => Promise.reject(new Error('offline')), ''))+ if (!load) throw new Error('The load did not start')+ try {+ await settle()+ expect(load.status.value).toBe('failed')+ expect(load.error.value).not.toBeNull()+ } finally {+ scope.stop()+ }+ })+})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 5eaaa486f..c931804bd 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -483,6 +483,7 @@ zh-cn:storage.waitlistOpenWebsitezh-cn:storage.waitlistUnavailablezh-cn:statuses.figmaShowszh-cn:statuses.presetHandoff+ja:cloudPortal.columnAddressja:cloudPortal.signInTitleja:cloudPortal.newHereja:cloudPortal.returnsToDesktop@@ -494,6 +495,7 @@ ja:cloudPortal.deviceWarningDescriptionja:cloudPortal.deviceApprovedDescriptionja:cloudPortal.deviceExpiredDescriptionja:cloudPortal.authenticatorOff+zh-cn:cloudPortal.columnAddresszh-cn:cloudPortal.signInTitlezh-cn:cloudPortal.newHerezh-cn:cloudPortal.returnsToDesktopdiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 2c1a62b71..6a7f77669 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -390,6 +390,7 @@ es:cloudPortal.deploymentOfficiales:cloudPortal.emailTransportSMTPes:cloudPortal.emailTransportCloudflarees:cloudPortal.pictureZoom+it:cloudPortal.filterEmailit:cloudPortal.productNameit:cloudPortal.emailit:cloudPortal.password@@ -409,6 +410,7 @@ it:cloudPortal.emailTransportSMTPit:cloudPortal.emailTransportCloudflareit:cloudPortal.emailKindOtherit:cloudPortal.pictureZoom+de:cloudPortal.columnStatusde:cloudPortal.productNamede:cloudPortal.namede:cloudPortal.sectionServer@@ -424,6 +426,9 @@ de:cloudPortal.deploymentOfficialde:cloudPortal.emailTransportSMTPde:cloudPortal.emailTransportCloudflarede:cloudPortal.pictureZoom+fr:cloudPortal.columnAction+fr:cloudPortal.columnActions+fr:cloudPortal.columnMessagefr:cloudPortal.productNamefr:cloudPortal.providerGooglefr:cloudPortal.providerApple@@ -452,6 +457,7 @@ zh-cn:cloudPortal.methodApplezh-cn:cloudPortal.deploymentOfficialzh-cn:cloudPortal.emailTransportSMTPzh-cn:cloudPortal.emailTransportCloudflare+pl:cloudPortal.columnStatuspl:cloudPortal.productNamepl:cloudPortal.emailPlaceholderpl:cloudPortal.providerGoogle