From 307018953750124efa9ecf1d9563abd3f4502c49 Mon Sep 17 00:00:00 2001 From: Aitor Alonso Date: Mon, 20 Apr 2026 21:58:54 +0200 Subject: [PATCH 1/8] fix: fixes 4186 Some database providers, like supabase, provides two URLs to access the database. A main URL behind pgBouncer's for load balancing, and a direct separated URL to perform migrations (running DDL operations), as does not support advisory locks or multi-statement DDL required by migrations. Before v3.1.0, adding `directUrl` along with `url` to `prisma/schema.prisma` was enought. Now, I'm making a commit to use direct url when set --- scripts/check-db.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/check-db.js b/scripts/check-db.js index 8c806cd8f..aaa128af5 100644 --- a/scripts/check-db.js +++ b/scripts/check-db.js @@ -67,7 +67,8 @@ async function checkDatabaseVersion() { async function applyMigration() { if (!process.env.SKIP_DB_MIGRATION) { - console.log(execSync('prisma migrate deploy').toString()); + const directUrl = process.env.DIRECT_DATABASE_URL || process.env.DATABASE_URL; + console.log(execSync('prisma migrate deploy', { env: { ...process.env, DATABASE_URL: directUrl } }).toString()); success('Database is up to date.'); } From 1e711d79e1a64ee2cb5944370caa1a10cb0039f0 Mon Sep 17 00:00:00 2001 From: Cobal Date: Sat, 25 Apr 2026 14:30:31 +0200 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=8C=90=20fix(i18n):=20add=20missing?= =?UTF-8?q?=20'saved'=20labels=20for=20german=20and=20swiss=20locales?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/intl/messages/de-CH.json | 1 + public/intl/messages/de-DE.json | 1 + 2 files changed, 2 insertions(+) diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json index fecef5cc1..019336190 100644 --- a/public/intl/messages/de-CH.json +++ b/public/intl/messages/de-CH.json @@ -338,6 +338,7 @@ "unique-events": "Einzigartige Ereignisse", "unique-visitors": "Einzigartigi Bsuecher", "uniqueCustomers": "Einzigartigi Kunde", + "saved": "Gspeichert", "unknown": "Unbekannt", "untitled": "Unbennant", "update": "Aktualisieren", diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json index e5be06cb9..3038b4a31 100644 --- a/public/intl/messages/de-DE.json +++ b/public/intl/messages/de-DE.json @@ -338,6 +338,7 @@ "unique-events": "Einzigartige Ereignisse", "unique-visitors": "Einzigartige Besucher", "uniqueCustomers": "Einzigartige Kunden", + "saved": "Gespeichert", "unknown": "Unbekannt", "untitled": "Unbenannt", "update": "Aktualisieren", From 17a00f62a449ec9b537528aed89c72f7a1c01fb4 Mon Sep 17 00:00:00 2001 From: JLUpengjiaji Date: Wed, 29 Apr 2026 14:57:24 +0800 Subject: [PATCH 3/8] =?UTF-8?q?fix:=20=E7=A7=BB=E9=99=A4=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E7=9A=84=E6=90=9C=E7=B4=A2=E6=9D=A1=E4=BB=B6=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E5=B9=B6=E4=BF=AE=E5=A4=8D=E6=90=9C=E7=B4=A2=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/queries/sql/getValues.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/queries/sql/getValues.ts b/src/queries/sql/getValues.ts index 8573335bf..cc5f3a489 100644 --- a/src/queries/sql/getValues.ts +++ b/src/queries/sql/getValues.ts @@ -83,10 +83,6 @@ async function clickhouseQuery(websiteId: string, column: string, filters: Query excludeDomain = `and referrer_domain != hostname and referrer_domain != ''`; } - if (search) { - searchQuery = `and positionCaseInsensitive(${column}, {search:String}) > 0`; - } - if (search) { if (decodeURIComponent(search).includes(',')) { searchQuery = `AND (${decodeURIComponent(search) From f6703d3d6d63ab9ec1d8b2560edcc399aab335bd Mon Sep 17 00:00:00 2001 From: JLUpengjiaji Date: Wed, 29 Apr 2026 15:04:08 +0800 Subject: [PATCH 4/8] =?UTF-8?q?refactor(data):=20=E9=87=8D=E6=9E=84=20JSON?= =?UTF-8?q?=20=E6=89=81=E5=B9=B3=E5=8C=96=E5=87=BD=E6=95=B0=E5=B9=B6?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 flattenJSON 重构为更简洁的递归实现 - 提取 KeyValueData 接口并导出 createKeyValue 函数 - 添加完整的单元测试覆盖所有功能 --- src/lib/__tests__/data.test.ts | 246 +++++++++++++++++++++++++++++++++ src/lib/data.ts | 55 +++----- 2 files changed, 269 insertions(+), 32 deletions(-) create mode 100644 src/lib/__tests__/data.test.ts diff --git a/src/lib/__tests__/data.test.ts b/src/lib/__tests__/data.test.ts new file mode 100644 index 000000000..61882f6c3 --- /dev/null +++ b/src/lib/__tests__/data.test.ts @@ -0,0 +1,246 @@ +import { DATA_TYPE } from '../constants'; +import { + flattenJSON, + createKeyValue, + isValidDateValue, + getDataType, + getStringValue, + objectToArray, + type KeyValueData, +} from '../data'; + +describe('isValidDateValue', () => { + test.each([ + ['2024-01-15T10:30:00Z', true], + ['2024-01-15T10:30:00.123Z', true], + ['2024-01-15T10:30:00+02:00', true], + ['not-a-date', false], + ['2024/01/15', false], + ['', false], + ])('validates datetime strings correctly (%s → %s)', (input, expected) => { + expect(isValidDateValue(input)).toBe(expected); + }); + + test('returns false for non-string values', () => { + expect(isValidDateValue(123 as any)).toBe(false); + expect(isValidDateValue(null as any)).toBe(false); + expect(isValidDateValue(undefined as any)).toBe(false); + }); +}); + +describe('getDataType', () => { + test.each([ + ['string', 'string'], + [123, 'number'], + [true, 'boolean'], + [null, 'object'], + [[], 'object'], + [{}, 'object'], + ['2024-01-15T10:30:00Z', 'date'], + ])('detects type correctly (%s → %s)', (input, expected) => { + expect(getDataType(input)).toBe(expected); + }); +}); + +describe('createKeyValue', () => { + test('handles string values', () => { + const result = createKeyValue('name', 'test'); + expect(result).toEqual({ + key: 'name', + value: 'test', + dataType: DATA_TYPE.string, + }); + }); + + test('handles number values', () => { + const result = createKeyValue('count', 42); + expect(result).toEqual({ + key: 'count', + value: 42, + dataType: DATA_TYPE.number, + }); + }); + + test('handles boolean values and converts to string', () => { + expect(createKeyValue('active', true)).toEqual({ + key: 'active', + value: 'true', + dataType: DATA_TYPE.boolean, + }); + expect(createKeyValue('active', false)).toEqual({ + key: 'active', + value: 'false', + dataType: DATA_TYPE.boolean, + }); + }); + + test('handles date strings', () => { + const dateStr = '2024-01-15T10:30:00Z'; + const result = createKeyValue('timestamp', dateStr); + expect(result).toEqual({ + key: 'timestamp', + value: dateStr, + dataType: DATA_TYPE.date, + }); + }); + + test('handles arrays and converts to JSON string', () => { + const arr = [1, 2, 3]; + const result = createKeyValue('items', arr); + expect(result).toEqual({ + key: 'items', + value: '[1,2,3]', + dataType: DATA_TYPE.array, + }); + }); + + test('handles null values', () => { + const result = createKeyValue('nullable', null); + expect(result.dataType).toBe(DATA_TYPE.array); + expect(result.value).toBe('null'); + }); +}); + +describe('getStringValue', () => { + test('formats number values with 4 decimal places', () => { + expect(getStringValue('42', DATA_TYPE.number)).toBe('42.0000'); + expect(getStringValue('3.14159', DATA_TYPE.number)).toBe('3.1416'); + }); + + test('converts date values to ISO string', () => { + const result = getStringValue('2024-01-15T10:30:00', DATA_TYPE.date); + expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/); + }); + + test('returns string values as-is for other types', () => { + expect(getStringValue('test', DATA_TYPE.string)).toBe('test'); + expect(getStringValue('true', DATA_TYPE.boolean)).toBe('true'); + }); +}); + +describe('objectToArray', () => { + test('converts object values to array', () => { + const obj = { a: 1, b: 2, c: 3 }; + const result = objectToArray(obj); + expect(result).toEqual([1, 2, 3]); + }); + + test('returns empty array for empty object', () => { + expect(objectToArray({})).toEqual([]); + }); +}); + +describe('flattenJSON', () => { + test('flattens simple object', () => { + const input = { + name: 'test', + count: 42, + }; + + const result = flattenJSON(input); + + expect(result).toHaveLength(2); + expect(result).toContainEqual(expect.objectContaining({ key: 'name', value: 'test' })); + expect(result).toContainEqual(expect.objectContaining({ key: 'count', value: 42 })); + }); + + test('flattens nested object with dot notation', () => { + const input = { + user: { + name: 'John', + age: 30, + }, + }; + + const result = flattenJSON(input); + + expect(result).toHaveLength(2); + expect(result).toContainEqual(expect.objectContaining({ key: 'user.name', value: 'John' })); + expect(result).toContainEqual(expect.objectContaining({ key: 'user.age', value: 30 })); + }); + + test('flattens deeply nested object', () => { + const input = { + level1: { + level2: { + level3: { + value: 'deep', + }, + }, + }, + }; + + const result = flattenJSON(input); + + expect(result).toHaveLength(1); + expect(result[0].key).toBe('level1.level2.level3.value'); + expect(result[0].value).toBe('deep'); + }); + + test('treats arrays as leaf values (converts to JSON string)', () => { + const input = { + tags: ['a', 'b', 'c'], + }; + + const result = flattenJSON(input); + + expect(result).toHaveLength(1); + expect(result[0].key).toBe('tags'); + expect(result[0].value).toBe('["a","b","c"]'); + expect(result[0].dataType).toBe(DATA_TYPE.array); + }); + + test('treats date strings as leaf values', () => { + const input = { + createdAt: '2024-01-15T10:30:00Z', + }; + + const result = flattenJSON(input); + + expect(result).toHaveLength(1); + expect(result[0].key).toBe('createdAt'); + expect(result[0].dataType).toBe(DATA_TYPE.date); + }); + + test('handles mixed nested and flat structure', () => { + const input = { + id: '123', + metadata: { + timestamp: '2024-01-15T10:30:00Z', + source: 'web', + details: { + referrer: 'google', + }, + }, + }; + + const result = flattenJSON(input); + const keys = result.map(r => r.key); + + expect(result).toHaveLength(4); + expect(keys).toContain('id'); + expect(keys).toContain('metadata.timestamp'); + expect(keys).toContain('metadata.source'); + expect(keys).toContain('metadata.details.referrer'); + }); + + test('returns empty array for empty object', () => { + expect(flattenJSON({})).toEqual([]); + }); + + test('converts boolean values to strings', () => { + const input = { + isActive: true, + isAdmin: false, + }; + + const result = flattenJSON(input); + + expect(result).toContainEqual( + expect.objectContaining({ key: 'isActive', value: 'true', dataType: DATA_TYPE.boolean }), + ); + expect(result).toContainEqual( + expect.objectContaining({ key: 'isAdmin', value: 'false', dataType: DATA_TYPE.boolean }), + ); + }); +}); diff --git a/src/lib/data.ts b/src/lib/data.ts index fe69edf04..07eae52a5 100644 --- a/src/lib/data.ts +++ b/src/lib/data.ts @@ -1,27 +1,26 @@ import { DATA_TYPE, DATETIME_REGEX } from './constants'; import type { DynamicDataType } from './types'; -export function flattenJSON( - eventData: Record, - keyValues: { key: string; value: any; dataType: DynamicDataType }[] = [], - parentKey = '', -): { key: string; value: any; dataType: DynamicDataType }[] { - return Object.keys(eventData).reduce( - (acc, key) => { - const value = eventData[key]; - const type = typeof eventData[key]; +export interface KeyValueData { + key: string; + value: any; + dataType: DynamicDataType; +} - // nested object - if (value && type === 'object' && !Array.isArray(value) && !isValidDateValue(value)) { - flattenJSON(value, acc.keyValues, getKeyName(key, parentKey)); - } else { - createKey(getKeyName(key, parentKey), value, acc); +export function flattenJSON(eventData: Record): KeyValueData[] { + function flatten(obj: Record, parentKey: string): KeyValueData[] { + return Object.entries(obj).flatMap(([key, value]) => { + const fullKey = parentKey ? `${parentKey}.${key}` : key; + + if (value && typeof value === 'object' && !Array.isArray(value) && !isValidDateValue(value)) { + return flatten(value, fullKey); } - return acc; - }, - { keyValues, parentKey }, - ).keyValues; + return [createKeyValue(fullKey, value)]; + }); + } + + return flatten(eventData, ''); } export function isValidDateValue(value: string) { @@ -50,10 +49,10 @@ export function getStringValue(value: string, dataType: number) { return value; } -function createKey(key: string, value: string, acc: { keyValues: any[]; parentKey: string }) { +export function createKeyValue(key: string, value: any): KeyValueData { const type = getDataType(value); - - let dataType = null; + let dataType: DynamicDataType; + let processedValue = value; switch (type) { case 'number': @@ -64,29 +63,21 @@ function createKey(key: string, value: string, acc: { keyValues: any[]; parentKe break; case 'boolean': dataType = DATA_TYPE.boolean; - value = value ? 'true' : 'false'; + processedValue = value ? 'true' : 'false'; break; case 'date': dataType = DATA_TYPE.date; break; case 'object': dataType = DATA_TYPE.array; - value = JSON.stringify(value); + processedValue = JSON.stringify(value); break; default: dataType = DATA_TYPE.string; break; } - acc.keyValues.push({ key, value, dataType }); -} - -function getKeyName(key: string, parentKey: string) { - if (!parentKey) { - return key; - } - - return `${parentKey}.${key}`; + return { key, value: processedValue, dataType }; } export function objectToArray(obj: object) { From 55f515aa4dad3e5be05586779fc0504e62ad19b4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 4 May 2026 08:42:48 +0000 Subject: [PATCH 5/8] Bump uuid from 13.0.0 to 14.0.0 Bumps [uuid](https://github.com/uuidjs/uuid) from 13.0.0 to 14.0.0. - [Release notes](https://github.com/uuidjs/uuid/releases) - [Changelog](https://github.com/uuidjs/uuid/blob/main/CHANGELOG.md) - [Commits](https://github.com/uuidjs/uuid/compare/v13.0.0...v14.0.0) --- updated-dependencies: - dependency-name: uuid dependency-version: 14.0.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- package.json | 2 +- pnpm-lock.yaml | 60 +++++--------------------------------------------- 2 files changed, 7 insertions(+), 55 deletions(-) diff --git a/package.json b/package.json index 1d6fc31ee..8e6985cd2 100644 --- a/package.json +++ b/package.json @@ -112,7 +112,7 @@ "serialize-error": "^12.0.0", "thenby": "^1.3.4", "ua-parser-js": "^2.0.9", - "uuid": "^13.0.0", + "uuid": "^14.0.0", "zod": "^4.3.6", "zustand": "^5.0.12" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 740288d7a..b1367a1e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -192,8 +192,8 @@ importers: specifier: ^2.0.9 version: 2.0.9 uuid: - specifier: ^13.0.0 - version: 13.0.0 + specifier: ^14.0.0 + version: 14.0.0 zod: specifier: ^4.3.6 version: 4.3.6 @@ -313,8 +313,6 @@ importers: specifier: ^5.9.3 version: 5.9.3 - dist: {} - packages: '@ampproject/remapping@2.3.0': @@ -520,28 +518,24 @@ packages: engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [musl] '@biomejs/cli-linux-arm64@2.4.10': resolution: {integrity: sha512-7MH1CMW5uuxQ/s7FLST63qF8B3Hgu2HRdZ7tA1X1+mk+St4JOuIrqdhIBnnyqeyWJNI+Bww7Es5QZ0wIc1Cmkw==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [glibc] '@biomejs/cli-linux-x64-musl@2.4.10': resolution: {integrity: sha512-kDTi3pI6PBN6CiczsWYOyP2zk0IJI08EWEQyDMQWW221rPaaEz6FvjLhnU07KMzLv8q3qSuoB93ua6inSQ55Tw==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [musl] '@biomejs/cli-linux-x64@2.4.10': resolution: {integrity: sha512-tZLvEEi2u9Xu1zAqRjTcpIDGVtldigVvzug2fTuPG0ME/g8/mXpRPcNgLB22bGn6FvLJpHHnqLnwliOu8xjYrg==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [glibc] '@biomejs/cli-win32-arm64@2.4.10': resolution: {integrity: sha512-umwQU6qPzH+ISTf/eHyJ/QoQnJs3V9Vpjz2OjZXe9MVBZ7prgGafMy7yYeRGnlmDAn87AKTF3Q6weLoMGpeqdQ==} @@ -1108,105 +1102,89 @@ packages: resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} cpu: [arm64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-arm@1.2.4': resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} cpu: [arm] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.2.4': resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} cpu: [ppc64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.2.4': resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} cpu: [riscv64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-s390x@1.2.4': resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} cpu: [s390x] os: [linux] - libc: [glibc] '@img/sharp-libvips-linux-x64@1.2.4': resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} cpu: [x64] os: [linux] - libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.2.4': resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} cpu: [arm64] os: [linux] - libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.2.4': resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} cpu: [x64] os: [linux] - libc: [musl] '@img/sharp-linux-arm64@0.34.5': resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] - libc: [glibc] '@img/sharp-linux-arm@0.34.5': resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm] os: [linux] - libc: [glibc] '@img/sharp-linux-ppc64@0.34.5': resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [ppc64] os: [linux] - libc: [glibc] '@img/sharp-linux-riscv64@0.34.5': resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [riscv64] os: [linux] - libc: [glibc] '@img/sharp-linux-s390x@0.34.5': resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [s390x] os: [linux] - libc: [glibc] '@img/sharp-linux-x64@0.34.5': resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] - libc: [glibc] '@img/sharp-linuxmusl-arm64@0.34.5': resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] - libc: [musl] '@img/sharp-linuxmusl-x64@0.34.5': resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] - libc: [musl] '@img/sharp-wasm32@0.34.5': resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} @@ -1409,28 +1387,24 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] - libc: [glibc] '@next/swc-linux-arm64-musl@16.2.4': resolution: {integrity: sha512-iVMMp14514u7Nup2umQS03nT/bN9HurK8ufylC3FZNykrwjtx7V1A7+4kvhbDSCeonTVqV3Txnv0Lu+m2oDXNg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - libc: [musl] '@next/swc-linux-x64-gnu@16.2.4': resolution: {integrity: sha512-EZOvm1aQWgnI/N/xcWOlnS3RQBk0VtVav5Zo7n4p0A7UKyTDx047k8opDbXgBpHl4CulRqRfbw3QrX2w5UOXMQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [glibc] '@next/swc-linux-x64-musl@16.2.4': resolution: {integrity: sha512-h9FxsngCm9cTBf71AR4fGznDEDx1hS7+kSEiIRjq5kO1oXWm07DxVGZjCvk0SGx7TSjlUqhI8oOyz7NfwAdPoA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [musl] '@next/swc-win32-arm64-msvc@16.2.4': resolution: {integrity: sha512-3NdJV5OXMSOeJYijX+bjaLge3mJBlh4ybydbT4GFoB/2hAojWHtMhl3CYlYoMrjPuodp0nzFVi4Tj2+WaMg+Ow==} @@ -1485,42 +1459,36 @@ packages: engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm-musl@2.5.6': resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==} engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [musl] '@parcel/watcher-linux-arm64-glibc@2.5.6': resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm64-musl@2.5.6': resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [musl] '@parcel/watcher-linux-x64-glibc@2.5.6': resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-x64-musl@2.5.6': resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [musl] '@parcel/watcher-win32-arm64@2.5.6': resolution: {integrity: sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==} @@ -1925,79 +1893,66 @@ packages: resolution: {integrity: sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==} cpu: [arm] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.60.1': resolution: {integrity: sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==} cpu: [arm] os: [linux] - libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.60.1': resolution: {integrity: sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==} cpu: [arm64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.60.1': resolution: {integrity: sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==} cpu: [arm64] os: [linux] - libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.60.1': resolution: {integrity: sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==} cpu: [loong64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.60.1': resolution: {integrity: sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==} cpu: [loong64] os: [linux] - libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.60.1': resolution: {integrity: sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==} cpu: [ppc64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.60.1': resolution: {integrity: sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==} cpu: [ppc64] os: [linux] - libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.60.1': resolution: {integrity: sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==} cpu: [riscv64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.60.1': resolution: {integrity: sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==} cpu: [riscv64] os: [linux] - libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.60.1': resolution: {integrity: sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==} cpu: [s390x] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.60.1': resolution: {integrity: sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==} cpu: [x64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-musl@4.60.1': resolution: {integrity: sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==} cpu: [x64] os: [linux] - libc: [musl] '@rollup/rollup-openbsd-x64@4.60.1': resolution: {integrity: sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==} @@ -2162,28 +2117,24 @@ packages: engines: {node: '>=10'} cpu: [arm64] os: [linux] - libc: [glibc] '@swc/core-linux-arm64-musl@1.15.11': resolution: {integrity: sha512-PYftgsTaGnfDK4m6/dty9ryK1FbLk+LosDJ/RJR2nkXGc8rd+WenXIlvHjWULiBVnS1RsjHHOXmTS4nDhe0v0w==} engines: {node: '>=10'} cpu: [arm64] os: [linux] - libc: [musl] '@swc/core-linux-x64-gnu@1.15.11': resolution: {integrity: sha512-DKtnJKIHiZdARyTKiX7zdRjiDS1KihkQWatQiCHMv+zc2sfwb4Glrodx2VLOX4rsa92NLR0Sw8WLcPEMFY1szQ==} engines: {node: '>=10'} cpu: [x64] os: [linux] - libc: [glibc] '@swc/core-linux-x64-musl@1.15.11': resolution: {integrity: sha512-mUjjntHj4+8WBaiDe5UwRNHuEzLjIWBTSGTw0JT9+C9/Yyuh4KQqlcEQ3ro6GkHmBGXBFpGIj/o5VMyRWfVfWw==} engines: {node: '>=10'} cpu: [x64] os: [linux] - libc: [musl] '@swc/core-win32-arm64-msvc@1.15.11': resolution: {integrity: sha512-ZkNNG5zL49YpaFzfl6fskNOSxtcZ5uOYmWBkY4wVAvgbSAQzLRVBp+xArGWh2oXlY/WgL99zQSGTv7RI5E6nzA==} @@ -6005,12 +5956,13 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - uuid@13.0.0: - resolution: {integrity: sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==} + uuid@14.0.0: + resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==} hasBin: true uuid@8.3.2: resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true v8-compile-cache-lib@3.0.1: @@ -12171,7 +12123,7 @@ snapshots: util-deprecate@1.0.2: {} - uuid@13.0.0: {} + uuid@14.0.0: {} uuid@8.3.2: {} From f463a4ce3f1fdf8c8ba5b4e01f41c2f9dc3e4f5a Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 5 May 2026 10:48:56 -0700 Subject: [PATCH 6/8] rename propertyName parameter --- .../[websiteId]/sessions/SessionProperties.tsx | 2 +- .../[websiteId]/session-data/properties/route.ts | 6 +++--- .../hooks/queries/useSessionDataPropertiesQuery.ts | 8 ++++---- .../sql/sessions/getSessionDataProperties.ts | 14 +++++++------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/app/(main)/websites/[websiteId]/sessions/SessionProperties.tsx b/src/app/(main)/websites/[websiteId]/sessions/SessionProperties.tsx index 56643d2d8..cfc6d4f76 100644 --- a/src/app/(main)/websites/[websiteId]/sessions/SessionProperties.tsx +++ b/src/app/(main)/websites/[websiteId]/sessions/SessionProperties.tsx @@ -20,7 +20,7 @@ export function SessionProperties({ websiteId }: { websiteId: string }) { const { data, isLoading, isFetching, error } = usePropertyFieldsQuery('session', websiteId); const { data: scopedData } = useSessionDataPropertiesQuery( websiteId, - propertyName ? { selectedPropertyName: propertyName, propertyFilters } : undefined, + propertyName ? { propertyName, propertyFilters } : undefined, { enabled: !!propertyName }, ); diff --git a/src/app/api/websites/[websiteId]/session-data/properties/route.ts b/src/app/api/websites/[websiteId]/session-data/properties/route.ts index 61a5c13d9..8ac17e4b8 100644 --- a/src/app/api/websites/[websiteId]/session-data/properties/route.ts +++ b/src/app/api/websites/[websiteId]/session-data/properties/route.ts @@ -13,7 +13,7 @@ export async function GET( const schema = z.object({ startAt: z.coerce.number().int(), endAt: z.coerce.number().int(), - selectedPropertyName: z.string().optional(), + propertyName: z.string().optional(), ...filterParams, }); @@ -29,7 +29,7 @@ export async function GET( return unauthorized(); } - const { selectedPropertyName, ...rest } = query; + const { propertyName, ...rest } = query; const filters = await getQueryFilters(rest, websiteId); const propertyFilters = parsePropertyFilters(query); @@ -37,7 +37,7 @@ export async function GET( websiteId, filters, propertyFilters, - selectedPropertyName, + propertyName, ); return json(data); diff --git a/src/components/hooks/queries/useSessionDataPropertiesQuery.ts b/src/components/hooks/queries/useSessionDataPropertiesQuery.ts index fa52ae302..7bd041a0f 100644 --- a/src/components/hooks/queries/useSessionDataPropertiesQuery.ts +++ b/src/components/hooks/queries/useSessionDataPropertiesQuery.ts @@ -8,7 +8,7 @@ import { useFilterParameters } from '../useFilterParameters'; export function useSessionDataPropertiesQuery( websiteId: string, params?: { - selectedPropertyName?: string; + propertyName?: string; propertyFilters?: PropertyFilter[]; }, options?: ReactQueryOptions, @@ -16,14 +16,14 @@ export function useSessionDataPropertiesQuery( const { get, useQuery } = useApi(); const { startAt, endAt, unit, timezone } = useDateParameters(); const filters = useFilterParameters({ includePagination: false }); - const { selectedPropertyName, propertyFilters = [] } = params || {}; + const { propertyName, propertyFilters = [] } = params || {}; return useQuery({ queryKey: [ 'websites:session-data:properties', { websiteId, - selectedPropertyName, + propertyName, propertyFilters, startAt, endAt, @@ -38,7 +38,7 @@ export function useSessionDataPropertiesQuery( endAt, unit, timezone, - selectedPropertyName, + propertyName, ...serializePropertyFilters(propertyFilters), ...filters, }), diff --git a/src/queries/sql/sessions/getSessionDataProperties.ts b/src/queries/sql/sessions/getSessionDataProperties.ts index 446d8e465..2cae98b2c 100644 --- a/src/queries/sql/sessions/getSessionDataProperties.ts +++ b/src/queries/sql/sessions/getSessionDataProperties.ts @@ -10,7 +10,7 @@ export async function getSessionDataProperties( websiteId: string, filters: QueryFilters, propertyFilters?: PropertyFilter[], - selectedPropertyName?: string, + propertyName?: string, ] ) { return runQuery({ @@ -23,7 +23,7 @@ async function relationalQuery( websiteId: string, filters: QueryFilters, propertyFilters: PropertyFilter[] = [], - selectedPropertyName?: string, + propertyName?: string, ) { const { timezone = 'utc' } = filters; const { rawQuery, parseFilters, getPropertyFilterQuery } = prisma; @@ -56,7 +56,7 @@ async function relationalQuery( join filtered_sessions on filtered_sessions.session_id = session_data.session_id and filtered_sessions.website_id = session_data.website_id - ${selectedPropertyName ? 'where session_data.data_key = {{selectedPropertyName}}' : ''} + ${propertyName ? 'where session_data.data_key = {{propertyName}}' : ''} ) select data_key as "propertyName", @@ -70,7 +70,7 @@ async function relationalQuery( order by 3 desc, 1 asc limit 500 `, - { ...queryParams, websiteId, selectedPropertyName, ...pfParams }, + { ...queryParams, websiteId, propertyName, ...pfParams }, FUNCTION_NAME, ); } @@ -79,7 +79,7 @@ async function clickhouseQuery( websiteId: string, filters: QueryFilters, propertyFilters: PropertyFilter[] = [], - selectedPropertyName?: string, + propertyName?: string, ): Promise<{ propertyName: string; dataType: number; total: number }[]> { const { timezone = 'UTC' } = filters; const { rawQuery, parseFilters, getPropertyFilterQuery } = clickhouse; @@ -107,7 +107,7 @@ async function clickhouseQuery( join filtered_sessions on filtered_sessions.session_id = session_data.session_id and filtered_sessions.website_id = session_data.website_id - ${selectedPropertyName ? 'where session_data.data_key = {selectedPropertyName:String}' : ''} + ${propertyName ? 'where session_data.data_key = {propertyName:String}' : ''} ) select data_key as propertyName, @@ -123,7 +123,7 @@ async function clickhouseQuery( order by 3 desc, 1 asc limit 500 `, - { ...queryParams, websiteId, selectedPropertyName, ...pfParams }, + { ...queryParams, websiteId, propertyName, ...pfParams }, FUNCTION_NAME, ); } From 71893e4f89e077a72f2595472b586461b5b939ea Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Wed, 6 May 2026 09:51:28 -0700 Subject: [PATCH 7/8] fix maxheight on DialogButton --- src/components/input/DialogButton.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/input/DialogButton.tsx b/src/components/input/DialogButton.tsx index 6038d733b..98faf9d5d 100644 --- a/src/components/input/DialogButton.tsx +++ b/src/components/input/DialogButton.tsx @@ -42,7 +42,7 @@ export function DialogButton({ height, minWidth, minHeight, - maxHeight: 'calc(100dvh - 40px)', + maxHeight: 'min(80dvh, calc(100dvh - 40px))', overflowY: 'auto', padding: '32px', }; From 5ccfb6d0a52749897e8ea7ad32253d7bd0c9cd49 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Thu, 7 May 2026 10:46:03 -0700 Subject: [PATCH 8/8] implement datatable sorting on non-analytics tables. (website/board/link/pixel/team/admin) --- .../(main)/admin/teams/AdminTeamsTable.tsx | 13 ++- src/app/(main)/admin/users/UsersTable.tsx | 14 ++- .../admin/websites/AdminWebsitesTable.tsx | 11 ++- src/app/(main)/boards/BoardsTable.tsx | 16 +++- src/app/(main)/links/LinksTable.tsx | 13 ++- src/app/(main)/pixels/PixelsTable.tsx | 10 +- src/app/(main)/teams/TeamsTable.tsx | 3 +- .../teams/[teamId]/TeamWebsitesTable.tsx | 5 +- src/app/(main)/websites/WebsitesTable.tsx | 5 +- src/app/api/admin/teams/route.ts | 3 +- src/app/api/admin/users/route.ts | 3 +- src/app/api/admin/websites/route.ts | 3 +- src/app/api/boards/route.ts | 3 +- src/app/api/links/route.ts | 3 +- src/app/api/me/teams/route.ts | 3 +- src/app/api/me/websites/route.ts | 3 +- src/app/api/pixels/route.ts | 3 +- src/app/api/teams/[teamId]/boards/route.ts | 3 +- src/app/api/teams/[teamId]/links/route.ts | 3 +- src/app/api/teams/[teamId]/pixels/route.ts | 3 +- src/app/api/teams/[teamId]/websites/route.ts | 3 +- src/app/api/teams/route.ts | 3 +- src/app/api/users/[userId]/teams/route.ts | 3 +- src/app/api/users/[userId]/websites/route.ts | 3 +- src/app/api/websites/route.ts | 3 +- src/components/common/DataGrid.tsx | 2 +- src/components/common/Pager.tsx | 65 ++++++++----- src/components/common/SortableLabel.tsx | 94 +++++++++++++++++++ .../hooks/queries/useUserTeamsQuery.ts | 9 +- src/components/hooks/usePageParameters.ts | 6 +- src/components/hooks/usePagedQuery.ts | 6 +- src/lib/schema.ts | 10 ++ src/lib/sort.ts | 27 ++++++ src/queries/prisma/board.ts | 8 +- src/queries/prisma/link.ts | 8 +- src/queries/prisma/pixel.ts | 8 +- src/queries/prisma/team.ts | 8 +- src/queries/prisma/user.ts | 15 +-- src/queries/prisma/website.ts | 18 ++-- 39 files changed, 322 insertions(+), 100 deletions(-) create mode 100644 src/components/common/SortableLabel.tsx create mode 100644 src/lib/sort.ts diff --git a/src/app/(main)/admin/teams/AdminTeamsTable.tsx b/src/app/(main)/admin/teams/AdminTeamsTable.tsx index 8213b6d04..1f7cca5be 100644 --- a/src/app/(main)/admin/teams/AdminTeamsTable.tsx +++ b/src/app/(main)/admin/teams/AdminTeamsTable.tsx @@ -2,6 +2,7 @@ import { DataColumn, DataTable, Dialog, Icon, MenuItem, Modal, Row, Text } from import Link from '@/components/common/Link'; import { useState } from 'react'; import { DateDistance } from '@/components/common/DateDistance'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { Edit, Trash } from '@/components/icons'; import { MenuButton } from '@/components/input/MenuButton'; @@ -21,7 +22,11 @@ export function AdminTeamsTable({ return ( <> - + } + width="1fr" + > {(row: any) => {row.name}} @@ -41,7 +46,11 @@ export function AdminTeamsTable({ ); }} - + } + width="160px" + > {(row: any) => } {showActions && ( diff --git a/src/app/(main)/admin/users/UsersTable.tsx b/src/app/(main)/admin/users/UsersTable.tsx index fafe0e139..299cf3da3 100644 --- a/src/app/(main)/admin/users/UsersTable.tsx +++ b/src/app/(main)/admin/users/UsersTable.tsx @@ -2,6 +2,7 @@ import { DataColumn, DataTable, Icon, MenuItem, Modal, Row, Text } from '@umami/ import Link from '@/components/common/Link'; import { useState } from 'react'; import { DateDistance } from '@/components/common/DateDistance'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { Edit, Trash } from '@/components/icons'; import { MenuButton } from '@/components/input/MenuButton'; @@ -22,10 +23,14 @@ export function UsersTable({ return ( <> - + } + width="2fr" + > {(row: any) => {row.username}} - + }> {(row: any) => t(labels[Object.keys(ROLES).find(key => ROLES[key] === row.role)] || labels.unknown) } @@ -33,7 +38,10 @@ export function UsersTable({ {(row: any) => row._count.websites} - + } + > {(row: any) => } {showActions && ( diff --git a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx index 751dc7583..edf048120 100644 --- a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx +++ b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx @@ -3,6 +3,7 @@ import Link from '@/components/common/Link'; import { useState } from 'react'; import { WebsiteDeleteForm } from '@/app/(main)/websites/[websiteId]/settings/WebsiteDeleteForm'; import { DateDistance } from '@/components/common/DateDistance'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { Edit, Trash, Users } from '@/components/icons'; import { MenuButton } from '@/components/input/MenuButton'; @@ -14,14 +15,14 @@ export function AdminWebsitesTable({ data = [], ...props }: { data: any[] }) { return ( <> - + }> {(row: any) => ( {row.name} )} - + }> {(row: any) => {row.domain}} @@ -45,7 +46,11 @@ export function AdminWebsitesTable({ data = [], ...props }: { data: any[] }) { ); }} - + } + width="180px" + > {(row: any) => } diff --git a/src/app/(main)/boards/BoardsTable.tsx b/src/app/(main)/boards/BoardsTable.tsx index b21cbee00..0465012cc 100644 --- a/src/app/(main)/boards/BoardsTable.tsx +++ b/src/app/(main)/boards/BoardsTable.tsx @@ -1,6 +1,7 @@ import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-zen'; import Link from '@/components/common/Link'; import { DateDistance } from '@/components/common/DateDistance'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages, useNavigation } from '@/components/hooks'; import { BoardDeleteButton } from './BoardDeleteButton'; import { BoardDesignButton } from './BoardDesignButton'; @@ -12,16 +13,23 @@ export function BoardsTable(props: DataTableProps) { return ( - + }> {({ id, name }: any) => { return {name}; }} - - + } + /> + }> {({ type }: any) => type ? type.charAt(0).toUpperCase() + type.slice(1) : ''} - + } + width="200px" + > {(row: any) => } diff --git a/src/app/(main)/links/LinksTable.tsx b/src/app/(main)/links/LinksTable.tsx index bf9b5ef7f..1758272e9 100644 --- a/src/app/(main)/links/LinksTable.tsx +++ b/src/app/(main)/links/LinksTable.tsx @@ -2,6 +2,7 @@ import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-ze import Link from '@/components/common/Link'; import { DateDistance } from '@/components/common/DateDistance'; import { ExternalLink } from '@/components/common/ExternalLink'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages, useNavigation, useSlug } from '@/components/hooks'; import { LinkDeleteButton } from './LinkDeleteButton'; import { LinkEditButton } from './LinkEditButton'; @@ -17,23 +18,27 @@ export function LinksTable({ showActions, ...props }: LinksTableProps) { return ( - + }> {({ id, name }: any) => { return {name}; }} - + }> {({ slug }: any) => { const url = getSlugUrl(slug); return {url}; }} - + }> {({ url }: any) => { return {url}; }} - + } + width="200px" + > {(row: any) => } {showActions && ( diff --git a/src/app/(main)/pixels/PixelsTable.tsx b/src/app/(main)/pixels/PixelsTable.tsx index e9bc76ad8..362bffa78 100644 --- a/src/app/(main)/pixels/PixelsTable.tsx +++ b/src/app/(main)/pixels/PixelsTable.tsx @@ -2,6 +2,7 @@ import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-ze import Link from '@/components/common/Link'; import { DateDistance } from '@/components/common/DateDistance'; import { ExternalLink } from '@/components/common/ExternalLink'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages, useNavigation, useSlug } from '@/components/hooks'; import { PixelDeleteButton } from './PixelDeleteButton'; import { PixelEditButton } from './PixelEditButton'; @@ -17,12 +18,12 @@ export function PixelsTable({ showActions, ...props }: PixelsTableProps) { return ( - + }> {({ id, name }: any) => { return {name}; }} - + }> {({ slug }: any) => { const url = getSlugUrl(slug); return ( @@ -32,7 +33,10 @@ export function PixelsTable({ showActions, ...props }: PixelsTableProps) { ); }} - + } + > {(row: any) => } {showActions && ( diff --git a/src/app/(main)/teams/TeamsTable.tsx b/src/app/(main)/teams/TeamsTable.tsx index 66c7355ac..77515b7b2 100644 --- a/src/app/(main)/teams/TeamsTable.tsx +++ b/src/app/(main)/teams/TeamsTable.tsx @@ -1,5 +1,6 @@ import { DataColumn, DataTable, type DataTableProps } from '@umami/react-zen'; import type { ReactNode } from 'react'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { ROLES } from '@/lib/constants'; @@ -12,7 +13,7 @@ export function TeamsTable({ renderLink, ...props }: TeamsTableProps) { return ( - + }> {renderLink} diff --git a/src/app/(main)/teams/[teamId]/TeamWebsitesTable.tsx b/src/app/(main)/teams/[teamId]/TeamWebsitesTable.tsx index 86d846bb2..e57a10775 100644 --- a/src/app/(main)/teams/[teamId]/TeamWebsitesTable.tsx +++ b/src/app/(main)/teams/[teamId]/TeamWebsitesTable.tsx @@ -2,6 +2,7 @@ import { DataColumn, DataTable, Row } from '@umami/react-zen'; import Link from '@/components/common/Link'; import { TeamMemberEditButton } from '@/app/(main)/teams/[teamId]/TeamMemberEditButton'; import { TeamMemberRemoveButton } from '@/app/(main)/teams/[teamId]/TeamMemberRemoveButton'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages } from '@/components/hooks'; import { ROLES } from '@/lib/constants'; @@ -18,10 +19,10 @@ export function TeamWebsitesTable({ return ( - + }> {(row: any) => {row.name}} - + } /> {(row: any) => row?.createUser?.username} diff --git a/src/app/(main)/websites/WebsitesTable.tsx b/src/app/(main)/websites/WebsitesTable.tsx index 714e1c66c..bfa13e4ae 100644 --- a/src/app/(main)/websites/WebsitesTable.tsx +++ b/src/app/(main)/websites/WebsitesTable.tsx @@ -1,6 +1,7 @@ import { DataColumn, DataTable, type DataTableProps, Icon } from '@umami/react-zen'; import type { ReactNode } from 'react'; import { LinkButton } from '@/components/common/LinkButton'; +import { SortableLabel } from '@/components/common/SortableLabel'; import { useMessages, useNavigation } from '@/components/hooks'; import { SquarePen } from '@/components/icons'; @@ -17,10 +18,10 @@ export function WebsitesTable({ showActions, renderLink, ...props }: WebsitesTab return ( - + }> {renderLink} - + } /> {showActions && ( {(row: any) => { diff --git a/src/app/api/admin/teams/route.ts b/src/app/api/admin/teams/route.ts index ceb16ab11..35c3f5363 100644 --- a/src/app/api/admin/teams/route.ts +++ b/src/app/api/admin/teams/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewAllTeams } from '@/permissions'; import { getTeams } from '@/queries/prisma/team'; @@ -9,6 +9,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/admin/users/route.ts b/src/app/api/admin/users/route.ts index 2e5226157..0bf94d511 100644 --- a/src/app/api/admin/users/route.ts +++ b/src/app/api/admin/users/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewUsers } from '@/permissions'; import { getUsers } from '@/queries/prisma/user'; @@ -9,6 +9,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/admin/websites/route.ts b/src/app/api/admin/websites/route.ts index 09b2ef98d..0150e21fd 100644 --- a/src/app/api/admin/websites/route.ts +++ b/src/app/api/admin/websites/route.ts @@ -2,7 +2,7 @@ import { z } from 'zod'; import { ROLES } from '@/lib/constants'; import { parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewAllWebsites } from '@/permissions'; import { getWebsites } from '@/queries/prisma/website'; @@ -10,6 +10,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/boards/route.ts b/src/app/api/boards/route.ts index bb0710370..655486182 100644 --- a/src/app/api/boards/route.ts +++ b/src/app/api/boards/route.ts @@ -3,7 +3,7 @@ import { BOARD_TYPES, normalizeBoardType } from '@/lib/boards'; import { uuid } from '@/lib/crypto'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canCreateTeamWebsite, canCreateWebsite } from '@/permissions'; import { createBoard, getUserBoards } from '@/queries/prisma'; @@ -11,6 +11,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/links/route.ts b/src/app/api/links/route.ts index a639888bd..7c9172546 100644 --- a/src/app/api/links/route.ts +++ b/src/app/api/links/route.ts @@ -2,7 +2,7 @@ import { z } from 'zod'; import { uuid } from '@/lib/crypto'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canCreateTeamWebsite, canCreateWebsite } from '@/permissions'; import { createLink, getUserLinks } from '@/queries/prisma'; @@ -10,6 +10,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/me/teams/route.ts b/src/app/api/me/teams/route.ts index 555bf3003..12c6de43f 100644 --- a/src/app/api/me/teams/route.ts +++ b/src/app/api/me/teams/route.ts @@ -1,12 +1,13 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json } from '@/lib/response'; -import { pagingParams } from '@/lib/schema'; +import { pagingParams, sortingParams } from '@/lib/schema'; import { getUserTeams } from '@/queries/prisma'; export async function GET(request: Request) { const schema = z.object({ ...pagingParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/me/websites/route.ts b/src/app/api/me/websites/route.ts index 0880f84e1..809c6e502 100644 --- a/src/app/api/me/websites/route.ts +++ b/src/app/api/me/websites/route.ts @@ -1,12 +1,13 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json } from '@/lib/response'; -import { pagingParams } from '@/lib/schema'; +import { pagingParams, sortingParams } from '@/lib/schema'; import { getAllUserWebsitesIncludingTeamAccess, getUserWebsites } from '@/queries/prisma'; export async function GET(request: Request) { const schema = z.object({ ...pagingParams, + ...sortingParams, includeTeams: z.string().optional(), }); diff --git a/src/app/api/pixels/route.ts b/src/app/api/pixels/route.ts index 8baae4f3e..453ede247 100644 --- a/src/app/api/pixels/route.ts +++ b/src/app/api/pixels/route.ts @@ -2,7 +2,7 @@ import { z } from 'zod'; import { uuid } from '@/lib/crypto'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canCreateTeamWebsite, canCreateWebsite } from '@/permissions'; import { createPixel, getUserPixels } from '@/queries/prisma'; @@ -10,6 +10,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/teams/[teamId]/boards/route.ts b/src/app/api/teams/[teamId]/boards/route.ts index 2e60b77e2..b4e645e49 100644 --- a/src/app/api/teams/[teamId]/boards/route.ts +++ b/src/app/api/teams/[teamId]/boards/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewTeam } from '@/permissions'; import { getTeamBoards } from '@/queries/prisma'; @@ -9,6 +9,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ team const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { teamId } = await params; const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/teams/[teamId]/links/route.ts b/src/app/api/teams/[teamId]/links/route.ts index 41e139b33..4794902a1 100644 --- a/src/app/api/teams/[teamId]/links/route.ts +++ b/src/app/api/teams/[teamId]/links/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewTeam } from '@/permissions'; import { getTeamLinks } from '@/queries/prisma'; @@ -9,6 +9,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ team const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { teamId } = await params; const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/teams/[teamId]/pixels/route.ts b/src/app/api/teams/[teamId]/pixels/route.ts index daac2040d..2ce204f7b 100644 --- a/src/app/api/teams/[teamId]/pixels/route.ts +++ b/src/app/api/teams/[teamId]/pixels/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewTeam } from '@/permissions'; import { getTeamPixels } from '@/queries/prisma'; @@ -9,6 +9,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ team const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { teamId } = await params; const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/teams/[teamId]/websites/route.ts b/src/app/api/teams/[teamId]/websites/route.ts index 05c6d8045..5d010799b 100644 --- a/src/app/api/teams/[teamId]/websites/route.ts +++ b/src/app/api/teams/[teamId]/websites/route.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canViewTeam } from '@/permissions'; import { getTeamWebsites } from '@/queries/prisma'; @@ -9,6 +9,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ team const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, }); const { teamId } = await params; const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/teams/route.ts b/src/app/api/teams/route.ts index 2e2424a2f..6c79be7fc 100644 --- a/src/app/api/teams/route.ts +++ b/src/app/api/teams/route.ts @@ -5,13 +5,14 @@ import { fetchAccount } from '@/lib/load'; import redis from '@/lib/redis'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams } from '@/lib/schema'; +import { pagingParams, sortingParams } from '@/lib/schema'; import { canCreateTeam } from '@/permissions'; import { createTeam, getUserTeams } from '@/queries/prisma'; export async function GET(request: Request) { const schema = z.object({ ...pagingParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/users/[userId]/teams/route.ts b/src/app/api/users/[userId]/teams/route.ts index 7a834a3f1..ff8b88290 100644 --- a/src/app/api/users/[userId]/teams/route.ts +++ b/src/app/api/users/[userId]/teams/route.ts @@ -1,12 +1,13 @@ import { z } from 'zod'; import { parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams } from '@/lib/schema'; +import { pagingParams, sortingParams } from '@/lib/schema'; import { getUserTeams } from '@/queries/prisma'; export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) { const schema = z.object({ ...pagingParams, + ...sortingParams, }); const { auth, query, error } = await parseRequest(request, schema); diff --git a/src/app/api/users/[userId]/websites/route.ts b/src/app/api/users/[userId]/websites/route.ts index 4587354fb..c706dae9e 100644 --- a/src/app/api/users/[userId]/websites/route.ts +++ b/src/app/api/users/[userId]/websites/route.ts @@ -1,13 +1,14 @@ import { z } from 'zod'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { getAllUserWebsitesIncludingTeamAccess, getUserWebsites } from '@/queries/prisma/website'; export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, includeTeams: z.string().optional(), }); diff --git a/src/app/api/websites/route.ts b/src/app/api/websites/route.ts index 288ddfe30..fd4553fb8 100644 --- a/src/app/api/websites/route.ts +++ b/src/app/api/websites/route.ts @@ -4,7 +4,7 @@ import { uuid } from '@/lib/crypto'; import { fetchAccount } from '@/lib/load'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; -import { pagingParams, searchParams } from '@/lib/schema'; +import { pagingParams, searchParams, sortingParams } from '@/lib/schema'; import { canCreateTeamWebsite, canCreateWebsite } from '@/permissions'; import { createShare, createWebsite, getWebsiteCount } from '@/queries/prisma'; import { getAllUserWebsitesIncludingTeamAccess, getUserWebsites } from '@/queries/prisma/website'; @@ -15,6 +15,7 @@ export async function GET(request: Request) { const schema = z.object({ ...pagingParams, ...searchParams, + ...sortingParams, includeTeams: z.string().optional(), }); diff --git a/src/components/common/DataGrid.tsx b/src/components/common/DataGrid.tsx index 8d18321cf..9a601a129 100644 --- a/src/components/common/DataGrid.tsx +++ b/src/components/common/DataGrid.tsx @@ -41,7 +41,7 @@ export function DataGrid({ const { data, error, isLoading, isFetching } = query; const { router, updateParams, query: queryParams } = useNavigation(); const [search, setSearch] = useState(queryParams?.search || data?.search || ''); - const showPager = allowPaging && data && (data.count > data.pageSize || data.isCapped); + const showPager = allowPaging && data && data.count > 0; const { isMobile } = useMobile(); const displayMode = isMobile ? 'cards' : undefined; diff --git a/src/components/common/Pager.tsx b/src/components/common/Pager.tsx index ff22dc70e..f3d72fb47 100644 --- a/src/components/common/Pager.tsx +++ b/src/components/common/Pager.tsx @@ -11,11 +11,18 @@ export interface PagerProps { className?: string; } -export function Pager({ page, pageSize, count, isCapped, onPageChange }: PagerProps) { +export function Pager({ + page, + pageSize, + count, + isCapped, + onPageChange, +}: PagerProps) { const { t, labels } = useMessages(); const maxPage = pageSize && count ? Math.ceil(+count / +pageSize) : 0; const lastPage = page === maxPage; const firstPage = page === 1; + const showNavigation = maxPage > 1 || isCapped; if (count === 0 || !maxPage) { return null; @@ -29,34 +36,40 @@ export function Pager({ page, pageSize, count, isCapped, onPageChange }: PagerPr } }; - if (maxPage === 1 && !isCapped) { - return null; - } - const displayCount = isCapped ? `10,000+` : (+count).toLocaleString(); return ( - - {t(labels.numberOfRecords, { x: displayCount })} - - - {t(labels.pageOf, { - current: page.toLocaleString(), - total: maxPage.toLocaleString(), - })} - - - - - + + {t(labels.numberOfRecords, { x: displayCount })} + + {showNavigation && ( + <> + + {t(labels.pageOf, { + current: page.toLocaleString(), + total: maxPage.toLocaleString(), + })} + + + + + + + )} ); diff --git a/src/components/common/SortableLabel.tsx b/src/components/common/SortableLabel.tsx new file mode 100644 index 000000000..c45550c8c --- /dev/null +++ b/src/components/common/SortableLabel.tsx @@ -0,0 +1,94 @@ +'use client'; + +import type { ReactNode } from 'react'; +import { Icon } from '@umami/react-zen'; +import { ChevronDown, ChevronUp } from '@/components/icons'; +import { useNavigation } from '@/components/hooks'; + +type SortDirection = 'asc' | 'desc'; + +export interface SortableLabelProps { + label: ReactNode; + sortKey: string; + defaultDirection?: SortDirection; +} + +export function SortableLabel({ + label, + sortKey, + defaultDirection = 'asc', +}: SortableLabelProps) { + const { router, query, updateParams } = useNavigation(); + const isActive = query.orderBy === sortKey; + const isDescending = query.sortDescending === 'true'; + const direction = isActive ? (isDescending ? 'desc' : 'asc') : undefined; + const activeColor = 'var(--text-primary)'; + + const getNextDirection = (): SortDirection => { + if (!isActive) { + return defaultDirection; + } + + return direction === 'desc' ? 'asc' : 'desc'; + }; + + const handleSort = () => { + const nextDirection = getNextDirection(); + + router.push( + updateParams({ + orderBy: sortKey, + sortDescending: nextDirection === 'desc' ? 'true' : undefined, + page: 1, + }), + ); + }; + + return ( + + ); +} diff --git a/src/components/hooks/queries/useUserTeamsQuery.ts b/src/components/hooks/queries/useUserTeamsQuery.ts index 82f65496b..825e8def3 100644 --- a/src/components/hooks/queries/useUserTeamsQuery.ts +++ b/src/components/hooks/queries/useUserTeamsQuery.ts @@ -1,14 +1,15 @@ import { useApi } from '../useApi'; import { useModified } from '../useModified'; +import { usePagedQuery } from '../usePagedQuery'; export function useUserTeamsQuery(userId: string) { - const { get, useQuery } = useApi(); + const { get } = useApi(); const { modified } = useModified(`teams`); - return useQuery({ + return usePagedQuery({ queryKey: ['teams', { userId, modified }], - queryFn: () => { - return get(`/users/${userId}/teams`); + queryFn: params => { + return get(`/users/${userId}/teams`, params); }, enabled: !!userId, }); diff --git a/src/components/hooks/usePageParameters.ts b/src/components/hooks/usePageParameters.ts index 42cf3911c..0644e6900 100644 --- a/src/components/hooks/usePageParameters.ts +++ b/src/components/hooks/usePageParameters.ts @@ -3,7 +3,7 @@ import { useNavigation } from './useNavigation'; export function usePageParameters() { const { - query: { page, pageSize, search }, + query: { page, pageSize, search, orderBy, sortDescending }, } = useNavigation(); return useMemo(() => { @@ -11,6 +11,8 @@ export function usePageParameters() { page, pageSize, search, + orderBy, + sortDescending, }; - }, [page, pageSize, search]); + }, [orderBy, page, pageSize, search, sortDescending]); } diff --git a/src/components/hooks/usePagedQuery.ts b/src/components/hooks/usePagedQuery.ts index c818de643..73a1ead99 100644 --- a/src/components/hooks/usePagedQuery.ts +++ b/src/components/hooks/usePagedQuery.ts @@ -15,13 +15,13 @@ export function usePagedQuery({ queryFn: (params?: object) => Promise> | PageResult; }): UseQueryResult, TError> { const { - query: { page, search }, + query: { page, search, orderBy, sortDescending }, } = useNavigation(); const { useQuery } = useApi(); return useQuery, TError>({ - queryKey: [...queryKey, page, search] as const, - queryFn: () => queryFn({ page, search }), + queryKey: [...queryKey, page, search, orderBy, sortDescending] as const, + queryFn: () => queryFn({ page, search, orderBy, sortDescending }), ...options, }); } diff --git a/src/lib/schema.ts b/src/lib/schema.ts index 113b24cf8..71f8bb22b 100644 --- a/src/lib/schema.ts +++ b/src/lib/schema.ts @@ -82,6 +82,16 @@ export const pagingParams = { export const sortingParams = { orderBy: z.string().optional(), + sortDescending: z + .enum(['true', 'false']) + .optional() + .transform(value => { + if (value === undefined) { + return undefined; + } + + return value === 'true'; + }), }; export const userRoleParam = z.enum(['admin', 'user', 'view-only']); diff --git a/src/lib/sort.ts b/src/lib/sort.ts new file mode 100644 index 000000000..881c2371a --- /dev/null +++ b/src/lib/sort.ts @@ -0,0 +1,27 @@ +import type { QueryFilters } from './types'; + +export function sanitizeSortFilters( + filters: QueryFilters = {}, + allowedFields: T, + defaults: Partial> = {}, +): QueryFilters { + const { orderBy, sortDescending, ...rest } = filters; + const fallbackOrderBy = defaults.orderBy; + const fallbackSortDescending = defaults.sortDescending; + const isAllowed = orderBy ? allowedFields.includes(orderBy as T[number]) : false; + + return { + ...rest, + ...(isAllowed + ? { + orderBy, + sortDescending, + } + : { + ...(fallbackOrderBy && { orderBy: fallbackOrderBy }), + ...(fallbackSortDescending !== undefined && { + sortDescending: fallbackSortDescending, + }), + }), + }; +} diff --git a/src/queries/prisma/board.ts b/src/queries/prisma/board.ts index 862ec36dd..d433850d7 100644 --- a/src/queries/prisma/board.ts +++ b/src/queries/prisma/board.ts @@ -1,8 +1,11 @@ import type { Prisma } from '@/generated/prisma/client'; import { BOARD_TYPES } from '@/lib/boards'; import prisma from '@/lib/prisma'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { QueryFilters } from '@/lib/types'; +const BOARD_SORT_FIELDS = ['name', 'description', 'type', 'createdAt'] as const; + export async function findBoard(criteria: Prisma.BoardFindUniqueArgs) { return prisma.client.board.findUnique(criteria); } @@ -16,7 +19,8 @@ export async function getBoard(boardId: string) { } export async function getBoards(criteria: Prisma.BoardFindManyArgs, filters: QueryFilters = {}) { - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, BOARD_SORT_FIELDS); + const { search } = sortFilters; const { getSearchParameters, pagedQuery } = prisma; const where: Prisma.BoardWhereInput = { @@ -24,7 +28,7 @@ export async function getBoards(criteria: Prisma.BoardFindManyArgs, filters: Que ...getSearchParameters(search, [{ name: 'contains' }, { description: 'contains' }]), }; - return pagedQuery('board', { ...criteria, where }, filters); + return pagedQuery('board', { ...criteria, where }, sortFilters); } export async function getUserBoards(userId: string, filters?: QueryFilters) { diff --git a/src/queries/prisma/link.ts b/src/queries/prisma/link.ts index 9b971dec4..c59adc025 100644 --- a/src/queries/prisma/link.ts +++ b/src/queries/prisma/link.ts @@ -1,7 +1,10 @@ import type { Prisma } from '@/generated/prisma/client'; import prisma from '@/lib/prisma'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { QueryFilters } from '@/lib/types'; +const LINK_SORT_FIELDS = ['name', 'slug', 'url', 'createdAt'] as const; + export async function findLink(criteria: Prisma.LinkFindUniqueArgs) { return prisma.client.link.findUnique(criteria); } @@ -15,7 +18,8 @@ export async function getLink(linkId: string) { } export async function getLinks(criteria: Prisma.LinkFindManyArgs, filters: QueryFilters = {}) { - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, LINK_SORT_FIELDS); + const { search } = sortFilters; const { getSearchParameters, pagedQuery } = prisma; const where: Prisma.LinkWhereInput = { @@ -27,7 +31,7 @@ export async function getLinks(criteria: Prisma.LinkFindManyArgs, filters: Query ]), }; - return pagedQuery('link', { ...criteria, where }, filters); + return pagedQuery('link', { ...criteria, where }, sortFilters); } export async function getUserLinks(userId: string, filters?: QueryFilters) { diff --git a/src/queries/prisma/pixel.ts b/src/queries/prisma/pixel.ts index 4c9e132d5..2ea9c6f28 100644 --- a/src/queries/prisma/pixel.ts +++ b/src/queries/prisma/pixel.ts @@ -1,7 +1,10 @@ import type { Prisma } from '@/generated/prisma/client'; import prisma from '@/lib/prisma'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { QueryFilters } from '@/lib/types'; +const PIXEL_SORT_FIELDS = ['name', 'slug', 'createdAt'] as const; + export async function findPixel(criteria: Prisma.PixelFindUniqueArgs) { return prisma.client.pixel.findUnique(criteria); } @@ -15,14 +18,15 @@ export async function getPixel(pixelId: string) { } export async function getPixels(criteria: Prisma.PixelFindManyArgs, filters: QueryFilters = {}) { - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, PIXEL_SORT_FIELDS); + const { search } = sortFilters; const where: Prisma.PixelWhereInput = { ...criteria.where, ...prisma.getSearchParameters(search, [{ name: 'contains' }, { slug: 'contains' }]), }; - return prisma.pagedQuery('pixel', { ...criteria, where }, filters); + return prisma.pagedQuery('pixel', { ...criteria, where }, sortFilters); } export async function getUserPixels(userId: string, filters?: QueryFilters) { diff --git a/src/queries/prisma/team.ts b/src/queries/prisma/team.ts index de938df35..7315921e1 100644 --- a/src/queries/prisma/team.ts +++ b/src/queries/prisma/team.ts @@ -2,10 +2,13 @@ import { Prisma, type Team } from '@/generated/prisma/client'; import { ROLES } from '@/lib/constants'; import { uuid } from '@/lib/crypto'; import prisma from '@/lib/prisma'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { PageResult, QueryFilters } from '@/lib/types'; import TeamFindManyArgs = Prisma.TeamFindManyArgs; +const TEAM_SORT_FIELDS = ['name', 'createdAt'] as const; + export async function findTeam(criteria: Prisma.TeamFindUniqueArgs): Promise { return prisma.client.team.findUnique(criteria); } @@ -29,7 +32,8 @@ export async function getTeams( filters: QueryFilters, ): Promise> { const { getSearchParameters } = prisma; - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, TEAM_SORT_FIELDS); + const { search } = sortFilters; const where: Prisma.TeamWhereInput = { ...criteria.where, @@ -42,7 +46,7 @@ export async function getTeams( ...criteria, where, }, - filters, + sortFilters, ); } diff --git a/src/queries/prisma/user.ts b/src/queries/prisma/user.ts index 467ea1e02..0d9b1c4cf 100644 --- a/src/queries/prisma/user.ts +++ b/src/queries/prisma/user.ts @@ -2,10 +2,13 @@ import { Prisma } from '@/generated/prisma/client'; import { ROLES } from '@/lib/constants'; import { getRandomChars } from '@/lib/generate'; import prisma from '@/lib/prisma'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { QueryFilters, Role } from '@/lib/types'; import UserFindManyArgs = Prisma.UserFindManyArgs; +const USER_SORT_FIELDS = ['username', 'role', 'createdAt'] as const; + export interface GetUserOptions { includePassword?: boolean; showDeleted?: boolean; @@ -46,7 +49,11 @@ export async function getUserByUsername(username: string, options: GetUserOption } export async function getUsers(criteria: UserFindManyArgs, filters: QueryFilters = {}) { - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, USER_SORT_FIELDS, { + orderBy: 'createdAt', + sortDescending: true, + }); + const { search } = sortFilters; const where: Prisma.UserWhereInput = { ...criteria.where, @@ -60,11 +67,7 @@ export async function getUsers(criteria: UserFindManyArgs, filters: QueryFilters ...criteria, where, }, - { - orderBy: 'createdAt', - sortDescending: true, - ...filters, - }, + sortFilters, ); } diff --git a/src/queries/prisma/website.ts b/src/queries/prisma/website.ts index ae7ea6c96..254e27e15 100644 --- a/src/queries/prisma/website.ts +++ b/src/queries/prisma/website.ts @@ -2,8 +2,11 @@ import type { Prisma, Website } from '@/generated/prisma/client'; import { ROLES } from '@/lib/constants'; import prisma from '@/lib/prisma'; import redis from '@/lib/redis'; +import { sanitizeSortFilters } from '@/lib/sort'; import type { QueryFilters } from '@/lib/types'; +const WEBSITE_SORT_FIELDS = ['name', 'domain', 'createdAt'] as const; + export async function findWebsite(criteria: Prisma.WebsiteFindUniqueArgs) { return prisma.client.website.findUnique(criteria); } @@ -23,7 +26,8 @@ export async function getWebsite(websiteId: string) { } export async function getWebsites(criteria: Prisma.WebsiteFindManyArgs, filters: QueryFilters) { - const { search } = filters; + const sortFilters = sanitizeSortFilters(filters, WEBSITE_SORT_FIELDS); + const { search } = sortFilters; const { getSearchParameters, pagedQuery } = prisma; const where: Prisma.WebsiteWhereInput = { @@ -37,7 +41,7 @@ export async function getWebsites(criteria: Prisma.WebsiteFindManyArgs, filters: deletedAt: null, }; - const websites = await pagedQuery('website', { ...criteria, where }, filters); + const websites = await pagedQuery('website', { ...criteria, where }, sortFilters); return attachShareIdToWebsites(websites); } @@ -62,10 +66,7 @@ export async function getAllUserWebsitesIncludingTeamAccess(userId: string, filt ], }, }, - { - orderBy: 'name', - ...filters, - }, + sanitizeSortFilters(filters, WEBSITE_SORT_FIELDS, { orderBy: 'name' }), ); } @@ -84,10 +85,7 @@ export async function getUserWebsites(userId: string, filters?: QueryFilters) { }, }, }, - { - orderBy: 'name', - ...filters, - }, + sanitizeSortFilters(filters, WEBSITE_SORT_FIELDS, { orderBy: 'name' }), ); }