From abc0e65a86e394998658f6214130d85b84a84bc8 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 17:13:23 +0200 Subject: [PATCH 01/44] fix wrangler + send magic link --- apps/api/src/routers/clientInvites.ts | 20 +++++++++++++++++++- apps/clients/package.json | 2 +- apps/clients/tsconfig.tsbuildinfo | 1 + apps/clients/wrangler.toml | 7 +------ package.json | 1 + 5 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 apps/clients/tsconfig.tsbuildinfo diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index c93f7c0..ba91a15 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -56,7 +56,7 @@ const createClientInvite = (middlewareManager: ReturnType", + to: rawEmail, + subject: "Vous avez été invité sur Xtablo", + html: ` +

Vous avez été invité à collaborer sur un tablo

+

Bonjour,

+

Cliquez sur le lien ci-dessous pour accéder à votre espace client :

+

Accéder à mon espace

+

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.

+ `, + }); + } catch (emailError) { + console.error("Failed to send client invite email:", emailError); + } } return c.json({ success: true }); diff --git a/apps/clients/package.json b/apps/clients/package.json index 088606a..ce72e83 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -8,7 +8,7 @@ "build": "tsc -b && vite build --mode production", "build:staging": "tsc -b && vite build --mode staging", "build:prod": "tsc -b && vite build --mode production", - "deploy": "wrangler deploy", + "deploy:prod": "wrangler deploy --env=\"\"", "typecheck": "tsc -b", "lint": "biome check .", "lint:fix": "biome check --write .", diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo new file mode 100644 index 0000000..a7db947 --- /dev/null +++ b/apps/clients/tsconfig.tsbuildinfo @@ -0,0 +1 @@ +{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/clients/wrangler.toml b/apps/clients/wrangler.toml index 13aff9a..8baaf4a 100644 --- a/apps/clients/wrangler.toml +++ b/apps/clients/wrangler.toml @@ -1,6 +1,7 @@ name = "xtablo-clients" main = "worker/index.ts" compatibility_date = "2025-07-09" +route = { pattern = "clients.xtablo.com", custom_domain = true } [assets] directory = "./dist/" @@ -8,9 +9,3 @@ not_found_handling = "single-page-application" [observability] enabled = true - -[env.staging] -route = { pattern = "clients-staging.xtablo.com", custom_domain = true } - -[env.production] -route = { pattern = "clients.xtablo.com", custom_domain = true } diff --git a/package.json b/package.json index bf99826..5366d4f 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "deploy:main:prod": "turbo deploy:prod --filter=@xtablo/main", "deploy:chat": "turbo deploy --filter=@xtablo/chat-worker", "deploy:external": "turbo deploy --filter=@xtablo/external", + "deploy:clients": "turbo deploy:prod --filter=@xtablo/clients", "lint": "turbo lint", "lint:fix": "turbo lint:fix", "format": "turbo format", From 3c8e3c6af32956f557f1f4bb871319e809e1784d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 17:19:13 +0200 Subject: [PATCH 02/44] Add recipes in turbo.json --- turbo.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/turbo.json b/turbo.json index 48afb1d..1a1beb2 100644 --- a/turbo.json +++ b/turbo.json @@ -43,6 +43,28 @@ "cache": false, "persistent": true }, + "deploy": { + "dependsOn": ["build"], + "cache": false + }, + "deploy:staging": { + "dependsOn": ["build:staging"], + "cache": false + }, + "deploy:prod": { + "dependsOn": ["build:prod"], + "cache": false + }, + "build:staging": { + "dependsOn": ["^build"], + "outputs": ["dist/**"], + "outputLogs": "new-only" + }, + "build:prod": { + "dependsOn": ["^build"], + "outputs": ["dist/**"], + "outputLogs": "new-only" + }, "clean": { "cache": false } From 29debcbf25f838edda98819c7606cdf780ee0f0b Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 21:39:08 +0200 Subject: [PATCH 03/44] Fix session context --- apps/clients/.env.production | 4 ++++ packages/shared/src/contexts/SessionContext.tsx | 4 ++++ 2 files changed, 8 insertions(+) create mode 100644 apps/clients/.env.production diff --git a/apps/clients/.env.production b/apps/clients/.env.production new file mode 100644 index 0000000..f63a9df --- /dev/null +++ b/apps/clients/.env.production @@ -0,0 +1,4 @@ +VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co +VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM + +VITE_API_URL=https://xablo-api-636270553187.europe-west1.run.app diff --git a/packages/shared/src/contexts/SessionContext.tsx b/packages/shared/src/contexts/SessionContext.tsx index e4fb6a9..6827fee 100644 --- a/packages/shared/src/contexts/SessionContext.tsx +++ b/packages/shared/src/contexts/SessionContext.tsx @@ -21,6 +21,10 @@ export const SessionProvider = ({ supabase, children }: Props) => { const [session, setSession] = useState(null); useEffect(() => { + supabase.auth.getSession().then(({ data: { session } }) => { + setSession(session); + }); + const authStateListener = supabase.auth.onAuthStateChange(async (_, session) => { setSession(session); }); From ebf6d8a25532d98d874c0172ece33a8b16249db4 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 21:51:20 +0200 Subject: [PATCH 04/44] Avoid checking regularUserCheck in acceptClientInvite --- apps/api/src/routers/clientInvites.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index ba91a15..f14f977 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -89,8 +89,8 @@ const createClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, async (c) => { +const acceptClientInvite = (_middlewareManager: ReturnType) => + factory.createHandlers(async (c) => { const user = c.get("user"); const supabase = c.get("supabase"); const token = c.req.param("token"); From d69bfffd6fbccb18a44293f6fb47576df433d56a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:18:27 +0200 Subject: [PATCH 05/44] docs: add client portal tablo parity design spec --- ...04-15-client-portal-tablo-parity-design.md | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md diff --git a/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md b/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md new file mode 100644 index 0000000..8cedbad --- /dev/null +++ b/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md @@ -0,0 +1,216 @@ +# Client Portal Tablo Parity + +**Date**: 2026-04-15 +**Status**: Approved + +## Overview + +Make the client portal route in `apps/clients` match the visual design of the main app route `apps/main` `/tablos/:tabloId` as closely as possible. + +The target route in `apps/clients` remains `/tablo/:tabloId`, but it should present the same shell language as `TabloDetailsPage`: + +- same header structure +- same metadata bar +- same sticky tab navigation +- same overview card layout and styling +- same Tailwind/CSS visual system +- same translation strategy through i18n + +The client portal keeps its simpler local tab state and stays read-only except for discussion. + +## Goals + +- Match the current `apps/main` `TabloDetailsPage` look as closely as possible +- Prevent visual drift between `apps/main` and `apps/clients` +- Reuse the existing shared `@xtablo/tablo-views` section components +- Keep the client portal safe by removing admin and mutation affordances +- Use shared i18n keys wherever possible instead of hardcoded copy + +## Non-Goals + +- Rebuilding the client portal as a separate visual concept +- Copying the main app's `?section=` route model into `apps/clients` +- Enabling client file uploads, task completion, task creation, or layout editing +- Refactoring unrelated app-level layout or navigation outside the tablo detail view + +## Chosen Approach + +Use a shared presentational shell for the tablo detail page, backed by a shared stylesheet source. + +This shell should live close to the existing shared tablo view layer, likely in `packages/tablo-views`, because that package already contains the shared section components used by both apps. + +Each app remains responsible for its own routing, data hooks, and permissions: + +- `apps/main` keeps full `TabloDetailsPage` behavior +- `apps/clients` keeps local internal tab state and client-specific data loading + +The shared shell owns the route-level presentation so visual changes land in one place and are inherited by both apps. + +## Shared CSS Source + +Exact visual parity requires shared CSS, not just shared JSX. + +Today both apps import `@xtablo/ui/styles/globals.css`, but `apps/main/src/main.css` and `apps/clients/src/main.css` already diverge on important visual tokens such as: + +- navbar colors +- dark mode tokens +- chat surface colors +- other route-level color variables + +Because of that, `apps/clients` must not keep an independent competing style source for this page. + +### Requirement + +Extract the route-relevant visual styles currently coming from `apps/main/src/main.css` into a shared stylesheet layer that both apps import. + +This shared stylesheet should include whatever is required for the tablo detail route to render identically, including: + +- theme tokens needed by the page shell +- chat-related styling used in the discussion tab +- any utility styles relied on by the shared shell + +### Constraint + +Do not import `apps/main/src/main.css` directly from `apps/clients`. That would create brittle cross-app coupling and make ownership unclear. + +Instead: + +- move route-relevant shared styles into a shared import +- keep app-specific styles in each app-local `main.css` + +## Shared Shell Responsibilities + +The shared tablo detail shell should own: + +- the project header layout +- the icon/image block next to the project title +- header action placement +- the metadata bar layout and styling +- sticky tab navigation styling and behavior hooks +- the overview page card grid and visual treatment + +The shell should accept data and slots through props rather than owning app-specific mutations or routing decisions. + +Suggested inputs: + +- `tablo` +- status label and badge styling +- progress values +- role label +- created-at label +- tab definitions +- active tab +- tab change handler +- header action slot +- overview capability flags or overview card content +- per-section capability flags such as read-only settings + +## `apps/main` Responsibilities + +`apps/main` remains the owner of: + +- `?section=` URL state +- invite and share flows +- client invite management +- overview layout editing +- task creation and mutation +- file mutations +- admin-only controls + +The main app should adopt the shared shell without losing any existing behavior. + +## `apps/clients` Responsibilities + +`apps/clients` adopts the same visual shell, but keeps a restricted capability profile. + +### Navigation + +- Keep the current local tab state in React +- Do not add `?section=` routing +- Keep the same visible tab order, icons, and active styling as `apps/main` + +### Header + +- Keep the same header structure and spacing as `apps/main` +- Keep the discussion CTA styling and placement +- Remove the `Inviter` action entirely + +### Metadata Bar + +- Keep the same metadata structure and styling +- Use client-safe translated labels for role and status copy + +### Overview + +- Use the same card layout and card styling as the main app +- Remove layout edit controls +- Remove task creation controls +- Make task completion non-interactive +- Keep file previews informational only + +### Read-only Scope + +The client portal should be read-only except for discussion. + +That means: + +- `discussion`: interactive +- `tasks`: readable, no mutations +- `etapes`: readable, no mutations +- `events`: readable, no mutations +- `roadmap`: readable, no mutations +- `files`: readable, no upload, rename, move, create-folder, delete, or overflow action UI + +## i18n + +The shared shell must not introduce new hardcoded French strings. + +### Rules + +- Reuse existing translation keys from `apps/main` when the copy already matches the desired wording +- Add missing keys only where the shared shell needs copy that does not already exist +- Ensure both `apps/main` and `apps/clients` can resolve the keys used by the shared shell +- Prefer shared wording for labels like tab names, metadata labels, and overview headings + +This keeps parity at the copy level and avoids one app silently diverging from the other. + +## Testing And Verification + +Implementation should prove both parity and restrictions. + +### Automated + +- Add tests that verify the client shell renders the same key structure as the main shell +- Add tests that verify client mode hides admin and mutation controls +- Add tests that discussion remains interactive while other sections are read-only + +### Manual + +Perform side-by-side checks between: + +- `apps/main` `/tablos/:tabloId` +- `apps/clients` `/tablo/:tabloId` + +Compare at minimum: + +- header layout +- metadata bar +- sticky tabs +- overview cards +- tab content framing +- discussion styling + +## Risks + +- Shared CSS extraction may expose assumptions currently embedded in app-local stylesheets +- Some `TabloDetailsPage` copy is currently hardcoded and will need i18n cleanup before sharing +- If the shared shell grows to own business logic, parity will become harder to maintain + +## Success Criteria + +This work is successful when: + +- the client portal visually matches the main app tablo detail route +- the shared shell and shared style source make future parity maintainable +- the client portal remains read-only except for discussion +- the route continues to use simpler internal navigation rather than query-param section routing From 3c6a0fb037fa9a62a37dc52a99a34420356e0242 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:34:31 +0200 Subject: [PATCH 06/44] test: fix main app baseline chat and tablo tests --- apps/main/src/i18n.test.ts | 4 ++ .../src/pages/tablo-details.layout.test.tsx | 53 +++++++++++++++++++ apps/main/src/setupTests.ts | 1 + 3 files changed, 58 insertions(+) diff --git a/apps/main/src/i18n.test.ts b/apps/main/src/i18n.test.ts index 5254707..3dfccc7 100644 --- a/apps/main/src/i18n.test.ts +++ b/apps/main/src/i18n.test.ts @@ -2,6 +2,7 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import authEn from "./locales/en/auth.json"; import availabilitiesEn from "./locales/en/availabilities.json"; +import chatEn from "./locales/en/chat.json"; import commonEn from "./locales/en/common.json"; import componentsEn from "./locales/en/components.json"; import modalsEn from "./locales/en/modals.json"; @@ -13,6 +14,7 @@ import settingsEn from "./locales/en/settings.json"; import tabloEn from "./locales/en/tablo.json"; import authFr from "./locales/fr/auth.json"; import availabilitiesFr from "./locales/fr/availabilities.json"; +import chatFr from "./locales/fr/chat.json"; import commonFr from "./locales/fr/common.json"; import componentsFr from "./locales/fr/components.json"; import modalsFr from "./locales/fr/modals.json"; @@ -31,6 +33,7 @@ i18n.use(initReactI18next).init({ pages: pagesFr, settings: settingsFr, availabilities: availabilitiesFr, + chat: chatFr, auth: authFr, planning: planningFr, modals: modalsFr, @@ -44,6 +47,7 @@ i18n.use(initReactI18next).init({ pages: pagesEn, settings: settingsEn, availabilities: availabilitiesEn, + chat: chatEn, auth: authEn, planning: planningEn, modals: modalsEn, diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 67da71d..76bfe34 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -62,6 +62,20 @@ vi.mock("../hooks/tablo_invites", () => ({ }), })); +vi.mock("../hooks/client_invites", () => ({ + usePendingClientInvites: () => ({ + data: [], + }), + useCreateClientInvite: () => ({ + mutate: vi.fn(), + isPending: false, + }), + useCancelClientInvite: () => ({ + mutate: vi.fn(), + isPending: false, + }), +})); + vi.mock("../hooks/invite", () => ({ useInviteUser: () => ({ mutate: vi.fn(), @@ -69,6 +83,14 @@ vi.mock("../hooks/invite", () => ({ }), })); +vi.mock("../hooks/events", () => ({ + useEventsByTablo: () => ({ + data: [], + isLoading: false, + error: null, + }), +})); + vi.mock("../hooks/tasks", () => ({ useAllTasks: () => ({ data: [ @@ -97,6 +119,9 @@ vi.mock("../hooks/tasks", () => ({ useCreateTask: () => ({ mutate: vi.fn(), }), + useUpdateTaskPositions: () => ({ + mutate: vi.fn(), + }), })); vi.mock("../hooks/tablo_data", () => ({ @@ -105,6 +130,34 @@ vi.mock("../hooks/tablo_data", () => ({ fileNames: [], }, }), + useDownloadTabloFile: () => ({ + mutateAsync: vi.fn(), + }), + useUploadTabloFile: () => ({ + mutateAsync: vi.fn(), + }), + useDeleteTabloFile: () => ({ + mutateAsync: vi.fn(), + }), +})); + +vi.mock("../hooks/tablo_folders", () => ({ + useTabloFolders: () => ({ + data: [], + isLoading: false, + error: null, + }), + useCreateTabloFolder: () => ({ + mutateAsync: vi.fn(), + isPending: false, + }), + useUpdateTabloFolder: () => ({ + mutateAsync: vi.fn(), + isPending: false, + }), + useDeleteTabloFolder: () => ({ + mutateAsync: vi.fn(), + }), })); vi.mock("../providers/UserStoreProvider", async (importOriginal) => { diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 9960601..1fa4e83 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -23,6 +23,7 @@ global.ResizeObserver = class ResizeObserver { // Mock scrollIntoView for Radix UI components Element.prototype.scrollIntoView = vi.fn(); +Element.prototype.scrollTo = vi.fn(); Object.defineProperty(window, "matchMedia", { writable: true, From 01960a0102dd8a3838d82ad37b0a842facc9b11a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:34:37 +0200 Subject: [PATCH 07/44] test: add clients app vitest harness --- apps/clients/package.json | 7 +++ apps/clients/src/i18n.test.ts | 43 ++++++++++++++ apps/clients/src/i18n.ts | 20 +++++++ apps/clients/src/setupTests.ts | 31 +++++++++++ apps/clients/src/test/testHelpers.test.tsx | 11 ++++ apps/clients/src/test/testHelpers.tsx | 65 ++++++++++++++++++++++ apps/clients/vite.config.ts | 11 ++++ pnpm-lock.yaml | 15 +++++ 8 files changed, 203 insertions(+) create mode 100644 apps/clients/src/i18n.test.ts create mode 100644 apps/clients/src/setupTests.ts create mode 100644 apps/clients/src/test/testHelpers.test.tsx create mode 100644 apps/clients/src/test/testHelpers.tsx diff --git a/apps/clients/package.json b/apps/clients/package.json index ce72e83..68c5563 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -10,6 +10,8 @@ "build:prod": "tsc -b && vite build --mode production", "deploy:prod": "wrangler deploy --env=\"\"", "typecheck": "tsc -b", + "test": "vitest run --mode test --passWithNoTests", + "test:watch": "vitest watch --passWithNoTests", "lint": "biome check .", "lint:fix": "biome check --write .", "format": "biome format --write .", @@ -20,14 +22,19 @@ "@biomejs/biome": "2.2.5", "@cloudflare/vite-plugin": "^1.9.4", "@tailwindcss/vite": "^4.0.14", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.0", + "@testing-library/user-event": "^14.6.1", "@types/react": "19.0.10", "@types/react-dom": "19.0.4", "@vitejs/plugin-react": "^4.3.4", + "jsdom": "^20.0.3", "tailwindcss": "^4.0.14", "tw-animate-css": "^1.4.0", "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts new file mode 100644 index 0000000..e7747d7 --- /dev/null +++ b/apps/clients/src/i18n.test.ts @@ -0,0 +1,43 @@ +import i18n from "i18next"; +import { initReactI18next } from "react-i18next"; +import bookingEn from "./locales/en/booking.json"; +import bookingFr from "./locales/fr/booking.json"; +import chatEn from "../../main/src/locales/en/chat.json"; +import commonEn from "../../main/src/locales/en/common.json"; +import componentsEn from "../../main/src/locales/en/components.json"; +import pagesEn from "../../main/src/locales/en/pages.json"; +import tabloEn from "../../main/src/locales/en/tablo.json"; +import chatFr from "../../main/src/locales/fr/chat.json"; +import commonFr from "../../main/src/locales/fr/common.json"; +import componentsFr from "../../main/src/locales/fr/components.json"; +import pagesFr from "../../main/src/locales/fr/pages.json"; +import tabloFr from "../../main/src/locales/fr/tablo.json"; + +i18n.use(initReactI18next).init({ + resources: { + fr: { + booking: bookingFr, + chat: chatFr, + common: commonFr, + components: componentsFr, + pages: pagesFr, + tablo: tabloFr, + }, + en: { + booking: bookingEn, + chat: chatEn, + common: commonEn, + components: componentsEn, + pages: pagesEn, + tablo: tabloEn, + }, + }, + lng: "fr", + fallbackLng: "fr", + defaultNS: "booking", + interpolation: { + escapeValue: false, + }, +}); + +export default i18n; diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 334b18e..5612ccd 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -4,6 +4,16 @@ import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; // Import translation files import bookingFr from "./locales/fr/booking.json"; +import chatEn from "../../main/src/locales/en/chat.json"; +import commonEn from "../../main/src/locales/en/common.json"; +import componentsEn from "../../main/src/locales/en/components.json"; +import pagesEn from "../../main/src/locales/en/pages.json"; +import tabloEn from "../../main/src/locales/en/tablo.json"; +import chatFr from "../../main/src/locales/fr/chat.json"; +import commonFr from "../../main/src/locales/fr/common.json"; +import componentsFr from "../../main/src/locales/fr/components.json"; +import pagesFr from "../../main/src/locales/fr/pages.json"; +import tabloFr from "../../main/src/locales/fr/tablo.json"; i18n .use(LanguageDetector) @@ -12,9 +22,19 @@ i18n resources: { fr: { booking: bookingFr, + chat: chatFr, + common: commonFr, + components: componentsFr, + pages: pagesFr, + tablo: tabloFr, }, en: { booking: bookingEn, + chat: chatEn, + common: commonEn, + components: componentsEn, + pages: pagesEn, + tablo: tabloEn, }, }, fallbackLng: "fr", diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts new file mode 100644 index 0000000..ae81371 --- /dev/null +++ b/apps/clients/src/setupTests.ts @@ -0,0 +1,31 @@ +import "@testing-library/jest-dom"; +import { cleanup } from "@testing-library/react"; +import { vi } from "vitest"; +import "./i18n.test"; + +afterEach(() => { + cleanup(); +}); + +global.ResizeObserver = class ResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +}; + +Element.prototype.scrollIntoView = vi.fn(); +Element.prototype.scrollTo = vi.fn(); + +Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), +}); diff --git a/apps/clients/src/test/testHelpers.test.tsx b/apps/clients/src/test/testHelpers.test.tsx new file mode 100644 index 0000000..435c9bc --- /dev/null +++ b/apps/clients/src/test/testHelpers.test.tsx @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; +import { screen } from "@testing-library/react"; +import { renderWithProviders } from "./testHelpers"; + +describe("client test harness", () => { + it("renders a smoke test placeholder", () => { + renderWithProviders(
client test harness
); + + expect(screen.getByText("client test harness")).toBeInTheDocument(); + }); +}); diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx new file mode 100644 index 0000000..ede64d8 --- /dev/null +++ b/apps/clients/src/test/testHelpers.tsx @@ -0,0 +1,65 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { render, type RenderResult } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import React from "react"; +import { I18nextProvider } from "react-i18next"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import testI18n from "../i18n.test"; + +const defaultUser = { + id: "client-user-1", + app_metadata: {}, + aud: "test", + created_at: "2021-01-01", + email: "client@example.com", + user_metadata: { + full_name: "Client User", + }, +}; + +interface RenderWithProvidersOptions { + route?: string; + path?: string; + language?: string; +} + +export const renderWithProviders = ( + ui: React.ReactNode, + { route = "/", path, language = "fr" }: RenderWithProvidersOptions = {} +): RenderResult & { user: ReturnType } => { + testI18n.changeLanguage(language); + + const testQueryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + + const content = path ? ( + + + + ) : ( + ui + ); + + return { + user: userEvent.setup(), + ...render( + + + + + {content} + + + + + ), + }; +}; diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index dfed7ff..7b36df3 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -14,5 +14,16 @@ export default defineConfig(({ mode }) => { return { plugins, server: { cors: false }, + define: process.env.VITEST + ? { + "import.meta.env.VITE_SUPABASE_URL": JSON.stringify("https://test.supabase.co"), + "import.meta.env.VITE_SUPABASE_ANON_KEY": JSON.stringify("test-anon-key"), + } + : undefined, + test: { + globals: true, + environment: "jsdom", + setupFiles: "./src/setupTests.ts", + }, }; }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ecad098..e797dbd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -197,6 +197,15 @@ importers: '@tailwindcss/vite': specifier: ^4.0.14 version: 4.1.15(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + '@testing-library/jest-dom': + specifier: ^6.9.1 + version: 6.9.1 + '@testing-library/react': + specifier: ^16.3.0 + version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + '@testing-library/user-event': + specifier: ^14.6.1 + version: 14.6.1(@testing-library/dom@10.4.1) '@types/react': specifier: 19.0.10 version: 19.0.10 @@ -206,6 +215,9 @@ importers: '@vitejs/plugin-react': specifier: ^4.3.4 version: 4.7.0(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + jsdom: + specifier: ^20.0.3 + version: 20.0.3 tailwindcss: specifier: ^4.0.14 version: 4.1.15 @@ -221,6 +233,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) From 8f3927b68d06df96750a11ba13c7aaf88e4f3fbe Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:42:02 +0200 Subject: [PATCH 08/44] feat: align client tablo page with main shell --- apps/clients/src/main.tsx | 1 + .../src/pages/ClientTabloPage.test.tsx | 131 +++++++ apps/clients/src/pages/ClientTabloPage.tsx | 327 +++++++++++++++--- apps/clients/src/setupTests.ts | 2 +- apps/main/src/locales/en/pages.json | 6 + apps/main/src/locales/fr/pages.json | 6 + packages/tablo-views/package.json | 1 + .../tablo-views/src/TabloDetailsShell.tsx | 119 +++++++ packages/tablo-views/src/index.ts | 2 + .../src/styles/tablo-details-shell.css | 40 +++ 10 files changed, 588 insertions(+), 47 deletions(-) create mode 100644 apps/clients/src/pages/ClientTabloPage.test.tsx create mode 100644 packages/tablo-views/src/TabloDetailsShell.tsx create mode 100644 packages/tablo-views/src/styles/tablo-details-shell.css diff --git a/apps/clients/src/main.tsx b/apps/clients/src/main.tsx index d158df1..073fb40 100644 --- a/apps/clients/src/main.tsx +++ b/apps/clients/src/main.tsx @@ -10,6 +10,7 @@ import App from "./App"; import { supabase } from "./lib/supabase"; import "@xtablo/ui/styles/globals.css"; +import "@xtablo/tablo-views/styles/tablo-details-shell.css"; import "./main.css"; import "./i18n"; diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx new file mode 100644 index 0000000..8380d98 --- /dev/null +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -0,0 +1,131 @@ +import { screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ClientTabloPage } from "./ClientTabloPage"; + +vi.mock("@tanstack/react-query", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + useQuery: ({ queryKey }: { queryKey: string[] }) => { + switch (queryKey[0]) { + case "client-tablo": + return { + data: { + id: "tablo-1", + name: "Client Project", + color: "bg-blue-500", + image: null, + created_at: "2026-01-01T00:00:00.000Z", + deleted_at: null, + position: 0, + status: "todo", + user_id: "user-1", + is_admin: false, + access_level: "guest", + }, + isLoading: false, + }; + case "client-tasks": + return { + data: [ + { + id: "task-1", + title: "Prepare proposal", + status: "todo", + tablo_id: "tablo-1", + assignee_id: "client-user-1", + }, + ], + isLoading: false, + error: null, + }; + case "client-etapes": + return { + data: [ + { + id: "etape-1", + title: "Kickoff", + status: "in_progress", + position: 0, + }, + ], + isLoading: false, + error: null, + }; + case "client-events": + case "client-members": + case "client-tablo-folders": + return { + data: [], + isLoading: false, + error: null, + }; + case "client-tablo-files": + return { + data: { fileNames: [] }, + isLoading: false, + error: null, + }; + default: + return { + data: undefined, + isLoading: false, + error: null, + }; + } + }, + }; +}); + +vi.mock("@xtablo/tablo-views", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + EtapesSection: () =>
Etapes section
, + RoadmapSection: () =>
Roadmap section
, + TabloDiscussionSection: () =>
Discussion section
, + TabloEventsSection: () =>
Events section
, + TabloFilesSection: () =>
Files section
, + TabloTasksSection: () =>
Tasks section
, + }; +}); + +describe("ClientTabloPage parity shell", () => { + it("renders the main-route style header metadata and discussion CTA", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.getByText("Client Project")).toBeInTheDocument(); + expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2); + expect(screen.getByText("Rôle :")).toBeInTheDocument(); + expect(screen.getByText("Créé le :")).toBeInTheDocument(); + expect(screen.getByText("Progression :")).toBeInTheDocument(); + }); + + it("keeps client restrictions by hiding invite and layout-edit controls", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.queryByRole("button", { name: "Inviter" })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Modifier la mise en page" })).not.toBeInTheDocument(); + }); + + it("renders a read-only overview matching the main route cards", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.getByText("Description du projet")).toBeInTheDocument(); + expect(screen.getByText("Mes tâches")).toBeInTheDocument(); + expect(screen.getByText("Informations")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Ajouter" })).not.toBeInTheDocument(); + }); +}); diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 3da9be0..0f536d4 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,13 +1,34 @@ import { useQuery } from "@tanstack/react-query"; +import { cn } from "@xtablo/shared"; import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; -import { CalendarIcon, FolderIcon, KanbanIcon, ListChecksIcon, MapIcon, MessageCircleIcon } from "lucide-react"; +import { + CalendarIcon, + Compass, + Flame, + FolderIcon, + Gem, + Heart, + KanbanIcon, + LayoutDashboardIcon, + Leaf, + ListChecksIcon, + MapIcon, + MessageCircleIcon, + Sparkles, + Star, + Sun, + Waves, + Zap, +} from "lucide-react"; import { useState } from "react"; +import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, + TabloDetailsShell, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, @@ -137,12 +158,92 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } +function getTabloIcon(color: string | null | undefined) { + switch (color) { + case "bg-blue-500": + return Zap; + case "bg-green-500": + return Leaf; + case "bg-purple-500": + return Gem; + case "bg-red-500": + return Flame; + case "bg-yellow-500": + return Star; + case "bg-indigo-500": + return Compass; + case "bg-pink-500": + return Heart; + case "bg-teal-500": + return Waves; + case "bg-orange-500": + return Sun; + case "bg-cyan-500": + return Sparkles; + default: + return FolderIcon; + } +} + +function getTabloIconColor(color: string | null | undefined): string { + switch (color) { + case "bg-yellow-500": + case "bg-cyan-500": + return "text-gray-700"; + default: + return "text-white"; + } +} + +function getStatusConfig(status: string) { + switch (status) { + case "in_progress": + return { + label: "En cours", + badgeClass: + "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", + }; + case "done": + return { + label: "Terminé", + badgeClass: + "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", + }; + default: + return { + label: "À faire", + badgeClass: + "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", + }; + } +} + +function getEtapeProgressStats(etapes: Etape[]) { + const total = etapes.length; + const done = etapes.filter((etape) => etape.status === "done").length; + const started = etapes.filter((etape) => + new Set(["in_progress", "in_review", "done"]).has(etape.status ?? "todo") + ).length; + + if (total === 0) { + return { + startedPercentage: 0, + donePercentage: 0, + }; + } + + return { + startedPercentage: Math.round((started / total) * 100), + donePercentage: Math.round((done / total) * 100), + }; +} + // ─── Tabs ───────────────────────────────────────────────────────────────────── type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ - { id: "overview", label: "Aperçu", icon: ListChecksIcon }, + { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, { id: "etapes", label: "Étapes", icon: ListChecksIcon }, { id: "tasks", label: "Tâches", icon: KanbanIcon }, { id: "files", label: "Fichiers", icon: FolderIcon }, @@ -154,6 +255,7 @@ const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ // ─── Page ───────────────────────────────────────────────────────────────────── export function ClientTabloPage() { + const { t } = useTranslation(["pages", "chat"]); const { tabloId } = useParams<{ tabloId: string }>(); const { session } = useSession(); const [activeTab, setActiveTab] = useState("overview"); @@ -189,50 +291,184 @@ export function ClientTabloPage() { ); } - return ( -
- {/* Tablo header */} -
-

{tablo.name}

-
+ const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); + const progress = getEtapeProgressStats(etapes); + const isDiscussionView = activeTab === "discussion"; + const TabloIcon = getTabloIcon(tablo.color); + const iconColor = getTabloIconColor(tablo.color); - {/* Tab bar */} -
- -
- - {/* Tab content */} -
- {activeTab === "overview" && ( -
- {/* Simple overview: list etapes with progress */} - {}} - onCreateEtape={async () => {}} + const metadata = [ + { + key: "role", + label: t("pages:tablo.details.roleLabel"), + value: ( + {t("pages:tablo.role.guest")} + ), + }, + { + key: "created-at", + label: t("pages:tablo.details.createdAtLabel"), + value: ( + + {new Intl.DateTimeFormat("fr-FR", { + year: "numeric", + month: "short", + day: "2-digit", + }).format(new Date(tablo.created_at))} + + ), + }, + { + key: "status", + label: t("pages:tablo.details.statusLabel"), + value: {statusLabel}, + }, + { + key: "progress", + label: t("pages:tablo.details.progressLabel"), + value: ( + <> +
+
+
+
+ {progress.donePercentage}% + + ), + }, + ]; + + const headerVisual = ( +
+ {tablo.image ? ( + {tablo.name} + ) : ( + + )} +
+ ); + + const headerActions = ( + + ); + + return ( + setActiveTab(tabId as TabId)} + isDiscussionView={isDiscussionView} + > + {activeTab === "overview" && ( +
+
+
+

+ Description du projet +

+

+ Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les + onglets ci-dessus pour naviguer entre les différentes sections. +

+
+ +
+
+

+ Mes tâches +

+
+
+ {tasks.length === 0 ? ( +
+ Aucune tâche +
+ ) : ( + tasks.slice(0, 5).map((task) => ( +
+
+

+ {task.title} +

+
+ )) + )} +
+
+
+ +
+
+
+

Fichiers

+
+
+ {fileNames.length === 0 ? ( +

Aucun fichier

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+
+ +
+
+

{fileName}

+
+
+ )) + )} +
+
+ +
+

Informations

+
+
+
Tâches
+
{tasks.length}
+
+
+
Fichiers
+
{fileNames.length}
+
+
+
Statut
+
+ {statusLabel} +
+
+
+
Rôle
+
{t("pages:tablo.role.guest")}
+
+
+
+
)} @@ -304,7 +540,6 @@ export function ClientTabloPage() { onTaskStatusChange={() => {}} /> )} -
-
+ ); } diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index ae81371..23c7532 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -1,6 +1,6 @@ import "@testing-library/jest-dom"; import { cleanup } from "@testing-library/react"; -import { vi } from "vitest"; +import { afterEach, vi } from "vitest"; import "./i18n.test"; afterEach(() => { diff --git a/apps/main/src/locales/en/pages.json b/apps/main/src/locales/en/pages.json index 1c2f7e9..2a173a0 100644 --- a/apps/main/src/locales/en/pages.json +++ b/apps/main/src/locales/en/pages.json @@ -27,6 +27,12 @@ "admin": "Admin", "guest": "Guest" }, + "details": { + "roleLabel": "Role:", + "createdAtLabel": "Created on:", + "statusLabel": "Status:", + "progressLabel": "Progress:" + }, "status": { "todo": "To Do", "inProgress": "In Progress", diff --git a/apps/main/src/locales/fr/pages.json b/apps/main/src/locales/fr/pages.json index ea5cd2b..e8b8fb2 100644 --- a/apps/main/src/locales/fr/pages.json +++ b/apps/main/src/locales/fr/pages.json @@ -27,6 +27,12 @@ "admin": "Admin", "guest": "Invité" }, + "details": { + "roleLabel": "Rôle :", + "createdAtLabel": "Créé le :", + "statusLabel": "Statut :", + "progressLabel": "Progression :" + }, "status": { "todo": "À faire", "inProgress": "En cours", diff --git a/packages/tablo-views/package.json b/packages/tablo-views/package.json index 5de94b5..c0a5110 100644 --- a/packages/tablo-views/package.json +++ b/packages/tablo-views/package.json @@ -7,6 +7,7 @@ "types": "./src/index.ts", "exports": { ".": "./src/index.ts", + "./styles/tablo-details-shell.css": "./src/styles/tablo-details-shell.css", "./components/*": "./src/components/*.tsx", "./hooks/*": "./src/hooks/*.ts", "./*": "./src/*.tsx" diff --git a/packages/tablo-views/src/TabloDetailsShell.tsx b/packages/tablo-views/src/TabloDetailsShell.tsx new file mode 100644 index 0000000..b0eae62 --- /dev/null +++ b/packages/tablo-views/src/TabloDetailsShell.tsx @@ -0,0 +1,119 @@ +import { cn } from "@xtablo/shared"; +import type { UserTablo } from "@xtablo/shared-types"; + +type TabId = string; + +export interface TabloDetailsShellTab { + id: TabId; + label: string; + icon: React.ElementType; + disabled?: boolean; + hasUnread?: boolean; +} + +export interface TabloDetailsShellMetadataItem { + key: string; + label: string; + value: React.ReactNode; +} + +interface TabloDetailsShellProps { + tablo: Pick; + headerVisual?: React.ReactNode; + headerActions?: React.ReactNode; + metadata: TabloDetailsShellMetadataItem[]; + tabs: TabloDetailsShellTab[]; + activeTab: TabId; + onTabChange: (tabId: TabId) => void; + children: React.ReactNode; + isDiscussionView?: boolean; +} + +export function TabloDetailsShell({ + tablo, + headerVisual, + headerActions, + metadata, + tabs, + activeTab, + onTabChange, + children, + isDiscussionView = false, +}: TabloDetailsShellProps) { + return ( +
+
+
+
+ {headerVisual} +

{tablo.name}

+
+ + {headerActions &&
{headerActions}
} +
+ +
+ {metadata.map((item, index) => ( +
+ {item.label} + {item.value} +
+ ))} +
+
+ +
+
+
+ {tabs.map((tab) => { + const isActive = activeTab === tab.id; + return ( + + ); + })} +
+
+
+ +
+ {children} +
+
+ ); +} diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index eb6ae02..b67c572 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -6,6 +6,7 @@ export { EtapesSection } from "./EtapesSection"; export { RoadmapSection } from "./RoadmapSection"; export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; +export { TabloDetailsShell } from "./TabloDetailsShell"; // Sub-components export { GanttChart } from "./components/gantt/GanttChart"; @@ -18,3 +19,4 @@ export { useChatUnread } from "./hooks/useChatUnread"; // Types export type { TabloMember } from "./components/kanban/types"; +export type { TabloDetailsShellMetadataItem, TabloDetailsShellTab } from "./TabloDetailsShell"; diff --git a/packages/tablo-views/src/styles/tablo-details-shell.css b/packages/tablo-views/src/styles/tablo-details-shell.css new file mode 100644 index 0000000..c1a9286 --- /dev/null +++ b/packages/tablo-views/src/styles/tablo-details-shell.css @@ -0,0 +1,40 @@ +@import "@xtablo/chat-ui/chat-ui.css"; + +:root { + --navbar-background: rgb(249, 250, 251); + --navbar-darker: #e5e7eb; +} + +.dark { + --navbar-background: #1e1b2e; + --navbar-darker: #141121; +} + +.str-chat { + --str-chat__primary-color: #804eec; + --str-chat__active-primary-color: #6f3fd4; + --str-chat__surface-color: #f5f3f7; + --str-chat__secondary-surface-color: #e8e4ec; + --str-chat__primary-surface-color: #f4f3ff; + --str-chat__primary-surface-color-low-emphasis: #f8f7ff; + --str-chat__border-radius-circle: 6px; + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; +} + +.dark .str-chat { + --str-chat__primary-color: #9b6ff0; + --str-chat__active-primary-color: #804eec; + --str-chat__surface-color: rgba(128, 78, 236, 0.12); + --str-chat__secondary-surface-color: rgba(128, 78, 236, 0.08); + --str-chat__primary-surface-color: rgba(128, 78, 236, 0.1); + --str-chat__primary-surface-color-low-emphasis: rgba(128, 78, 236, 0.05); + --str-chat__background-color: rgba(30, 27, 46, 0.6); + --str-chat__secondary-background-color: rgba(20, 17, 33, 0.5); + --str-chat__border-color: rgba(128, 78, 236, 0.15); + --str-chat__text-color: #eeeaf5; + --str-chat__text-low-emphasis-color: #a8a0b8; + --str-chat__disabled-color: rgba(128, 78, 236, 0.2); + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; +} From 84d94c49e999f91abe4b521012d3d64739e77836 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 23:00:12 +0200 Subject: [PATCH 09/44] fix: align client portal shell and chat styles --- .../src/components/ClientLayout.test.tsx | 23 ++++ apps/clients/src/components/ClientLayout.tsx | 15 +-- apps/clients/src/main.css | 106 ++++++++++-------- apps/clients/src/mainCss.test.ts | 15 +++ 4 files changed, 105 insertions(+), 54 deletions(-) create mode 100644 apps/clients/src/components/ClientLayout.test.tsx create mode 100644 apps/clients/src/mainCss.test.ts diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx new file mode 100644 index 0000000..17c3972 --- /dev/null +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ClientLayout } from "./ClientLayout"; + +describe("ClientLayout", () => { + it("uses the main app style header shell and centered content container", () => { + const { container } = renderWithProviders(); + + const header = container.querySelector("header"); + expect(header).toHaveClass("h-[75px]"); + expect(header).toHaveClass("bg-navbar-background"); + + const headerInner = header?.firstElementChild; + expect(headerInner).toHaveClass("w-full"); + expect(headerInner).toHaveClass("max-w-7xl"); + expect(headerInner).toHaveClass("mx-auto"); + + const main = container.querySelector("main"); + expect(main).toHaveClass("w-full"); + expect(main).toHaveClass("max-w-7xl"); + expect(main).toHaveClass("mx-auto"); + }); +}); diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 20719a0..16609cf 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -36,14 +36,10 @@ export function ClientLayout() { }; return ( -
- {/* Top bar */} -
-
- {/* Brand */} - Xtablo - - {/* User info + logout */} +
+
+
+ Xtablo
@@ -58,8 +54,7 @@ export function ClientLayout() {
- {/* Page content */} -
+
diff --git a/apps/clients/src/main.css b/apps/clients/src/main.css index a896ff7..2782768 100644 --- a/apps/clients/src/main.css +++ b/apps/clients/src/main.css @@ -1,6 +1,8 @@ @import "tailwindcss"; @import "tw-animate-css"; +@source "../../../packages/chat-ui/src/**/*.{ts,tsx}"; + @custom-variant dark (&:is(.dark *)); :root { @@ -37,41 +39,45 @@ --sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-border: oklch(0.922 0 0); --sidebar-ring: oklch(0.708 0 0); + --navbar-background: rgb(249, 250, 251); + --navbar-darker: #e5e7eb; } .dark { - --background: oklch(0.145 0 0); - --foreground: oklch(0.985 0 0); - --card: oklch(0.145 0 0); - --card-foreground: oklch(0.985 0 0); - --popover: oklch(0.145 0 0); - --popover-foreground: oklch(0.985 0 0); - --primary: oklch(0.985 0 0); - --primary-foreground: oklch(0.205 0 0); - --secondary: oklch(0.269 0 0); - --secondary-foreground: oklch(0.985 0 0); - --muted: oklch(0.269 0 0); - --muted-foreground: oklch(0.708 0 0); - --accent: oklch(0.269 0 0); - --accent-foreground: oklch(0.985 0 0); + --background: oklch(0.17 0.012 290); + --foreground: oklch(0.985 0.005 290); + --card: oklch(0.16 0.014 290); + --card-foreground: oklch(0.985 0.005 290); + --popover: oklch(0.16 0.014 290); + --popover-foreground: oklch(0.985 0.005 290); + --primary: oklch(0.985 0.005 290); + --primary-foreground: oklch(0.2 0.012 290); + --secondary: oklch(0.22 0.018 290); + --secondary-foreground: oklch(0.985 0.005 290); + --muted: oklch(0.22 0.018 290); + --muted-foreground: oklch(0.65 0.02 290); + --accent: oklch(0.22 0.018 290); + --accent-foreground: oklch(0.985 0.005 290); --destructive: oklch(0.396 0.141 25.723); --destructive-foreground: oklch(0.637 0.237 25.331); - --border: oklch(0.269 0 0); - --input: oklch(0.269 0 0); - --ring: oklch(0.439 0 0); - --chart-1: oklch(0.488 0.243 264.376); + --border: oklch(0.26 0.02 290); + --input: oklch(0.26 0.02 290); + --ring: oklch(0.45 0.03 290); + --chart-1: oklch(0.55 0.2 290); --chart-2: oklch(0.696 0.17 162.48); --chart-3: oklch(0.769 0.188 70.08); --chart-4: oklch(0.627 0.265 303.9); --chart-5: oklch(0.645 0.246 16.439); - --sidebar: oklch(0.205 0 0); - --sidebar-foreground: oklch(0.985 0 0); - --sidebar-primary: oklch(0.488 0.243 264.376); - --sidebar-primary-foreground: oklch(0.985 0 0); - --sidebar-accent: oklch(0.269 0 0); - --sidebar-accent-foreground: oklch(0.985 0 0); - --sidebar-border: oklch(0.269 0 0); - --sidebar-ring: oklch(0.439 0 0); + --sidebar: oklch(0.18 0.016 290); + --sidebar-foreground: oklch(0.985 0.005 290); + --sidebar-primary: oklch(0.55 0.2 290); + --sidebar-primary-foreground: oklch(0.985 0.005 290); + --sidebar-accent: oklch(0.24 0.02 290); + --sidebar-accent-foreground: oklch(0.985 0.005 290); + --sidebar-border: oklch(0.26 0.02 290); + --sidebar-ring: oklch(0.45 0.03 290); + --navbar-background: #1e1b2e; + --navbar-darker: #141121; } @theme inline { @@ -111,8 +117,8 @@ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-border: var(--sidebar-border); --color-sidebar-ring: var(--sidebar-ring); - --color-navbar-background: #292e39; - --color-navbar-darker: #171920; + --color-navbar-background: var(--navbar-background); + --color-navbar-darker: var(--navbar-darker); } @layer base { @@ -122,31 +128,43 @@ body { @apply bg-background text-foreground; } + @media (display-mode: standalone) { + body { + padding-top: env(safe-area-inset-top); + padding-bottom: env(safe-area-inset-bottom); + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); + } + } } .str-chat { - --str-chat__primary-color: #8b7396; - --str-chat__active-primary-color: #6e5c7d; + --str-chat__primary-color: #804eec; + --str-chat__active-primary-color: #6f3fd4; --str-chat__surface-color: #f5f3f7; --str-chat__secondary-surface-color: #e8e4ec; - --str-chat__primary-surface-color: #ebe7f0; - --str-chat__primary-surface-color-low-emphasis: #f2f0f5; + --str-chat__primary-surface-color: #f4f3ff; + --str-chat__primary-surface-color-low-emphasis: #f8f7ff; --str-chat__border-radius-circle: 6px; + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; } .dark .str-chat { - --str-chat__primary-color: #a68bb5; - --str-chat__active-primary-color: #8b7396; - --str-chat__surface-color: rgba(120, 107, 130, 0.25); - --str-chat__secondary-surface-color: rgba(140, 130, 150, 0.18); - --str-chat__primary-surface-color: rgba(166, 139, 181, 0.12); - --str-chat__primary-surface-color-low-emphasis: rgba(166, 139, 181, 0.06); - --str-chat__background-color: rgba(110, 100, 120, 0.2); - --str-chat__secondary-background-color: rgba(80, 72, 88, 0.35); - --str-chat__border-color: rgba(120, 107, 130, 0.28); - --str-chat__text-color: #f5f3f7; - --str-chat__text-low-emphasis-color: #b8b0c0; - --str-chat__disabled-color: rgba(155, 143, 165, 0.35); + --str-chat__primary-color: #9b6ff0; + --str-chat__active-primary-color: #804eec; + --str-chat__surface-color: rgba(128, 78, 236, 0.12); + --str-chat__secondary-surface-color: rgba(128, 78, 236, 0.08); + --str-chat__primary-surface-color: rgba(128, 78, 236, 0.1); + --str-chat__primary-surface-color-low-emphasis: rgba(128, 78, 236, 0.05); + --str-chat__background-color: rgba(30, 27, 46, 0.6); + --str-chat__secondary-background-color: rgba(20, 17, 33, 0.5); + --str-chat__border-color: rgba(128, 78, 236, 0.15); + --str-chat__text-color: #eeeaf5; + --str-chat__text-low-emphasis-color: #a8a0b8; + --str-chat__disabled-color: rgba(128, 78, 236, 0.2); + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; } @keyframes gradient-x { diff --git a/apps/clients/src/mainCss.test.ts b/apps/clients/src/mainCss.test.ts new file mode 100644 index 0000000..c150cce --- /dev/null +++ b/apps/clients/src/mainCss.test.ts @@ -0,0 +1,15 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8"); + +describe("clients main.css", () => { + it("keeps the chat source and theme tokens aligned with the main app", () => { + expect(mainCss).toContain('@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain("--navbar-background: rgb(249, 250, 251);"); + expect(mainCss).toContain("--color-navbar-background: var(--navbar-background);"); + expect(mainCss).toContain("--str-chat__own-message-bubble-color: #804eec;"); + expect(mainCss).toContain("--str-chat__own-message-text-color: #ffffff;"); + }); +}); From b1c1c595abfe3ee480a70fa1e33c6e246ebae630 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 08:07:08 +0200 Subject: [PATCH 10/44] fix: restore standard tablo invite flow --- .../src/pages/tablo-details.layout.test.tsx | 17 + apps/main/src/pages/tablo-details.tsx | 313 ++++++++++++------ 2 files changed, 223 insertions(+), 107 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 76bfe34..e591c75 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -1,4 +1,5 @@ import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; import { TabloDetailsPage } from "./tablo-details"; @@ -195,4 +196,20 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument(); }); + + it("uses the standard email invite UI in the share dialog", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Inviter" })); + + expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument(); + expect(screen.queryByText("Accès client")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument(); + }); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index df06def..a9cd3e5 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -186,6 +186,9 @@ const TABS: { { id: "roadmap", label: "Roadmap", icon: MapIcon }, ]; +// Temporary rollback until the client portal invite flow is ready to be used again. +const USE_CLIENT_MAGIC_LINK_INVITES = false; + // ─── Page ───────────────────────────────────────────────────────────────────── export const TabloDetailsPage = () => { @@ -202,6 +205,7 @@ export const TabloDetailsPage = () => { ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); + const [inviteEmail, setInviteEmail] = useState(""); const [clientInviteEmail, setClientInviteEmail] = useState(""); const [isLayoutEditMode, setIsLayoutEditMode] = useState(false); const [draggedOverviewBlock, setDraggedOverviewBlock] = useState<{ @@ -255,6 +259,13 @@ export const TabloDetailsPage = () => { (member) => !pendingInvites?.some((invite) => invite.invited_email === member.email) ); + const handleSendInvite = () => { + if (!tabloId || !inviteEmail.trim()) return; + + inviteUser({ email: inviteEmail, tablo_id: tabloId }); + setInviteEmail(""); + }; + const openTaskModal = (dueDate?: Date) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); setIsTaskModalOpen(true); @@ -1002,117 +1013,205 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {/* Client Access Section */} -
-

Accès client

-

- Invitez des clients externes via un lien magique -

-
- - {/* Client Invite Input */} -
- setClientInviteEmail(e.target.value)} - placeholder="Email du client" - className="flex-1 min-h-[44px]" - /> - {isCreatingClientInvite ? ( -
-
+ {USE_CLIENT_MAGIC_LINK_INVITES ? ( + <> +
+

Accès client

+

+ Invitez des clients externes via un lien magique +

- ) : ( - - )} -
- {/* Pending Client Invites */} - {pendingClientInvites && pendingClientInvites.length > 0 && ( -
-

- Invitations client en attente ({pendingClientInvites.length}) -

-
- {pendingClientInvites.map((invite) => { - const daysUntilExpiry = Math.ceil( - (new Date(invite.expires_at).getTime() - Date.now()) / (1000 * 60 * 60 * 24) - ); - const isExpiringSoon = daysUntilExpiry < 5; - return ( -
-
- +
+
+
+ ) : ( + + )} +
+ + {pendingClientInvites && pendingClientInvites.length > 0 && ( +
+

+ Invitations client en attente ({pendingClientInvites.length}) +

+
+ {pendingClientInvites.map((invite) => { + const daysUntilExpiry = Math.ceil( + (new Date(invite.expires_at).getTime() - Date.now()) / + (1000 * 60 * 60 * 24) + ); + const isExpiringSoon = daysUntilExpiry < 5; + return ( +
- - -
-
- - {invite.invited_email} - - - {isExpiringSoon && "⚠ "} - Expire dans {daysUntilExpiry} jour{daysUntilExpiry !== 1 ? "s" : ""} - -
- {isExpiringSoon && ( - - Bientôt expiré - - )} - +
+ ); + })} +
+
+ )} + + ) : ( + <> +
+

Inviter un utilisateur

+

+ Utilisez le système d'invitation standard par email pour le moment +

+
+ +
+ setInviteEmail(e.target.value)} + placeholder="Email de l'utilisateur à inviter" + className="flex-1 min-h-[44px]" + /> + {isInvitingUser ? ( +
+
+
+ ) : ( + + )} +
+ + {pendingInvites && pendingInvites.length > 0 && ( +
+

+ Invitations en attente ({pendingInvites.length}) +

+
+ {pendingInvites.map((invite) => ( +
- - -
- ); - })} -
-
+
+ + + +
+
+ + {invite.invited_email} + + (En attente) +
+ +
+ ))} +
+
+ )} + )}
From 423d41989323c1b1358d68e6e58d3f3834390159 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 09:01:39 +0200 Subject: [PATCH 11/44] docs: add exact clients tablo parity design --- ...04-16-clients-exact-tablo-parity-design.md | 249 ++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md diff --git a/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md b/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md new file mode 100644 index 0000000..3b43b5a --- /dev/null +++ b/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md @@ -0,0 +1,249 @@ +# Clients Exact Tablo Parity + +**Date**: 2026-04-16 +**Status**: Draft +**Supersedes**: `docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md` + +## Overview + +`clients.xtablo.com` is intended to be a portal for the clients of our clients. For the single-tablo experience, it must render the exact same UI surface as `app.xtablo.com` on `apps/main/src/pages/tablo-details.tsx`. + +The current codebase does not guarantee that outcome because `apps/main` and `apps/clients` still compose the page separately. Shared sections and some shared CSS exist, but the full single-tablo route is not owned by one shared render surface. + +The target is stricter than "close parity": + +- same page shell +- same header structure +- same metadata row +- same tab bar +- same overview layout +- same section framing +- same responsive behavior +- same route-level CSS source +- same component tree for the single-tablo view + +The only intended differences are: + +- `apps/main` keeps URL-backed section state +- `apps/clients` keeps in-memory section state +- `apps/main` exposes full admin and mutation capabilities +- `apps/clients` exposes a restricted client-safe capability set + +## Problem Statement + +`clients.xtablo.com` is not at feature parity today for structural reasons, not because of one isolated CSS bug. + +### Current causes of drift + +1. `apps/clients/src/pages/ClientTabloPage.tsx` reconstructs a client-specific page instead of rendering the same single-tablo surface as `apps/main`. +2. `apps/clients/src/components/ClientLayout.tsx` owns a separate app shell, so spacing, header behavior, and responsive layout can drift from the main app. +3. Shared CSS exists only partially. Route-level tokens and chat/page styling have been extracted in places, but the full single-tablo view is still not governed by one shared route stylesheet plus one shared render tree. +4. Permissions are mixed into page composition instead of being expressed as a clean capability model. That forces `clients` to fork render logic instead of rendering the same surface with different behavior gates. + +The result is predictable: any visual or structural change to the main tablo route risks being manually reimplemented in `clients`, and parity becomes a maintenance task instead of an invariant. + +## Goals + +- Make the single-tablo UI in `clients.xtablo.com` visually identical to `apps/main/src/pages/tablo-details.tsx` +- Enforce parity through one shared single-tablo render surface +- Share the route-level CSS and responsive behavior between both apps +- Keep `apps/clients` on in-memory tab state +- Keep `discussion` writable in client mode +- Keep the rest of the client experience read-only or admin-hidden as approved + +## Non-Goals + +- Rebuilding the client portal as a separate visual concept +- Introducing query-param section routing into `apps/clients` +- Enabling client-side admin actions +- Refactoring unrelated routes outside the single-tablo experience +- Deleting the newer client-specific invite system from the codebase + +## Hard Requirement + +The UI must be the exact same. + +That rules out maintaining two parallel page compositions for the single-tablo route. "Shared components plus duplicated page assembly" is not sufficient because parity will drift again. The single-tablo view must be rendered from one shared composition surface consumed by both apps. + +## Chosen Approach + +Create a shared single-tablo route surface in `packages/tablo-views` and make both apps consume it. + +This shared surface owns the exact structure, responsive layout, CSS import, tab order, overview composition, and section framing for the route. + +Each app becomes a thin adapter: + +- `apps/main` passes full-capability handlers and URL-backed section state +- `apps/clients` passes restricted capabilities and in-memory section state + +This is a consolidation, not a styling pass. + +## Architecture + +### Shared package ownership + +`packages/tablo-views` should own the single-tablo route surface for both apps, including: + +- header layout +- title and icon/image block +- metadata row +- sticky tab navigation +- overview block composition +- section container layout +- discussion full-height layout behavior +- route-specific CSS for this surface + +This shared surface should render the same DOM structure and use the same styling hooks regardless of app. + +### App adapter ownership + +`apps/main` should own: + +- `?section=` query-param state +- full mutation handlers +- admin-only actions +- share and invite workflows +- main-only routing integrations + +`apps/clients` should own: + +- local in-memory tab state +- client-safe data loading +- capability restrictions +- client-safe app shell concerns outside the single-tablo surface + +### Key principle + +The apps must differ by inputs, not by page composition. + +## Capability Model + +The shared single-tablo surface should branch on capabilities rather than on app identity. + +Suggested capability contract: + +- `canCreateTasks` +- `canEditTasks` +- `canEditEvents` +- `canManageFiles` +- `canManageMembers` +- `canInviteMembers` +- `canEditLayout` +- `canWriteDiscussion` + +### Approved client boundary + +For `clients.xtablo.com`: + +- `discussion`: writable +- file read/download behavior: allowed where already supported +- task edits: disabled +- event edits: disabled +- layout edits: hidden +- member management: hidden or read-only +- invite/share management: hidden + +This preserves the same page structure while changing behavior safely. + +## CSS And Responsiveness + +Exact UI parity requires a single route-level CSS source for the single-tablo experience. + +### Requirements + +- the shared single-tablo surface imports one shared route stylesheet from `packages/tablo-views` +- route-level tokens for navbar, metadata, sticky tabs, and discussion/chat visuals come from that shared stylesheet +- responsive breakpoints and overflow behavior are not redefined independently in `apps/main` and `apps/clients` + +### Constraint + +`apps/clients` must not carry a competing route-specific single-tablo style layer that can override the shared surface in divergent ways. + +App-local CSS can remain for app-wide concerns, but the single-tablo route must have one styling owner. + +## State Model + +The visual surface is shared, but tab state differs by app. + +### Main app + +- active section comes from `?section=...` +- existing route behavior remains intact + +### Clients app + +- active section is stored in local React state +- no query-param synchronization is required + +This is acceptable because the user explicitly approved in-memory state for clients. + +## Migration Plan + +### Phase 1: Consolidate the surface + +- identify all remaining structure in `apps/main/src/pages/tablo-details.tsx` that is still page-owned instead of shared +- move that structure into a shared single-tablo route surface in `packages/tablo-views` +- make `apps/main` consume the shared surface first, preserving current behavior + +### Phase 2: Convert the clients app into an adapter + +- remove duplicated page composition from `apps/clients/src/pages/ClientTabloPage.tsx` +- replace it with a thin adapter that passes client-safe data and capability flags into the shared surface +- keep local in-memory tab state in the adapter only + +### Phase 3: Normalize the shell + +- ensure the surrounding shell and route-level CSS used by the single-tablo surface are shared consistently +- keep `ClientLayout` responsible only for client-portal app concerns, not for redefining the single-tablo view + +### Phase 4: Lock parity with tests + +- add tests that assert `main` and `clients` render the same shared single-tablo structure +- add client-mode tests for capability restrictions +- add responsive regression coverage where practical + +## Testing Strategy + +Verification must prove parity, not just correctness. + +### Automated + +- shared render tests for the single-tablo route surface in `packages/tablo-views` +- adapter tests proving `apps/main` and `apps/clients` pass different state/capabilities into the same surface +- regression tests that the client app hides or disables admin-only actions while keeping discussion writable +- targeted CSS contract tests ensuring both apps import the same shared route stylesheet + +### Manual + +Side-by-side comparison between: + +- `apps/main` `/tablos/:tabloId` +- `apps/clients` `/tablo/:tabloId` + +At minimum verify: + +- desktop layout +- mobile layout +- sticky tabs +- overview cards +- discussion layout +- header wrapping and spacing +- empty states + +## Risks + +- `apps/main/src/pages/tablo-details.tsx` may still contain too much mixed business logic and render logic, making extraction noisy +- some shared sections may still assume main-app permissions implicitly +- partial CSS ownership may continue to cause drift if not fully normalized +- client-safe data access may reveal places where the UI currently assumes admin or member-level data is always present + +## Success Criteria + +This work is successful when: + +- `clients.xtablo.com` renders the same single-tablo UI as `app.xtablo.com` +- future UI changes to the single-tablo route normally require edits in one shared place +- `apps/clients` remains in-memory for tab state +- client restrictions match the approved boundary +- discussion remains writable in client mode +- parity is enforced structurally, not maintained manually From 1a404bb4368d75d05345558073a00fe801cd739a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:09:27 +0200 Subject: [PATCH 12/44] fix: restore etape and task ui actions --- .../src/pages/tablo-details.layout.test.tsx | 55 +- apps/main/src/pages/tablo-details.tsx | 825 ++++-------------- packages/tablo-views/src/EtapesSection.tsx | 20 +- .../tablo-views/src/TabloTasksSection.tsx | 3 + .../src/components/kanban/TaskModal.tsx | 19 + 5 files changed, 267 insertions(+), 655 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index e591c75..17c103e 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -6,6 +6,8 @@ import { TabloDetailsPage } from "./tablo-details"; const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); +const mutateCreateEtape = vi.fn(); +const mutateDeleteTask = vi.fn(); const tablosData = [ { @@ -110,11 +112,14 @@ vi.mock("../hooks/tasks", () => ({ useUpdateTask: () => ({ mutate: mutateUpdateTask, }), + useDeleteTask: () => ({ + mutate: mutateDeleteTask, + }), useTask: () => ({ data: null, }), useCreateEtape: () => ({ - mutateAsync: vi.fn(), + mutateAsync: mutateCreateEtape, isPending: false, }), useCreateTask: () => ({ @@ -174,6 +179,54 @@ vi.mock("../providers/UserStoreProvider", async (importOriginal) => { }); describe("TabloDetailsPage overview layout", () => { + it("keeps the add etape action enabled before typing", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + + expect(screen.getByRole("button", { name: "Ajouter une étape" })).toBeEnabled(); + }); + + it("creates an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateCreateEtape.mockResolvedValueOnce(undefined); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.type(screen.getByPlaceholderText("Nom de la nouvelle étape..."), "Kickoff"); + await user.click(screen.getByRole("button", { name: "Ajouter une étape" })); + + expect(mutateCreateEtape).toHaveBeenCalledWith({ + tabloId: "tablo-1", + title: "Kickoff", + position: 0, + }); + }); + + it("deletes a task from the task modal", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Tâches" })); + await user.click(screen.getByText("Task A")); + await user.click(screen.getByRole("button", { name: "Supprimer la tâche" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); + it("renders overview cards in persisted left-zone order", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index a9cd3e5..50dfa93 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -1,15 +1,24 @@ import { LoadingSpinner } from "@ui/components/LoadingSpinner"; -import { cn, toast } from "@xtablo/shared"; +import { toast } from "@xtablo/shared"; import type { UserTablo } from "@xtablo/shared/types/tablos.types"; import type { KanbanTask } from "@xtablo/shared-types"; import { + DEFAULT_OVERVIEW_LAYOUT, EtapesSection, + type OverviewLayoutV1, RoadmapSection, + SingleTabloOverview, + SingleTabloView, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, TaskModal, + getSingleTabloStatusConfig, + moveBetweenZones, + moveWithinZone, + sanitizeOverviewLayout, + type SingleTabloTabId, useChatUnread, } from "@xtablo/tablo-views"; import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar"; @@ -22,33 +31,9 @@ import { DialogTitle, } from "@xtablo/ui/components/dialog"; import { Input } from "@xtablo/ui/components/input"; -import { - CalendarIcon, - CircleCheckIcon, - Compass, - EllipsisVerticalIcon, - FileTextIcon, - Flame, - FolderIcon, - Gem, - Heart, - KanbanIcon, - LayoutDashboardIcon, - Leaf, - ListChecksIcon, - MapIcon, - MessageCircleIcon, - PlusIcon, - Sparkles, - Star, - Sun, - UserPlusIcon, - Waves, - XIcon, - Zap, -} from "lucide-react"; +import { XIcon } from "lucide-react"; import { useEffect, useState } from "react"; -import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"; +import { useNavigate, useParams, useSearchParams } from "react-router-dom"; import { useCancelClientInvite, useCreateClientInvite, @@ -79,111 +64,24 @@ import { useAllTasks, useCreateEtape, useCreateTask, + useDeleteTask, useTabloEtapes, useUpdateTask, useUpdateTaskPositions, } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; import { getEtapeProgressStats } from "../utils/etapeProgress"; -import { - DEFAULT_OVERVIEW_LAYOUT, - type OverviewBlockId, - type OverviewLayoutV1, - sanitizeOverviewLayout, -} from "./tablo-details/overviewLayout"; -import { moveBetweenZones, moveWithinZone } from "./tablo-details/overviewReorder"; -// ─── Icon helpers ───────────────────────────────────────────────────────────── +type TabSection = SingleTabloTabId; -function getTabloIcon(color: string | null | undefined) { - switch (color) { - case "bg-blue-500": - return Zap; - case "bg-green-500": - return Leaf; - case "bg-purple-500": - return Gem; - case "bg-red-500": - return Flame; - case "bg-yellow-500": - return Star; - case "bg-indigo-500": - return Compass; - case "bg-pink-500": - return Heart; - case "bg-teal-500": - return Waves; - case "bg-orange-500": - return Sun; - case "bg-cyan-500": - return Sparkles; - default: - return FolderIcon; - } -} - -function getTabloIconColor(color: string | null | undefined): string { - switch (color) { - case "bg-yellow-500": - case "bg-cyan-500": - return "text-gray-700"; - default: - return "text-white"; - } -} - -// ─── Status helpers ─────────────────────────────────────────────────────────── - -function getStatusConfig(status: string) { - switch (status) { - case "in_progress": - return { - label: "En cours", - badgeClass: - "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", - }; - case "done": - return { - label: "Terminé", - badgeClass: - "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", - }; - default: - return { - label: "À faire", - badgeClass: - "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", - }; - } -} - -// ─── Tabs ───────────────────────────────────────────────────────────────────── - -type TabSection = - | "overview" - | "board" - | "list" - | "roadmap" - | "calendar" - | "files" - | "discussion" - | "events" - | "tasks" - | "etapes"; - -const TABS: { - id: TabSection; - label: string; - icon: React.ElementType; - disabled?: boolean; -}[] = [ - { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, - { id: "etapes", label: "Étapes", icon: ListChecksIcon }, - { id: "tasks", label: "Tâches", icon: KanbanIcon }, - { id: "files", label: "Fichiers", icon: FolderIcon }, - { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, - { id: "events", label: "Événements", icon: CalendarIcon }, - { id: "roadmap", label: "Roadmap", icon: MapIcon }, +const TAB_SECTIONS: TabSection[] = [ + "overview", + "etapes", + "tasks", + "files", + "discussion", + "events", + "roadmap", ]; // Temporary rollback until the client portal invite flow is ready to be used again. @@ -225,6 +123,7 @@ export const TabloDetailsPage = () => { const { mutate: cancelClientInvite, isPending: isCancellingClientInvite } = useCancelClientInvite(); const { mutate: updateTask } = useUpdateTask(); + const { mutate: deleteTask } = useDeleteTask(); const { mutate: updateTablo, mutateAsync: updateTabloAsync } = useUpdateTablo(); const { mutate: createTask } = useCreateTask(); const { mutateAsync: createEtape, isPending: isCreatingEtape } = useCreateEtape(); @@ -278,9 +177,7 @@ export const TabloDetailsPage = () => { const sectionParam = searchParams.get("section") as TabSection | null; const activeSection: TabSection = - sectionParam && TABS.some((t) => t.id === sectionParam && !t.disabled) - ? sectionParam - : "overview"; + sectionParam && TAB_SECTIONS.includes(sectionParam) ? sectionParam : "overview"; const [tablo, setTablo] = useState(null); @@ -330,11 +227,9 @@ export const TabloDetailsPage = () => { if (!tablo) return null; - const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); + const { label: statusLabel, badgeClass } = getSingleTabloStatusConfig(tablo.status); const progress = getEtapeProgressStats(etapes); const isAdmin = tablo.is_admin; - const TabloIcon = getTabloIcon(tablo.color); - const iconColor = getTabloIconColor(tablo.color); const persistOverviewLayout = ( nextLayout: OverviewLayoutV1, @@ -431,528 +326,165 @@ export const TabloDetailsPage = () => { }; return ( -
- {/* ── Header ──────────────────────────────────────────────────────── */} -
-
-
-
- {tablo.image ? ( - {tablo.name} - ) : ( - - )} -
-

{tablo.name}

-
+ <> + setSearchParams({ section: tabId })} + hasUnreadDiscussion={hasUnreadDiscussion} + discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} + canInviteMembers={isAdmin} + onOpenInviteDialog={() => setIsShareDialogOpen(true)} + > + {activeSection === "overview" && ( + setSearchParams({ section: "tasks" })} + onOpenFiles={() => setSearchParams({ section: "files" })} + onCreateTask={() => openTaskModal()} + onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} + showAllTasks={showAllOverviewTasks} + onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} + layout={overviewLayout} + canEditLayout={isAdmin} + isLayoutEditMode={isLayoutEditMode} + draggedBlock={draggedOverviewBlock} + onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} + onResetLayout={handleResetOverviewLayout} + onBlockDragStart={handleOverviewBlockDragStart} + onBlockDragOver={handleOverviewBlockDragOver} + onBlockDrop={handleOverviewBlockDrop} + onBlockDragEnd={() => setDraggedOverviewBlock(null)} + /> + )} -
- - - Discussion - - {isAdmin && ( - - )} -
-
- - {/* ── Metadata bar ──────────────────────────────────────────────── */} -
-
- Rôle : - {isAdmin ? "Admin" : "Invité"} -
-
- Créé le : - - {new Intl.DateTimeFormat("fr-FR", { - year: "numeric", - month: "short", - day: "2-digit", - }).format(new Date(tablo.created_at))} - -
-
- Statut : - - {statusLabel} - -
-
- Progression : -
-
-
-
- {progress.donePercentage}% -
-
-
- - {/* ── Tab navigation ──────────────────────────────────────────────── */} -
-
-
- {TABS.map((tab) => { - const isActive = activeSection === tab.id; - return ( - - ); - })} -
-
-
- - {/* ── Tab content ─────────────────────────────────────────────────── */} -
- {activeSection === "overview" && - (() => { - const overviewBlocks: Record = { - description: ( -
-

- Description du projet -

-

- Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les - onglets ci-dessus pour naviguer entre les différentes sections. -

-
- ), - myTasks: ( -
-
-

- Mes tâches -

- -
-
- {myTabloTasks.length === 0 ? ( -
- Aucune tâche -
- ) : ( - visibleOverviewTasks.map((task) => ( -
setSearchParams({ section: "tasks" })} - > - -

- {task.title} -

-
- )) - )} - {myTabloTasks.length > 5 && ( - - )} -
-
- ), - files: ( -
-
-

Fichiers

- -
-
- {fileNames.length === 0 ? ( -

Aucun fichier

- ) : ( - fileNames.slice(0, 5).map((fileName) => ( -
-
- -
-
-

- {fileName} -

-
- -
- )) - )} -
-
- ), - info: ( -
-

Informations

-
-
-
Tâches
-
{tabloTasks.length}
-
-
-
Fichiers
-
{fileNames.length}
-
-
-
Statut
-
- {statusLabel} -
-
-
-
Rôle
-
- {isAdmin ? "Admin" : "Invité"} -
-
-
-
- ), - }; - - return ( - <> - {isAdmin && ( -
- {isLayoutEditMode && ( - - )} - -
- )} - -
-
{ - event.preventDefault(); - handleOverviewBlockDrop("left", overviewLayout.leftZone.length); - }} - > - {overviewLayout.leftZone.map((blockId, index) => ( -
handleOverviewBlockDragStart(event, "left", index)} - onDragOver={handleOverviewBlockDragOver} - onDrop={(event) => { - event.preventDefault(); - event.stopPropagation(); - handleOverviewBlockDrop("left", index); - }} - onDragEnd={() => setDraggedOverviewBlock(null)} - className={cn( - isLayoutEditMode && "cursor-move", - isLayoutEditMode && - draggedOverviewBlock?.zone === "left" && - draggedOverviewBlock.index === index && - "opacity-60" - )} - > - {isLayoutEditMode && ( -
- - Glisser pour réorganiser -
- )} - {overviewBlocks[blockId]} -
- ))} - {isLayoutEditMode && overviewLayout.leftZone.length === 0 && ( -
- Déposez un bloc ici -
- )} -
- -
{ - event.preventDefault(); - handleOverviewBlockDrop("right", overviewLayout.rightZone.length); - }} - > - {overviewLayout.rightZone.map((blockId, index) => ( -
handleOverviewBlockDragStart(event, "right", index)} - onDragOver={handleOverviewBlockDragOver} - onDrop={(event) => { - event.preventDefault(); - event.stopPropagation(); - handleOverviewBlockDrop("right", index); - }} - onDragEnd={() => setDraggedOverviewBlock(null)} - className={cn( - isLayoutEditMode && "cursor-move", - isLayoutEditMode && - draggedOverviewBlock?.zone === "right" && - draggedOverviewBlock.index === index && - "opacity-60" - )} - > - {isLayoutEditMode && ( -
- - Glisser pour réorganiser -
- )} - {overviewBlocks[blockId]} -
- ))} - {isLayoutEditMode && overviewLayout.rightZone.length === 0 && ( -
- Déposez un bloc ici -
- )} -
-
- - ); - })()} - - {activeSection === "tasks" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateTask={(task) => createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "files" && ( - ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "files" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + isCreatingFolder={isCreatingFolder} + isUpdatingFolder={isUpdatingFolder} + onCreateFile={(params) => uploadFile(params).then(() => undefined)} + onDeleteFile={(params) => deleteFile(params).then(() => undefined)} + onDownloadFile={(params) => downloadFile(params).then(() => undefined)} + onCreateFolder={(params) => createFolder(params).then(() => undefined)} + onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} + onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "discussion" && ( +
+ !f.startsWith("."))} - filesLoading={false} - filesError={null} - folders={foldersData?.folders ?? []} - foldersLoading={foldersLoading} - foldersError={foldersError as Error | null} - currentUser={currentUser} members={members} - pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - isCreatingFolder={isCreatingFolder} - isUpdatingFolder={isUpdatingFolder} - onCreateFile={(params) => uploadFile(params).then(() => undefined)} - onDeleteFile={(params) => deleteFile(params).then(() => undefined)} - onDownloadFile={(params) => downloadFile(params).then(() => undefined)} - onCreateFolder={(params) => createFolder(params).then(() => undefined)} - onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} - onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } /> - )} - {activeSection === "discussion" && ( -
- -
- )} - {activeSection === "events" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateEvent={() => undefined} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} +
+ )} + {activeSection === "events" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateEvent={() => undefined} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} - {activeSection === "etapes" && ( - - createTask({ - ...task, - status: task.status as "todo" | "in_progress" | "in_review" | "done", - }) - } - onCreateEtape={(params) => createEtape(params).then(() => undefined)} - isCreatingEtape={isCreatingEtape} - /> - )} + {activeSection === "etapes" && ( + + createTask({ + ...task, + status: task.status as "todo" | "in_progress" | "in_review" | "done", + }) + } + onCreateEtape={(params) => createEtape(params).then(() => undefined)} + isCreatingEtape={isCreatingEtape} + /> + )} - {activeSection === "roadmap" && ( - updateTask({ id: taskId, status })} - /> - )} -
+ {activeSection === "roadmap" && ( + updateTask({ id: taskId, status })} + /> + )} + {/* Task Create Modal */} {tabloId && ( @@ -962,6 +494,9 @@ export const TabloDetailsPage = () => { onClose={closeTaskModal} initialStatus="todo" initialDueDate={taskModalInitialDueDate} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} /> )} @@ -1217,6 +752,6 @@ export const TabloDetailsPage = () => {
-
+ ); }; diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index c671847..9f4d0f1 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -108,27 +108,29 @@ export function EtapesSection({ return (
{isAdmin && ( -
+
{ + event.preventDefault(); + void handleAddEtape(); + }} + > setNewEtapeTitle(event.target.value)} placeholder="Nom de la nouvelle étape..." - onKeyDown={(event) => { - if (event.key === "Enter") { - void handleAddEtape(); - } - }} + required className="h-11 sm:h-9 sm:w-80" /> -
+ )} {etapes.length === 0 ? ( diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 0743baa..350a38c 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -38,6 +38,7 @@ interface TabloTasksSectionProps { isCancellingInvite?: boolean; onCreateTask?: (task: KanbanTaskInsert) => void; onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; + onDeleteTask?: (taskId: string) => void; onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void; onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; @@ -56,6 +57,7 @@ export const TabloTasksSection = ({ isCancellingInvite, onCreateTask, onUpdateTask, + onDeleteTask, onUpdateTaskPositions, onUpdateTablo, onInviteUser, @@ -278,6 +280,7 @@ export const TabloTasksSection = ({ etapes={etapes} onCreateTask={onCreateTask} onUpdateTask={onUpdateTask} + onDeleteTask={onDeleteTask} />
); diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index 6fea2df..b87066b 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -40,6 +40,8 @@ interface TaskModalProps { onCreateTask?: (task: KanbanTaskInsert) => void; /** Called when updating an existing task. */ onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; + /** Called when deleting an existing task. */ + onDeleteTask?: (taskId: string) => void; } export const TaskModal = ({ @@ -56,6 +58,7 @@ export const TaskModal = ({ initialDueDate, onCreateTask, onUpdateTask, + onDeleteTask, }: TaskModalProps) => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); @@ -137,6 +140,12 @@ export const TaskModal = ({ onClose(); }; + const handleDelete = () => { + if (!taskId || !task) return; + onDeleteTask?.(task.id); + onClose(); + }; + if (!isOpen) return null; return ( @@ -252,6 +261,16 @@ export const TaskModal = ({ {/* Actions */}
+ {taskId && task && ( + + )} From fc82ea1949c8e72084d634b2d90da7c46cb6a43b Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:31:59 +0200 Subject: [PATCH 13/44] test: stabilize api suite --- .../__tests__/routes/clientInvites.test.ts | 12 ++++----- apps/api/src/__tests__/routes/tablo.test.ts | 26 +++++++++++++++++-- apps/api/vitest.config.ts | 1 + 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts index 6b7cb25..17bfc08 100644 --- a/apps/api/src/__tests__/routes/clientInvites.test.ts +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -143,10 +143,10 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(true); }); - it("should reject non-admin users with 403", async () => { + it("should reject temporary users before admin check", async () => { // tempUser is NOT admin of adminTabloId (owner user owns it) const res = await postInvite(tempUser, adminTabloId, testEmail); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 400 for an invalid email", async () => { @@ -292,9 +292,9 @@ describe("Client Invites Endpoints", () => { expect(found.is_pending).toBe(true); }); - it("should return 403 for a non-admin user", async () => { + it("should return 401 for a temporary user before admin check", async () => { const res = await getPending(tempUser, adminTabloId); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 401 for unauthenticated requests", async () => { @@ -342,7 +342,7 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(false); }); - it("should return 403 for a non-admin user", async () => { + it("should return 401 for a temporary user before admin check", async () => { const token = `test_cancel_nonadmin_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -352,7 +352,7 @@ describe("Client Invites Endpoints", () => { }); const res = await deleteInvite(tempUser, adminTabloId, inviteId); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 404 for a non-existent invite", async () => { diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index b445c90..923fa38 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -1,7 +1,7 @@ import { createClient } from "@supabase/supabase-js"; import { randomUUID } from "node:crypto"; import { testClient } from "hono/testing"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; @@ -34,6 +34,7 @@ describe("Tablo Endpoint", () => { const supabaseAdmin = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false }, }); + const createdTabloIds: string[] = []; beforeEach(() => { // Reset all mocks before each test @@ -41,6 +42,16 @@ describe("Tablo Endpoint", () => { mockSendMail.mockResolvedValue({ messageId: "test-message-id" }); }); + afterEach(async () => { + if (createdTabloIds.length === 0) { + return; + } + + const idsToDelete = createdTabloIds.splice(0, createdTabloIds.length); + await supabaseAdmin.from("tablo_access").delete().in("tablo_id", idsToDelete); + await supabaseAdmin.from("tablos").delete().in("id", idsToDelete); + }); + // Helper function to create tablo const createTabloRequest = async ( user: TestUserData, @@ -171,6 +182,8 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(200); const data = await res.json(); expect(data.message).toBe("Tablo created successfully"); + expect(data.tablo?.id).toBeDefined(); + createdTabloIds.push(data.tablo.id); }); it("should deny temp user from creating a tablo (regularUserCheck blocks temporary users)", async () => { @@ -271,7 +284,16 @@ describe("Tablo Endpoint", () => { } if (fillerTablos.length > 0) { - await supabaseAdmin.from("tablos").insert(fillerTablos); + const { data: insertedTablos, error: insertError } = await supabaseAdmin + .from("tablos") + .insert(fillerTablos) + .select("id"); + + if (insertError) { + throw new Error(`Failed to insert filler tablos: ${insertError.message}`); + } + + createdTabloIds.push(...(insertedTablos ?? []).map((tablo) => tablo.id)); } try { diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index e2c7fcf..8586540 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ exclude: ["node_modules", "dist"], reporters: ["verbose"], pool: "forks", + fileParallelism: false, }, resolve: { alias: { From 37ab73bced34a847e56d50aacd4a188231f8ab23 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:34:49 +0200 Subject: [PATCH 14/44] feat: add shared single tablo view --- apps/clients/tsconfig.tsbuildinfo | 2 +- packages/tablo-views/src/index.ts | 10 + .../src/single-tablo/SingleTabloOverview.tsx | 262 ++++++++++++++++++ .../src/single-tablo/SingleTabloView.tsx | 169 +++++++++++ .../src/single-tablo/overviewLayout.ts | 66 +++++ .../src/single-tablo/overviewReorder.ts | 46 +++ .../tablo-views/src/single-tablo/shared.tsx | 31 +++ 7 files changed, 585 insertions(+), 1 deletion(-) create mode 100644 packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx create mode 100644 packages/tablo-views/src/single-tablo/SingleTabloView.tsx create mode 100644 packages/tablo-views/src/single-tablo/overviewLayout.ts create mode 100644 packages/tablo-views/src/single-tablo/overviewReorder.ts create mode 100644 packages/tablo-views/src/single-tablo/shared.tsx diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index a7db947..1df4210 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index b67c572..ab47c35 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -7,6 +7,16 @@ export { RoadmapSection } from "./RoadmapSection"; export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; export { TabloDetailsShell } from "./TabloDetailsShell"; +export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; +export { SingleTabloView } from "./single-tablo/SingleTabloView"; +export { + DEFAULT_OVERVIEW_LAYOUT, + sanitizeOverviewLayout, +} from "./single-tablo/overviewLayout"; +export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; +export { moveBetweenZones, moveWithinZone } from "./single-tablo/overviewReorder"; +export { getSingleTabloStatusConfig } from "./single-tablo/shared"; +export type { SingleTabloTabId } from "./single-tablo/shared"; // Sub-components export { GanttChart } from "./components/gantt/GanttChart"; diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx new file mode 100644 index 0000000..012828d --- /dev/null +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -0,0 +1,262 @@ +import { cn } from "@xtablo/shared"; +import type { KanbanTask } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { FileIcon, GripVerticalIcon, LayoutPanelTopIcon, ListChecksIcon, RotateCcwIcon } from "lucide-react"; +import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout"; + +interface DraggedBlock { + zone: "left" | "right"; + index: number; +} + +interface SingleTabloOverviewProps { + roleLabel?: string; + statusLabel?: string; + statusBadgeClass?: string; + description: string; + tasks: KanbanTask[]; + projectTaskCount: number; + personalTaskCount: number; + fileNames: string[]; + showFileMenu?: boolean; + onOpenTasks: () => void; + onOpenFiles: () => void; + onCreateTask: () => void; + onToggleTaskDone: (taskId: string) => void; + showAllTasks: boolean; + onToggleShowAllTasks: () => void; + layout: OverviewLayoutV1; + canEditLayout: boolean; + isLayoutEditMode: boolean; + draggedBlock: DraggedBlock | null; + onToggleLayoutEditMode: () => void; + onResetLayout: () => void; + onBlockDragStart: ( + event: React.DragEvent, + zone: "left" | "right", + index: number + ) => void; + onBlockDragOver: (event: React.DragEvent) => void; + onBlockDrop: (zone: "left" | "right", index: number) => void; + onBlockDragEnd: () => void; +} + +function OverviewCard({ + title, + actions, + children, + draggable = false, + onDragStart, + onDragOver, + onDrop, + onDragEnd, + isDragged = false, +}: { + title: string; + actions?: React.ReactNode; + children: React.ReactNode; + draggable?: boolean; + onDragStart?: (event: React.DragEvent) => void; + onDragOver?: (event: React.DragEvent) => void; + onDrop?: (event: React.DragEvent) => void; + onDragEnd?: () => void; + isDragged?: boolean; +}) { + return ( +
+
+
+ {draggable && } +

{title}

+
+ {actions} +
+ {children} +
+ ); +} + +export function SingleTabloOverview({ + description, + tasks, + projectTaskCount, + personalTaskCount, + fileNames, + onOpenTasks, + onOpenFiles, + onCreateTask, + onToggleTaskDone, + showAllTasks, + onToggleShowAllTasks, + layout, + canEditLayout, + isLayoutEditMode, + draggedBlock, + onToggleLayoutEditMode, + onResetLayout, + onBlockDragStart, + onBlockDragOver, + onBlockDrop, + onBlockDragEnd, +}: SingleTabloOverviewProps) { + const renderBlockContent = (blockId: OverviewBlockId) => { + switch (blockId) { + case "description": + return { + title: "Description du projet", + children: ( +

+ {description} +

+ ), + }; + case "myTasks": + return { + title: "Mes tâches", + actions: ( +
+ + +
+ ), + children: ( +
+ {tasks.length === 0 ? ( +

Aucune tâche.

+ ) : ( + tasks.map((task) => ( + + )) + )} + {personalTaskCount > 5 && ( + + )} +
+ ), + }; + case "files": + return { + title: "Fichiers", + actions: ( + + ), + children: ( +
+ {fileNames.length === 0 ? ( +

Aucun fichier.

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+ + {fileName} +
+ )) + )} +
+ ), + }; + case "info": + return { + title: "Informations", + children: ( +
+
+ + {projectTaskCount} tâches sur le projet +
+
+ + {personalTaskCount} tâches pour vous +
+
+ ), + }; + } + }; + + const renderZone = (zone: "left" | "right", blocks: OverviewBlockId[]) => ( +
+ {blocks.map((blockId, index) => { + const block = renderBlockContent(blockId); + + return ( +
onBlockDrop(zone, index)} + > + onBlockDragStart(event, zone, index)} + onDragOver={onBlockDragOver} + onDrop={() => onBlockDrop(zone, index)} + onDragEnd={onBlockDragEnd} + isDragged={draggedBlock?.zone === zone && draggedBlock.index === index} + > + {block.children} + +
+ ); + })} +
+ ); + + return ( +
+ {canEditLayout && ( +
+ + {isLayoutEditMode && ( + + )} +
+ )} + +
+
{renderZone("left", layout.leftZone)}
+
{renderZone("right", layout.rightZone)}
+
+
+ ); +} diff --git a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx new file mode 100644 index 0000000..4e3b44e --- /dev/null +++ b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx @@ -0,0 +1,169 @@ +import { cn } from "@xtablo/shared"; +import type { UserTablo } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { + CalendarIcon, + FolderIcon, + KanbanIcon, + LayoutDashboardIcon, + ListChecksIcon, + MapIcon, + MessageCircleIcon, +} from "lucide-react"; +import { Link } from "react-router-dom"; +import { + TabloDetailsShell, + type TabloDetailsShellMetadataItem, + type TabloDetailsShellTab, +} from "../TabloDetailsShell"; +import type { SingleTabloTabId } from "./shared"; + +const TABS: TabloDetailsShellTab[] = [ + { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, + { id: "etapes", label: "Étapes", icon: ListChecksIcon }, + { id: "tasks", label: "Tâches", icon: KanbanIcon }, + { id: "files", label: "Fichiers", icon: FolderIcon }, + { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, + { id: "events", label: "Événements", icon: CalendarIcon }, + { id: "roadmap", label: "Roadmap", icon: MapIcon }, +]; + +type DiscussionAction = + | { + kind: "link"; + to: string; + } + | { + kind: "button"; + onClick: () => void; + }; + +interface SingleTabloViewProps { + tablo: Pick; + roleLabel: string; + statusLabel: string; + statusBadgeClass: string; + progress: { + startedPercentage: number; + donePercentage: number; + }; + activeTab: SingleTabloTabId; + onTabChange: (tabId: SingleTabloTabId) => void; + hasUnreadDiscussion?: boolean; + discussionAction?: DiscussionAction; + canInviteMembers?: boolean; + onOpenInviteDialog?: () => void; + children: React.ReactNode; +} + +export function SingleTabloView({ + tablo, + roleLabel, + statusLabel, + statusBadgeClass, + progress, + activeTab, + onTabChange, + hasUnreadDiscussion = false, + discussionAction, + canInviteMembers = false, + onOpenInviteDialog, + children, +}: SingleTabloViewProps) { + const metadata: TabloDetailsShellMetadataItem[] = [ + { + key: "role", + label: "Rôle", + value: {roleLabel}, + }, + { + key: "created-at", + label: "Créé le", + value: ( + + {new Intl.DateTimeFormat("fr-FR", { + year: "numeric", + month: "short", + day: "2-digit", + }).format(new Date(tablo.created_at))} + + ), + }, + { + key: "status", + label: "Statut", + value: ( + + {statusLabel} + + ), + }, + { + key: "progress", + label: "Progression", + value: ( + <> +
+
+
+
+ {progress.donePercentage}% + + ), + }, + ]; + + const tabs = TABS.map((tab) => + tab.id === "discussion" ? { ...tab, hasUnread: hasUnreadDiscussion } : tab + ); + + const discussionButton = + discussionAction?.kind === "link" ? ( + + ) : discussionAction?.kind === "button" ? ( + + ) : null; + + const inviteButton = + canInviteMembers && onOpenInviteDialog ? ( + + ) : null; + + const headerActions = + discussionButton || inviteButton ? ( + <> + {discussionButton} + {inviteButton} + + ) : undefined; + + return ( + onTabChange(tabId as SingleTabloTabId)} + isDiscussionView={activeTab === "discussion"} + headerActions={headerActions} + > + {children} + + ); +} diff --git a/packages/tablo-views/src/single-tablo/overviewLayout.ts b/packages/tablo-views/src/single-tablo/overviewLayout.ts new file mode 100644 index 0000000..6424602 --- /dev/null +++ b/packages/tablo-views/src/single-tablo/overviewLayout.ts @@ -0,0 +1,66 @@ +type OverviewLayoutVersion = 1; + +export type OverviewBlockId = "description" | "myTasks" | "files" | "info"; + +export type OverviewLayoutV1 = { + version: OverviewLayoutVersion; + leftZone: OverviewBlockId[]; + rightZone: OverviewBlockId[]; + updatedAt?: string; + updatedBy?: string; +}; + +const DEFAULT_LEFT_ZONE: OverviewBlockId[] = ["description", "myTasks"]; +const DEFAULT_RIGHT_ZONE: OverviewBlockId[] = ["files", "info"]; +const ALL_BLOCK_IDS: OverviewBlockId[] = ["description", "myTasks", "files", "info"]; + +export const DEFAULT_OVERVIEW_LAYOUT: OverviewLayoutV1 = { + version: 1, + leftZone: DEFAULT_LEFT_ZONE, + rightZone: DEFAULT_RIGHT_ZONE, +}; + +function unique(items: T[]): T[] { + return [...new Set(items)]; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function parseZone(value: unknown): OverviewBlockId[] { + if (!Array.isArray(value)) return []; + const valid = value.filter( + (item): item is OverviewBlockId => + item === "description" || item === "myTasks" || item === "files" || item === "info" + ); + return unique(valid); +} + +export function sanitizeOverviewLayout(input: unknown): OverviewLayoutV1 { + if (!isObject(input)) { + return DEFAULT_OVERVIEW_LAYOUT; + } + + const leftZoneInput = parseZone(input.leftZone); + const rightZoneInput = parseZone(input.rightZone); + + const leftZoneSize = leftZoneInput.length; + const allBlocks = unique([...leftZoneInput, ...rightZoneInput]); + + for (const blockId of ALL_BLOCK_IDS) { + if (!allBlocks.includes(blockId)) { + allBlocks.push(blockId); + } + } + + const safeLeftZoneSize = Math.min(leftZoneSize, allBlocks.length); + const leftZone = allBlocks.slice(0, safeLeftZoneSize); + const rightZone = allBlocks.slice(safeLeftZoneSize); + + return { + version: 1, + leftZone, + rightZone, + }; +} diff --git a/packages/tablo-views/src/single-tablo/overviewReorder.ts b/packages/tablo-views/src/single-tablo/overviewReorder.ts new file mode 100644 index 0000000..c62c48d --- /dev/null +++ b/packages/tablo-views/src/single-tablo/overviewReorder.ts @@ -0,0 +1,46 @@ +export function moveWithinZone(items: T[], fromIndex: number, toIndex: number): T[] { + if (fromIndex < 0 || fromIndex >= items.length || toIndex < 0 || toIndex > items.length) { + return items; + } + + const next = [...items]; + const [moved] = next.splice(fromIndex, 1); + const insertionIndex = Math.min(toIndex, next.length); + next.splice(insertionIndex, 0, moved); + + if (next.every((item, index) => item === items[index])) { + return items; + } + + return next; +} + +export function moveBetweenZones( + sourceItems: T[], + targetItems: T[], + sourceIndex: number, + targetIndex: number +): { + sourceItems: T[]; + targetItems: T[]; +} { + if ( + sourceIndex < 0 || + sourceIndex >= sourceItems.length || + targetIndex < 0 || + targetIndex > targetItems.length + ) { + return { sourceItems, targetItems }; + } + + const nextSourceItems = [...sourceItems]; + const [moved] = nextSourceItems.splice(sourceIndex, 1); + const nextTargetItems = [...targetItems]; + const insertionIndex = Math.min(targetIndex, nextTargetItems.length); + nextTargetItems.splice(insertionIndex, 0, moved); + + return { + sourceItems: nextSourceItems, + targetItems: nextTargetItems, + }; +} diff --git a/packages/tablo-views/src/single-tablo/shared.tsx b/packages/tablo-views/src/single-tablo/shared.tsx new file mode 100644 index 0000000..2b879d3 --- /dev/null +++ b/packages/tablo-views/src/single-tablo/shared.tsx @@ -0,0 +1,31 @@ +export type SingleTabloTabId = + | "overview" + | "etapes" + | "tasks" + | "files" + | "discussion" + | "events" + | "roadmap"; + +export function getSingleTabloStatusConfig(status: string) { + switch (status) { + case "in_progress": + return { + label: "En cours", + badgeClass: + "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", + }; + case "done": + return { + label: "Terminé", + badgeClass: + "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", + }; + default: + return { + label: "À faire", + badgeClass: + "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", + }; + } +} From e36c536cf2e74ce1c6140dcc882ae06e1e022ef7 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:54:41 +0200 Subject: [PATCH 15/44] Allow updates deletions on etapes / tasks --- .../src/pages/tablo-details.layout.test.tsx | 73 ++++++- apps/main/src/pages/tablo-details.tsx | 8 + packages/tablo-views/src/EtapesSection.tsx | 187 +++++++++++++++--- 3 files changed, 239 insertions(+), 29 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 17c103e..a327343 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -7,6 +7,8 @@ import { TabloDetailsPage } from "./tablo-details"; const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); const mutateCreateEtape = vi.fn(); +const mutateUpdateEtape = vi.fn(); +const mutateDeleteEtape = vi.fn(); const mutateDeleteTask = vi.fn(); const tablosData = [ @@ -107,7 +109,22 @@ vi.mock("../hooks/tasks", () => ({ ], }), useTabloEtapes: () => ({ - data: [], + data: [ + { + id: "etape-1", + tablo_id: "tablo-1", + title: "Kickoff", + description: null, + status: "todo", + assignee_id: null, + position: 0, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + is_parent: true, + parent_task_id: null, + due_date: null, + }, + ], }), useUpdateTask: () => ({ mutate: mutateUpdateTask, @@ -122,6 +139,14 @@ vi.mock("../hooks/tasks", () => ({ mutateAsync: mutateCreateEtape, isPending: false, }), + useUpdateEtape: () => ({ + mutateAsync: mutateUpdateEtape, + isPending: false, + }), + useDeleteEtape: () => ({ + mutateAsync: mutateDeleteEtape, + isPending: false, + }), useCreateTask: () => ({ mutate: vi.fn(), }), @@ -208,10 +233,54 @@ describe("TabloDetailsPage overview layout", () => { expect(mutateCreateEtape).toHaveBeenCalledWith({ tabloId: "tablo-1", title: "Kickoff", - position: 0, + position: 1, }); }); + it("updates an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateUpdateEtape.mockResolvedValueOnce(undefined); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.click(screen.getByRole("button", { name: "Modifier l'étape Kickoff" })); + await user.clear(screen.getByDisplayValue("Kickoff")); + await user.type(screen.getByPlaceholderText("Nom de l'étape"), "Planification"); + await user.click(screen.getByRole("button", { name: "Enregistrer l'étape" })); + + expect(mutateUpdateEtape).toHaveBeenCalledWith({ + id: "etape-1", + tabloId: "tablo-1", + title: "Planification", + }); + }); + + it("deletes an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateDeleteEtape.mockResolvedValueOnce(undefined); + const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.click(screen.getByRole("button", { name: "Supprimer l'étape Kickoff" })); + + expect(confirmSpy).toHaveBeenCalled(); + expect(mutateDeleteEtape).toHaveBeenCalledWith({ + id: "etape-1", + tabloId: "tablo-1", + }); + + confirmSpy.mockRestore(); + }); + it("deletes a task from the task modal", async () => { const user = userEvent.setup(); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 50dfa93..824a74e 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -64,8 +64,10 @@ import { useAllTasks, useCreateEtape, useCreateTask, + useDeleteEtape, useDeleteTask, useTabloEtapes, + useUpdateEtape, useUpdateTask, useUpdateTaskPositions, } from "../hooks/tasks"; @@ -127,6 +129,8 @@ export const TabloDetailsPage = () => { const { mutate: updateTablo, mutateAsync: updateTabloAsync } = useUpdateTablo(); const { mutate: createTask } = useCreateTask(); const { mutateAsync: createEtape, isPending: isCreatingEtape } = useCreateEtape(); + const { mutateAsync: updateEtape, isPending: isUpdatingEtape } = useUpdateEtape(); + const { mutateAsync: deleteEtape, isPending: isDeletingEtape } = useDeleteEtape(); const { mutate: updateTaskPositions } = useUpdateTaskPositions(); // Files & folders hooks @@ -473,7 +477,11 @@ export const TabloDetailsPage = () => { }) } onCreateEtape={(params) => createEtape(params).then(() => undefined)} + onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} + onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} isCreatingEtape={isCreatingEtape} + isUpdatingEtape={isUpdatingEtape} + isDeletingEtape={isDeletingEtape} /> )} diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index 9f4d0f1..e1b22e8 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -4,11 +4,15 @@ import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { CalendarIcon, + CheckIcon, ChevronDownIcon, ChevronRightIcon, CircleCheckIcon, + PencilIcon, ListChecksIcon, PlusIcon, + Trash2Icon, + XIcon, } from "lucide-react"; import { useState } from "react"; @@ -26,7 +30,11 @@ interface EtapesSectionProps { position: number; }) => void; onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise; + onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise; isCreatingEtape?: boolean; + isUpdatingEtape?: boolean; + isDeletingEtape?: boolean; } export function EtapesSection({ @@ -36,7 +44,11 @@ export function EtapesSection({ isAdmin, onCreateTask, onCreateEtape, + onUpdateEtape, + onDeleteEtape, isCreatingEtape = false, + isUpdatingEtape = false, + isDeletingEtape = false, }: EtapesSectionProps) { const [expandedEtapes, setExpandedEtapes] = useState>( new Set(etapes.map((e) => e.id)) @@ -44,6 +56,8 @@ export function EtapesSection({ const [addingTaskToEtape, setAddingTaskToEtape] = useState(null); const [newEtapeTitle, setNewEtapeTitle] = useState(""); const [newTaskTitle, setNewTaskTitle] = useState(""); + const [editingEtapeId, setEditingEtapeId] = useState(null); + const [editingEtapeTitle, setEditingEtapeTitle] = useState(""); const toggleEtape = (id: string) => { setExpandedEtapes((prev) => { @@ -86,6 +100,46 @@ export function EtapesSection({ setNewEtapeTitle(""); }; + const startEditingEtape = (etapeId: string, title: string) => { + setEditingEtapeId(etapeId); + setEditingEtapeTitle(title); + }; + + const cancelEditingEtape = () => { + setEditingEtapeId(null); + setEditingEtapeTitle(""); + }; + + const handleUpdateEtape = async (etapeId: string) => { + const title = editingEtapeTitle.trim(); + if (!title || !tabloId) { + return; + } + + await onUpdateEtape?.({ + id: etapeId, + tabloId, + title, + }); + + cancelEditingEtape(); + }; + + const handleDeleteEtape = async (etapeId: string, title: string) => { + if (!tabloId) { + return; + } + + if (!window.confirm(`Supprimer l'étape "${title}" ?`)) { + return; + } + + await onDeleteEtape?.({ + id: etapeId, + tabloId, + }); + }; + const statusConfig: Record = { todo: { label: "À faire", @@ -159,6 +213,7 @@ export function EtapesSection({ ? "in_progress" : "todo"; const status = statusConfig[derivedStatus] ?? statusConfig.todo; + const isEditing = editingEtapeId === etape.id; return (
{/* Etape header */} -
+ +
+ + {index + 1} + +
+ +
+ {isEditing ? ( + setEditingEtapeTitle(event.target.value)} + onClick={(event) => event.stopPropagation()} + onKeyDown={(event) => { + if (event.key === "Enter") { + event.preventDefault(); + void handleUpdateEtape(etape.id); + } + + if (event.key === "Escape") { + event.preventDefault(); + cancelEditingEtape(); + } + }} + placeholder="Nom de l'étape" + aria-label="Nom de l'étape" + autoFocus + className="h-9" + /> + ) : ( + <> +

+ {etape.title} +

+ {etape.description && ( +

+ {etape.description} +

+ )} + + )} +
+
{etape.due_date && ( @@ -237,8 +319,59 @@ export function EtapesSection({
)} + + {isAdmin && ( +
+ {isEditing ? ( + <> + + + + ) : ( + <> + + + + )} +
+ )}
- +
{/* Child tasks + add task */} {isExpanded && ( From 983dbb01b52cb26503119098942dbbbd1323b913 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 12:02:18 +0200 Subject: [PATCH 16/44] fix: move task deletion to inline actions --- .../src/pages/tablo-details.layout.test.tsx | 5 +- apps/main/src/pages/tasks.test.tsx | 92 +++++++++++++++++++ apps/main/src/pages/tasks.tsx | 26 +++++- .../tablo-views/src/TabloTasksSection.tsx | 1 + .../src/components/kanban/KanbanBoard.tsx | 3 + .../src/components/kanban/KanbanColumn.tsx | 3 + .../src/components/kanban/KanbanTaskCard.tsx | 26 +++++- .../src/components/kanban/TaskModal.tsx | 17 ---- 8 files changed, 147 insertions(+), 26 deletions(-) create mode 100644 apps/main/src/pages/tasks.test.tsx diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index a327343..1e36a04 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -281,7 +281,7 @@ describe("TabloDetailsPage overview layout", () => { confirmSpy.mockRestore(); }); - it("deletes a task from the task modal", async () => { + it("deletes a task from the inline kanban action", async () => { const user = userEvent.setup(); renderWithProviders(, { @@ -290,8 +290,7 @@ describe("TabloDetailsPage overview layout", () => { }); await user.click(screen.getByRole("button", { name: "Tâches" })); - await user.click(screen.getByText("Task A")); - await user.click(screen.getByRole("button", { name: "Supprimer la tâche" })); + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); }); diff --git a/apps/main/src/pages/tasks.test.tsx b/apps/main/src/pages/tasks.test.tsx new file mode 100644 index 0000000..e421f12 --- /dev/null +++ b/apps/main/src/pages/tasks.test.tsx @@ -0,0 +1,92 @@ +import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { TasksPage } from "./tasks"; +import { renderWithProviders } from "../utils/testHelpers"; + +const mutateUpdateTask = vi.fn(); +const mutateDeleteTask = vi.fn(); + +vi.mock("../hooks/tablos", () => ({ + useTablosList: () => ({ + data: [ + { + id: "tablo-1", + name: "Projet Alpha", + color: "bg-blue-500", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tasks", () => ({ + useAllTasks: () => ({ + data: [ + { + id: "task-1", + tablo_id: "tablo-1", + title: "Task A", + description: "Description", + status: "todo", + due_date: null, + assignee_id: "123", + assignee_name: "John Doe", + assignee_avatar: null, + tablos: { + id: "tablo-1", + name: "Projet Alpha", + color: "bg-blue-500", + }, + }, + ], + isLoading: false, + }), + useUpdateTask: () => ({ + mutate: mutateUpdateTask, + }), + useDeleteTask: () => ({ + mutate: mutateDeleteTask, + }), +})); + +vi.mock("@xtablo/tablo-views", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + GanttChart: () =>
, + TaskModal: () => null, + }; +}); + +describe("TasksPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("deletes a task from the inline kanban action", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tasks?view=kanban", + path: "/tasks", + }); + + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); + + it("deletes a task from the inline list action", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tasks?view=aggregated", + path: "/tasks", + }); + + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); +}); diff --git a/apps/main/src/pages/tasks.tsx b/apps/main/src/pages/tasks.tsx index 40c6568..97ff27b 100644 --- a/apps/main/src/pages/tasks.tsx +++ b/apps/main/src/pages/tasks.tsx @@ -33,6 +33,7 @@ import { Sparkles, Star, Sun, + Trash2Icon, UserIcon, Waves, Zap, @@ -42,7 +43,7 @@ import { useTranslation } from "react-i18next"; import { useNavigate, useSearchParams } from "react-router-dom"; import { twMerge } from "tailwind-merge"; import { useTablosList } from "../hooks/tablos"; -import { useAllTasks, useUpdateTask } from "../hooks/tasks"; +import { useAllTasks, useDeleteTask, useUpdateTask } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; type TaskStatus = "all" | "todo" | "in_progress" | "in_review" | "done"; @@ -134,6 +135,7 @@ export function TasksPage() { // Mutation for updating task status const updateTaskMutation = useUpdateTask(); + const deleteTaskMutation = useDeleteTask(); const openTaskModal = (dueDate?: Date) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); @@ -556,6 +558,17 @@ export function TasksPage() { ))} +
{formattedDate && ( @@ -878,6 +891,17 @@ export function TasksPage() { ))} + ); diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 350a38c..90eef07 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -262,6 +262,7 @@ export const TabloTasksSection = ({ etapes={etapes} etapeTitles={etapeTitleMap} onTaskClick={handleTaskClick} + onDeleteTask={onDeleteTask} onAddTask={handleAddTask} onAddTaskInline={handleCreateTask} onTaskMove={handleTaskMove} diff --git a/packages/tablo-views/src/components/kanban/KanbanBoard.tsx b/packages/tablo-views/src/components/kanban/KanbanBoard.tsx index 35293c7..0522fd2 100644 --- a/packages/tablo-views/src/components/kanban/KanbanBoard.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanBoard.tsx @@ -14,6 +14,7 @@ interface KanbanBoardProps { etapes: Etape[]; etapeTitles: Record; onTaskClick: (task: KanbanTask) => void; + onDeleteTask?: (taskId: string) => void; onAddTask: (status: TaskStatus) => void; onAddTaskInline: (task: { title: string; @@ -30,6 +31,7 @@ export const KanbanBoard = ({ members, etapes, onTaskClick, + onDeleteTask, onAddTask, onAddTaskInline, onTaskMove, @@ -63,6 +65,7 @@ export const KanbanBoard = ({ members={members} etapes={etapes} onTaskClick={onTaskClick} + onDeleteTask={onDeleteTask} onAddTask={onAddTask} onAddTaskInline={onAddTaskInline} onDragStart={handleDragStart} diff --git a/packages/tablo-views/src/components/kanban/KanbanColumn.tsx b/packages/tablo-views/src/components/kanban/KanbanColumn.tsx index 516db0a..a913ae6 100644 --- a/packages/tablo-views/src/components/kanban/KanbanColumn.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanColumn.tsx @@ -15,6 +15,7 @@ interface KanbanColumnProps { members: TabloMember[]; etapes: Etape[]; onTaskClick: (task: KanbanTask) => void; + onDeleteTask?: (taskId: string) => void; onAddTask: (status: KanbanColumnType["status"]) => void; onAddTaskInline: (task: { title: string; @@ -33,6 +34,7 @@ export const KanbanColumn = ({ members, etapes, onTaskClick, + onDeleteTask, onAddTask, onAddTaskInline, onDragStart, @@ -84,6 +86,7 @@ export const KanbanColumn = ({ task={task} etapeTitle={etape?.title} onClick={() => onTaskClick(task)} + onDelete={onDeleteTask ? () => onDeleteTask(task.id) : undefined} />
); diff --git a/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx b/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx index ba58c74..8ceaae9 100644 --- a/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx @@ -1,11 +1,12 @@ import type { KanbanTask } from "@xtablo/shared-types"; import { TypographyH4, TypographyMuted } from "@xtablo/ui/components/typography"; -import { CalendarIcon, User } from "lucide-react"; +import { CalendarIcon, Trash2Icon, User } from "lucide-react"; interface KanbanTaskCardProps { task: KanbanTask; etapeTitle?: string; onClick: () => void; + onDelete?: () => void; } function formatDueDate(dateStr: string): string { @@ -23,7 +24,7 @@ function isOverdue(dateStr: string): boolean { return due < today; } -export const KanbanTaskCard = ({ task, etapeTitle, onClick }: KanbanTaskCardProps) => { +export const KanbanTaskCard = ({ task, etapeTitle, onClick, onDelete }: KanbanTaskCardProps) => { const overdue = task.due_date && task.status !== "done" && isOverdue(task.due_date); return ( @@ -31,9 +32,24 @@ export const KanbanTaskCard = ({ task, etapeTitle, onClick }: KanbanTaskCardProp onClick={onClick} className="bg-card border border-border rounded-lg p-3 hover:shadow-md transition-shadow cursor-pointer group" > - - {task.title} - +
+ + {task.title} + + {onDelete && ( + + )} +
{task.description && ( diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index b87066b..aebfe4f 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -58,7 +58,6 @@ export const TaskModal = ({ initialDueDate, onCreateTask, onUpdateTask, - onDeleteTask, }: TaskModalProps) => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); @@ -140,12 +139,6 @@ export const TaskModal = ({ onClose(); }; - const handleDelete = () => { - if (!taskId || !task) return; - onDeleteTask?.(task.id); - onClose(); - }; - if (!isOpen) return null; return ( @@ -261,16 +254,6 @@ export const TaskModal = ({ {/* Actions */}
- {taskId && task && ( - - )} From e3673b7040d6e3b030e9e8c1579a44e1f6f575be Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 13:34:26 +0200 Subject: [PATCH 17/44] Fix tablo overview --- .../main/src/pages/tablo-details.layout.test.tsx | 16 ++++++++++++++++ .../src/single-tablo/SingleTabloOverview.tsx | 15 +++++++++------ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 1e36a04..7314c00 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -309,6 +309,22 @@ describe("TabloDetailsPage overview layout", () => { ); }); + it("uses a dominant overview first column and purple primary actions", () => { + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + expect(screen.getByTestId("single-tablo-overview-grid")).toHaveClass( + "lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]" + ); + expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( + "bg-primary" + ); + expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-primary"); + expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("bg-primary"); + }); + it("shows layout edit toggle for admin users", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index 012828d..c652b23 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -126,7 +126,7 @@ export function SingleTabloOverview({ title: "Mes tâches", actions: (
- ), @@ -241,11 +241,11 @@ export function SingleTabloOverview({
{canEditLayout && (
- {isLayoutEditMode && ( - @@ -253,8 +253,11 @@ export function SingleTabloOverview({
)} -
-
{renderZone("left", layout.leftZone)}
+
+
{renderZone("left", layout.leftZone)}
{renderZone("right", layout.rightZone)}
From 916dba496a88f396bd663a10cc0e113626a6109f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 13:43:30 +0200 Subject: [PATCH 18/44] fix: restore tablo overview layout and colors --- .../src/pages/tablo-details.layout.test.tsx | 14 ++++++--- .../src/single-tablo/SingleTabloOverview.tsx | 30 ++++++++++++++++--- .../src/single-tablo/SingleTabloView.tsx | 22 ++++++++++---- 3 files changed, 53 insertions(+), 13 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 7314c00..43c80a9 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -318,11 +318,17 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByTestId("single-tablo-overview-grid")).toHaveClass( "lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]" ); - expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( - "bg-primary" + expect(screen.getByRole("link", { name: "Discussion" })).toHaveClass("bg-[#804EEC]"); + expect(screen.getByRole("button", { name: "Inviter" })).toHaveClass( + "border-[#804EEC]", + "text-[#804EEC]" ); - expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-primary"); - expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("bg-primary"); + expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( + "border-[#804EEC]", + "text-[#804EEC]" + ); + expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-[#804EEC]"); + expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("text-[#804EEC]"); }); it("shows layout edit toggle for admin users", () => { diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index c652b23..a5646a9 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -126,10 +126,21 @@ export function SingleTabloOverview({ title: "Mes tâches", actions: (
- -
@@ -170,7 +181,13 @@ export function SingleTabloOverview({ return { title: "Fichiers", actions: ( - ), @@ -241,7 +258,12 @@ export function SingleTabloOverview({
{canEditLayout && (
- {isLayoutEditMode && ( diff --git a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx index 4e3b44e..e95bc48 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx @@ -125,22 +125,34 @@ export function SingleTabloView({ const discussionButton = discussionAction?.kind === "link" ? ( - ) : discussionAction?.kind === "button" ? ( - ) : null; const inviteButton = canInviteMembers && onOpenInviteDialog ? ( - ) : null; From 740bedaf50a69f27e6ee0372c7524acaa24104d9 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 22:21:16 +0200 Subject: [PATCH 19/44] Improve task management --- .../src/pages/tablo-details.layout.test.tsx | 72 ++++++++++++++++++- apps/main/src/pages/tablo-details.tsx | 12 +++- .../tablo-views/src/TabloTasksSection.tsx | 4 +- .../src/components/kanban/TaskModal.tsx | 38 ++++++++-- 4 files changed, 112 insertions(+), 14 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 43c80a9..e30a059 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -1,11 +1,24 @@ -import { screen } from "@testing-library/react"; +import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; import { TabloDetailsPage } from "./tablo-details"; +if (!HTMLElement.prototype.hasPointerCapture) { + HTMLElement.prototype.hasPointerCapture = () => false; +} + +if (!HTMLElement.prototype.setPointerCapture) { + HTMLElement.prototype.setPointerCapture = () => undefined; +} + +if (!HTMLElement.prototype.releasePointerCapture) { + HTMLElement.prototype.releasePointerCapture = () => undefined; +} + const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); +const mutateCreateTask = vi.fn(); const mutateCreateEtape = vi.fn(); const mutateUpdateEtape = vi.fn(); const mutateDeleteEtape = vi.fn(); @@ -47,7 +60,15 @@ vi.mock("../hooks/tablos", () => ({ isLoading: false, }), useTabloMembers: () => ({ - data: [], + data: [ + { + id: "user-1", + name: "Test User", + email: "john@example.com", + avatar_url: null, + is_admin: true, + }, + ], }), useTabloOverviewLayout: () => ({ data: layoutData, @@ -105,6 +126,7 @@ vi.mock("../hooks/tasks", () => ({ assignee_id: "user-1", title: "Task A", status: "todo", + parent_task_id: "etape-1", }, ], }), @@ -148,7 +170,7 @@ vi.mock("../hooks/tasks", () => ({ isPending: false, }), useCreateTask: () => ({ - mutate: vi.fn(), + mutate: mutateCreateTask, }), useUpdateTaskPositions: () => ({ mutate: vi.fn(), @@ -295,6 +317,50 @@ describe("TabloDetailsPage overview layout", () => { expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); }); + it("restores the task etape when reopening the same edit modal", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1?section=tasks", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByText("Task A")); + await user.click(screen.getByRole("combobox", { name: "Étape" })); + await user.click(screen.getByRole("option", { name: "Aucune" })); + await user.click(screen.getByRole("button", { name: "Annuler" })); + + await user.click(screen.getByText("Task A")); + + expect(screen.getByRole("combobox", { name: "Étape" })).toHaveTextContent("Kickoff"); + }); + + it("assigns the current user when creating from mes tâches in overview", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Ajouter" })); + + await waitFor(() => { + expect(screen.getByRole("combobox", { name: "Assigné à" })).toHaveTextContent("Test User"); + }); + + await user.type(screen.getByLabelText("Titre *"), "Nouvelle tâche"); + await user.click(screen.getByRole("button", { name: "Créer" })); + + expect(mutateCreateTask).toHaveBeenCalledWith( + expect.objectContaining({ + tablo_id: "tablo-1", + title: "Nouvelle tâche", + assignee_id: "user-1", + }) + ); + }); + it("renders overview cards in persisted left-zone order", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 824a74e..4816bb3 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -103,6 +103,9 @@ export const TabloDetailsPage = () => { const [taskModalInitialDueDate, setTaskModalInitialDueDate] = useState( undefined ); + const [taskModalDefaultAssigneeId, setTaskModalDefaultAssigneeId] = useState( + undefined + ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); const [inviteEmail, setInviteEmail] = useState(""); @@ -169,14 +172,16 @@ export const TabloDetailsPage = () => { setInviteEmail(""); }; - const openTaskModal = (dueDate?: Date) => { + const openTaskModal = (dueDate?: Date, defaultAssigneeId?: string) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); + setTaskModalDefaultAssigneeId(defaultAssigneeId); setIsTaskModalOpen(true); }; const closeTaskModal = () => { setIsTaskModalOpen(false); setTaskModalInitialDueDate(undefined); + setTaskModalDefaultAssigneeId(undefined); }; const sectionParam = searchParams.get("section") as TabSection | null; @@ -357,7 +362,7 @@ export const TabloDetailsPage = () => { showFileMenu={true} onOpenTasks={() => setSearchParams({ section: "tasks" })} onOpenFiles={() => setSearchParams({ section: "files" })} - onCreateTask={() => openTaskModal()} + onCreateTask={() => openTaskModal(undefined, currentUser.id)} onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} showAllTasks={showAllOverviewTasks} onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} @@ -500,8 +505,11 @@ export const TabloDetailsPage = () => { tabloId={tabloId} isOpen={isTaskModalOpen} onClose={closeTaskModal} + members={members} + etapes={etapes} initialStatus="todo" initialDueDate={taskModalInitialDueDate} + defaultAssigneeId={taskModalDefaultAssigneeId} onCreateTask={(task) => createTask(task)} onUpdateTask={(task) => updateTask(task)} onDeleteTask={(taskId) => deleteTask(taskId)} diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 90eef07..1839fe9 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -245,9 +245,7 @@ export const TabloTasksSection = ({ {orphanedTasks.length} {pluralize("tâche", orphanedTasks.length)} sans Étape

- {orphanedTasks.length === 1 - ? "Cette tâche n'est associée à aucune Étape. Modifiez-la pour l'associer à une Étape." - : "Ces tâches ne sont associées à aucune Étape. Modifiez-les pour les associer à une Étape."} + Associez {orphanedTasks.length > 1 ? "ces" : "cette"} {pluralize("tâche", orphanedTasks.length)} à une étape.

diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index aebfe4f..df1dd2b 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -36,6 +36,7 @@ interface TaskModalProps { tablos?: MinimalTablo[]; allowTabloSelection?: boolean; initialDueDate?: Date; + defaultAssigneeId?: string; /** Called when creating a new task. */ onCreateTask?: (task: KanbanTaskInsert) => void; /** Called when updating an existing task. */ @@ -56,6 +57,7 @@ export const TaskModal = ({ tablos, allowTabloSelection = false, initialDueDate, + defaultAssigneeId, onCreateTask, onUpdateTask, }: TaskModalProps) => { @@ -69,8 +71,20 @@ export const TaskModal = ({ ); const currentTabloId = allowTabloSelection ? selectedTabloId : initialTabloId || ""; + const selectedAssigneeLabel = + assigneeId === "unassigned" + ? "Non assigné" + : providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"; + const selectedEtapeLabel = + etapeId === "none" + ? "Aucune Étape" + : providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"; useEffect(() => { + if (!isOpen) { + return; + } + if (task) { setTitle(task.title ?? ""); setDescription(task.description ?? ""); @@ -83,14 +97,14 @@ export const TaskModal = ({ } else { setTitle(""); setDescription(""); - setAssigneeId("unassigned"); + setAssigneeId(defaultAssigneeId ?? "unassigned"); setEtapeId("none"); setDueDate(initialDueDate ? new Date(initialDueDate) : undefined); if (allowTabloSelection && tablos && tablos.length > 0) { setSelectedTabloId(tablos[0].id); } } - }, [task, initialTabloId, allowTabloSelection, tablos, initialDueDate]); + }, [isOpen, task, initialTabloId, allowTabloSelection, tablos, initialDueDate, defaultAssigneeId]); // Format Date to YYYY-MM-DD string for database storage const formatDateForDb = (date: Date | undefined): string | null => { @@ -217,9 +231,15 @@ export const TaskModal = ({ {/* Assignee */}
- { + if (!value) return; + setAssigneeId(value); + }} + > - + {selectedAssigneeLabel} Non assigné @@ -236,9 +256,15 @@ export const TaskModal = ({ {providedEtapes.length > 0 && (
- { + if (!value) return; + setEtapeId(value); + }} + > - + {selectedEtapeLabel} Aucune From c2ad27c8c7d3c4eb0b39bc7351d9431256df5e36 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 09:03:53 +0200 Subject: [PATCH 20/44] docs: add client password invite flow spec --- ...4-18-client-password-invite-flow-design.md | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md diff --git a/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md b/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md new file mode 100644 index 0000000..5ab20f9 --- /dev/null +++ b/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md @@ -0,0 +1,318 @@ +# Client Password Invite Flow + +**Date**: 2026-04-18 +**Status**: Draft +**Supersedes**: `docs/superpowers/specs/2026-04-15-client-magic-links-design.md` + +## Overview + +The current client invite flow is built around a magic-link callback path. That model is no longer the target. + +`apps/clients` should become a normal password-based portal for invited client users. Invitations should bootstrap account access, not serve as the long-term authentication mechanism. + +The revised flow is: + +- a client is invited by email from `app.xtablo.com` +- if this email has not completed onboarding yet, the email contains a one-time password setup link +- the client sets a password once +- that setup link becomes invalid immediately after successful use +- all later access goes through a normal login form in `apps/clients` +- clients can reset their password themselves from the client login page + +Client accounts are reused across multiple tablos by email. If a client who already has a password-based account is invited to another tablo, they should receive an access notification email instead of another password-setup link. + +## Problem Statement + +The current magic-link callback flow creates the wrong steady-state model for the client portal. + +### Current issues + +1. The invite email behaves as an authentication mechanism instead of a one-time onboarding step. +2. `apps/clients` does not provide a standard login form for later access. +3. The current callback-style flow is a poor fit for a client portal meant to feel like a stable authenticated product. +4. Reinviting the same email is awkward because the current model is centered around link acceptance rather than an account reused across multiple tablos. +5. The current flow does not express a strong boundary between `apps/main` users and `apps/clients` users. + +## Goals + +- Replace callback-style magic-link onboarding with one-time password setup +- Make `apps/clients` a normal email/password application after onboarding +- Reuse one client account per email across multiple tablos +- Allow self-service password reset from the client login page +- Support direct notification links to `clients.xtablo.com/tablo/:tabloId` +- Keep clients restricted to `apps/clients` only +- Reuse the main login page visual design through a shared auth UI surface + +## Non-Goals + +- Permanent bearer links that grant direct tablo access without authentication +- Self-service client signup without invitation +- Creating a separate custom auth system outside Supabase +- Granting client-portal users access to `apps/main` +- Preserving the current callback-based onboarding as the primary flow + +## Hard Requirements + +- Client users must not have access to `apps/main` +- The password-setup link must be one-time use +- The setup link must become invalid immediately after successful password creation +- The same email must map to one reusable client account across multiple tablos +- Existing onboarded clients invited to another tablo must receive an access notification email, not a new setup link +- The notification email must link directly to `clients.xtablo.com/tablo/:tabloId` + +## Chosen Approach + +Keep Supabase as the underlying authentication provider, but move invitation control into an invite lifecycle owned by the backend. + +The backend creates or reuses a client auth user by email, grants access to the target tablo, and then chooses between two email modes: + +- onboarding email with a one-time setup token +- access notification email for an already-onboarded client + +`apps/clients` becomes a normal authenticated app with: + +- a login page +- a one-time set-password page +- a forgot-password flow +- protected routes that redirect unauthenticated users to login and then resume their intended destination + +## User Classes And App Boundary + +The system should treat main-app users and client-portal users as distinct user classes. + +### Main-app users + +- collaborators +- internal users +- users who are allowed to access `app.xtablo.com` + +### Client-portal users + +- external client users invited to tablos +- users who are allowed to access `clients.xtablo.com` +- users who must not be able to use `apps/main` + +### Boundary rule + +Sharing auth UI does not mean sharing authorization. + +Client accounts must be rejected by `apps/main` even if they hold a valid authenticated session. This boundary must be enforced in backend authorization as well as frontend routing. + +## Auth Model + +`apps/clients` becomes a normal password-based portal. + +### Steady state + +- one client account per email +- reused across multiple tablos +- normal email/password login after onboarding +- standard self-service password reset via "mot de passe oublié" + +### Invite role + +The invite email is no longer the long-term access credential. It is only the bootstrap mechanism for first-time password setup. + +## Invite Lifecycle + +Invite creation should branch based on whether the email already belongs to an onboarded client account. + +### First invite for an email without a password-based client account + +- create or reuse the client auth user for that email +- create or confirm the tablo access grant +- create a one-time setup token +- send a setup email to `clients.xtablo.com` + +### Later invite for an existing onboarded client account + +- create or confirm the tablo access grant +- do not create a setup token +- send a "you now have access" notification email + +This keeps onboarding single-use while allowing account reuse across many tablos. + +## End-To-End Flows + +### First-time onboarding flow + +1. Admin invites a client from `app.xtablo.com`. +2. Backend creates or reuses the client auth user. +3. Backend grants access to the target tablo. +4. Backend creates a one-time setup token. +5. Email sends a setup URL into `clients.xtablo.com`. +6. Client opens the link and validates the token. +7. Client sets a password. +8. Backend invalidates the token immediately. +9. Client is signed in and redirected into the client portal. + +### Additional tablo access for an already-onboarded client + +1. Admin invites the same email to another tablo. +2. Backend reuses the same client account. +3. Backend grants access to the target tablo. +4. Email sends a notification link to `clients.xtablo.com/tablo/:tabloId`. +5. If the client already has a session, the tablo opens directly. +6. If not authenticated, `apps/clients` redirects to login and returns to that tablo after successful login. + +## Frontend Design + +`apps/clients` should expose three auth surfaces: + +- `LoginPage` +- `SetPasswordPage` +- existing authenticated portal routes + +### LoginPage + +Requirements: + +- minimal standalone auth screen +- visually matches the main login page +- built from a shared auth UI package instead of importing directly from `apps/main` +- email and password fields +- forgot-password entry point +- no self-service signup + +### SetPasswordPage + +Requirements: + +- dedicated route for one-time invite setup +- validates token before allowing password creation +- handles invalid, expired, and already-used tokens clearly +- on success, invalidates token and transitions into an authenticated client session + +### Protected route behavior + +- unauthenticated access to `clients.xtablo.com/tablo/:tabloId` redirects to login +- login preserves and resumes the intended destination +- fallback destination remains the client tablo list if no target route was captured + +## Shared Auth UI + +The login page in `apps/clients` should look like the main login page, but this should be done through extraction, not duplication. + +Recommended ownership split: + +- shared package owns auth shell, layout, form framing, banners, and visual treatment +- `apps/main` and `apps/clients` own submit handlers, route targets, and app-specific copy + +This keeps visual parity durable without coupling `apps/clients` directly to `apps/main` internals. + +## Backend Design + +`client_invites` should remain the lifecycle/control record, but its meaning changes. + +### Previous role + +- pending invite accepted through callback-style magic-link flow + +### New role + +- one-time password-setup authorization record for first-time onboarding + +### Backend responsibilities + +`POST /client-invites/:tabloId` + +- create or reuse client auth user by email +- create or confirm tablo access +- decide whether this email needs onboarding or only an access notification +- send the correct email type + +Token validation endpoint: + +- used by `SetPasswordPage` +- verifies token exists, is pending, and is still valid + +Password setup completion endpoint: + +- verifies token again +- sets password for the underlying auth user +- invalidates token immediately +- completes the onboarding transition cleanly + +Admin visibility and cancellation endpoints: + +- remain available for operational control +- cancelling a pending setup invite invalidates that setup path immediately + +## Authorization Model + +Authorization must reflect the split between apps. + +### Required behavior + +- client-portal users can access `apps/clients` resources they were granted +- client-portal users cannot use `apps/main` flows +- main-app authorization cannot assume that every authenticated user is a main-app user + +This must be enforced on the backend, not only in the frontend shell. + +## Error Handling + +### Frontend + +`SetPasswordPage` must handle: + +- invalid token +- expired token +- already-used token +- password policy failure + +`LoginPage` must handle: + +- wrong credentials +- reset email sent state +- reset failure + +Protected routes must: + +- redirect unauthenticated users to login +- preserve intended destination +- resume navigation after login + +### Backend + +Invite creation must distinguish: + +- first-time onboarding invite +- additional-access notification + +Token completion must fail cleanly on: + +- expired token +- reused token +- cancelled token + +## Testing Strategy + +### API tests + +- first invite for a new client creates a setup token and sends setup email +- second invite for an already-onboarded client skips setup token creation and sends access notification +- setup token can be used exactly once +- expired or reused setup token is rejected +- client-only accounts are rejected by main-app authorization paths + +### Frontend tests + +- login page renders through shared auth UI and submits email/password flow +- forgot-password flow is reachable from the client login page +- set-password page handles success, invalid token, expired token, and reused token states +- protected `tablo/:tabloId` route redirects to login and resumes correctly after authentication +- access notification deep-link opens the intended tablo after login + +### Manual verification + +- first invite email for a new client leads to one-time setup, then normal login +- second invite for the same client leads to access notification only +- `clients.xtablo.com/tablo/:tabloId` works both with and without an existing session +- client user cannot enter `app.xtablo.com` + +## Migration Notes + +- the current `apps/clients/src/pages/AuthCallback.tsx` route should be removed or reduced to legacy compatibility once this flow is live +- existing frontend code that assumes invitation equals magic-link acceptance should be replaced with setup-token and login flows +- because the feature is not yet live, no legacy client-user migration path is required From f02c36dbb70d7ff2cc2dc09243c2ce44f944d08f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:09:04 +0200 Subject: [PATCH 21/44] feat: add client password invite flow --- .../__tests__/routes/clientInvites.test.ts | 204 ++++-- apps/api/src/helpers/helpers.ts | 206 ++++-- apps/api/src/routers/clientInvites.ts | 336 +++++++--- apps/api/src/routers/maybeAuthRouter.ts | 2 + apps/clients/package.json | 1 + .../clients/src/components/ClientAuthGate.tsx | 56 ++ .../src/components/ClientLayout.test.tsx | 12 + apps/clients/src/components/ClientLayout.tsx | 14 +- apps/clients/src/i18n.test.ts | 4 + apps/clients/src/i18n.ts | 4 + apps/clients/src/pages/AuthCallback.tsx | 65 +- apps/clients/src/pages/LoginPage.test.tsx | 62 ++ apps/clients/src/pages/LoginPage.tsx | 102 +++ .../src/pages/ResetPasswordPage.test.tsx | 42 ++ apps/clients/src/pages/ResetPasswordPage.tsx | 71 ++ .../src/pages/SetPasswordPage.test.tsx | 91 +++ apps/clients/src/pages/SetPasswordPage.tsx | 205 ++++++ apps/clients/src/routes.tsx | 15 +- apps/clients/src/test/testHelpers.tsx | 10 +- apps/clients/tsconfig.json | 2 + apps/clients/tsconfig.tsbuildinfo | 2 +- apps/main/package.json | 1 + .../src/components/ProtectedRoute.test.tsx | 1 + .../src/components/SubscriptionCard.test.tsx | 1 + .../main/src/components/UpgradePanel.test.tsx | 1 + .../src/contexts/UpgradeBlockContext.test.tsx | 1 + apps/main/src/hooks/client_invites.ts | 23 +- apps/main/src/pages/login.test.tsx | 1 + apps/main/src/pages/login.tsx | 273 +++----- apps/main/src/pages/reset-password.test.tsx | 1 + apps/main/src/pages/reset-password.tsx | 162 ++--- .../src/pages/tablo-details.layout.test.tsx | 11 +- apps/main/src/pages/tablo-details.tsx | 10 +- .../src/providers/UserStoreProvider.test.tsx | 1 + apps/main/src/utils/testHelpers.tsx | 1 + apps/main/tsconfig.app.json | 2 + .../2026-04-18-client-password-invite-flow.md | 626 ++++++++++++++++++ packages/auth-ui/package.json | 32 + packages/auth-ui/src/AuthCardShell.tsx | 125 ++++ .../auth-ui/src/AuthEmailPasswordForm.tsx | 83 +++ packages/auth-ui/src/AuthInfoBanner.tsx | 33 + packages/auth-ui/src/index.ts | 3 + packages/auth-ui/tsconfig.json | 27 + packages/shared-types/src/database.types.ts | 15 + pnpm-lock.yaml | 43 ++ ...20260418110000_client_password_invites.sql | 27 + 46 files changed, 2419 insertions(+), 591 deletions(-) create mode 100644 apps/clients/src/components/ClientAuthGate.tsx create mode 100644 apps/clients/src/pages/LoginPage.test.tsx create mode 100644 apps/clients/src/pages/LoginPage.tsx create mode 100644 apps/clients/src/pages/ResetPasswordPage.test.tsx create mode 100644 apps/clients/src/pages/ResetPasswordPage.tsx create mode 100644 apps/clients/src/pages/SetPasswordPage.test.tsx create mode 100644 apps/clients/src/pages/SetPasswordPage.tsx create mode 100644 docs/superpowers/plans/2026-04-18-client-password-invite-flow.md create mode 100644 packages/auth-ui/package.json create mode 100644 packages/auth-ui/src/AuthCardShell.tsx create mode 100644 packages/auth-ui/src/AuthEmailPasswordForm.tsx create mode 100644 packages/auth-ui/src/AuthInfoBanner.tsx create mode 100644 packages/auth-ui/src/index.ts create mode 100644 packages/auth-ui/tsconfig.json create mode 100644 supabase/migrations/20260418110000_client_password_invites.sql diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts index 17bfc08..5ffcefb 100644 --- a/apps/api/src/__tests__/routes/clientInvites.test.ts +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -62,19 +62,23 @@ describe("Client Invites Endpoints", () => { { headers: { Authorization: `Bearer ${user.accessToken}` } } ); - const acceptInvite = (user: TestUserData, token: string) => - client["client-invites"].accept[":token"].$post( - { param: { token } }, - { headers: { Authorization: `Bearer ${user.accessToken}` } } - ); + const getSetupInvite = (token: string) => + client["client-invites"].setup[":token"].$get({ + param: { token }, + }); - // ─── Helper: insert a client_invite row directly via admin ────────────────── + const completeSetupInvite = (token: string, password: string) => + client["client-invites"].setup[":token"].$post({ + param: { token }, + json: { password }, + }); const insertClientInvite = async (opts: { tabloId: string; invitedEmail: string; invitedBy: string; token: string; + inviteType?: string; isPending?: boolean; expiresAt?: string; }) => { @@ -87,6 +91,7 @@ describe("Client Invites Endpoints", () => { invited_email: opts.invitedEmail, invited_by: opts.invitedBy, invite_token: opts.token, + invite_type: opts.inviteType ?? "setup", is_pending: opts.isPending ?? true, expires_at: expiresAt, }) @@ -97,11 +102,9 @@ describe("Client Invites Endpoints", () => { return data.id as number; }; - // ─── Cleanup helper ────────────────────────────────────────────────────────── - const cleanupInvitesByEmail = async (email: string) => { await supabaseAdmin.from("client_invites").delete().eq("invited_email", email); - // Also clean up any client user that may have been created + const { data: usersData } = await supabaseAdmin.auth.admin.listUsers(); // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const users = usersData as any; @@ -113,50 +116,118 @@ describe("Client Invites Endpoints", () => { } }; + const createClientAccount = async ( + email: string, + input?: { onboarded?: boolean; password?: string } + ) => { + const password = input?.password ?? "client_password_123"; + const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({ + email, + password, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + throw new Error(`Failed to create client account: ${authError?.message}`); + } + + const updates: Record = { is_client: true }; + if (input?.onboarded) { + updates.client_onboarded_at = new Date().toISOString(); + } + + const { error: profileError } = await supabaseAdmin + .from("profiles") + .update(updates) + .eq("id", authData.user.id); + + if (profileError) { + throw new Error(`Failed to update client profile: ${profileError.message}`); + } + + return authData.user; + }; + // ════════════════════════════════════════════════════════════════════════════ // POST /:tabloId — Create client invite // ════════════════════════════════════════════════════════════════════════════ describe("POST /client-invites/:tabloId", () => { const testEmail = "test_client_invite_new@example.com"; + const existingClientEmail = "test_existing_client_invite@example.com"; beforeEach(async () => { await cleanupInvitesByEmail(testEmail); + await cleanupInvitesByEmail(existingClientEmail); }); - it("should create a client invite for a valid email (admin)", async () => { + it("creates a setup token for a first-time client invite", async () => { const res = await postInvite(ownerUser, adminTabloId, testEmail); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); + expect(data.inviteMode).toBe("setup"); - // Verify row was inserted const { data: invite } = await supabaseAdmin .from("client_invites") - .select("id, invited_email, is_pending") + .select("id, invited_email, is_pending, invite_token, invite_type") .eq("tablo_id", adminTabloId) .eq("invited_email", testEmail) .single(); expect(invite).toBeDefined(); expect(invite?.is_pending).toBe(true); + expect(invite?.invite_token).toBeTruthy(); + expect(invite?.invite_type).toBe("setup"); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain("/set-password?token="); }); - it("should reject temporary users before admin check", async () => { - // tempUser is NOT admin of adminTabloId (owner user owns it) + it("sends an access notification for an already-onboarded client", async () => { + await createClientAccount(existingClientEmail, { onboarded: true }); + + const res = await postInvite(ownerUser, adminTabloId, existingClientEmail); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.inviteMode).toBe("notification"); + + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("id") + .eq("tablo_id", adminTabloId) + .eq("invited_email", existingClientEmail) + .maybeSingle(); + + expect(invite).toBeNull(); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain(`/tablo/${adminTabloId}`); + }); + + it("rejects emails already used by a main-app account", async () => { + const res = await postInvite(ownerUser, adminTabloId, ownerUser.email); + + expect(res.status).toBe(409); + const data = await res.json(); + expect(data.error).toContain("already belongs"); + }); + + it("rejects temporary users before admin check", async () => { const res = await postInvite(tempUser, adminTabloId, testEmail); expect(res.status).toBe(401); }); - it("should return 400 for an invalid email", async () => { + it("returns 400 for an invalid email", async () => { const res = await postInvite(ownerUser, adminTabloId, "not-an-email"); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toContain("valid email"); }); - it("should return 400 for a missing email", async () => { + it("returns 400 for a missing email", async () => { const res = client["client-invites"][":tabloId"].$post( { param: { tabloId: adminTabloId }, json: {} }, { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } } @@ -164,7 +235,7 @@ describe("Client Invites Endpoints", () => { expect((await res).status).toBe(400); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].$post({ param: { tabloId: adminTabloId }, json: { email: testEmail }, @@ -174,54 +245,50 @@ describe("Client Invites Endpoints", () => { }); // ════════════════════════════════════════════════════════════════════════════ - // POST /accept/:token — Accept a client invite + // GET/POST /setup/:token — Validate and complete a client setup invite // ════════════════════════════════════════════════════════════════════════════ - describe("POST /client-invites/accept/:token", () => { - it("should accept an invite and return tabloId", async () => { - const token = `test_accept_valid_${Date.now()}`; + describe("GET/POST /client-invites/setup/:token", () => { + const setupEmail = "test_client_setup@example.com"; - // Insert invite for the owner user's email + beforeEach(async () => { + await cleanupInvitesByEmail(setupEmail); + }); + + it("returns invite metadata for a valid pending setup token", async () => { + const token = `test_setup_valid_${Date.now()}`; await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(200); const data = await res.json(); - expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); expect(data.tabloId).toBe(adminTabloId); - - // Verify invite is now not pending - const { data: invite } = await supabaseAdmin - .from("client_invites") - .select("is_pending") - .eq("invite_token", token) - .single(); - expect(invite?.is_pending).toBe(false); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 410 for an expired invite", async () => { + it("returns 410 for an expired invite", async () => { const token = `test_expired_${Date.now()}`; - const pastDate = new Date(Date.now() - 1000).toISOString(); // already expired + const pastDate = new Date(Date.now() - 1000).toISOString(); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, expiresAt: pastDate, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(410); const data = await res.json(); expect(data.error).toContain("expired"); @@ -230,35 +297,50 @@ describe("Client Invites Endpoints", () => { } }); - it("should return 403 when email does not match the authenticated user", async () => { - const token = `test_email_mismatch_${Date.now()}`; - - // Invite is for tempUser's email but we authenticate as ownerUser + it("completes password setup once and rejects reuse", async () => { + const token = `test_setup_complete_${Date.now()}`; + await createClientAccount(setupEmail); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: tempUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); // wrong user - expect(res.status).toBe(403); + const res = await completeSetupInvite(token, "new_password_123"); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); + expect(data.tabloId).toBe(adminTabloId); + + const reused = await completeSetupInvite(token, "new_password_456"); + expect(reused.status).toBe(404); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 404 for a non-existent token", async () => { - const res = await acceptInvite(ownerUser, "nonexistent_token_xyz"); + it("returns 404 for a non-existent token", async () => { + const res = await getSetupInvite("nonexistent_token_xyz"); expect(res.status).toBe(404); }); - it("should return 401 for unauthenticated requests", async () => { - const res = await client["client-invites"].accept[":token"].$post({ - param: { token: "some_token" }, + it("marks cancelled pending setup tokens unusable", async () => { + const token = `test_setup_cancelled_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: setupEmail, + invitedBy: ownerUser.userId, + token, }); - expect(res.status).toBe(401); + + const cancelRes = await deleteInvite(ownerUser, adminTabloId, inviteId); + expect(cancelRes.status).toBe(200); + + const res = await getSetupInvite(token); + expect(res.status).toBe(404); }); }); @@ -280,7 +362,7 @@ describe("Client Invites Endpoints", () => { }); }); - it("should return pending invites for an admin", async () => { + it("returns pending invites for an admin", async () => { const res = await getPending(ownerUser, adminTabloId); expect(res.status).toBe(200); const data = await res.json(); @@ -292,12 +374,12 @@ describe("Client Invites Endpoints", () => { expect(found.is_pending).toBe(true); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const res = await getPending(tempUser, adminTabloId); expect(res.status).toBe(401); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].pending.$get({ param: { tabloId: adminTabloId }, }); @@ -316,8 +398,7 @@ describe("Client Invites Endpoints", () => { await cleanupInvitesByEmail(cancelEmail); }); - it("should cancel a pending invite and revoke client access", async () => { - // First create a client user and tablo_access entry via the API + it("cancels a pending invite and revokes client access", async () => { const token = `test_cancel_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -326,14 +407,11 @@ describe("Client Invites Endpoints", () => { token, }); - // Create a mock profile to revoke (uses admin client to simulate client user existing) - // We'll skip verifying the user's actual auth account since we just need to test cancellation const res = await deleteInvite(ownerUser, adminTabloId, inviteId); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); - // Verify invite is now not pending const { data: invite } = await supabaseAdmin .from("client_invites") .select("is_pending") @@ -342,7 +420,7 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(false); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const token = `test_cancel_nonadmin_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -355,19 +433,19 @@ describe("Client Invites Endpoints", () => { expect(res.status).toBe(401); }); - it("should return 404 for a non-existent invite", async () => { + it("returns 404 for a non-existent invite", async () => { const res = await deleteInvite(ownerUser, adminTabloId, 999999); expect(res.status).toBe(404); }); - it("should return 400 for an already-cancelled invite", async () => { + it("returns 400 for an already-cancelled invite", async () => { const token = `test_cancel_already_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, invitedEmail: cancelEmail, invitedBy: ownerUser.userId, token, - isPending: false, // already cancelled + isPending: false, }); const res = await deleteInvite(ownerUser, adminTabloId, inviteId); @@ -376,7 +454,7 @@ describe("Client Invites Endpoints", () => { expect(data.error).toContain("pending"); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"][":inviteId"].$delete({ param: { tabloId: adminTabloId, inviteId: "1" }, }); diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index f559288..99a3acb 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -364,67 +364,193 @@ export const createInvitedUser = async ( return { success: true, userId: newUser.user.id }; }; -/** - * Creates or finds a client user, marks them as is_client, and grants tablo access. - */ -export async function createClientUser( - supabase: SupabaseClient, - recipientEmail: string, - tabloId: string, - grantedBy: string -): Promise<{ success: boolean; error?: string; userId?: string }> { - // Check if user already exists - const { data: existingUsersData } = await supabase.auth.admin.listUsers(); +type ClientAccount = { + email: string; + is_client: boolean; + client_onboarded_at: string | null; + userId: string; +}; + +type ClientAccountResult = + | { success: true; account: ClientAccount; wasCreated: boolean } + | { success: false; error: string }; + +const getAuthUserByEmail = async (supabase: SupabaseClient, email: string) => { + const { data: existingUsersData, error } = await supabase.auth.admin.listUsers(); + if (error) { + return { user: null, error: error.message }; + } + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const existingUsers = existingUsersData as any; const existingUser = existingUsers?.users?.find( // biome-ignore lint/suspicious/noExplicitAny: admin user type - (u: any) => u.email?.toLowerCase() === recipientEmail.toLowerCase() + (u: any) => u.email?.toLowerCase() === email.toLowerCase() ); - let userId: string; + return { user: existingUser ?? null, error: null }; +}; - if (existingUser) { - userId = existingUser.id; - // Mark as client if not already - await supabase - .from("profiles") - .update({ is_client: true }) - .eq("id", userId) - .eq("is_client", false); - } else { - // Create new auth user (no password — magic link only) - const { data: authData, error: authError } = await supabase.auth.admin.createUser({ - email: recipientEmail, - email_confirm: true, - user_metadata: { role: "client" }, - }); - if (authError || !authData?.user) { - return { success: false, error: authError?.message ?? "Failed to create user" }; - } - userId = authData.user.id; - await supabase.from("profiles").update({ is_client: true }).eq("id", userId); +export async function hasCompletedClientOnboarding( + supabase: SupabaseClient, + userId: string +): Promise<{ completed: boolean; error?: string }> { + const { data: profile, error } = await supabase + .from("profiles") + .select("client_onboarded_at") + .eq("id", userId) + .maybeSingle(); + + if (error) { + return { completed: false, error: error.message }; } - // Grant tablo access if not already granted - const { data: existingAccess } = await supabase + return { completed: !!profile?.client_onboarded_at }; +} + +export async function findOrCreateClientAccount( + supabase: SupabaseClient, + recipientEmail: string +): Promise { + const normalizedEmail = recipientEmail.trim().toLowerCase(); + const { user: existingUser, error: lookupError } = await getAuthUserByEmail(supabase, normalizedEmail); + + if (lookupError) { + return { success: false, error: lookupError }; + } + + if (existingUser) { + const { data: existingProfile, error: profileError } = await supabase + .from("profiles") + .select("email, is_client, client_onboarded_at") + .eq("id", existingUser.id) + .maybeSingle(); + + if (profileError) { + return { success: false, error: profileError.message }; + } + + if (!existingProfile) { + return { success: false, error: "Client profile not found" }; + } + + if (!existingProfile.is_client) { + return { + success: false, + error: "This email already belongs to a main app account", + }; + } + + return { + success: true, + wasCreated: false, + account: { + email: existingProfile.email ?? normalizedEmail, + is_client: existingProfile.is_client, + client_onboarded_at: existingProfile.client_onboarded_at, + userId: existingUser.id, + }, + }; + } + + const { data: authData, error: authError } = await supabase.auth.admin.createUser({ + email: normalizedEmail, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + return { success: false, error: authError?.message ?? "Failed to create client user" }; + } + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ is_client: true, client_onboarded_at: null }) + .eq("id", authData.user.id); + + if (updateProfileError) { + return { success: false, error: updateProfileError.message }; + } + + return { + success: true, + wasCreated: true, + account: { + email: normalizedEmail, + is_client: true, + client_onboarded_at: null, + userId: authData.user.id, + }, + }; +} + +export async function ensureClientTabloAccess( + supabase: SupabaseClient, + tabloId: string, + userId: string, + grantedBy: string +): Promise<{ success: boolean; error?: string }> { + const { data: existingAccess, error: accessError } = await supabase .from("tablo_access") .select("id, is_active") .eq("tablo_id", tabloId) .eq("user_id", userId) - .single(); + .maybeSingle(); + + if (accessError) { + return { success: false, error: accessError.message }; + } if (!existingAccess) { - await supabase.from("tablo_access").insert({ + const { error: insertError } = await supabase.from("tablo_access").insert({ tablo_id: tabloId, user_id: userId, granted_by: grantedBy, is_admin: false, is_active: true, }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); + if (insertError) { + return { success: false, error: insertError.message }; + } + return { success: true }; } - return { success: true, userId }; + if (!existingAccess.is_active) { + const { error: updateError } = await supabase + .from("tablo_access") + .update({ is_active: true }) + .eq("id", existingAccess.id); + if (updateError) { + return { success: false, error: updateError.message }; + } + } + + return { success: true }; +} + +export async function createClientSetupInvite( + supabase: SupabaseClient, + input: { + tabloId: string; + invitedEmail: string; + invitedBy: string; + token: string; + expiresAt: string; + } +): Promise<{ success: boolean; error?: string }> { + const { error } = await supabase.from("client_invites").insert({ + tablo_id: input.tabloId, + invited_email: input.invitedEmail, + invited_by: input.invitedBy, + invite_token: input.token, + invite_type: "setup", + is_pending: true, + expires_at: input.expiresAt, + }); + + if (error) { + return { success: false, error: error.message }; + } + + return { success: true }; } diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index f14f977..d42da4c 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -1,19 +1,97 @@ import { Hono } from "hono"; import { createFactory } from "hono/factory"; -import { checkTabloAdmin, createClientUser } from "../helpers/helpers.js"; +import { + checkTabloAdmin, + createClientSetupInvite, + ensureClientTabloAccess, + findOrCreateClientAccount, +} from "../helpers/helpers.js"; import { generateToken } from "../helpers/token.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; -import type { AuthEnv } from "../types/app.types.js"; +import type { AuthEnv, BaseEnv } from "../types/app.types.js"; -const factory = createFactory(); +const authFactory = createFactory(); +const publicFactory = createFactory(); const CLIENT_INVITE_EXPIRY_HOURS = 72; +const getClientsUrl = () => process.env.CLIENTS_URL || "https://clients.xtablo.com"; + +const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); + +const findInviteByToken = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => + supabase + .from("client_invites") + .select( + "id, tablo_id, invited_email, invited_by, invite_type, is_pending, expires_at, used_at, cancelled_at, setup_completed_at" + ) + .eq("invite_token", token) + .maybeSingle(); + +const validateSetupInvite = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => { + const { data: invite, error } = await findInviteByToken(token, supabase); + + if (error) { + return { status: 500 as const, body: { error: error.message } }; + } + + if (!invite || invite.invite_type !== "setup" || !invite.is_pending) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.cancelled_at || invite.used_at || invite.setup_completed_at) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.expires_at && new Date(invite.expires_at) < new Date()) { + return { status: 410 as const, body: { error: "This invite has expired" } }; + } + + return { status: 200 as const, invite }; +}; + +const sendSetupEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; setupUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Configurez votre accès client Xtablo", + html: ` +

Vous avez été invité sur Xtablo

+

Bonjour,

+

Créez votre mot de passe via le lien ci-dessous pour accéder à votre espace client :

+

Configurer mon mot de passe

+

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures et ne peut être utilisé qu'une seule fois.

+ `, + }); +}; + +const sendAccessNotificationEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; tabloUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Vous avez maintenant accès à un nouveau tablo", + html: ` +

Vous avez maintenant accès à un tablo

+

Bonjour,

+

Votre accès a été ajouté. Utilisez le lien ci-dessous pour ouvrir directement le tablo :

+

Ouvrir le tablo

+

Si vous n'êtes pas connecté, vous serez redirigé vers la page de connexion.

+ `, + }); +}; + /** POST /:tabloId — Create a client invite (admin only) */ const createClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const user = c.get("user"); const supabase = c.get("supabase"); + const transporter = c.get("transporter"); const tabloId = c.req.param("tabloId"); const body = await c.req.json(); @@ -21,14 +99,42 @@ const createClientInvite = (middlewareManager: ReturnType", - to: rawEmail, - subject: "Vous avez été invité sur Xtablo", - html: ` -

Vous avez été invité à collaborer sur un tablo

-

Bonjour,

-

Cliquez sur le lien ci-dessous pour accéder à votre espace client :

-

Accéder à mon espace

-

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.

- `, - }); - } catch (emailError) { - console.error("Failed to send client invite email:", emailError); - } + try { + await sendSetupEmail(transporter, { + email: rawEmail, + setupUrl: `${clientsUrl}/set-password?token=${encodeURIComponent(token)}`, + }); + } catch (emailError) { + console.error("Failed to send client setup email:", emailError); } - return c.json({ success: true }); + return c.json({ success: true, inviteMode: "setup" as const }); }); -/** POST /accept/:token — Accept a client invite */ -const acceptClientInvite = (_middlewareManager: ReturnType) => - factory.createHandlers(async (c) => { - const user = c.get("user"); +/** GET /setup/:token — Validate a setup invite token */ +const getSetupInvite = () => + publicFactory.createHandlers(async (c) => { const supabase = c.get("supabase"); const token = c.req.param("token"); - const { data: invite, error: inviteError } = await supabase + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + return c.json({ + email: validation.invite.invited_email, + tabloId: validation.invite.tablo_id, + }); + }); + +/** POST /setup/:token — Complete one-time password setup */ +const completeSetupInvite = () => + publicFactory.createHandlers(async (c) => { + const supabase = c.get("supabase"); + const token = c.req.param("token"); + const body = await c.req.json(); + const password = String(body.password || ""); + + if (password.length < 8) { + return c.json({ error: "Password must be at least 8 characters long" }, 400); + } + + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + const invite = validation.invite; + const { data: usersData, error: listUsersError } = await supabase.auth.admin.listUsers(); + if (listUsersError) { + return c.json({ error: listUsersError.message }, 500); + } + + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime + const users = usersData as any; + // biome-ignore lint/suspicious/noExplicitAny: admin user type + const clientUser = users?.users?.find((candidate: any) => { + return candidate.email?.toLowerCase() === invite.invited_email?.toLowerCase(); + }); + + if (!clientUser?.id) { + return c.json({ error: "Client account not found" }, 404); + } + + const { error: updateUserError } = await supabase.auth.admin.updateUserById(clientUser.id, { + password, + }); + if (updateUserError) { + return c.json({ error: updateUserError.message }, 500); + } + + const completedAt = new Date().toISOString(); + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ client_onboarded_at: completedAt, is_client: true }) + .eq("id", clientUser.id); + if (updateProfileError) { + return c.json({ error: updateProfileError.message }, 500); + } + + const { error: consumeInviteError } = await supabase .from("client_invites") - .select("id, tablo_id, invited_email, invited_by, is_pending, expires_at") - .eq("invite_token", token) - .maybeSingle(); - - if (inviteError) { - return c.json({ error: inviteError.message }, 500); + .update({ + is_pending: false, + used_at: completedAt, + setup_completed_at: completedAt, + }) + .eq("id", invite.id) + .eq("is_pending", true); + if (consumeInviteError) { + return c.json({ error: consumeInviteError.message }, 500); } - if (!invite || !invite.is_pending) { - return c.json({ error: "Invite not found or already used" }, 404); - } - - // Check expiration - if (invite.expires_at && new Date(invite.expires_at) < new Date()) { - return c.json({ error: "This invite has expired" }, 410); - } - - // Email must match the authenticated user - if (invite.invited_email?.toLowerCase() !== user.email?.toLowerCase()) { - return c.json({ error: "This invite was not issued to your account" }, 403); - } - - // Mark invite as accepted - await supabase.from("client_invites").update({ is_pending: false }).eq("id", invite.id); - - // Ensure tablo access is active - const { data: existingAccess } = await supabase - .from("tablo_access") - .select("id, is_active") - .eq("tablo_id", invite.tablo_id) - .eq("user_id", user.id) - .maybeSingle(); - - if (!existingAccess) { - await supabase.from("tablo_access").insert({ - tablo_id: invite.tablo_id, - user_id: user.id, - granted_by: invite.invited_by, - is_admin: false, - is_active: true, - }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); - } - - return c.json({ success: true, tabloId: invite.tablo_id }); + return c.json({ + success: true, + email: invite.invited_email, + tabloId: invite.tablo_id, + }); }); /** GET /:tabloId/pending — List pending client invites (admin only) */ const getPendingClientInvites = ( middlewareManager: ReturnType ) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const { data: invites, error } = await supabase .from("client_invites") - .select("id, invited_email, expires_at, is_pending, created_at") + .select("id, invited_email, expires_at, is_pending, created_at, invite_type") .eq("tablo_id", tabloId) + .eq("invite_type", "setup") .eq("is_pending", true) .order("created_at", { ascending: false }); @@ -169,7 +282,7 @@ const getPendingClientInvites = ( /** DELETE /:tabloId/:inviteId — Cancel a client invite (admin only) */ const cancelClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const inviteId = Number(c.req.param("inviteId")); @@ -180,7 +293,7 @@ const cancelClientInvite = (middlewareManager: ReturnType { const middlewareManager = MiddlewareManager.getInstance(); router.post("/:tabloId", ...createClientInvite(middlewareManager)); - router.post("/accept/:token", ...acceptClientInvite(middlewareManager)); router.get("/:tabloId/pending", ...getPendingClientInvites(middlewareManager)); router.delete("/:tabloId/:inviteId", ...cancelClientInvite(middlewareManager)); return router; }; + +export const getPublicClientInvitesRouter = () => { + const router = new Hono(); + + router.get("/setup/:token", ...getSetupInvite()); + router.post("/setup/:token", ...completeSetupInvite()); + + return router; +}; diff --git a/apps/api/src/routers/maybeAuthRouter.ts b/apps/api/src/routers/maybeAuthRouter.ts index 7da5c8e..b01a6c5 100644 --- a/apps/api/src/routers/maybeAuthRouter.ts +++ b/apps/api/src/routers/maybeAuthRouter.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { MaybeAuthEnv } from "../types/app.types.js"; +import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getBookingRouter } from "./invite.js"; export const getMaybeAuthenticatedRouter = () => { @@ -11,6 +12,7 @@ export const getMaybeAuthenticatedRouter = () => { maybeAuthenticated.use(middlewareManager.maybeAuthenticated); maybeAuthenticated.route("/book", getBookingRouter()); + maybeAuthenticated.route("/client-invites", getPublicClientInvitesRouter()); return maybeAuthenticated; }; diff --git a/apps/clients/package.json b/apps/clients/package.json index 68c5563..699fa82 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -39,6 +39,7 @@ }, "dependencies": { "@tanstack/react-query": "^5.69.0", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/clients/src/components/ClientAuthGate.tsx b/apps/clients/src/components/ClientAuthGate.tsx new file mode 100644 index 0000000..4c75eda --- /dev/null +++ b/apps/clients/src/components/ClientAuthGate.tsx @@ -0,0 +1,56 @@ +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useEffect, useState } from "react"; +import { Navigate, Outlet, useLocation } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ClientAuthGate() { + const { session } = useSession(); + const location = useLocation(); + const [isCheckingSession, setIsCheckingSession] = useState(true); + const [hasSession, setHasSession] = useState(false); + + useEffect(() => { + let isMounted = true; + + if (session) { + setHasSession(true); + setIsCheckingSession(false); + return () => { + isMounted = false; + }; + } + + supabase.auth + .getSession() + .then(({ data }) => { + if (!isMounted) return; + setHasSession(Boolean(data.session)); + }) + .finally(() => { + if (isMounted) { + setIsCheckingSession(false); + } + }); + + return () => { + isMounted = false; + }; + }, [session]); + + if (session || hasSession) { + return ; + } + + if (isCheckingSession) { + return ( +
+
+
+ ); + } + + const redirectUrl = `${location.pathname}${location.search}${location.hash}`; + localStorage.setItem("clients.redirectUrl", redirectUrl); + + return ; +} diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx index 17c3972..709a0c0 100644 --- a/apps/clients/src/components/ClientLayout.test.tsx +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -1,4 +1,6 @@ +import { screen } from "@testing-library/react"; import { describe, expect, it } from "vitest"; +import AppRoutes from "../routes"; import { renderWithProviders } from "../test/testHelpers"; import { ClientLayout } from "./ClientLayout"; @@ -20,4 +22,14 @@ describe("ClientLayout", () => { expect(main).toHaveClass("max-w-7xl"); expect(main).toHaveClass("mx-auto"); }); + + it("redirects unauthenticated client routes to the login page", async () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + testUser: undefined, + }); + + expect(await screen.findByTestId("auth-card-shell")).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); }); diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 16609cf..5ef32f4 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -14,19 +14,7 @@ function getInitials(email: string): string { export function ClientLayout() { const { session } = useSession(); - - if (!session) { - return ( -
-
-

Accès non autorisé

-

- Veuillez utiliser le lien reçu dans votre email pour accéder à cette page. -

-
-
- ); - } + if (!session) return null; const email = session.user.email ?? ""; const initials = email ? getInitials(email) : "?"; diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts index e7747d7..7ca4e6c 100644 --- a/apps/clients/src/i18n.test.ts +++ b/apps/clients/src/i18n.test.ts @@ -2,11 +2,13 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -16,6 +18,7 @@ import tabloFr from "../../main/src/locales/fr/tablo.json"; i18n.use(initReactI18next).init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -24,6 +27,7 @@ i18n.use(initReactI18next).init({ tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 5612ccd..92423b4 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -4,11 +4,13 @@ import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; // Import translation files import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -21,6 +23,7 @@ i18n .init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -29,6 +32,7 @@ i18n tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/pages/AuthCallback.tsx b/apps/clients/src/pages/AuthCallback.tsx index b34427b..806d3cb 100644 --- a/apps/clients/src/pages/AuthCallback.tsx +++ b/apps/clients/src/pages/AuthCallback.tsx @@ -1,66 +1,5 @@ -import { useSession } from "@xtablo/shared/contexts/SessionContext"; -import { useEffect, useRef, useState } from "react"; -import { useNavigate, useSearchParams } from "react-router-dom"; +import { Navigate } from "react-router-dom"; export function AuthCallback() { - const [searchParams] = useSearchParams(); - const token = searchParams.get("token"); - const { session } = useSession(); - const navigate = useNavigate(); - const [error, setError] = useState(null); - const hasAccepted = useRef(false); - - useEffect(() => { - if (!session || !token || hasAccepted.current) { - return; - } - - hasAccepted.current = true; - - const apiUrl = import.meta.env.VITE_API_URL as string; - - fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, { - method: "POST", - headers: { - Authorization: `Bearer ${session.access_token}`, - "Content-Type": "application/json", - }, - }) - .then(async (res) => { - if (!res.ok) { - const body = await res.json().catch(() => ({})); - throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"); - } - return res.json() as Promise<{ tabloId: string }>; - }) - .then((data) => { - navigate(`/tablo/${data.tabloId}`, { replace: true }); - }) - .catch((err: unknown) => { - console.error("Accept invite error:", err); - setError( - "Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invité." - ); - }); - }, [session, token, navigate]); - - if (error) { - return ( -
-
-

Erreur

-

{error}

-
-
- ); - } - - return ( -
-
-
-

Authentification en cours...

-
-
- ); + return ; } diff --git a/apps/clients/src/pages/LoginPage.test.tsx b/apps/clients/src/pages/LoginPage.test.tsx new file mode 100644 index 0000000..425eac6 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { LoginPage } from "./LoginPage"; + +const { mockSignInWithPassword, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("LoginPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + mockSignInWithPassword.mockResolvedValue({ + data: { user: { email_confirmed_at: new Date().toISOString() } }, + error: null, + }); + }); + + it("renders the shared auth shell and form", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); + + it("submits email/password login and resumes the stored redirect", async () => { + localStorage.setItem("clients.redirectUrl", "/tablo/tablo-42"); + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.click(screen.getByRole("button", { name: "Connexion" })); + + await waitFor(() => { + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-42"); + }); + }); +}); diff --git a/apps/clients/src/pages/LoginPage.tsx b/apps/clients/src/pages/LoginPage.tsx new file mode 100644 index 0000000..f38f582 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.tsx @@ -0,0 +1,102 @@ +import { AuthCardShell, AuthEmailPasswordForm, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link, useNavigate } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function LoginPage() { + const { t } = useTranslation(["auth", "common"]); + const { session } = useSession(); + const navigate = useNavigate(); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [isPending, setIsPending] = useState(false); + const [error, setError] = useState(null); + + if (session) { + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + } + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: signInError } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (signInError) { + setError(signInError.message); + setIsPending(false); + return; + } + + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + }; + + return ( + + + + + {t("auth:common.backHome")} + + } + showThemeToggle + > +
+ {error ? : null} + + + + {t("auth:login.forgotPassword")} + +
+ } + /> +
+ + ); +} diff --git a/apps/clients/src/pages/ResetPasswordPage.test.tsx b/apps/clients/src/pages/ResetPasswordPage.test.tsx new file mode 100644 index 0000000..18a4657 --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.test.tsx @@ -0,0 +1,42 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ResetPasswordPage } from "./ResetPasswordPage"; + +const { mockResetPasswordForEmail } = vi.hoisted(() => ({ + mockResetPasswordForEmail: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + resetPasswordForEmail: mockResetPasswordForEmail, + }, + }, +})); + +describe("ResetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockResetPasswordForEmail.mockResolvedValue({ error: null }); + }); + + it("renders the shared auth shell", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + }); + + it("submits a password reset email", async () => { + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.click(screen.getByRole("button", { name: "Envoyer le lien de réinitialisation" })); + + await waitFor(() => { + expect(mockResetPasswordForEmail).toHaveBeenCalled(); + expect(screen.getByText(/vérifiez votre boîte mail/i)).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/clients/src/pages/ResetPasswordPage.tsx b/apps/clients/src/pages/ResetPasswordPage.tsx new file mode 100644 index 0000000..85d591e --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.tsx @@ -0,0 +1,71 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ResetPasswordPage() { + const { t } = useTranslation(["auth", "common"]); + const [email, setEmail] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, { + redirectTo: `${window.location.origin}/set-password`, + }); + + if (resetError) { + setError(resetError.message); + setIsPending(false); + return; + } + + setIsSubmitted(true); + setIsPending(false); + }; + + return ( + +
+ {error ? : null} + {isSubmitted ? ( +
+ + + + +
+ ) : ( +
+
+ + setEmail(event.target.value)} + placeholder={t("auth:resetPassword.emailPlaceholder")} + required + disabled={isPending} + /> +
+ + +
+ )} +
+
+ ); +} diff --git a/apps/clients/src/pages/SetPasswordPage.test.tsx b/apps/clients/src/pages/SetPasswordPage.test.tsx new file mode 100644 index 0000000..1cce2ee --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.test.tsx @@ -0,0 +1,91 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { SetPasswordPage } from "./SetPasswordPage"; + +const { mockSignInWithPassword, mockUpdateUser, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockUpdateUser: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + updateUser: mockUpdateUser, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("SetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", vi.fn()); + mockSignInWithPassword.mockResolvedValue({ data: {}, error: null }); + mockUpdateUser.mockResolvedValue({ data: {}, error: null }); + }); + + it("renders an invalid-token state when invite validation fails", async () => { + vi.mocked(fetch).mockResolvedValueOnce( + new Response(JSON.stringify({ error: "Invite not found or already used" }), { status: 404 }) + ); + + renderWithProviders(, { + route: "/set-password?token=bad-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByText(/lien invalide/i)).toBeInTheDocument(); + }); + }); + + it("submits invite-based password setup once", async () => { + vi.mocked(fetch) + .mockResolvedValueOnce( + new Response(JSON.stringify({ email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ); + + renderWithProviders(, { + route: "/set-password?token=good-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + }); + + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.change(screen.getByLabelText("Confirmer le mot de passe"), { + target: { value: "password123" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Définir mon mot de passe" })); + + await waitFor(() => { + expect(fetch).toHaveBeenCalledTimes(2); + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-1"); + }); + }); +}); diff --git a/apps/clients/src/pages/SetPasswordPage.tsx b/apps/clients/src/pages/SetPasswordPage.tsx new file mode 100644 index 0000000..f775c4b --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.tsx @@ -0,0 +1,205 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useEffect, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +type InviteDetails = { + email: string; + tabloId: string; +}; + +type InviteState = "loading" | "ready" | "invalid"; + +function getApiUrl() { + return import.meta.env.VITE_API_URL ?? ""; +} + +async function parseError(response: Response) { + const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string }; + return body.error ?? body.message ?? "Une erreur est survenue."; +} + +export function SetPasswordPage() { + const { t } = useTranslation("auth"); + const { session } = useSession(); + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const token = searchParams.get("token"); + const [inviteState, setInviteState] = useState(token ? "loading" : "ready"); + const [inviteDetails, setInviteDetails] = useState(null); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + + const isInviteFlow = Boolean(token); + const description = useMemo( + () => + isInviteFlow + ? "Définissez votre mot de passe pour accéder à votre espace client." + : t("updatePassword.description"), + [isInviteFlow, t] + ); + + useEffect(() => { + if (!token) { + return; + } + + let isMounted = true; + + fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`) + .then(async (response) => { + if (!response.ok) { + throw new Error(await parseError(response)); + } + + return (await response.json()) as InviteDetails; + }) + .then((details) => { + if (!isMounted) return; + setInviteDetails(details); + setInviteState("ready"); + }) + .catch((err: unknown) => { + if (!isMounted) return; + setError(err instanceof Error ? err.message : "Lien invalide"); + setInviteState("invalid"); + }); + + return () => { + isMounted = false; + }; + }, [token]); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setError(null); + + if (password.length < 8) { + setError(t("signup.errors.passwordLength")); + return; + } + + if (password !== confirmPassword) { + setError(t("signup.errors.passwordMatch")); + return; + } + + setIsPending(true); + + try { + if (token && inviteDetails) { + const response = await fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ password }), + }); + + if (!response.ok) { + throw new Error(await parseError(response)); + } + + const result = (await response.json()) as InviteDetails & { success: boolean }; + const { error: signInError } = await supabase.auth.signInWithPassword({ + email: result.email, + password, + }); + + if (signInError) { + throw signInError; + } + + navigate(`/tablo/${result.tabloId}`); + return; + } + + const { error: updateError } = await supabase.auth.updateUser({ password }); + if (updateError) { + throw updateError; + } + + navigate("/login"); + } catch (err) { + setError(err instanceof Error ? err.message : "Une erreur est survenue."); + } finally { + setIsPending(false); + } + }; + + if (inviteState === "loading") { + return ( + +
+
+
+ + ); + } + + if (inviteState === "invalid") { + return ( + + + + ); + } + + const shouldShowRecoveryHint = !isInviteFlow && !session; + + return ( + +
+ {error ? : null} + {shouldShowRecoveryHint ? ( + + ) : null} + +
+
+ + setPassword(event.target.value)} + required + disabled={isPending} + /> +
+ +
+ + setConfirmPassword(event.target.value)} + required + disabled={isPending} + /> +
+ + +
+
+
+ ); +} diff --git a/apps/clients/src/routes.tsx b/apps/clients/src/routes.tsx index 57a23ce..e10531f 100644 --- a/apps/clients/src/routes.tsx +++ b/apps/clients/src/routes.tsx @@ -1,16 +1,25 @@ import { Route, Routes } from "react-router-dom"; +import { ClientAuthGate } from "./components/ClientAuthGate"; import { ClientLayout } from "./components/ClientLayout"; import { AuthCallback } from "./pages/AuthCallback"; import { ClientTabloListPage } from "./pages/ClientTabloListPage"; import { ClientTabloPage } from "./pages/ClientTabloPage"; +import { LoginPage } from "./pages/LoginPage"; +import { ResetPasswordPage } from "./pages/ResetPasswordPage"; +import { SetPasswordPage } from "./pages/SetPasswordPage"; export default function AppRoutes() { return ( + } /> + } /> + } /> } /> - }> - } /> - } /> + }> + }> + } /> + } /> + ); diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index ede64d8..ac7b2ab 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -23,12 +23,18 @@ interface RenderWithProvidersOptions { route?: string; path?: string; language?: string; + testUser?: typeof defaultUser | undefined; } export const renderWithProviders = ( ui: React.ReactNode, - { route = "/", path, language = "fr" }: RenderWithProvidersOptions = {} + options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { + const { route = "/", path, language = "fr" } = options; + const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") + ? options.testUser + : defaultUser; + testI18n.changeLanguage(language); const testQueryClient = new QueryClient({ @@ -55,7 +61,7 @@ export const renderWithProviders = ( - {content} + {content} diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index f2fa327..2431c00 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -18,6 +18,8 @@ "noFallthroughCasesInSwitch": true, "baseUrl": ".", "paths": { + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui": ["../../packages/ui/src"], "@xtablo/ui/*": ["../../packages/ui/src/*"], "@xtablo/shared": ["../../packages/shared/src"], diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index 1df4210..6ab4cf9 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/main/package.json b/apps/main/package.json index 18574d9..97bdeda 100644 --- a/apps/main/package.json +++ b/apps/main/package.json @@ -100,6 +100,7 @@ "@types/react-router-dom": "^5.3.3", "@typescript/native-preview": "7.0.0-dev.20251010.1", "@xtablo/chat-ui": "workspace:*", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index 19143ed..c7e6375 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -85,6 +85,7 @@ describe("ProtectedRoute", () => { last_name: "User", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index f065c5b..7eebb0e 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -40,6 +40,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/components/UpgradePanel.test.tsx b/apps/main/src/components/UpgradePanel.test.tsx index 3b00d34..b82f2a7 100644 --- a/apps/main/src/components/UpgradePanel.test.tsx +++ b/apps/main/src/components/UpgradePanel.test.tsx @@ -36,6 +36,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/contexts/UpgradeBlockContext.test.tsx b/apps/main/src/contexts/UpgradeBlockContext.test.tsx index f4b29f7..cedf044 100644 --- a/apps/main/src/contexts/UpgradeBlockContext.test.tsx +++ b/apps/main/src/contexts/UpgradeBlockContext.test.tsx @@ -23,6 +23,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/hooks/client_invites.ts b/apps/main/src/hooks/client_invites.ts index 3c6125e..71c6e5a 100644 --- a/apps/main/src/hooks/client_invites.ts +++ b/apps/main/src/hooks/client_invites.ts @@ -10,6 +10,11 @@ type PendingClientInvite = { created_at: string; }; +type CreateClientInviteResponse = { + success: true; + inviteMode: "notification" | "setup"; +}; + export const usePendingClientInvites = (tabloId: string) => { const api = useAuthedApi(); const { session } = useSession(); @@ -32,17 +37,23 @@ export const useCreateClientInvite = () => { return useMutation({ mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => { - const { data } = await api.post(`/api/v1/client-invites/${tabloId}`, { - email, - }); + const { data } = await api.post( + `/api/v1/client-invites/${tabloId}`, + { + email, + } + ); return data; }, - onSuccess: (_data, { tabloId }) => { + onSuccess: (data, { tabloId }) => { queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); toast.add( { - title: "Lien magique envoyé", - description: "L'invitation client a été envoyée avec succès", + title: data.inviteMode === "setup" ? "Invitation client envoyée" : "Accès client accordé", + description: + data.inviteMode === "setup" + ? "Un email de configuration du mot de passe a été envoyé au client." + : "Le client a été informé de son nouvel accès et pourra se connecter à son espace.", type: "success", }, { timeout: 3000 } diff --git a/apps/main/src/pages/login.test.tsx b/apps/main/src/pages/login.test.tsx index a3c0361..b39deef 100644 --- a/apps/main/src/pages/login.test.tsx +++ b/apps/main/src/pages/login.test.tsx @@ -34,6 +34,7 @@ describe("LoginPage", () => { it("renders all form elements", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByLabelText(/password/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /log in/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/login.tsx b/apps/main/src/pages/login.tsx index 41ca566..c6e3eaa 100644 --- a/apps/main/src/pages/login.tsx +++ b/apps/main/src/pages/login.tsx @@ -1,10 +1,5 @@ import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle"; -import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; -import { Button } from "@xtablo/ui/components/button"; -import { FieldError } from "@xtablo/ui/components/field"; -import { Input } from "@xtablo/ui/components/input"; -import { Label } from "@xtablo/ui/components/label"; -import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import { AuthCardShell, AuthEmailPasswordForm } from "@xtablo/auth-ui"; import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useSearchParams } from "react-router-dom"; @@ -60,32 +55,6 @@ export function LoginPage() { setIsHovered(false); }; - // Theme - const { theme, setTheme } = useTheme(); - - const toggleTheme = () => { - if (theme === "light") { - setTheme("dark"); - } else if (theme === "dark") { - setTheme("system"); - } else { - setTheme("light"); - } - }; - - const getThemeIcon = () => { - switch (theme) { - case "light": - return ; - case "dark": - return ; - case "system": - return ; - default: - return ; - } - }; - const onSubmit = (e: React.FormEvent) => { e.preventDefault(); login({ @@ -95,168 +64,100 @@ export function LoginPage() { }; return ( -
- -
e.stopPropagation()} - > - {/* Glow effect behind the card */} -
- -
} + topLeft={ + -
- - - - - {t("auth:common.backHome")} - - - {/* Theme Toggle */} - -
- - {/* Xtablo Icon */} -
- Xtablo + - Xtablo -
+ + {t("auth:common.backHome")} + + } + showThemeToggle + wrapperClassName="transition-transform duration-200 ease-out will-change-transform" + wrapperStyle={{ transform }} + onWrapperMouseMove={handleMouseMove} + onWrapperMouseLeave={handleMouseLeave} + isHovered={isHovered} + > +
+ + {t("auth:login.newExperienceLink")} + +
-

- {t("auth:login.title")} -

- -
- - {t("auth:login.newExperienceLink")} - -
- -
-
-
- - setFormData({ ...formData, email: e.target.value })} - required - placeholder={t("auth:login.emailPlaceholder")} - /> - {errors?.email && } -
- -
- - setFormData({ ...formData, password: e.target.value })} - required - placeholder={t("auth:login.passwordPlaceholder")} - /> - {errors?.password && } -
- -
- - {t("auth:login.forgotPassword")} - -
- - -
- -
-
-
-
-
- - {t("auth:common.orContinue")} - -
-
- - - -

- {t("auth:login.noAccount")}{" "} +

+ setFormData({ ...formData, email })} + onPasswordChange={(password: string) => setFormData({ ...formData, password })} + onSubmit={onSubmit} + submitLabel={isPending ? t("auth:common.connecting") : t("auth:login.loginButton")} + emailLabel={`${t("common:labels.email")} *`} + passwordLabel={`${t("common:labels.password")} *`} + emailPlaceholder={t("auth:login.emailPlaceholder")} + passwordPlaceholder={t("auth:login.passwordPlaceholder")} + emailError={errors?.email} + passwordError={errors?.password} + extraContent={ +
- {t("auth:login.signupLink")} + {t("auth:login.forgotPassword")} -

+
+ } + /> + +
+
+
+
+
+ + {t("auth:common.orContinue")} +
+ + + +

+ {t("auth:login.noAccount")}{" "} + + {t("auth:login.signupLink")} + +

-
+ ); } diff --git a/apps/main/src/pages/reset-password.test.tsx b/apps/main/src/pages/reset-password.test.tsx index beddf74..1e07af5 100644 --- a/apps/main/src/pages/reset-password.test.tsx +++ b/apps/main/src/pages/reset-password.test.tsx @@ -16,6 +16,7 @@ describe("ResetPasswordPage", () => { it("renders form with email input", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByText(/forgot your password/i)).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /send reset link/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/reset-password.tsx b/apps/main/src/pages/reset-password.tsx index 9633d68..acc4a75 100644 --- a/apps/main/src/pages/reset-password.tsx +++ b/apps/main/src/pages/reset-password.tsx @@ -1,13 +1,13 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; import { toast } from "@xtablo/shared"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { Label } from "@xtablo/ui/components/label"; import { Text } from "@xtablo/ui/components/typography"; -import { AlertCircle, CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; +import { CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useNavigate } from "react-router-dom"; -import { twMerge } from "tailwind-merge"; import { supabase } from "../lib/supabase"; export function ResetPasswordPage() { @@ -49,113 +49,83 @@ export function ResetPasswordPage() { if (isSubmitted) { return ( -
navigate("/login")} + {t("resetPassword.checkInbox", { email })}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-
- -
+
+
+
+
-
-

{t("resetPassword.emailSent")}

- - {t("resetPassword.checkInbox", { email })} - -
-
-
- - - {t("resetPassword.emailInstructions")} - -
-
- - -
+ + + + + +
-
+ ); } return ( -
navigate("/login")} + {t("resetPassword.description")}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-

{t("resetPassword.title")}

- {t("resetPassword.description")} +
+ {error ? : null} + +
+
+ + setEmail(e.target.value)} + placeholder={t("resetPassword.emailPlaceholder")} + required + disabled={isPending} + className="transition-opacity disabled:opacity-50" + />
- {error && ( -
-
- - {error} -
-
- )} + +
-
-
- - setEmail(e.target.value)} - placeholder={t("resetPassword.emailPlaceholder")} - required - disabled={isPending} - className="transition-opacity disabled:opacity-50" - /> -
- - -
- -

- - {t("resetPassword.backToLogin")} - -

+
+
+ + + {t("resetPassword.emailInstructions")} + +
+ +

+ + {t("resetPassword.backToLogin")} + +

-
+ ); } diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index e30a059..ec1ace7 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -406,7 +406,7 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument(); }); - it("uses the standard email invite UI in the share dialog", async () => { + it("uses the client password invite UI in the share dialog", async () => { const user = userEvent.setup(); renderWithProviders(, { @@ -416,9 +416,10 @@ describe("TabloDetailsPage overview layout", () => { await user.click(screen.getByRole("button", { name: "Inviter" })); - expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument(); - expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument(); - expect(screen.queryByText("Accès client")).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument(); + expect(screen.getByText("Accès client")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Email du client")).toBeInTheDocument(); + expect(screen.getByText(/définir son mot de passe/i)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Envoyer l'invitation" })).toBeInTheDocument(); + expect(screen.queryByText("Inviter un utilisateur")).not.toBeInTheDocument(); }); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 4816bb3..a6db9de 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -86,8 +86,7 @@ const TAB_SECTIONS: TabSection[] = [ "roadmap", ]; -// Temporary rollback until the client portal invite flow is ready to be used again. -const USE_CLIENT_MAGIC_LINK_INVITES = false; +const USE_CLIENT_PASSWORD_INVITES = true; // ─── Page ───────────────────────────────────────────────────────────────────── @@ -564,12 +563,13 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {USE_CLIENT_MAGIC_LINK_INVITES ? ( + {USE_CLIENT_PASSWORD_INVITES ? ( <>

Accès client

- Invitez des clients externes via un lien magique + Le client recevra un email pour définir son mot de passe ou, s'il a déjà + un compte, une notification d'accès directe à ce tablo.

@@ -598,7 +598,7 @@ export const TabloDetailsPage = () => { }} disabled={!isEmailValid(clientInviteEmail)} > - Envoyer le lien + Envoyer l'invitation )}
diff --git a/apps/main/src/providers/UserStoreProvider.test.tsx b/apps/main/src/providers/UserStoreProvider.test.tsx index 7f7e908..84b9bb2 100644 --- a/apps/main/src/providers/UserStoreProvider.test.tsx +++ b/apps/main/src/providers/UserStoreProvider.test.tsx @@ -63,6 +63,7 @@ describe("TestUserStoreProvider", () => { first_name: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_name: null, short_user_id: "short-id", last_signed_in: null, diff --git a/apps/main/src/utils/testHelpers.tsx b/apps/main/src/utils/testHelpers.tsx index f370ba2..c3a4cab 100644 --- a/apps/main/src/utils/testHelpers.tsx +++ b/apps/main/src/utils/testHelpers.tsx @@ -19,6 +19,7 @@ const defaultUser = { avatar_url: "https://example.com/avatar.jpg", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/tsconfig.app.json b/apps/main/tsconfig.app.json index b633f54..5b1c16f 100644 --- a/apps/main/tsconfig.app.json +++ b/apps/main/tsconfig.app.json @@ -27,6 +27,8 @@ "paths": { "*": ["./*"], "@ui/*": ["./src/*"], + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui/*": ["../../packages/ui/src/*"] } }, diff --git a/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md new file mode 100644 index 0000000..733f66e --- /dev/null +++ b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md @@ -0,0 +1,626 @@ +# Client Password Invite Flow Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the client magic-link callback flow with one-time password setup plus normal email/password login in `apps/clients`, while keeping client users restricted to the client portal. + +**Architecture:** Keep Supabase Auth as the identity provider, but move invite lifecycle decisions into the API. The backend creates or reuses one client account per email, then branches between an onboarding email with a one-time setup token and an access-notification email for already-onboarded clients. On the frontend, extract the main login visual shell into a shared auth UI surface, add client login/set-password/reset routes, and redirect protected client routes through login with destination resume. + +**Tech Stack:** Hono API, Supabase Auth, React 19, React Router, TanStack Query, Tailwind CSS v4, pnpm workspaces, Vitest. + +**Spec:** `docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md` + +--- + +## File Structure + +### New files + +**Database** +- `supabase/migrations/20260418110000_client_password_invites.sql` — replaces callback-oriented invite semantics with setup-token lifecycle fields and client-only auth metadata + +**Shared auth UI** +- `packages/auth-ui/package.json` — shared auth UI package manifest if no existing package is a clean fit +- `packages/auth-ui/tsconfig.json` — package tsconfig +- `packages/auth-ui/src/index.ts` — barrel exports +- `packages/auth-ui/src/AuthCardShell.tsx` — shared auth page background, card shell, logo, theme toggle, and content slot +- `packages/auth-ui/src/AuthEmailPasswordForm.tsx` — shared email/password form layout with error and loading states +- `packages/auth-ui/src/AuthInfoBanner.tsx` — shared inline success/error/info banner component used by login/reset/setup screens + +**Client auth pages** +- `apps/clients/src/pages/LoginPage.tsx` — client login screen using shared auth UI +- `apps/clients/src/pages/ResetPasswordPage.tsx` — client forgot-password page +- `apps/clients/src/pages/SetPasswordPage.tsx` — one-time invite setup screen +- `apps/clients/src/pages/LoginPage.test.tsx` +- `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- `apps/clients/src/pages/SetPasswordPage.test.tsx` +- `apps/clients/src/components/ClientAuthGate.tsx` — preserves intended route and redirects unauthenticated users to login + +**API tests** +- No brand-new top-level test files required if the current route tests remain focused; extend: + - `apps/api/src/__tests__/routes/clientInvites.test.ts` + - `apps/api/src/__tests__/middlewares/middlewares.test.ts` + +### Modified files + +**API** +- `apps/api/src/routers/clientInvites.ts` — replace callback accept flow with setup-token create/validate/complete flow plus access-notification branch +- `apps/api/src/helpers/helpers.ts` — split current `createClientUser()` into clearer helpers for create/reuse account, detect onboarding state, and grant tablo access +- `apps/api/src/routers/index.ts` or the file that mounts `clientInvites` — ensure new routes are exposed +- `apps/api/src/middlewares/middleware.ts` — keep client users blocked from regular main-app routes; tighten behavior if needed +- `apps/api/src/__tests__/routes/clientInvites.test.ts` — cover onboarding vs notification, token validation, single use, cancellation, and app-boundary expectations +- `apps/api/src/__tests__/middlewares/middlewares.test.ts` — keep client-only users rejected by main-app middleware + +**Shared types** +- `packages/shared-types/src/database.types.ts` — add migration-driven type updates for `client_invites` and any new client auth columns + +**Main app frontend** +- `apps/main/src/pages/tablo-details.tsx` — update invite dialog submit flow and text for password-setup onboarding / access notification messaging +- `apps/main/src/pages/tablo-details.layout.test.tsx` — cover active magic-link invite UI copy and success states after the backend contract change +- `apps/main/src/pages/login.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/pages/reset-password.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/hooks/client_invites.ts` — adapt to the updated invite response shape if needed +- `apps/main/src/hooks/auth.ts` — optionally extract reusable login/reset behavior or keep app-specific logic while sharing visuals +- `apps/main/src/pages/login.test.tsx` +- `apps/main/src/pages/reset-password.test.tsx` + +**Client app frontend** +- `apps/clients/src/routes.tsx` — add `/login`, `/reset-password`, `/set-password`, and redirect handling; remove `/auth/callback` from primary flow +- `apps/clients/src/components/ClientLayout.tsx` — stop rendering dead-end unauthorized state and rely on auth gate redirect behavior +- `apps/clients/src/lib/supabase.ts` — no behavioral change expected, but verify redirect URLs and auth persistence assumptions +- `apps/clients/src/i18n.ts` — add auth namespaces reused from main or from shared locale files +- `apps/clients/src/main.tsx` — ensure new pages have needed providers +- `apps/clients/src/pages/AuthCallback.tsx` — remove or reduce to a temporary compatibility shim +- `apps/clients/src/pages/ClientTabloPage.tsx` +- `apps/clients/src/pages/ClientTabloListPage.tsx` +- `apps/clients/src/components/ClientLayout.test.tsx` +- `apps/clients/src/pages/ClientTabloPage.test.tsx` + +--- + +## Chunk 1: Database And API Invite Lifecycle + +### Task 1: Replace callback invite semantics with setup-token lifecycle + +**Files:** +- Create: `supabase/migrations/20260418110000_client_password_invites.sql` +- Modify: `packages/shared-types/src/database.types.ts` +- Test: `apps/api/src/__tests__/routes/clientInvites.test.ts` + +- [ ] **Step 1: Write the failing API test cases for the new lifecycle** + +Add or replace route tests in `apps/api/src/__tests__/routes/clientInvites.test.ts` for: + +```ts +it("creates a setup token for a first-time client invite", async () => {}); +it("does not create a setup token for an already-onboarded client", async () => {}); +it("rejects reused setup tokens", async () => {}); +it("rejects expired setup tokens", async () => {}); +it("marks cancelled pending setup tokens unusable", async () => {}); +``` + +Model the first-time case so it asserts: +- `client_invites.is_pending === true` +- a setup token exists +- `sendMail` is called with a setup URL targeting `clients.xtablo.com` + +Model the onboarded case so it asserts: +- no new setup token row is created +- `sendMail` is called with a direct `/tablo/:tabloId` URL + +- [ ] **Step 2: Run the targeted API tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts +``` + +Expected: +- FAIL because the current router still creates magic-link callback invites and still exposes `/accept/:token` + +- [ ] **Step 3: Write the migration** + +In `supabase/migrations/20260418110000_client_password_invites.sql`, evolve `client_invites` for setup-token lifecycle. Prefer modifying the existing table shape over creating a second invite table. + +The migration should include the minimal schema required for: + +```sql +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +-- If the old callback flow uses invite_token generically, keep the column +-- but redefine its meaning as the setup token for setup invites. + +CREATE INDEX IF NOT EXISTS idx_client_invites_email_tablo_pending + ON public.client_invites (invited_email, tablo_id, is_pending); +``` + +Also add any client-account marker needed to distinguish: +- invited client users who have not completed password setup +- onboarded client users who already have password login + +Keep the schema minimal. Avoid adding fields that can be derived from auth state unless tests require them. + +- [ ] **Step 4: Update generated database types** + +Update `packages/shared-types/src/database.types.ts` to reflect the migration: +- new `client_invites` columns +- any added client-profile/account lifecycle columns + +Use the repo’s current type-generation practice if available; otherwise make the minimal manual edit and note it in the commit message. + +- [ ] **Step 5: Refactor helper boundaries before touching the router** + +In `apps/api/src/helpers/helpers.ts`, split the current client invite helper behavior into smaller pieces with one responsibility each: + +```ts +export async function findOrCreateClientAccount(...) {} +export async function ensureClientTabloAccess(...) {} +export async function hasCompletedClientOnboarding(...) {} +export async function createClientSetupInvite(...) {} +``` + +Do not keep all onboarding, auth-user creation, and tablo-access behavior fused into one large helper. + +- [ ] **Step 6: Replace callback endpoints with setup-token endpoints** + +In `apps/api/src/routers/clientInvites.ts`, change the route surface to: + +```ts +POST /client-invites/:tabloId +GET /client-invites/setup/:token +POST /client-invites/setup/:token +GET /client-invites/:tabloId/pending +DELETE /client-invites/:tabloId/:inviteId +``` + +Behavior: +- `POST /:tabloId` + - create/reuse client account + - ensure tablo access + - if account is not onboarded: create pending setup token + send setup email + - if account is onboarded: skip setup token + send access notification email to `/tablo/:tabloId` +- `GET /setup/:token` + - return token metadata for `SetPasswordPage` + - reject missing / expired / cancelled / already-used tokens +- `POST /setup/:token` + - validate token again + - set password for the client auth user + - mark invite consumed immediately + - return success payload for the frontend + +Remove callback-style `accept/:token` logic from the primary flow. + +- [ ] **Step 7: Keep `apps/main` protected from client-only users** + +In `apps/api/src/middlewares/middleware.ts`, verify that `regularUserCheck` or equivalent main-app guard rejects `is_client` users cleanly. If the current behavior is already correct, only tighten the tests and leave code untouched. + +Add or update targeted test coverage in `apps/api/src/__tests__/middlewares/middlewares.test.ts`: + +```ts +it("returns 401 for client-only users on main-app protected routes", async () => {}); +``` + +- [ ] **Step 8: Run API verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +``` + +Expected: +- PASS for invite lifecycle and middleware protection coverage + +- [ ] **Step 9: Commit** + +```bash +git add supabase/migrations/20260418110000_client_password_invites.sql \ + packages/shared-types/src/database.types.ts \ + apps/api/src/helpers/helpers.ts \ + apps/api/src/routers/clientInvites.ts \ + apps/api/src/__tests__/routes/clientInvites.test.ts \ + apps/api/src/__tests__/middlewares/middlewares.test.ts \ + apps/api/src/middlewares/middleware.ts +git commit -m "feat(api): add client password setup invite flow" +``` + +--- + +## Chunk 2: Shared Auth UI Extraction + +### Task 2: Extract the main login visual shell into a shared package + +**Files:** +- Create: `packages/auth-ui/package.json` +- Create: `packages/auth-ui/tsconfig.json` +- Create: `packages/auth-ui/src/index.ts` +- Create: `packages/auth-ui/src/AuthCardShell.tsx` +- Create: `packages/auth-ui/src/AuthEmailPasswordForm.tsx` +- Create: `packages/auth-ui/src/AuthInfoBanner.tsx` +- Modify: `apps/main/src/pages/login.tsx` +- Modify: `apps/main/src/pages/reset-password.tsx` +- Test: `apps/main/src/pages/login.test.tsx` +- Test: `apps/main/src/pages/reset-password.test.tsx` + +- [ ] **Step 1: Write failing rendering tests around the shared auth shell contract** + +Before extracting, add or update tests that pin the current main auth page structure at the right level: + +```ts +it("renders the main login page through a reusable auth shell", async () => {}); +it("renders the reset-password page through the shared auth shell", async () => {}); +``` + +Assert only stable behavior: +- heading renders +- email/password fields render +- forgot-password link renders +- shared shell wrapper test id or landmark renders + +Do not snapshot the entire page. + +- [ ] **Step 2: Run the main auth tests to verify current coverage gap** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +``` + +Expected: +- FAIL or insufficient coverage for the extraction seam + +- [ ] **Step 3: Extract presentation-only auth UI** + +Create `packages/auth-ui` and move only visual/auth-form composition into it. + +Recommended split: + +```tsx +// AuthCardShell.tsx +export function AuthCardShell(props: { + title: string; + children: React.ReactNode; + backHomeHref?: string; + footer?: React.ReactNode; +}) {} + +// AuthEmailPasswordForm.tsx +export function AuthEmailPasswordForm(props: { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (e: React.FormEvent) => void; + isPending?: boolean; + emailError?: string; + passwordError?: string; + submitLabel: string; + forgotPasswordHref?: string; +}) {} +``` + +Keep: +- theme toggle +- background +- card framing +- logo block +- stable form spacing and typography + +Out of scope for the shared package: +- actual Supabase mutations +- route-specific navigation +- Google login wiring +- signup flow behavior + +- [ ] **Step 4: Refactor main login and reset pages onto the shared auth UI** + +Update: +- `apps/main/src/pages/login.tsx` +- `apps/main/src/pages/reset-password.tsx` + +Keep existing behavior intact while removing duplicated layout markup. + +- [ ] **Step 5: Run verification for main auth pages** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/auth-ui typecheck +``` + +Expected: +- PASS with no behavior regression in main auth pages + +- [ ] **Step 6: Commit** + +```bash +git add packages/auth-ui \ + apps/main/src/pages/login.tsx \ + apps/main/src/pages/reset-password.tsx \ + apps/main/src/pages/login.test.tsx \ + apps/main/src/pages/reset-password.test.tsx +git commit -m "refactor(auth): extract shared auth ui" +``` + +--- + +## Chunk 3: Client Portal Auth Routes And Redirect Flow + +### Task 3: Add client login, reset-password, set-password, and redirect memory + +**Files:** +- Create: `apps/clients/src/components/ClientAuthGate.tsx` +- Create: `apps/clients/src/pages/LoginPage.tsx` +- Create: `apps/clients/src/pages/ResetPasswordPage.tsx` +- Create: `apps/clients/src/pages/SetPasswordPage.tsx` +- Modify: `apps/clients/src/routes.tsx` +- Modify: `apps/clients/src/components/ClientLayout.tsx` +- Modify: `apps/clients/src/pages/AuthCallback.tsx` +- Modify: `apps/clients/src/i18n.ts` +- Test: `apps/clients/src/pages/LoginPage.test.tsx` +- Test: `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- Test: `apps/clients/src/pages/SetPasswordPage.test.tsx` +- Test: `apps/clients/src/components/ClientLayout.test.tsx` +- Test: `apps/clients/src/pages/ClientTabloPage.test.tsx` + +- [ ] **Step 1: Write failing client auth route tests** + +Add coverage for the new expected client behavior: + +```ts +it("redirects unauthenticated /tablo/:tabloId requests to /login and resumes after login", async () => {}); +it("renders the client login page with shared auth ui", async () => {}); +it("submits forgot-password from the client login flow", async () => {}); +it("renders an invalid-token state on the set-password page", async () => {}); +it("submits password setup once and rejects token reuse", async () => {}); +``` + +Prefer route-level tests with mocked Supabase/API behavior over isolated unit tests. + +- [ ] **Step 2: Run the client auth tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +``` + +Expected: +- FAIL because `/login`, `/reset-password`, and `/set-password` do not exist and protected client routes do not redirect correctly + +- [ ] **Step 3: Add a client auth gate with redirect memory** + +Create `apps/clients/src/components/ClientAuthGate.tsx` with behavior like: + +```tsx +export function ClientAuthGate({ children }: { children: React.ReactNode }) { + // if no session: + // store current pathname + search in localStorage + // navigate("/login") + // else render children +} +``` + +Use a client-specific storage key such as: + +```ts +const CLIENT_REDIRECT_KEY = "clients.redirectUrl"; +``` + +Do not reuse the main app’s generic redirect key unless the semantics are already isolated per app. + +- [ ] **Step 4: Build the client login and reset pages on top of shared auth UI** + +Implement: +- `apps/clients/src/pages/LoginPage.tsx` +- `apps/clients/src/pages/ResetPasswordPage.tsx` + +Behavior: +- login via `supabase.auth.signInWithPassword` +- forgot-password via `supabase.auth.resetPasswordForEmail` +- no signup affordance +- successful login resumes `clients.redirectUrl` if present, otherwise `/` + +- [ ] **Step 5: Build the one-time set-password page** + +Implement `apps/clients/src/pages/SetPasswordPage.tsx`: +- read the token from the URL +- call `GET /api/v1/client-invites/setup/:token` on mount +- render clear invalid / expired / used states +- submit new password to `POST /api/v1/client-invites/setup/:token` +- after success, sign in the user and navigate to the granted destination + +If the API returns enough information to sign the user in directly, use it. If not, perform a normal `signInWithPassword` after successful setup using the freshly set password. + +- [ ] **Step 6: Update client routes and remove callback-first flow** + +In `apps/clients/src/routes.tsx`, move to: + +```tsx +} /> +} /> +} /> +}> + } /> + } /> + +``` + +Reduce `AuthCallback.tsx` to: +- temporary compatibility notice, or +- redirect to `/login` + +Do not leave it as the primary entry path. + +- [ ] **Step 7: Update client translations and copy** + +In `apps/clients/src/i18n.ts`, reuse the main auth namespace if practical. If not, add the minimal client auth keys needed without duplicating the entire namespace unnecessarily. + +Required copy states: +- login +- forgot password +- set password +- invalid token +- expired token +- already-used token +- access granted / password set success + +- [ ] **Step 8: Run client verification** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +pnpm --filter @xtablo/clients typecheck +``` + +Expected: +- PASS for login, reset-password, set-password, and redirect-resume flow + +- [ ] **Step 9: Commit** + +```bash +git add apps/clients/src/routes.tsx \ + apps/clients/src/components/ClientAuthGate.tsx \ + apps/clients/src/components/ClientLayout.tsx \ + apps/clients/src/pages/LoginPage.tsx \ + apps/clients/src/pages/ResetPasswordPage.tsx \ + apps/clients/src/pages/SetPasswordPage.tsx \ + apps/clients/src/pages/AuthCallback.tsx \ + apps/clients/src/i18n.ts \ + apps/clients/src/pages/LoginPage.test.tsx \ + apps/clients/src/pages/ResetPasswordPage.test.tsx \ + apps/clients/src/pages/SetPasswordPage.test.tsx \ + apps/clients/src/components/ClientLayout.test.tsx \ + apps/clients/src/pages/ClientTabloPage.test.tsx +git commit -m "feat(clients): add password auth onboarding flow" +``` + +--- + +## Chunk 4: Main Invite UI And Full Verification + +### Task 4: Update main-app invite UX to match the new backend contract + +**Files:** +- Modify: `apps/main/src/pages/tablo-details.tsx` +- Modify: `apps/main/src/hooks/client_invites.ts` +- Modify: `apps/main/src/pages/tablo-details.layout.test.tsx` + +- [ ] **Step 1: Write failing main invite flow tests** + +Extend `apps/main/src/pages/tablo-details.layout.test.tsx` with cases like: + +```ts +it("shows password-setup onboarding messaging for first-time client invites", async () => {}); +it("shows access-notification messaging for already-onboarded client invites", async () => {}); +``` + +Assert only the user-facing contract: +- client invite UI is visible +- email field submits +- success state reflects either setup email sent or access notification sent + +- [ ] **Step 2: Run the targeted main invite tests** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx --mode dev +``` + +Expected: +- FAIL because current UI still assumes the callback-style invite flow + +- [ ] **Step 3: Update the main invite hook contract** + +In `apps/main/src/hooks/client_invites.ts`, align the mutation response typing with the new API payload, for example: + +```ts +type ClientInviteResponse = { + success: true; + inviteMode: "setup" | "notification"; +}; +``` + +Avoid frontend logic that infers email mode from copy alone. + +- [ ] **Step 4: Update share-dialog copy and success handling** + +In `apps/main/src/pages/tablo-details.tsx`, keep the client invite UI active, but change the submission/success states to match the new flow: +- first-time invite: explain that the client will receive a password-setup email +- existing client: explain that the client will receive a direct access notification + +Do not reintroduce the old standard-email collaborator invite UI for this flow. + +- [ ] **Step 5: Run focused frontend verification** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run \ + src/pages/tablo-details.layout.test.tsx \ + src/pages/login.test.tsx \ + src/pages/reset-password.test.tsx \ + --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: +- PASS for share dialog copy, login page extraction, and reset page extraction + +- [ ] **Step 6: Run cross-app final verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +pnpm --filter @xtablo/auth-ui typecheck +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/clients exec vitest run src/components/ClientLayout.test.tsx src/pages/ClientTabloPage.test.tsx src/pages/LoginPage.test.tsx src/pages/ResetPasswordPage.test.tsx src/pages/SetPasswordPage.test.tsx --mode dev +``` + +If the API tests require local Supabase migrations first, run the repo-standard migration command before rerunning tests and record that in the implementation notes. + +- [ ] **Step 7: Commit** + +```bash +git add apps/main/src/pages/tablo-details.tsx \ + apps/main/src/hooks/client_invites.ts \ + apps/main/src/pages/tablo-details.layout.test.tsx +git commit -m "feat(main): update client invite onboarding messaging" +``` + +--- + +## Completion Notes + +- Keep commits small and aligned with the chunks above. +- Do not reintroduce permanent bearer links. +- Do not allow client-only users through `apps/main` guards, even if they authenticate successfully. +- Do not preserve `AuthCallback` as a hidden second primary flow; either remove it or make it an explicit compatibility dead-end. +- Prefer reusing the existing main auth translations where possible, but avoid coupling `apps/clients` directly to `apps/main` internals if extraction into a shared package is cleaner. diff --git a/packages/auth-ui/package.json b/packages/auth-ui/package.json new file mode 100644 index 0000000..7569c83 --- /dev/null +++ b/packages/auth-ui/package.json @@ -0,0 +1,32 @@ +{ + "name": "@xtablo/auth-ui", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write ." + }, + "dependencies": { + "@xtablo/shared": "workspace:*", + "@xtablo/ui": "workspace:*", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "tailwind-merge": "^3.0.2" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "typescript": "^5.7.0", + "vite": "^6.2.2" + } +} diff --git a/packages/auth-ui/src/AuthCardShell.tsx b/packages/auth-ui/src/AuthCardShell.tsx new file mode 100644 index 0000000..3baca34 --- /dev/null +++ b/packages/auth-ui/src/AuthCardShell.tsx @@ -0,0 +1,125 @@ +import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; +import { Button } from "@xtablo/ui/components/button"; +import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import type { CSSProperties, MouseEventHandler, ReactNode } from "react"; +import { twMerge } from "tailwind-merge"; + +type AuthCardShellProps = { + title: string; + description?: ReactNode; + children: ReactNode; + background?: ReactNode; + topLeft?: ReactNode; + showThemeToggle?: boolean; + onBackdropClick?: () => void; + wrapperClassName?: string; + wrapperStyle?: CSSProperties; + onWrapperMouseMove?: MouseEventHandler; + onWrapperMouseLeave?: () => void; + isHovered?: boolean; + cardClassName?: string; +}; + +export function AuthCardShell({ + title, + description, + children, + background, + topLeft, + showThemeToggle = false, + onBackdropClick, + wrapperClassName, + wrapperStyle, + onWrapperMouseMove, + onWrapperMouseLeave, + isHovered = false, + cardClassName, +}: AuthCardShellProps) { + const { theme, setTheme } = useTheme(); + + const toggleTheme = () => { + if (theme === "light") { + setTheme("dark"); + } else if (theme === "dark") { + setTheme("system"); + } else { + setTheme("light"); + } + }; + + const themeIcon = + theme === "light" ? ( + + ) : theme === "dark" ? ( + + ) : ( + + ); + + return ( +
+ {background} + +
event.stopPropagation()} + > +
+ +
+ {topLeft || showThemeToggle ? ( +
+
{topLeft}
+ {showThemeToggle ? ( + + ) : null} +
+ ) : null} + +
+ Xtablo + Xtablo +
+ +
+

{title}

+ {description ?
{description}
: null} +
+ + {children} +
+
+
+ ); +} diff --git a/packages/auth-ui/src/AuthEmailPasswordForm.tsx b/packages/auth-ui/src/AuthEmailPasswordForm.tsx new file mode 100644 index 0000000..b97c1be --- /dev/null +++ b/packages/auth-ui/src/AuthEmailPasswordForm.tsx @@ -0,0 +1,83 @@ +import { Button } from "@xtablo/ui/components/button"; +import { FieldError } from "@xtablo/ui/components/field"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import type { ReactNode } from "react"; + +type AuthEmailPasswordFormProps = { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (event: React.FormEvent) => void; + submitLabel: string; + emailLabel: string; + passwordLabel: string; + emailPlaceholder: string; + passwordPlaceholder: string; + emailError?: string; + passwordError?: string; + isPending?: boolean; + footer?: ReactNode; + extraContent?: ReactNode; +}; + +export function AuthEmailPasswordForm({ + email, + password, + onEmailChange, + onPasswordChange, + onSubmit, + submitLabel, + emailLabel, + passwordLabel, + emailPlaceholder, + passwordPlaceholder, + emailError, + passwordError, + isPending = false, + footer, + extraContent, +}: AuthEmailPasswordFormProps) { + return ( +
+
+ + onEmailChange(event.target.value)} + required + placeholder={emailPlaceholder} + disabled={isPending} + /> + {emailError ? : null} +
+ +
+ + onPasswordChange(event.target.value)} + required + placeholder={passwordPlaceholder} + disabled={isPending} + /> + {passwordError ? : null} +
+ + {extraContent} + + + + {footer} +
+ ); +} diff --git a/packages/auth-ui/src/AuthInfoBanner.tsx b/packages/auth-ui/src/AuthInfoBanner.tsx new file mode 100644 index 0000000..a5554d2 --- /dev/null +++ b/packages/auth-ui/src/AuthInfoBanner.tsx @@ -0,0 +1,33 @@ +import { AlertCircle, CheckCircle2, InfoIcon } from "lucide-react"; +import { twMerge } from "tailwind-merge"; + +type AuthInfoBannerProps = { + message: string; + variant: "error" | "info" | "success"; +}; + +const variantStyles: Record = { + error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", + info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800", + success: + "bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800", +}; + +const variantIcon = { + error: AlertCircle, + info: InfoIcon, + success: CheckCircle2, +} satisfies Record; + +export function AuthInfoBanner({ message, variant }: AuthInfoBannerProps) { + const Icon = variantIcon[variant]; + + return ( +
+
+ +

{message}

+
+
+ ); +} diff --git a/packages/auth-ui/src/index.ts b/packages/auth-ui/src/index.ts new file mode 100644 index 0000000..5c6d6f3 --- /dev/null +++ b/packages/auth-ui/src/index.ts @@ -0,0 +1,3 @@ +export { AuthCardShell } from "./AuthCardShell"; +export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm"; +export { AuthInfoBanner } from "./AuthInfoBanner"; diff --git a/packages/auth-ui/tsconfig.json b/packages/auth-ui/tsconfig.json new file mode 100644 index 0000000..4976ebd --- /dev/null +++ b/packages/auth-ui/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../ui/src"], + "@xtablo/ui/*": ["../ui/src/*"], + "@xtablo/shared": ["../shared/src"], + "@xtablo/shared/*": ["../shared/src/*"] + } + }, + "include": ["src", "src/vite-env.d.ts"] +} diff --git a/packages/shared-types/src/database.types.ts b/packages/shared-types/src/database.types.ts index 3ab03a5..66b30a0 100644 --- a/packages/shared-types/src/database.types.ts +++ b/packages/shared-types/src/database.types.ts @@ -83,31 +83,43 @@ export type Database = { created_at: string; expires_at: string; id: number; + invite_type: string; invited_by: string; invited_email: string; invite_token: string; is_pending: boolean; + cancelled_at: string | null; + setup_completed_at: string | null; tablo_id: string; + used_at: string | null; }; Insert: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by: string; invited_email: string; invite_token: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id: string; + used_at?: string | null; }; Update: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by?: string; invited_email?: string; invite_token?: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id?: string; + used_at?: string | null; }; Relationships: [ { @@ -429,6 +441,7 @@ export type Database = { profiles: { Row: { avatar_url: string | null; + client_onboarded_at: string | null; created_at: string | null; email: string | null; first_name: string | null; @@ -443,6 +456,7 @@ export type Database = { }; Insert: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; @@ -457,6 +471,7 @@ export type Database = { }; Update: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e797dbd..240d4f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,9 @@ importers: '@tanstack/react-query': specifier: ^5.69.0 version: 5.90.5(react@19.0.0) + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -405,6 +408,9 @@ importers: '@typescript/native-preview': specifier: 7.0.0-dev.20251010.1 version: 7.0.0-dev.20251010.1 + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -629,6 +635,43 @@ importers: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + packages/auth-ui: + dependencies: + '@xtablo/shared': + specifier: workspace:* + version: link:../shared + '@xtablo/ui': + specifier: workspace:* + version: link:../ui + lucide-react: + specifier: ^0.460.0 + version: 0.460.0(react@19.0.0) + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + tailwind-merge: + specifier: ^3.0.2 + version: 3.3.1 + devDependencies: + '@biomejs/biome': + specifier: 2.2.5 + version: 2.2.5 + '@types/react': + specifier: 19.0.10 + version: 19.0.10 + '@types/react-dom': + specifier: 19.0.4 + version: 19.0.4(@types/react@19.0.10) + typescript: + specifier: ^5.7.0 + version: 5.9.3 + vite: + specifier: ^6.2.2 + version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + packages/chat-ui: dependencies: '@xtablo/shared': diff --git a/supabase/migrations/20260418110000_client_password_invites.sql b/supabase/migrations/20260418110000_client_password_invites.sql new file mode 100644 index 0000000..0746c80 --- /dev/null +++ b/supabase/migrations/20260418110000_client_password_invites.sql @@ -0,0 +1,27 @@ +ALTER TABLE public.profiles + ADD COLUMN IF NOT EXISTS client_onboarded_at timestamptz; + +COMMENT ON COLUMN public.profiles.client_onboarded_at IS + 'Timestamp when a client portal user completed their one-time password setup.'; + +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +COMMENT ON COLUMN public.client_invites.invite_type IS + 'Invite lifecycle type. setup = first-time password onboarding token.'; +COMMENT ON COLUMN public.client_invites.used_at IS + 'Timestamp when the setup token was consumed.'; +COMMENT ON COLUMN public.client_invites.cancelled_at IS + 'Timestamp when a pending setup invite was cancelled.'; +COMMENT ON COLUMN public.client_invites.setup_completed_at IS + 'Timestamp when password setup completed successfully.'; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_client_invites_pending_setup_email_tablo + ON public.client_invites (tablo_id, invited_email) + WHERE is_pending = true AND invite_type = 'setup'; + +CREATE INDEX IF NOT EXISTS idx_client_invites_token_pending + ON public.client_invites (invite_token, is_pending); From fa12aa34a5c56ae0c5977fd10250aa04c169dd0c Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:39:38 +0200 Subject: [PATCH 22/44] fix: expose public client setup routes --- apps/api/src/routers/index.ts | 4 ++++ apps/api/src/routers/maybeAuthRouter.ts | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routers/index.ts b/apps/api/src/routers/index.ts index 1ca996e..4c7928c 100644 --- a/apps/api/src/routers/index.ts +++ b/apps/api/src/routers/index.ts @@ -3,6 +3,7 @@ import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { BaseEnv } from "../types/app.types.js"; import { getAuthenticatedRouter } from "./authRouter.js"; +import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js"; import { getPublicRouter } from "./public.js"; import { getStripeWebhookRouter } from "./stripe.js"; @@ -31,6 +32,9 @@ export const getMainRouter = (config: AppConfig) => { // webhooks mainRouter.route("/stripe-webhook", getStripeWebhookRouter()); + // public client onboarding routes + mainRouter.route("/client-invites", getPublicClientInvitesRouter()); + // maybe authenticated routes (checked first to allow unauthenticated booking) mainRouter.route("/", getMaybeAuthenticatedRouter()); diff --git a/apps/api/src/routers/maybeAuthRouter.ts b/apps/api/src/routers/maybeAuthRouter.ts index b01a6c5..7da5c8e 100644 --- a/apps/api/src/routers/maybeAuthRouter.ts +++ b/apps/api/src/routers/maybeAuthRouter.ts @@ -1,7 +1,6 @@ import { Hono } from "hono"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { MaybeAuthEnv } from "../types/app.types.js"; -import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getBookingRouter } from "./invite.js"; export const getMaybeAuthenticatedRouter = () => { @@ -12,7 +11,6 @@ export const getMaybeAuthenticatedRouter = () => { maybeAuthenticated.use(middlewareManager.maybeAuthenticated); maybeAuthenticated.route("/book", getBookingRouter()); - maybeAuthenticated.route("/client-invites", getPublicClientInvitesRouter()); return maybeAuthenticated; }; From 4e6be584448db2b9a3a174126dd591401e58cd78 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:43:58 +0200 Subject: [PATCH 23/44] fix: load auth logos from assets host --- apps/clients/src/pages/LoginPage.test.tsx | 4 ++++ packages/auth-ui/src/AuthCardShell.tsx | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/clients/src/pages/LoginPage.test.tsx b/apps/clients/src/pages/LoginPage.test.tsx index 425eac6..47f77d7 100644 --- a/apps/clients/src/pages/LoginPage.test.tsx +++ b/apps/clients/src/pages/LoginPage.test.tsx @@ -41,6 +41,10 @@ describe("LoginPage", () => { expect(screen.getByLabelText("Email")).toBeInTheDocument(); expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument(); + expect(screen.getAllByAltText("Xtablo")[0]).toHaveAttribute( + "src", + "https://assets.xtablo.com/logo_dark.png" + ); }); it("submits email/password login and resumes the stored redirect", async () => { diff --git a/packages/auth-ui/src/AuthCardShell.tsx b/packages/auth-ui/src/AuthCardShell.tsx index 3baca34..eaa1113 100644 --- a/packages/auth-ui/src/AuthCardShell.tsx +++ b/packages/auth-ui/src/AuthCardShell.tsx @@ -20,6 +20,8 @@ type AuthCardShellProps = { cardClassName?: string; }; +const XTABLO_ASSETS_BASE_URL = "https://assets.xtablo.com"; + export function AuthCardShell({ title, description, @@ -101,12 +103,12 @@ export function AuthCardShell({
Xtablo Xtablo From e568b342ade1f5cdac16e31abc8d4ed7ab7ded89 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:54:15 +0200 Subject: [PATCH 24/44] apps/clients target staging backend for now --- apps/clients/.env.production | 2 +- apps/clients/src/envProduction.test.ts | 13 +++++++++++++ apps/clients/tsconfig.tsbuildinfo | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 apps/clients/src/envProduction.test.ts diff --git a/apps/clients/.env.production b/apps/clients/.env.production index f63a9df..7f10812 100644 --- a/apps/clients/.env.production +++ b/apps/clients/.env.production @@ -1,4 +1,4 @@ VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM -VITE_API_URL=https://xablo-api-636270553187.europe-west1.run.app +VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app diff --git a/apps/clients/src/envProduction.test.ts b/apps/clients/src/envProduction.test.ts new file mode 100644 index 0000000..a2481d2 --- /dev/null +++ b/apps/clients/src/envProduction.test.ts @@ -0,0 +1,13 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +const productionEnv = readFileSync(resolve(process.cwd(), ".env.production"), "utf8"); + +describe("clients production env", () => { + it("points the API URL to staging while client portal testing is in progress", () => { + expect(productionEnv).toContain( + "VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app" + ); + }); +}); diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index 6ab4cf9..ed49639 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/envproduction.test.ts","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file From cc37bf2a7870d92e093589cc25d431ac855f94b1 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 12:04:55 +0200 Subject: [PATCH 25/44] Improve client portal --- .../src/pages/ClientTabloPage.test.tsx | 21 ++- apps/clients/src/pages/ClientTabloPage.tsx | 168 ++---------------- 2 files changed, 30 insertions(+), 159 deletions(-) diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 8380d98..4055037 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -102,9 +102,24 @@ describe("ClientTabloPage parity shell", () => { expect(screen.getByText("Client Project")).toBeInTheDocument(); expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2); - expect(screen.getByText("Rôle :")).toBeInTheDocument(); - expect(screen.getByText("Créé le :")).toBeInTheDocument(); - expect(screen.getByText("Progression :")).toBeInTheDocument(); + expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0); + expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0); + expect(screen.getAllByText("Progression").length).toBeGreaterThan(0); + }); + + it("keeps the shared main-app header labels even when the client locale is english", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + language: "en", + }); + + expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0); + expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0); + expect(screen.getAllByText("Progression").length).toBeGreaterThan(0); + expect(screen.queryByText("Role")).not.toBeInTheDocument(); + expect(screen.queryByText("Created on")).not.toBeInTheDocument(); + expect(screen.queryByText("Progress")).not.toBeInTheDocument(); }); it("keeps client restrictions by hiding invite and layout-edit controls", () => { diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 0f536d4..aaeb3eb 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -4,31 +4,15 @@ import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; import { - CalendarIcon, - Compass, - Flame, FolderIcon, - Gem, - Heart, - KanbanIcon, - LayoutDashboardIcon, - Leaf, - ListChecksIcon, - MapIcon, - MessageCircleIcon, - Sparkles, - Star, - Sun, - Waves, - Zap, } from "lucide-react"; import { useState } from "react"; -import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, - TabloDetailsShell, + SingleTabloView, + type SingleTabloTabId, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, @@ -158,43 +142,6 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } -function getTabloIcon(color: string | null | undefined) { - switch (color) { - case "bg-blue-500": - return Zap; - case "bg-green-500": - return Leaf; - case "bg-purple-500": - return Gem; - case "bg-red-500": - return Flame; - case "bg-yellow-500": - return Star; - case "bg-indigo-500": - return Compass; - case "bg-pink-500": - return Heart; - case "bg-teal-500": - return Waves; - case "bg-orange-500": - return Sun; - case "bg-cyan-500": - return Sparkles; - default: - return FolderIcon; - } -} - -function getTabloIconColor(color: string | null | undefined): string { - switch (color) { - case "bg-yellow-500": - case "bg-cyan-500": - return "text-gray-700"; - default: - return "text-white"; - } -} - function getStatusConfig(status: string) { switch (status) { case "in_progress": @@ -238,27 +185,12 @@ function getEtapeProgressStats(etapes: Etape[]) { }; } -// ─── Tabs ───────────────────────────────────────────────────────────────────── - -type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; - -const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ - { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, - { id: "etapes", label: "Étapes", icon: ListChecksIcon }, - { id: "tasks", label: "Tâches", icon: KanbanIcon }, - { id: "files", label: "Fichiers", icon: FolderIcon }, - { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, - { id: "events", label: "Événements", icon: CalendarIcon }, - { id: "roadmap", label: "Roadmap", icon: MapIcon }, -]; - // ─── Page ───────────────────────────────────────────────────────────────────── export function ClientTabloPage() { - const { t } = useTranslation(["pages", "chat"]); const { tabloId } = useParams<{ tabloId: string }>(); const { session } = useSession(); - const [activeTab, setActiveTab] = useState("overview"); + const [activeTab, setActiveTab] = useState("overview"); const accessToken = session?.access_token; const currentUserId = session?.user.id ?? ""; @@ -293,93 +225,17 @@ export function ClientTabloPage() { const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); const progress = getEtapeProgressStats(etapes); - const isDiscussionView = activeTab === "discussion"; - const TabloIcon = getTabloIcon(tablo.color); - const iconColor = getTabloIconColor(tablo.color); - - const metadata = [ - { - key: "role", - label: t("pages:tablo.details.roleLabel"), - value: ( - {t("pages:tablo.role.guest")} - ), - }, - { - key: "created-at", - label: t("pages:tablo.details.createdAtLabel"), - value: ( - - {new Intl.DateTimeFormat("fr-FR", { - year: "numeric", - month: "short", - day: "2-digit", - }).format(new Date(tablo.created_at))} - - ), - }, - { - key: "status", - label: t("pages:tablo.details.statusLabel"), - value: {statusLabel}, - }, - { - key: "progress", - label: t("pages:tablo.details.progressLabel"), - value: ( - <> -
-
-
-
- {progress.donePercentage}% - - ), - }, - ]; - - const headerVisual = ( -
- {tablo.image ? ( - {tablo.name} - ) : ( - - )} -
- ); - - const headerActions = ( - - ); return ( - setActiveTab(tabId as TabId)} - isDiscussionView={isDiscussionView} + onTabChange={setActiveTab} + discussionAction={{ kind: "button", onClick: () => setActiveTab("discussion") }} > {activeTab === "overview" && (
@@ -464,7 +320,7 @@ export function ClientTabloPage() {
Rôle
-
{t("pages:tablo.role.guest")}
+
Invité
@@ -540,6 +396,6 @@ export function ClientTabloPage() { onTaskStatusChange={() => {}} /> )} - + ); } From 68ad61b5a9765b0a99853f747db371714f7abcbc Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 13:05:21 +0200 Subject: [PATCH 26/44] Fix css not wired in clients --- .../clients/src/components/ClientLayout.test.tsx | 16 ++++++++++++---- apps/clients/src/components/ClientLayout.tsx | 8 +++++--- apps/clients/src/main.css | 2 ++ apps/clients/src/mainCss.test.ts | 4 +++- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx index 709a0c0..4578431 100644 --- a/apps/clients/src/components/ClientLayout.test.tsx +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -5,7 +5,7 @@ import { renderWithProviders } from "../test/testHelpers"; import { ClientLayout } from "./ClientLayout"; describe("ClientLayout", () => { - it("uses the main app style header shell and centered content container", () => { + it("uses the main app style header shell and scrolling main viewport", () => { const { container } = renderWithProviders(); const header = container.querySelector("header"); @@ -18,9 +18,17 @@ describe("ClientLayout", () => { expect(headerInner).toHaveClass("mx-auto"); const main = container.querySelector("main"); - expect(main).toHaveClass("w-full"); - expect(main).toHaveClass("max-w-7xl"); - expect(main).toHaveClass("mx-auto"); + expect(main).toHaveClass("flex-1"); + expect(main).toHaveClass("overflow-auto"); + expect(main).not.toHaveClass("max-w-7xl"); + expect(main).not.toHaveClass("mx-auto"); + + const contentWrapper = main?.firstElementChild; + expect(contentWrapper).toHaveClass("mx-auto"); + expect(contentWrapper).toHaveClass("w-full"); + expect(contentWrapper).toHaveClass("max-w-7xl"); + expect(contentWrapper).toHaveClass("px-4"); + expect(contentWrapper).toHaveClass("sm:px-6"); }); it("redirects unauthenticated client routes to the login page", async () => { diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 5ef32f4..a2079db 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -24,7 +24,7 @@ export function ClientLayout() { }; return ( -
+
Xtablo @@ -42,8 +42,10 @@ export function ClientLayout() {
-
- +
+
+ +
); diff --git a/apps/clients/src/main.css b/apps/clients/src/main.css index 2782768..104b0b7 100644 --- a/apps/clients/src/main.css +++ b/apps/clients/src/main.css @@ -2,6 +2,8 @@ @import "tw-animate-css"; @source "../../../packages/chat-ui/src/**/*.{ts,tsx}"; +@source "../../../packages/tablo-views/src/**/*.{ts,tsx}"; +@source "../../../packages/auth-ui/src/**/*.{ts,tsx}"; @custom-variant dark (&:is(.dark *)); diff --git a/apps/clients/src/mainCss.test.ts b/apps/clients/src/mainCss.test.ts index c150cce..a7f2a5c 100644 --- a/apps/clients/src/mainCss.test.ts +++ b/apps/clients/src/mainCss.test.ts @@ -5,8 +5,10 @@ import { describe, expect, it } from "vitest"; const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8"); describe("clients main.css", () => { - it("keeps the chat source and theme tokens aligned with the main app", () => { + it("keeps shared package sources and theme tokens aligned with the main app", () => { expect(mainCss).toContain('@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain('@source "../../../packages/tablo-views/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain('@source "../../../packages/auth-ui/src/**/*.{ts,tsx}";'); expect(mainCss).toContain("--navbar-background: rgb(249, 250, 251);"); expect(mainCss).toContain("--color-navbar-background: var(--navbar-background);"); expect(mainCss).toContain("--str-chat__own-message-bubble-color: #804eec;"); From a37c4ddf258f74185c9525be4d3725ce29c7be04 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 23:15:01 +0200 Subject: [PATCH 27/44] fix: allow deleting tablos with etapes --- apps/api/src/__tests__/routes/tablo.test.ts | 47 +++++++++++++++++++++ apps/api/src/routers/tablo.ts | 22 ++-------- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index 923fa38..a8fa3ea 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { TEST_USERS } from "../fixtures/testData.js"; import type { TestUserData } from "../helpers/dbSetup.js"; import { getTestUser } from "../helpers/dbSetup.js"; @@ -109,6 +110,23 @@ describe("Tablo Endpoint", () => { ); }; + const signInAsTestUser = async (email: string, password: string) => { + const userClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { + autoRefreshToken: false, + persistSession: false, + }, + }); + + const { data, error } = await userClient.auth.signInWithPassword({ email, password }); + + if (error || !data.session) { + throw new Error(`Failed to sign in ${email}: ${error?.message ?? "missing session"}`); + } + + return userClient; + }; + // Helper function to get tablo members // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access const getTabloMembersRequest = async (user: TestUserData, client: any, tabloId: string) => { @@ -415,6 +433,35 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(403); }); + + it("should allow owner to delete a tablo that contains etapes", async () => { + const createRes = await createTabloRequest(ownerUser, client, { + name: "Delete With Etape", + status: "todo", + color: "#804EEC", + }); + + expect(createRes.status).toBe(200); + const createData = await createRes.json(); + const createdTabloId = createData.tablo.id as string; + createdTabloIds.push(createdTabloId); + + const ownerClient = await signInAsTestUser(TEST_USERS.owner.email, TEST_USERS.owner.password); + const { error: createEtapeError } = await ownerClient.from("tasks").insert({ + tablo_id: createdTabloId, + title: "Delete me", + is_parent: true, + status: "todo", + }); + + expect(createEtapeError).toBeNull(); + + const res = await deleteTabloRequest(ownerUser, client, createdTabloId); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.message).toBe("Tablo deleted successfully"); + }); }); describe("GET /tablos/members/:tablo_id - Get Tablo Members", () => { diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 5ce02b7..105e21c 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -126,26 +126,10 @@ const deleteTablo = factory.createHandlers(async (c) => { const deletedAt = new Date().toISOString(); - const { error: tasksSoftDeleteError } = await supabase - .from("tasks") - .update({ deleted_at: deletedAt }) - .eq("tablo_id", id) - .is("deleted_at", null); + const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksSoftDeleteError) { - // Backward compatibility for environments where tasks.deleted_at is not migrated yet. - const isMissingDeletedAtColumn = - tasksSoftDeleteError.code === "42703" || - tasksSoftDeleteError.message?.toLowerCase().includes("deleted_at"); - - if (isMissingDeletedAtColumn) { - const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksDeleteError) { - return c.json({ error: tasksDeleteError.message }, 500); - } - } else { - return c.json({ error: tasksSoftDeleteError.message }, 500); - } + if (tasksDeleteError) { + return c.json({ error: tasksDeleteError.message }, 500); } const { error } = await supabase.from("tablos").update({ deleted_at: deletedAt }).eq("id", id); From 515a875e889ce5df34abc5c9867f3fcbf4c29428 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 23:15:01 +0200 Subject: [PATCH 28/44] fix: allow deleting tablos with etapes --- apps/api/src/__tests__/routes/tablo.test.ts | 47 +++++++++++++++++++++ apps/api/src/routers/tablo.ts | 22 ++-------- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index 923fa38..a8fa3ea 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { TEST_USERS } from "../fixtures/testData.js"; import type { TestUserData } from "../helpers/dbSetup.js"; import { getTestUser } from "../helpers/dbSetup.js"; @@ -109,6 +110,23 @@ describe("Tablo Endpoint", () => { ); }; + const signInAsTestUser = async (email: string, password: string) => { + const userClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { + autoRefreshToken: false, + persistSession: false, + }, + }); + + const { data, error } = await userClient.auth.signInWithPassword({ email, password }); + + if (error || !data.session) { + throw new Error(`Failed to sign in ${email}: ${error?.message ?? "missing session"}`); + } + + return userClient; + }; + // Helper function to get tablo members // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access const getTabloMembersRequest = async (user: TestUserData, client: any, tabloId: string) => { @@ -415,6 +433,35 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(403); }); + + it("should allow owner to delete a tablo that contains etapes", async () => { + const createRes = await createTabloRequest(ownerUser, client, { + name: "Delete With Etape", + status: "todo", + color: "#804EEC", + }); + + expect(createRes.status).toBe(200); + const createData = await createRes.json(); + const createdTabloId = createData.tablo.id as string; + createdTabloIds.push(createdTabloId); + + const ownerClient = await signInAsTestUser(TEST_USERS.owner.email, TEST_USERS.owner.password); + const { error: createEtapeError } = await ownerClient.from("tasks").insert({ + tablo_id: createdTabloId, + title: "Delete me", + is_parent: true, + status: "todo", + }); + + expect(createEtapeError).toBeNull(); + + const res = await deleteTabloRequest(ownerUser, client, createdTabloId); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.message).toBe("Tablo deleted successfully"); + }); }); describe("GET /tablos/members/:tablo_id - Get Tablo Members", () => { diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 5ce02b7..105e21c 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -126,26 +126,10 @@ const deleteTablo = factory.createHandlers(async (c) => { const deletedAt = new Date().toISOString(); - const { error: tasksSoftDeleteError } = await supabase - .from("tasks") - .update({ deleted_at: deletedAt }) - .eq("tablo_id", id) - .is("deleted_at", null); + const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksSoftDeleteError) { - // Backward compatibility for environments where tasks.deleted_at is not migrated yet. - const isMissingDeletedAtColumn = - tasksSoftDeleteError.code === "42703" || - tasksSoftDeleteError.message?.toLowerCase().includes("deleted_at"); - - if (isMissingDeletedAtColumn) { - const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksDeleteError) { - return c.json({ error: tasksDeleteError.message }, 500); - } - } else { - return c.json({ error: tasksSoftDeleteError.message }, 500); - } + if (tasksDeleteError) { + return c.json({ error: tasksDeleteError.message }, 500); } const { error } = await supabase.from("tablos").update({ deleted_at: deletedAt }).eq("id", id); From 46d2eb027775870fc108df46d69b0668f99bce20 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 09:51:35 +0200 Subject: [PATCH 29/44] fix: wire client portal interactions --- apps/chat-worker/src/index.ts | 3 +- apps/clients/.env.production | 3 + apps/clients/src/envProduction.test.ts | 4 +- .../src/pages/ClientTabloPage.test.tsx | 472 +++++++++++++++++- apps/clients/src/pages/ClientTabloPage.tsx | 314 +++++++++++- packages/tablo-views/src/EtapesSection.tsx | 17 +- .../tablo-views/src/TabloFilesSection.tsx | 130 ++--- 7 files changed, 865 insertions(+), 78 deletions(-) diff --git a/apps/chat-worker/src/index.ts b/apps/chat-worker/src/index.ts index 5eb2a65..6f3adee 100644 --- a/apps/chat-worker/src/index.ts +++ b/apps/chat-worker/src/index.ts @@ -10,12 +10,13 @@ export { ChatRoom }; const app = new Hono<{ Bindings: Env }>(); -// CORS — allow the main app origins +// CORS — allow the web app origins that embed chat app.use("*", cors({ origin: [ "http://localhost:5173", "https://app.xtablo.com", "https://app-staging.xtablo.com", + "https://clients.xtablo.com", ], allowHeaders: ["Authorization", "Content-Type"], allowMethods: ["GET", "POST", "OPTIONS"], diff --git a/apps/clients/.env.production b/apps/clients/.env.production index 7f10812..7c3ba26 100644 --- a/apps/clients/.env.production +++ b/apps/clients/.env.production @@ -1,4 +1,7 @@ VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM +VITE_CHAT_WS_URL=wss://chat.xtablo.com +VITE_CHAT_API_URL=https://chat.xtablo.com + VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app diff --git a/apps/clients/src/envProduction.test.ts b/apps/clients/src/envProduction.test.ts index a2481d2..90f3834 100644 --- a/apps/clients/src/envProduction.test.ts +++ b/apps/clients/src/envProduction.test.ts @@ -5,9 +5,11 @@ import { describe, expect, it } from "vitest"; const productionEnv = readFileSync(resolve(process.cwd(), ".env.production"), "utf8"); describe("clients production env", () => { - it("points the API URL to staging while client portal testing is in progress", () => { + it("points the API URL to staging while client portal testing is in progress and keeps chat endpoints configured", () => { expect(productionEnv).toContain( "VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app" ); + expect(productionEnv).toContain("VITE_CHAT_API_URL=https://chat.xtablo.com"); + expect(productionEnv).toContain("VITE_CHAT_WS_URL=wss://chat.xtablo.com"); }); }); diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 4055037..2f0dc18 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -1,14 +1,114 @@ -import { screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; +import { screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../test/testHelpers"; import { ClientTabloPage } from "./ClientTabloPage"; +const { + apiGetMock, + apiPostMock, + apiPutMock, + apiDeleteMock, + updateTaskMock, + insertTaskMock, + deleteTaskMock, + supabaseFromMock, +} = vi.hoisted(() => { + const apiGetMock = vi.fn(async (url: string) => { + if (url.endsWith("/brief.pdf")) { + return { + status: 200, + data: { content: "test file content", contentType: "application/pdf" }, + }; + } + + return { status: 200, data: { folders: [] } }; + }); + const apiPostMock = vi.fn(async () => ({ + status: 200, + data: { + message: "ok", + fileName: "brief.pdf", + tabloId: "tablo-1", + folder: { id: "folder-1", name: "Livrable", description: "" }, + }, + })); + const apiPutMock = vi.fn(async () => ({ + status: 200, + data: { folder: { id: "folder-1", name: "Livrable mis à jour", description: "Desc" } }, + })); + const apiDeleteMock = vi.fn(async () => ({ status: 200, data: { message: "ok" } })); + const createUpdateBuilder = () => { + const builder = { + error: null as null, + eq: vi.fn(() => builder), + select: vi.fn(() => ({ + single: async () => ({ data: { id: "task-1" }, error: null }), + })), + }; + return builder; + }; + const updateTaskMock = vi.fn(() => createUpdateBuilder()); + const insertTaskMock = vi.fn(() => ({ + select: () => ({ + single: async () => ({ data: { id: "task-created" }, error: null }), + }), + })); + const deleteTaskMock = vi.fn(() => ({ + eq: vi.fn(async () => ({ error: null })), + })); + const supabaseFromMock = vi.fn(() => ({ + insert: insertTaskMock, + update: updateTaskMock, + delete: deleteTaskMock, + })); + + return { + apiGetMock, + apiPostMock, + apiPutMock, + apiDeleteMock, + updateTaskMock, + insertTaskMock, + deleteTaskMock, + supabaseFromMock, + }; +}); +let latestTabloTasksSectionProps: Record | null = null; +let latestEtapesSectionProps: Record | null = null; +let latestRoadmapSectionProps: Record | null = null; +let latestTabloFilesSectionProps: Record | null = null; + +vi.mock("@xtablo/shared", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + buildApi: () => ({ + create: () => ({ + get: apiGetMock, + post: apiPostMock, + put: apiPutMock, + delete: apiDeleteMock, + }), + }), + }; +}); + +vi.mock("../lib/supabase", () => ({ + supabase: { + from: supabaseFromMock, + }, +})); + vi.mock("@tanstack/react-query", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - useQuery: ({ queryKey }: { queryKey: string[] }) => { + useQuery: ({ queryKey, queryFn }: { queryKey: string[]; queryFn?: () => Promise }) => { + if (queryKey[0] === "client-tablo-folders" && queryFn) { + void queryFn(); + } switch (queryKey[0]) { case "client-tablo": return { @@ -84,16 +184,321 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { return { ...actual, - EtapesSection: () =>
Etapes section
, - RoadmapSection: () =>
Roadmap section
, + EtapesSection: (props: Record) => { + latestEtapesSectionProps = props; + return ( +
+
Etapes section
+ + +
+ ); + }, + RoadmapSection: (props: Record) => { + latestRoadmapSectionProps = props; + return ( +
+
Roadmap section
+ +
+ ); + }, TabloDiscussionSection: () =>
Discussion section
, TabloEventsSection: () =>
Events section
, - TabloFilesSection: () =>
Files section
, - TabloTasksSection: () =>
Tasks section
, + TabloFilesSection: (props: Record) => { + latestTabloFilesSectionProps = props; + return ( +
+
Files section
+ + + + + +
+ ); + }, + TabloTasksSection: (props: Record) => { + latestTabloTasksSectionProps = props; + return ( +
+
Tasks section
+ + + + +
+ ); + }, }; }); describe("ClientTabloPage parity shell", () => { + beforeEach(() => { + window.URL.createObjectURL = vi.fn(() => "blob:test"); + window.URL.revokeObjectURL = vi.fn(); + HTMLAnchorElement.prototype.click = vi.fn(); + apiGetMock.mockClear(); + apiPostMock.mockClear(); + apiPutMock.mockClear(); + apiDeleteMock.mockClear(); + updateTaskMock.mockClear(); + insertTaskMock.mockClear(); + deleteTaskMock.mockClear(); + supabaseFromMock.mockClear(); + latestTabloTasksSectionProps = null; + latestEtapesSectionProps = null; + latestRoadmapSectionProps = null; + latestTabloFilesSectionProps = null; + }); + + it("requests folders from the tablo-data API route", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders"); + }); + + it("wires real task mutation callbacks throughout the client task surfaces", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + + expect(latestEtapesSectionProps?.onCreateTask).toBeTypeOf("function"); + expect(latestEtapesSectionProps?.onTaskStatusChange).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Créer tâche d'étape test" })); + await user.click(screen.getByRole("button", { name: "Terminer tâche d'étape test" })); + + await user.click(screen.getByRole("button", { name: "Tâches" })); + + expect(latestTabloTasksSectionProps?.onCreateTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onUpdateTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onDeleteTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onUpdateTaskPositions).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Créer tâche test" })); + await user.click(screen.getByRole("button", { name: "Modifier tâche test" })); + await user.click(screen.getByRole("button", { name: "Supprimer tâche test" })); + await user.click(screen.getByRole("button", { name: "Déplacer la tâche test" })); + + await user.click(screen.getByRole("button", { name: "Roadmap" })); + + expect(latestRoadmapSectionProps?.onTaskStatusChange).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Changer statut roadmap test" })); + + await waitFor(() => { + expect(supabaseFromMock).toHaveBeenCalledWith("tasks"); + expect(insertTaskMock).toHaveBeenCalledTimes(2); + expect(insertTaskMock).toHaveBeenCalledWith( + expect.objectContaining({ + tablo_id: "tablo-1", + title: "Task from etape", + status: "todo", + assignee_id: null, + position: 0, + parent_task_id: "etape-1", + is_parent: false, + description: null, + due_date: null, + }) + ); + expect(updateTaskMock).toHaveBeenCalledWith({ title: "Updated task title" }); + expect(updateTaskMock).toHaveBeenCalledWith({ position: 7, status: "done" }); + expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" }); + expect(deleteTaskMock).toHaveBeenCalledTimes(1); + }); + }); + it("renders the main-route style header metadata and discussion CTA", () => { renderWithProviders(, { route: "/tablo/tablo-1", @@ -143,4 +548,57 @@ describe("ClientTabloPage parity shell", () => { expect(screen.getByText("Informations")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Ajouter" })).not.toBeInTheDocument(); }); + + it("lets the client quickly toggle a task from the overview card", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Prepare proposal" })); + + await waitFor(() => { + expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" }); + }); + }); + + it("wires file and folder actions in the client files tab while keeping file deletion disabled", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Fichiers" })); + + expect(latestTabloFilesSectionProps?.isReadOnly).toBe(false); + expect(latestTabloFilesSectionProps?.onCreateFile).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDownloadFile).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onCreateFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onUpdateFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDeleteFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDeleteFile).toBeUndefined(); + + await user.click(screen.getByRole("button", { name: "Créer fichier test" })); + await user.click(screen.getByRole("button", { name: "Télécharger fichier test" })); + await user.click(screen.getByRole("button", { name: "Créer livrable test" })); + await user.click(screen.getByRole("button", { name: "Modifier livrable test" })); + await user.click(screen.getByRole("button", { name: "Supprimer livrable test" })); + + await waitFor(() => { + expect(apiPostMock).toHaveBeenCalledWith( + "/api/v1/tablo-data/tablo-1/file/brief.pdf", + { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" } + ); + expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/brief.pdf"); + expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders", { + name: "Livrable", + description: "Desc", + }); + expect(apiPutMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1", { + name: "Livrable mis à jour", + description: "Desc", + }); + expect(apiDeleteMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1"); + }); + }); }); diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index aaeb3eb..4be1e85 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,8 +1,15 @@ -import { useQuery } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { cn } from "@xtablo/shared"; import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; -import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; +import type { + Etape, + KanbanTask, + KanbanTaskUpdate, + TabloFolder, + TaskStatus, + UserTablo, +} from "@xtablo/shared-types"; import { FolderIcon, } from "lucide-react"; @@ -135,13 +142,254 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) return useQuery({ queryKey: ["client-tablo-folders", tabloId], queryFn: async () => { - const { data } = await api.get<{ folders: TabloFolder[] }>(`/api/v1/tablo-folders/${tabloId}`); + const { data } = await api.get<{ folders: TabloFolder[] }>( + `/api/v1/tablo-data/${tabloId}/folders` + ); return data.folders ?? []; }, enabled: !!tabloId && !!accessToken, }); } +const invalidateClientFileQueries = (queryClient: ReturnType, tabloId: string) => { + queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] }); + queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] }); +}; + +function useClientCreateFile(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + fileName: string; + data: { content: string; contentType: string }; + }) => { + const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, params.data); + if (response.status !== 200) { + throw new Error("Failed to create file"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientDownloadFile(accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + + return useMutation({ + mutationFn: async ({ tabloId, fileName }: { tabloId: string; fileName: string }) => { + const response = await api.get(`/api/v1/tablo-data/${tabloId}/${fileName}`); + if (response.status !== 200) { + throw new Error("Failed to download file"); + } + + const fileData = response.data as { content: string; contentType?: string }; + let blob: Blob; + + if (fileData.content.startsWith("data:")) { + const fileResponse = await fetch(fileData.content); + blob = await fileResponse.blob(); + } else { + blob = new Blob([fileData.content], { + type: fileData.contentType || "application/octet-stream", + }); + } + + const url = window.URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + window.URL.revokeObjectURL(url); + }, + }); +} + +function useClientCreateFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + name: string; + description: string; + createdBy: string; + }) => { + const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/folders`, { + name: params.name, + description: params.description, + }); + if (response.status !== 200) { + throw new Error("Failed to create folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientUpdateFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + folderId: string; + name: string; + description: string; + }) => { + const response = await api.put(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, { + name: params.name, + description: params.description, + }); + if (response.status !== 200) { + throw new Error("Failed to update folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientDeleteFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + folderId: string; + folderName: string; + }) => { + const response = await api.delete(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`); + if (response.status !== 200) { + throw new Error("Failed to delete folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +type ClientTaskCreateInput = { + tablo_id: string; + title: string; + status?: TaskStatus | string; + parent_task_id?: string | null; + is_parent?: boolean; + position?: number; + description?: string | null; + assignee_id?: string | null; + due_date?: string | null; +}; + +const invalidateClientTaskQueries = (queryClient: ReturnType, tabloId: string) => { + queryClient.invalidateQueries({ queryKey: ["client-tasks", tabloId] }); +}; + +function useClientCreateTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (task: ClientTaskCreateInput) => { + const { data, error } = await supabase + .from("tasks") + .insert({ + tablo_id: task.tablo_id, + title: task.title, + status: (task.status as TaskStatus | undefined) ?? "todo", + assignee_id: task.assignee_id ?? null, + position: task.position ?? 0, + parent_task_id: task.parent_task_id ?? null, + is_parent: task.is_parent ?? false, + description: task.description ?? null, + due_date: task.due_date ?? null, + }) + .select() + .single(); + + if (error) throw error; + return data; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientUpdateTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ id, tablo_id: _tabloId, ...updates }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { + const { data, error } = await supabase + .from("tasks") + .update(updates) + .eq("id", id) + .select() + .single(); + + if (error) throw error; + return data; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientDeleteTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (taskId: string) => { + const { error } = await supabase.from("tasks").delete().eq("id", taskId); + if (error) throw error; + return taskId; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientUpdateTaskPositions(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ( + updates: Array<{ + id: string; + position: number; + status?: TaskStatus; + parent_task_id?: string | null; + }> + ) => { + const results = await Promise.all( + updates.map(({ id, position, status, parent_task_id }) => + supabase + .from("tasks") + .update({ + position, + ...(status && { status }), + ...(parent_task_id !== undefined ? { parent_task_id } : {}), + }) + .eq("id", id) + ) + ); + + const errors = results.filter((result) => result.error); + if (errors.length > 0) { + throw new Error("Failed to update some task positions"); + } + + return updates; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + function getStatusConfig(status: string) { switch (status) { case "in_progress": @@ -202,6 +450,15 @@ export function ClientTabloPage() { const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + const { mutate: createTask } = useClientCreateTask(tabloId ?? ""); + const { mutate: updateTask } = useClientUpdateTask(tabloId ?? ""); + const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? ""); + const { mutate: updateTaskPositions } = useClientUpdateTaskPositions(tabloId ?? ""); + const { mutateAsync: createFile } = useClientCreateFile(tabloId ?? "", accessToken); + const { mutateAsync: downloadFile } = useClientDownloadFile(accessToken); + const { mutateAsync: createFolder } = useClientCreateFolder(tabloId ?? "", accessToken); + const { mutateAsync: updateFolder } = useClientUpdateFolder(tabloId ?? "", accessToken); + const { mutateAsync: deleteFolder } = useClientDeleteFolder(tabloId ?? "", accessToken); const fileNames = (filesData?.fileNames ?? []).filter((f) => !f.startsWith(".")); @@ -263,12 +520,36 @@ export function ClientTabloPage() {
) : ( tasks.slice(0, 5).map((task) => ( -
-
-

+ )) )}

@@ -334,8 +615,9 @@ export function ClientTabloPage() { tabloTasks={tasks} tabloId={tablo.id} isAdmin={false} - onCreateTask={() => {}} + onCreateTask={(task) => createTask(task)} onCreateEtape={async () => {}} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} /> )} @@ -347,6 +629,10 @@ export function ClientTabloPage() { members={members} etapes={etapes} currentUser={currentUser} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} /> )} @@ -354,7 +640,10 @@ export function ClientTabloPage() { createFile(params)} + onDownloadFile={(params) => downloadFile(params)} + onCreateFolder={(params) => createFolder(params)} + onUpdateFolder={(params) => updateFolder(params)} + onDeleteFolder={(params) => deleteFolder(params)} /> )} @@ -393,7 +687,7 @@ export function ClientTabloPage() { {}} - onTaskStatusChange={() => {}} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} /> )} diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index e1b22e8..4f5f3ee 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -1,5 +1,5 @@ import { cn } from "@xtablo/shared"; -import type { Etape, KanbanTask } from "@xtablo/shared-types"; +import type { Etape, KanbanTask, TaskStatus } from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { @@ -30,6 +30,7 @@ interface EtapesSectionProps { position: number; }) => void; onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + onTaskStatusChange?: (taskId: string, status: TaskStatus) => void; onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise; onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise; isCreatingEtape?: boolean; @@ -44,6 +45,7 @@ export function EtapesSection({ isAdmin, onCreateTask, onCreateEtape, + onTaskStatusChange, onUpdateEtape, onDeleteEtape, isCreatingEtape = false, @@ -381,7 +383,18 @@ export function EtapesSection({ {childTasks.map((task) => (
+ onTaskStatusChange?.( + task.id, + task.status === "done" ? "todo" : "done" + ) + } > {task.status === "done" ? ( diff --git a/packages/tablo-views/src/TabloFilesSection.tsx b/packages/tablo-views/src/TabloFilesSection.tsx index e6b93f2..a96df14 100644 --- a/packages/tablo-views/src/TabloFilesSection.tsx +++ b/packages/tablo-views/src/TabloFilesSection.tsx @@ -270,8 +270,9 @@ const FolderDialog = ({ const FolderSection = ({ folder, files, - isAdmin, - isReadOnly, + canManageFolders, + canUploadFiles, + canDeleteFiles, isOpen, onToggle, onEdit, @@ -285,8 +286,9 @@ const FolderSection = ({ }: { folder: TabloFolder; files: string[]; - isAdmin: boolean; - isReadOnly: boolean; + canManageFolders: boolean; + canUploadFiles: boolean; + canDeleteFiles: boolean; isOpen: boolean; onToggle: () => void; onEdit: () => void; @@ -341,7 +343,7 @@ const FolderSection = ({
- {isAdmin && !isReadOnly && ( + {canManageFolders && ( <> -
+ {canUploadFiles && ( +
+ + +
+ )} {/* Files List */} {files.length > 0 ? ( @@ -427,7 +431,7 @@ const FolderSection = ({ onDownloadFile(fileName)} onDelete={() => onDeleteFile(fileName)} isDownloading={downloadingFile === fileName} @@ -483,6 +487,9 @@ interface TabloFilesSectionProps { isCancellingInvite?: boolean; isCreatingFolder?: boolean; isUpdatingFolder?: boolean; + canUploadFiles?: boolean; + canManageFolders?: boolean; + canDeleteFiles?: boolean; onCreateFile?: (params: { tabloId: string; fileName: string; data: { content: string; contentType: string } }) => Promise; onDeleteFile?: (params: { tabloId: string; fileName: string }) => Promise; onDownloadFile?: (params: { tabloId: string; fileName: string }) => Promise; @@ -512,6 +519,9 @@ export const TabloFilesSection = ({ isCancellingInvite, isCreatingFolder = false, isUpdatingFolder = false, + canUploadFiles, + canManageFolders, + canDeleteFiles, onCreateFile, onDeleteFile, onDownloadFile, @@ -534,6 +544,9 @@ export const TabloFilesSection = ({ const fileInputRef = useRef(null); const folderIds = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]); + const allowUploadFiles = canUploadFiles ?? !isReadOnly; + const allowManageFolders = canManageFolders ?? (isAdmin && !isReadOnly); + const allowDeleteFiles = canDeleteFiles ?? true; // Organize files by folder const { filesInFolders, unorganizedFiles } = useMemo(() => { @@ -805,7 +818,7 @@ export const TabloFilesSection = ({ )} {/* Create Folder Button - Admin Only */} - {isAdmin && !isReadOnly && ( + {allowManageFolders && (
{/* File Upload Area */} - {!selectedFile ? ( + {allowUploadFiles && !selectedFile ? (
- ) : ( + ) : allowUploadFiles && selectedFile ? (
@@ -979,11 +993,13 @@ export const TabloFilesSection = ({
- )} + ) : null} -

- Taille maximale par fichier: 20MB -

+ {allowUploadFiles && ( +

+ Taille maximale par fichier: 20MB +

+ )} {/* Unorganized Files List */} {unorganizedFiles.length > 0 && ( @@ -992,7 +1008,7 @@ export const TabloFilesSection = ({ handleDownloadFile(fileName)} onDelete={() => handleDeleteFile(fileName)} isDownloading={downloadingFile === fileName} From cab790dd2a5d3ea2cad49c5ae517e3318a2a30f8 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 11:33:30 +0200 Subject: [PATCH 30/44] Redirect clients to the clients app --- .../components/AuthenticationGateway.test.tsx | 67 ++++++++++ .../src/components/AuthenticationGateway.tsx | 14 ++- .../components/AuthenticationGateway.unit.tsx | 116 +++++++++++++++--- .../src/components/ProtectedRoute.test.tsx | 45 +++++++ apps/main/src/components/ProtectedRoute.tsx | 19 ++- apps/main/src/lib/clientPortal.ts | 24 ++++ 6 files changed, 264 insertions(+), 21 deletions(-) create mode 100644 apps/main/src/components/AuthenticationGateway.test.tsx create mode 100644 apps/main/src/lib/clientPortal.ts diff --git a/apps/main/src/components/AuthenticationGateway.test.tsx b/apps/main/src/components/AuthenticationGateway.test.tsx new file mode 100644 index 0000000..655a495 --- /dev/null +++ b/apps/main/src/components/AuthenticationGateway.test.tsx @@ -0,0 +1,67 @@ +import { screen, waitFor } from "@testing-library/react"; +import { AuthenticationGateway } from "@ui/components/AuthenticationGateway"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; +import { TestUserStoreProvider } from "../providers/UserStoreProvider"; +import { renderWithRouter } from "../utils/testHelpers"; + +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + +describe("AuthenticationGateway", () => { + it("redirects authenticated client users to the client portal instead of main auth pages", async () => { + renderWithRouter( + + + + }> + Login Page
} /> + + + + , + { route: "/login" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Login Page")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/main/src/components/AuthenticationGateway.tsx b/apps/main/src/components/AuthenticationGateway.tsx index 4c8e124..ba3a1b5 100644 --- a/apps/main/src/components/AuthenticationGateway.tsx +++ b/apps/main/src/components/AuthenticationGateway.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { Navigate, Outlet, useSearchParams } from "react-router-dom"; import { match } from "ts-pattern"; +import { redirectClientUserToPortal } from "../lib/clientPortal"; import { useMaybeUser } from "../providers/UserStoreProvider"; import { LoadingSpinner } from "./LoadingSpinner"; @@ -22,9 +23,11 @@ export const AuthenticationGateway = () => { return () => clearTimeout(timer); }, [user]); - let status: "loading" | "should-redirect" | "should-pass" = "loading"; + let status: "loading" | "should-redirect" | "should-redirect-client" | "should-pass" = "loading"; if (isLoading) { status = "loading"; + } else if (user?.is_client) { + status = "should-redirect-client"; } else if (user) { status = "should-redirect"; } else { @@ -34,6 +37,15 @@ export const AuthenticationGateway = () => { return match(status) .with("loading", () => ) .with("should-redirect", () => ) + .with("should-redirect-client", () => ) .with("should-pass", () => ) .exhaustive(); }; + +const ClientPortalRedirect = () => { + useEffect(() => { + redirectClientUserToPortal("/"); + }, []); + + return ; +}; diff --git a/apps/main/src/components/AuthenticationGateway.unit.tsx b/apps/main/src/components/AuthenticationGateway.unit.tsx index ee07143..77515e0 100644 --- a/apps/main/src/components/AuthenticationGateway.unit.tsx +++ b/apps/main/src/components/AuthenticationGateway.unit.tsx @@ -2,8 +2,18 @@ import { screen, waitFor } from "@testing-library/react"; import { AuthenticationGateway } from "@ui/components/AuthenticationGateway"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; +import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + describe("PublicRoute", () => { it("shows loading state initially", () => { renderWithRouter( @@ -38,29 +48,47 @@ describe("PublicRoute", () => { it("redirect to home when user is authenticated", async () => { renderWithRouter( - - - }> - Login Page
} /> - - Home Page
} /> - - , + + + }> + Login Page
} /> +
+ Home Page
} /> + + + , { route: "/login" } ); @@ -70,6 +98,56 @@ describe("PublicRoute", () => { }); }); + it("redirects authenticated client users to the client portal instead of main auth pages", async () => { + renderWithRouter( + + + + }> + Login Page
} /> + + + + , + { route: "/login" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Login Page")).not.toBeInTheDocument(); + }); + it("renders public content when user is not authenticated", async () => { renderWithRouter( diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index c7e6375..3a1de85 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -1,10 +1,19 @@ import { screen, waitFor } from "@testing-library/react"; +import { vi } from "vitest"; import { ProtectedRoute } from "@ui/components/ProtectedRoute"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + describe("ProtectedRoute", () => { beforeEach(() => { localStorage.setItem("xtablo-has-seen-landing-page", "true"); @@ -127,4 +136,40 @@ describe("ProtectedRoute", () => { expect(screen.getByText("Custom Login Page")).toBeInTheDocument(); }); }); + + it("redirects client users to the client portal instead of rendering main app content", async () => { + renderWithRouter( + + + + }> + Protected Content
} /> + + + + , + { route: "/" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Protected Content")).not.toBeInTheDocument(); + }); }); diff --git a/apps/main/src/components/ProtectedRoute.tsx b/apps/main/src/components/ProtectedRoute.tsx index adaeb24..c9c64a7 100644 --- a/apps/main/src/components/ProtectedRoute.tsx +++ b/apps/main/src/components/ProtectedRoute.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { Navigate, Outlet } from "react-router-dom"; import { match } from "ts-pattern"; +import { redirectClientUserToPortal } from "../lib/clientPortal"; import { useMaybeUser } from "../providers/UserStoreProvider"; import { LoadingSpinner } from "./LoadingSpinner"; @@ -28,7 +29,12 @@ export const ProtectedRoute = ({ return () => clearTimeout(timer); }, [user, fallback]); - let status: "loading" | "should-land-user" | "should-redirect" | "should-pass" = "loading"; + let status: + | "loading" + | "should-land-user" + | "should-redirect" + | "should-redirect-client" + | "should-pass" = "loading"; const isFirstTimeUser = localStorage.getItem("xtablo-has-seen-landing-page") === null; @@ -38,6 +44,8 @@ export const ProtectedRoute = ({ status = "should-land-user"; } else if (!user) { status = "should-redirect"; + } else if (user.is_client) { + status = "should-redirect-client"; } else if (onlyRegularUser && user.is_temporary) { status = "should-redirect"; } else { @@ -56,6 +64,15 @@ export const ProtectedRoute = ({ .with("loading", () => ) .with("should-land-user", () => ) .with("should-redirect", () => ) + .with("should-redirect-client", () => ) .with("should-pass", () => ) .exhaustive(); }; + +const ClientPortalRedirect = () => { + useEffect(() => { + redirectClientUserToPortal("/"); + }, []); + + return ; +}; diff --git a/apps/main/src/lib/clientPortal.ts b/apps/main/src/lib/clientPortal.ts new file mode 100644 index 0000000..9e026ca --- /dev/null +++ b/apps/main/src/lib/clientPortal.ts @@ -0,0 +1,24 @@ +const DEFAULT_CLIENTS_APP_URL = "https://clients.xtablo.com"; + +const trimTrailingSlash = (value: string) => value.replace(/\/+$/, ""); + +export function getClientPortalUrl(path = "/") { + const configuredUrl = import.meta.env.VITE_CLIENTS_APP_URL as string | undefined; + const normalizedPath = path.startsWith("/") ? path : `/${path}`; + + const baseUrl = configuredUrl + ? trimTrailingSlash(configuredUrl) + : window.location.hostname === "app.xtablo.com" + ? DEFAULT_CLIENTS_APP_URL + : window.location.hostname.startsWith("app.") + ? `${window.location.protocol}//clients.${window.location.hostname.slice(4)}${ + window.location.port ? `:${window.location.port}` : "" + }` + : DEFAULT_CLIENTS_APP_URL; + + return `${baseUrl}${normalizedPath}`; +} + +export function redirectClientUserToPortal(path = "/") { + window.location.replace(getClientPortalUrl(path)); +} From 46c7bb589e06ca5044fba23febea6fc7d6bcf6e3 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 13:51:54 +0200 Subject: [PATCH 31/44] Update title of webpage --- apps/clients/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/clients/index.html b/apps/clients/index.html index 9fb3e81..0c424af 100644 --- a/apps/clients/index.html +++ b/apps/clients/index.html @@ -3,7 +3,7 @@ - Xtablo — Client Portal + Xtablo — Portail client
From f43491052b5d32f3a20717b97a7ef16f4ff25493 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 17:28:11 +0200 Subject: [PATCH 32/44] Use github CI instead of circle ci --- .circleci/config.yml | 330 --------------------------------------- .dockerignore | 2 - .github/workflows/ci.yml | 54 +++++++ 3 files changed, 54 insertions(+), 332 deletions(-) delete mode 100644 .circleci/config.yml create mode 100644 .github/workflows/ci.yml diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index c40679e..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,330 +0,0 @@ -version: 2.1 - -# Import the Node orb -orbs: - node: circleci/node@7.2.1 - -# Jobs -jobs: - # ============================================ - # TEST PHASE - # ============================================ - - test-lint: - executor: - name: node/default - resource_class: small - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - - run: - name: Run linting - command: pnpm run lint - - test-typecheck: - executor: - name: node/default - resource_class: small - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Type check all packages - command: pnpm run typecheck - - test-unit: - executor: - name: node/default - resource_class: medium - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Run unit tests - command: pnpm --filter @xtablo/main run test - - test-api: - executor: - name: node/default - tag: 'lts' - resource_class: small - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Run API checks - command: | - if [ "${RUN_API_INTEGRATION_TESTS:-0}" = "1" ]; then - pnpm --filter @xtablo/api run test - else - echo "Skipping API integration tests (set RUN_API_INTEGRATION_TESTS=1 to enable)." - pnpm --filter @xtablo/api run build - fi - - # ============================================ - # BUILD PHASE - # ============================================ - - build-apps: - docker: - - image: cimg/node:lts - resource_class: small - parameters: - environment: - type: string - default: "staging" - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Build main app for << parameters.environment >> - command: | - cd apps/main - pnpm run build:<< parameters.environment >> - - run: - name: Build external app - command: | - cd apps/external - pnpm run build - - persist_to_workspace: - root: . - paths: - - apps/main/dist - - apps/external/dist - - store_artifacts: - path: apps/main/dist - destination: main-app-<< parameters.environment >> - - store_artifacts: - path: apps/external/dist - destination: external-app - - build-api: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Build API - command: pnpm --filter @xtablo/api run build - - persist_to_workspace: - root: . - paths: - - apps/api/dist - - store_artifacts: - path: apps/api/dist - destination: api - - # ============================================ - # DOCKER BUILD PHASE - # ============================================ - - build-docker-api: - machine: - image: ubuntu-2204:current - resource_class: medium - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Build API Docker image - command: docker build -f apps/api/Dockerfile -t xtablo-api:${CIRCLE_SHA1} -t xtablo-api:latest . - - run: - name: Save Docker image - command: | - mkdir -p /tmp/docker-images - docker save xtablo-api:${CIRCLE_SHA1} -o /tmp/docker-images/api.tar - - persist_to_workspace: - root: /tmp - paths: - - docker-images/api.tar - - # ============================================ - # DEPLOY PHASE - # ============================================ - - deploy-staging: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - attach_workspace: - at: . - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Deploy main app to staging - command: | - cd apps/main - echo "Deploying main app to staging environment..." - npx wrangler deploy --env staging - - run: - name: Deploy external app to staging - command: | - cd apps/external - echo "Deploying external app to staging..." - # Add external app staging deployment if needed - # npx wrangler deploy --env staging - - run: - name: Deploy API to staging - command: | - echo "Deploying API to staging environment..." - # Add your API deployment commands here - # Example for Google Cloud Run: - # gcloud run deploy xtablo-api-staging --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1 - - deploy-production: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - attach_workspace: - at: . - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Deploy main app to production - command: | - cd apps/main - echo "Deploying main app to production environment..." - npx wrangler deploy --env production - - run: - name: Deploy external app to production - command: | - cd apps/external - echo "Deploying external app to production..." - # Add external app production deployment if needed - # npx wrangler deploy --env production - - run: - name: Deploy API to production - command: | - echo "Deploying API to production environment..." - # Add your production API deployment commands here - # Example for Google Cloud Run: - # gcloud run deploy xtablo-api --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1 - -# Workflows -workflows: - version: 2 - - # Run on all branches (except main and develop) - test-and-build: - when: - and: - - not: - equal: [ main, << pipeline.git.branch >> ] - - not: - equal: [ develop, << pipeline.git.branch >> ] - jobs: - # Test phase - run in parallel - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase - run after tests pass - - build-apps: - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Staging deployment workflow (develop branch) - deploy-to-staging: - when: - equal: [ develop, << pipeline.git.branch >> ] - jobs: - # Test phase - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase for staging - - build-apps: - environment: "staging" - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Deploy to staging - - deploy-staging: - requires: - - build-apps - - build-docker-api - - # Production deployment workflow (main branch) - deploy-to-production: - when: - equal: [ main, << pipeline.git.branch >> ] - jobs: - # Test phase - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase for production - - build-apps: - environment: "prod" - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Manual approval gate before production - - hold-for-approval: - type: approval - requires: - - build-apps - - build-docker-api - - # Deploy to production - - deploy-production: - requires: - - hold-for-approval diff --git a/.dockerignore b/.dockerignore index 30331cb..aaa32d1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -38,7 +38,6 @@ node_modules # CI/CD .github **/cloudbuild.yaml -**/.circleci # Misc **/.turbo @@ -48,4 +47,3 @@ node_modules **/temp **/.next **/.nuxt - diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e1b6548 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + - develop + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + checks: + name: Checks + runs-on: + - self-hosted + - linux + - x64 + timeout-minutes: 45 + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.19.0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm lint + + - name: Typecheck + run: pnpm typecheck + + - name: Test main app + run: pnpm --filter @xtablo/main test + + - name: Test clients app + run: pnpm --filter @xtablo/clients test + + - name: Typecheck API + run: pnpm --filter @xtablo/api typecheck From cc918407beef8acccde386e6229fcf847495405d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:02:27 +0200 Subject: [PATCH 33/44] fix: stabilize lint and client portal flows --- .github/workflows/ci.yml | 4 +- .../__tests__/middlewares/middlewares.test.ts | 24 +- apps/api/src/__tests__/routes/tablo.test.ts | 2 +- apps/api/src/config.ts | 5 +- apps/api/src/helpers/helpers.ts | 5 +- apps/api/src/helpers/orgIcons.test.ts | 18 +- apps/api/src/routers/tablo.ts | 79 +- apps/api/src/routers/tablo_data.ts | 98 +-- apps/api/src/routers/user.ts | 1 - apps/clients/src/i18n.test.ts | 4 +- apps/clients/src/i18n.ts | 6 +- .../clients/src/pages/ClientTabloListPage.tsx | 6 +- .../src/pages/ClientTabloPage.test.tsx | 51 +- apps/clients/src/pages/ClientTabloPage.tsx | 439 +++++----- apps/clients/src/pages/ResetPasswordPage.tsx | 5 +- .../src/pages/SetPasswordPage.test.tsx | 9 +- apps/clients/src/setupTests.ts | 12 +- apps/clients/src/test/testHelpers.test.tsx | 2 +- apps/clients/src/test/testHelpers.tsx | 6 +- apps/clients/vite.config.ts | 6 +- .../src/components/ProtectedRoute.test.tsx | 2 +- .../src/components/SubscriptionCard.test.tsx | 17 +- apps/main/src/pages/tablo-details.tsx | 322 +++---- apps/main/src/pages/tasks.test.tsx | 2 +- biome.json | 12 + packages/auth-ui/src/AuthInfoBanner.tsx | 3 +- packages/chat-ui/src/chat-ui.css | 67 +- packages/chat-ui/src/components/chat.tsx | 789 +++++++++--------- packages/chat-ui/src/components/features.tsx | 284 ++++--- packages/chat-ui/src/components/layouts.tsx | 361 ++++---- packages/chat-ui/src/hooks.ts | 213 +++-- packages/chat-ui/src/index.ts | 174 ++-- packages/chat-ui/src/security.ts | 103 ++- packages/chat-ui/src/types.ts | 102 +-- packages/shared/package.json | 2 +- packages/tablo-views/src/ChatMessages.tsx | 27 +- packages/tablo-views/src/EtapesSection.tsx | 13 +- .../tablo-views/src/TabloDetailsShell.tsx | 7 +- .../src/TabloDiscussionSection.tsx | 2 +- .../tablo-views/src/TabloEventsSection.tsx | 6 +- .../tablo-views/src/TabloFilesSection.tsx | 32 +- .../tablo-views/src/TabloTasksSection.tsx | 15 +- .../src/components/kanban/TaskModal.tsx | 22 +- packages/tablo-views/src/hooks/useChat.ts | 126 +-- .../tablo-views/src/hooks/useChatUnread.ts | 2 +- packages/tablo-views/src/index.ts | 45 +- .../src/single-tablo/SingleTabloOverview.tsx | 21 +- 47 files changed, 1864 insertions(+), 1689 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1b6548..3fcca40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: CI +name: xtablo-ci on: pull_request: @@ -18,6 +18,8 @@ jobs: - self-hosted - linux - x64 + - xtablo-runner + timeout-minutes: 45 steps: diff --git a/apps/api/src/__tests__/middlewares/middlewares.test.ts b/apps/api/src/__tests__/middlewares/middlewares.test.ts index 52a9b20..08390ab 100644 --- a/apps/api/src/__tests__/middlewares/middlewares.test.ts +++ b/apps/api/src/__tests__/middlewares/middlewares.test.ts @@ -24,9 +24,7 @@ describe("Middleware Tests", () => { }), }); - const createBillingStateSupabaseMock = (input: { - ownerPlan?: string | null; - }) => { + const createBillingStateSupabaseMock = (input: { ownerPlan?: string | null }) => { const ownerPlan = input.ownerPlan ?? "none"; return { @@ -325,10 +323,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "temp-user" } as any); + (c as any).set("user", { id: "temp-user" }); await next(); }); app.use(middlewareManager.regularUserCheck); @@ -352,10 +350,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: false, is_client: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "client-user" } as any); + (c as any).set("user", { id: "client-user" }); await next(); }); app.use(middlewareManager.regularUserCheck); @@ -381,10 +379,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "temp-user" } as any); + (c as any).set("user", { id: "temp-user" }); await next(); }); app.use(middlewareManager.billingCheckoutAccess); @@ -409,10 +407,10 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "none", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "owner-user" } as any); + (c as any).set("user", { id: "owner-user" }); await next(); }); app.use(middlewareManager.activePlanAccess); @@ -435,10 +433,10 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "solo", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "owner-user" } as any); + (c as any).set("user", { id: "owner-user" }); await next(); }); app.use(middlewareManager.activePlanAccess); diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index a8fa3ea..3af1417 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -1,5 +1,5 @@ -import { createClient } from "@supabase/supabase-js"; import { randomUUID } from "node:crypto"; +import { createClient } from "@supabase/supabase-js"; import { testClient } from "hono/testing"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 38f74f0..0ed26af 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -85,10 +85,7 @@ export function createConfig(secrets?: Secrets): AppConfig { ? validateEnvVar("STRIPE_WEBHOOK_SECRET", process.env.STRIPE_WEBHOOK_SECRET) : getStripeWebhookSecretFromEnv() || getStripeWebhookSecret(isStagingMode), STRIPE_SOLO_PRICE_ID: validateEnvVar("STRIPE_SOLO_PRICE_ID", process.env.STRIPE_SOLO_PRICE_ID), - STRIPE_TEAM_PRICE_ID: validateEnvVar( - "STRIPE_TEAM_PRICE_ID", - process.env.STRIPE_TEAM_PRICE_ID - ), + STRIPE_TEAM_PRICE_ID: validateEnvVar("STRIPE_TEAM_PRICE_ID", process.env.STRIPE_TEAM_PRICE_ID), STRIPE_FOUNDER_PRICE_ID: validateEnvVar( "STRIPE_FOUNDER_PRICE_ID", process.env.STRIPE_FOUNDER_PRICE_ID diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index 99a3acb..298d6d2 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -413,7 +413,10 @@ export async function findOrCreateClientAccount( recipientEmail: string ): Promise { const normalizedEmail = recipientEmail.trim().toLowerCase(); - const { user: existingUser, error: lookupError } = await getAuthUserByEmail(supabase, normalizedEmail); + const { user: existingUser, error: lookupError } = await getAuthUserByEmail( + supabase, + normalizedEmail + ); if (lookupError) { return { success: false, error: lookupError }; diff --git a/apps/api/src/helpers/orgIcons.test.ts b/apps/api/src/helpers/orgIcons.test.ts index 6493d46..ef943dd 100644 --- a/apps/api/src/helpers/orgIcons.test.ts +++ b/apps/api/src/helpers/orgIcons.test.ts @@ -1,5 +1,5 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { resizeOrgIcon, buildOrgIconKey, ICON_SIZES, ORG_ICONS_BUCKET } from "./orgIcons.js"; +import { describe, expect, it } from "vitest"; +import { buildOrgIconKey, ICON_SIZES, resizeOrgIcon } from "./orgIcons.js"; describe("buildOrgIconKey", () => { it("builds the correct R2 key for a given org and size", () => { @@ -32,7 +32,12 @@ describe("resizeOrgIcon", () => { it("returns buffers for all required sizes from a valid PNG input", async () => { const sharp = (await import("sharp")).default; const input = await sharp({ - create: { width: 512, height: 512, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } }, + create: { + width: 512, + height: 512, + channels: 4, + background: { r: 255, g: 0, b: 0, alpha: 1 }, + }, }) .png() .toBuffer(); @@ -49,7 +54,12 @@ describe("resizeOrgIcon", () => { it("rejects images smaller than 512x512", async () => { const sharp = (await import("sharp")).default; const tooSmall = await sharp({ - create: { width: 256, height: 256, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } }, + create: { + width: 256, + height: 256, + channels: 4, + background: { r: 0, g: 0, b: 255, alpha: 1 }, + }, }) .png() .toBuffer(); diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 105e21c..7b843ae 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -28,44 +28,44 @@ const createTablo = (middlewareManager: ReturnType; + const tabloData = insertedTablo as Tables<"tablos">; - if (typedPayload.events) { - const eventsToInsert = typedPayload.events.map((event) => ({ - ...event, - tablo_id: tabloData.id, - created_by: user.id, - })); + if (typedPayload.events) { + const eventsToInsert = typedPayload.events.map((event) => ({ + ...event, + tablo_id: tabloData.id, + created_by: user.id, + })); - await supabase.from("events").insert(eventsToInsert); - } + await supabase.from("events").insert(eventsToInsert); + } return c.json({ message: "Tablo created successfully", tablo: tabloData }); } ); @@ -90,12 +90,7 @@ const updateTablo = (middlewareManager: ReturnType { const postTabloFile = (middlewareManager: ReturnType) => factory.createHandlers(checkTabloMember, async (c) => { - const tabloId = c.req.param("tabloId"); - const user = c.get("user"); - // Get the file path - supports both wildcard (*) and named parameter (:fileName) - const filePath = c.req.param("path") || c.req.param("fileName"); + const tabloId = c.req.param("tabloId"); + const user = c.get("user"); + // Get the file path - supports both wildcard (*) and named parameter (:fileName) + const filePath = c.req.param("path") || c.req.param("fileName"); - if (!filePath) { - return c.json({ error: "File path is required" }, 400); - } - - const s3_client = c.get("s3_client"); - - try { - const body = await c.req.json(); - const { content, contentType = "text/plain" } = body; - - if (!content) { - return c.json({ error: "Content is required" }, 400); + if (!filePath) { + return c.json({ error: "File path is required" }, 400); } - await s3_client.send( - new PutObjectCommand({ - Bucket: "tablo-data", - Key: `${tabloId}/${filePath}`, - Body: content, - ContentType: contentType, - Metadata: { - "uploaded-by": user.id, - }, - }) - ); - fileNamesCache.delete(tabloId); + const s3_client = c.get("s3_client"); - return c.json({ - message: "File uploaded successfully", - fileName: filePath, - tabloId, - }); - } catch (error) { - console.error("Error uploading file:", error); - return c.json({ error: "Failed to upload file" }, 500); - } + try { + const body = await c.req.json(); + const { content, contentType = "text/plain" } = body; + + if (!content) { + return c.json({ error: "Content is required" }, 400); + } + + await s3_client.send( + new PutObjectCommand({ + Bucket: "tablo-data", + Key: `${tabloId}/${filePath}`, + Body: content, + ContentType: contentType, + Metadata: { + "uploaded-by": user.id, + }, + }) + ); + fileNamesCache.delete(tabloId); + + return c.json({ + message: "File uploaded successfully", + fileName: filePath, + tabloId, + }); + } catch (error) { + console.error("Error uploading file:", error); + return c.json({ error: "Failed to upload file" }, 500); + } }); const deleteTabloFile = (middlewareManager: ReturnType) => @@ -336,10 +336,7 @@ const getTabloFolders = factory.createHandlers(checkTabloMember, async (c) => { // POST /tablo-data/:tabloId/folders - Create a new folder (admin only) const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const s3_client = c.get("s3_client"); const user = c.get("user"); @@ -380,15 +377,11 @@ const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -433,15 +426,11 @@ const updateTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -469,8 +458,7 @@ const deleteTabloFolder = (middlewareManager: ReturnType { if (removeAccessError) { return c.json({ error: "Failed to revoke member tablo permissions" }, 500); } - } const { error: inviteCleanupError } = await supabase diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts index 7ca4e6c..813951c 100644 --- a/apps/clients/src/i18n.test.ts +++ b/apps/clients/src/i18n.test.ts @@ -1,7 +1,5 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; -import bookingEn from "./locales/en/booking.json"; -import bookingFr from "./locales/fr/booking.json"; import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; @@ -14,6 +12,8 @@ import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; import pagesFr from "../../main/src/locales/fr/pages.json"; import tabloFr from "../../main/src/locales/fr/tablo.json"; +import bookingEn from "./locales/en/booking.json"; +import bookingFr from "./locales/fr/booking.json"; i18n.use(initReactI18next).init({ resources: { diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 92423b4..44c6469 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -1,9 +1,6 @@ import i18n from "i18next"; import LanguageDetector from "i18next-browser-languagedetector"; import { initReactI18next } from "react-i18next"; -import bookingEn from "./locales/en/booking.json"; -// Import translation files -import bookingFr from "./locales/fr/booking.json"; import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; @@ -16,6 +13,9 @@ import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; import pagesFr from "../../main/src/locales/fr/pages.json"; import tabloFr from "../../main/src/locales/fr/tablo.json"; +import bookingEn from "./locales/en/booking.json"; +// Import translation files +import bookingFr from "./locales/fr/booking.json"; i18n .use(LanguageDetector) diff --git a/apps/clients/src/pages/ClientTabloListPage.tsx b/apps/clients/src/pages/ClientTabloListPage.tsx index e3ce7c6..bbfff3d 100644 --- a/apps/clients/src/pages/ClientTabloListPage.tsx +++ b/apps/clients/src/pages/ClientTabloListPage.tsx @@ -1,6 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import type { UserTablo } from "@xtablo/shared-types"; -import { Navigate, Link } from "react-router-dom"; +import { Link, Navigate } from "react-router-dom"; import { supabase } from "../lib/supabase"; function useClientTablosList() { @@ -51,9 +51,7 @@ export function ClientTabloListPage() { to={`/tablo/${tablo.id}`} className="block p-5 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors space-y-2" > - {tablo.color && ( -
- )} + {tablo.color &&
}

{tablo.name}

))} diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 2f0dc18..b687b51 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -219,9 +219,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { type="button" onClick={() => ( - props.onTaskStatusChange as - | ((taskId: string, status: string) => void) - | undefined + props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined )?.("task-1", "done") } > @@ -239,9 +237,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { type="button" onClick={() => ( - props.onTaskStatusChange as - | ((taskId: string, status: string) => void) - | undefined + props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined )?.("task-1", "done") } > @@ -271,7 +267,10 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { )?.({ tabloId: "tablo-1", fileName: "brief.pdf", - data: { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" }, + data: { + content: "data:application/pdf;base64,AAAA", + contentType: "application/pdf", + }, }) } > @@ -338,11 +337,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { onClick={() => ( props.onDeleteFolder as - | ((params: { - tabloId: string; - folderId: string; - folderName: string; - }) => void) + | ((params: { tabloId: string; folderId: string; folderName: string }) => void) | undefined )?.({ tabloId: "tablo-1", @@ -364,11 +359,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { @@ -534,7 +527,9 @@ describe("ClientTabloPage parity shell", () => { }); expect(screen.queryByRole("button", { name: "Inviter" })).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Modifier la mise en page" })).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Modifier la mise en page" }) + ).not.toBeInTheDocument(); }); it("renders a read-only overview matching the main route cards", () => { @@ -585,10 +580,10 @@ describe("ClientTabloPage parity shell", () => { await user.click(screen.getByRole("button", { name: "Supprimer livrable test" })); await waitFor(() => { - expect(apiPostMock).toHaveBeenCalledWith( - "/api/v1/tablo-data/tablo-1/file/brief.pdf", - { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" } - ); + expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/file/brief.pdf", { + content: "data:application/pdf;base64,AAAA", + contentType: "application/pdf", + }); expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/brief.pdf"); expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders", { name: "Livrable", diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 4be1e85..2ff728d 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,6 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { cn } from "@xtablo/shared"; -import { buildApi } from "@xtablo/shared"; +import { buildApi, cn } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, @@ -10,21 +9,19 @@ import type { TaskStatus, UserTablo, } from "@xtablo/shared-types"; -import { - FolderIcon, -} from "lucide-react"; -import { useState } from "react"; -import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, - SingleTabloView, type SingleTabloTabId, + SingleTabloView, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, } from "@xtablo/tablo-views"; +import { FolderIcon } from "lucide-react"; +import { useState } from "react"; +import { useParams } from "react-router-dom"; import { supabase } from "../lib/supabase"; const API_URL = import.meta.env.VITE_API_URL as string; @@ -151,7 +148,10 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } -const invalidateClientFileQueries = (queryClient: ReturnType, tabloId: string) => { +const invalidateClientFileQueries = ( + queryClient: ReturnType, + tabloId: string +) => { queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] }); queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] }); }; @@ -166,7 +166,10 @@ function useClientCreateFile(tabloId: string, accessToken: string | undefined) { fileName: string; data: { content: string; contentType: string }; }) => { - const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, params.data); + const response = await api.post( + `/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, + params.data + ); if (response.status !== 200) { throw new Error("Failed to create file"); } @@ -245,10 +248,13 @@ function useClientUpdateFolder(tabloId: string, accessToken: string | undefined) name: string; description: string; }) => { - const response = await api.put(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, { - name: params.name, - description: params.description, - }); + const response = await api.put( + `/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, + { + name: params.name, + description: params.description, + } + ); if (response.status !== 200) { throw new Error("Failed to update folder"); } @@ -263,12 +269,10 @@ function useClientDeleteFolder(tabloId: string, accessToken: string | undefined) const queryClient = useQueryClient(); return useMutation({ - mutationFn: async (params: { - tabloId: string; - folderId: string; - folderName: string; - }) => { - const response = await api.delete(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`); + mutationFn: async (params: { tabloId: string; folderId: string; folderName: string }) => { + const response = await api.delete( + `/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}` + ); if (response.status !== 200) { throw new Error("Failed to delete folder"); } @@ -290,7 +294,10 @@ type ClientTaskCreateInput = { due_date?: string | null; }; -const invalidateClientTaskQueries = (queryClient: ReturnType, tabloId: string) => { +const invalidateClientTaskQueries = ( + queryClient: ReturnType, + tabloId: string +) => { queryClient.invalidateQueries({ queryKey: ["client-tasks", tabloId] }); }; @@ -326,7 +333,11 @@ function useClientUpdateTask(tabloId: string) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: async ({ id, tablo_id: _tabloId, ...updates }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { + mutationFn: async ({ + id, + tablo_id: _tabloId, + ...updates + }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { const { data, error } = await supabase .from("tasks") .update(updates) @@ -446,10 +457,22 @@ export function ClientTabloPage() { const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? ""); const { data: tasks = [] } = useClientTabloTasks(tabloId ?? ""); const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? ""); - const { data: events, isLoading: eventsLoading, error: eventsError } = useClientTabloEvents(tabloId ?? ""); + const { + data: events, + isLoading: eventsLoading, + error: eventsError, + } = useClientTabloEvents(tabloId ?? ""); const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); - const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); - const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + const { + data: filesData, + isLoading: filesLoading, + error: filesError, + } = useClientTabloFiles(tabloId ?? "", accessToken); + const { + data: folders = [], + isLoading: foldersLoading, + error: foldersError, + } = useClientTabloFolders(tabloId ?? "", accessToken); const { mutate: createTask } = useClientCreateTask(tabloId ?? ""); const { mutate: updateTask } = useClientUpdateTask(tabloId ?? ""); const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? ""); @@ -494,202 +517,200 @@ export function ClientTabloPage() { onTabChange={setActiveTab} discussionAction={{ kind: "button", onClick: () => setActiveTab("discussion") }} > - {activeTab === "overview" && ( -
-
-
-

- Description du projet -

-

- Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les - onglets ci-dessus pour naviguer entre les différentes sections. -

-
- -
-
-

- Mes tâches -

-
-
- {tasks.length === 0 ? ( -
- Aucune tâche -
- ) : ( - tasks.slice(0, 5).map((task) => ( - - )) - )} -
-
+ {activeTab === "overview" && ( +
+
+
+

+ Description du projet +

+

+ Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets + ci-dessus pour naviguer entre les différentes sections. +

-
-
-
-

Fichiers

-
-
- {fileNames.length === 0 ? ( -

Aucun fichier

- ) : ( - fileNames.slice(0, 5).map((fileName) => ( -
-
- -
-
-

{fileName}

-
-
- )) - )} -
+
+
+

+ Mes tâches +

- -
-

Informations

-
-
-
Tâches
-
{tasks.length}
-
-
-
Fichiers
-
{fileNames.length}
-
-
-
Statut
-
- {statusLabel} -
-
-
-
Rôle
-
Invité
-
-
+
+ {tasks.length === 0 ? ( +
Aucune tâche
+ ) : ( + tasks.slice(0, 5).map((task) => ( + + )) + )}
- )} - {activeTab === "etapes" && ( - createTask(task)} - onCreateEtape={async () => {}} - onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} - /> - )} +
+
+
+

Fichiers

+
+
+ {fileNames.length === 0 ? ( +

Aucun fichier

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+
+ +
+
+

{fileName}

+
+
+ )) + )} +
+
- {activeTab === "tasks" && ( - createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onDeleteTask={(taskId) => deleteTask(taskId)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - /> - )} +
+

Informations

+
+
+
Tâches
+
{tasks.length}
+
+
+
Fichiers
+
{fileNames.length}
+
+
+
Statut
+
+ {statusLabel} +
+
+
+
Rôle
+
Invité
+
+
+
+
+
+ )} - {activeTab === "files" && ( - createFile(params)} - onDownloadFile={(params) => downloadFile(params)} - onCreateFolder={(params) => createFolder(params)} - onUpdateFolder={(params) => updateFolder(params)} - onDeleteFolder={(params) => deleteFolder(params)} - /> - )} + {activeTab === "etapes" && ( + createTask(task)} + onCreateEtape={async () => undefined} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} + /> + )} - {activeTab === "discussion" && ( - - )} + {activeTab === "tasks" && ( + createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + /> + )} - {activeTab === "events" && ( - [0]["events"]} - isLoading={eventsLoading} - error={eventsError instanceof Error ? eventsError : null} - currentUser={currentUser} - members={members} - /> - )} + {activeTab === "files" && ( + createFile(params)} + onDownloadFile={(params) => downloadFile(params)} + onCreateFolder={(params) => createFolder(params)} + onUpdateFolder={(params) => updateFolder(params)} + onDeleteFolder={(params) => deleteFolder(params)} + /> + )} - {activeTab === "roadmap" && ( - {}} - onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} - /> - )} + {activeTab === "discussion" && ( + + )} + + {activeTab === "events" && ( + [0]["events"]} + isLoading={eventsLoading} + error={eventsError instanceof Error ? eventsError : null} + currentUser={currentUser} + members={members} + /> + )} + + {activeTab === "roadmap" && ( + undefined} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} + /> + )} ); } diff --git a/apps/clients/src/pages/ResetPasswordPage.tsx b/apps/clients/src/pages/ResetPasswordPage.tsx index 85d591e..15031cd 100644 --- a/apps/clients/src/pages/ResetPasswordPage.tsx +++ b/apps/clients/src/pages/ResetPasswordPage.tsx @@ -34,7 +34,10 @@ export function ResetPasswordPage() { }; return ( - +
{error ? : null} {isSubmitted ? ( diff --git a/apps/clients/src/pages/SetPasswordPage.test.tsx b/apps/clients/src/pages/SetPasswordPage.test.tsx index 1cce2ee..250d2c6 100644 --- a/apps/clients/src/pages/SetPasswordPage.test.tsx +++ b/apps/clients/src/pages/SetPasswordPage.test.tsx @@ -58,9 +58,12 @@ describe("SetPasswordPage", () => { }) ) .mockResolvedValueOnce( - new Response(JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), { - status: 200, - }) + new Response( + JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), + { + status: 200, + } + ) ); renderWithProviders(, { diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 23c7532..00791b7 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -8,9 +8,15 @@ afterEach(() => { }); global.ResizeObserver = class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} + observe() { + return undefined; + } + unobserve() { + return undefined; + } + disconnect() { + return undefined; + } }; Element.prototype.scrollIntoView = vi.fn(); diff --git a/apps/clients/src/test/testHelpers.test.tsx b/apps/clients/src/test/testHelpers.test.tsx index 435c9bc..b221b34 100644 --- a/apps/clients/src/test/testHelpers.test.tsx +++ b/apps/clients/src/test/testHelpers.test.tsx @@ -1,5 +1,5 @@ -import { describe, expect, it } from "vitest"; import { screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; import { renderWithProviders } from "./testHelpers"; describe("client test harness", () => { diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index ac7b2ab..51ae585 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -1,5 +1,5 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { render, type RenderResult } from "@testing-library/react"; +import { type RenderResult, render } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; @@ -31,9 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") - ? options.testUser - : defaultUser; + const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 7b36df3..8fbd39f 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -5,7 +5,11 @@ import { defineConfig, type PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig(({ mode }) => { - const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths({ ignoreConfigErrors: true })]; + const plugins: PluginOption[] = [ + react(), + tailwindcss(), + tsconfigPaths({ ignoreConfigErrors: true }), + ]; if (mode !== "test" && process.env.VITEST !== "true") { plugins.push(cloudflare({ inspectorPort: 9232 })); diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index 3a1de85..b07a8c1 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -1,8 +1,8 @@ import { screen, waitFor } from "@testing-library/react"; -import { vi } from "vitest"; import { ProtectedRoute } from "@ui/components/ProtectedRoute"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index 7eebb0e..8c779a7 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -29,6 +29,7 @@ import { useSubscription } from "../hooks/stripe"; const mockUseOrganization = vi.mocked(useOrganization); const mockUseSubscription = vi.mocked(useSubscription); +type SubscriptionData = NonNullable["data"]>; const baseUser: User = { id: "user-1", @@ -147,8 +148,8 @@ describe("SubscriptionCard", () => { status: "active", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 30, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, activeSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, activeSubscription); expect(screen.getByText("Actif")).toBeInTheDocument(); expect(screen.getByText("Gérer l'abonnement")).toBeInTheDocument(); expect(screen.getByText("Annuler")).toBeInTheDocument(); @@ -164,8 +165,8 @@ describe("SubscriptionCard", () => { status: "trialing", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 14, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, trialingSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, trialingSubscription); expect(screen.getByText("Période d'essai")).toBeInTheDocument(); }); @@ -179,8 +180,8 @@ describe("SubscriptionCard", () => { status: "past_due", current_period_end: Math.floor(Date.now() / 1000) - 86400, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, pastDueSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, pastDueSubscription); expect(screen.getByText("Paiement en retard")).toBeInTheDocument(); }); @@ -195,8 +196,8 @@ describe("SubscriptionCard", () => { status: "active", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 15, cancel_at_period_end: true, - }; - renderCard(baseUser, teamOrg, canceledSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, canceledSubscription); expect(screen.getByText(/Abonnement en cours d'annulation/)).toBeInTheDocument(); expect(screen.getByText("Réactiver l'abonnement")).toBeInTheDocument(); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index a6db9de..f198ce3 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -5,20 +5,20 @@ import type { KanbanTask } from "@xtablo/shared-types"; import { DEFAULT_OVERVIEW_LAYOUT, EtapesSection, + getSingleTabloStatusConfig, + moveBetweenZones, + moveWithinZone, type OverviewLayoutV1, RoadmapSection, SingleTabloOverview, + type SingleTabloTabId, SingleTabloView, + sanitizeOverviewLayout, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, TaskModal, - getSingleTabloStatusConfig, - moveBetweenZones, - moveWithinZone, - sanitizeOverviewLayout, - type SingleTabloTabId, useChatUnread, } from "@xtablo/tablo-views"; import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar"; @@ -336,166 +336,166 @@ export const TabloDetailsPage = () => { return ( <> setSearchParams({ section: tabId })} - hasUnreadDiscussion={hasUnreadDiscussion} - discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} - canInviteMembers={isAdmin} - onOpenInviteDialog={() => setIsShareDialogOpen(true)} - > - {activeSection === "overview" && ( - setSearchParams({ section: "tasks" })} - onOpenFiles={() => setSearchParams({ section: "files" })} - onCreateTask={() => openTaskModal(undefined, currentUser.id)} - onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} - showAllTasks={showAllOverviewTasks} - onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} - layout={overviewLayout} - canEditLayout={isAdmin} - isLayoutEditMode={isLayoutEditMode} - draggedBlock={draggedOverviewBlock} - onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} - onResetLayout={handleResetOverviewLayout} - onBlockDragStart={handleOverviewBlockDragStart} - onBlockDragOver={handleOverviewBlockDragOver} - onBlockDrop={handleOverviewBlockDrop} - onBlockDragEnd={() => setDraggedOverviewBlock(null)} - /> - )} + tablo={tablo} + roleLabel={isAdmin ? "Admin" : "Invité"} + statusLabel={statusLabel} + statusBadgeClass={badgeClass} + progress={progress} + activeTab={activeSection} + onTabChange={(tabId) => setSearchParams({ section: tabId })} + hasUnreadDiscussion={hasUnreadDiscussion} + discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} + canInviteMembers={isAdmin} + onOpenInviteDialog={() => setIsShareDialogOpen(true)} + > + {activeSection === "overview" && ( + setSearchParams({ section: "tasks" })} + onOpenFiles={() => setSearchParams({ section: "files" })} + onCreateTask={() => openTaskModal(undefined, currentUser.id)} + onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} + showAllTasks={showAllOverviewTasks} + onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} + layout={overviewLayout} + canEditLayout={isAdmin} + isLayoutEditMode={isLayoutEditMode} + draggedBlock={draggedOverviewBlock} + onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} + onResetLayout={handleResetOverviewLayout} + onBlockDragStart={handleOverviewBlockDragStart} + onBlockDragOver={handleOverviewBlockDragOver} + onBlockDrop={handleOverviewBlockDrop} + onBlockDragEnd={() => setDraggedOverviewBlock(null)} + /> + )} - {activeSection === "tasks" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateTask={(task) => createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onDeleteTask={(taskId) => deleteTask(taskId)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "files" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - isCreatingFolder={isCreatingFolder} - isUpdatingFolder={isUpdatingFolder} - onCreateFile={(params) => uploadFile(params).then(() => undefined)} - onDeleteFile={(params) => deleteFile(params).then(() => undefined)} - onDownloadFile={(params) => downloadFile(params).then(() => undefined)} - onCreateFolder={(params) => createFolder(params).then(() => undefined)} - onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} - onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "discussion" && ( -
- ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "files" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + isCreatingFolder={isCreatingFolder} + isUpdatingFolder={isUpdatingFolder} + onCreateFile={(params) => uploadFile(params).then(() => undefined)} + onDeleteFile={(params) => deleteFile(params).then(() => undefined)} + onDownloadFile={(params) => downloadFile(params).then(() => undefined)} + onCreateFolder={(params) => createFolder(params).then(() => undefined)} + onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} + onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } /> -
- )} - {activeSection === "events" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateEvent={() => undefined} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} + )} + {activeSection === "discussion" && ( +
+ +
+ )} + {activeSection === "events" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateEvent={() => undefined} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} - {activeSection === "etapes" && ( - - createTask({ - ...task, - status: task.status as "todo" | "in_progress" | "in_review" | "done", - }) - } - onCreateEtape={(params) => createEtape(params).then(() => undefined)} - onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} - onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} - isCreatingEtape={isCreatingEtape} - isUpdatingEtape={isUpdatingEtape} - isDeletingEtape={isDeletingEtape} - /> - )} + {activeSection === "etapes" && ( + + createTask({ + ...task, + status: task.status as "todo" | "in_progress" | "in_review" | "done", + }) + } + onCreateEtape={(params) => createEtape(params).then(() => undefined)} + onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} + onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} + isCreatingEtape={isCreatingEtape} + isUpdatingEtape={isUpdatingEtape} + isDeletingEtape={isDeletingEtape} + /> + )} - {activeSection === "roadmap" && ( - updateTask({ id: taskId, status })} - /> - )} + {activeSection === "roadmap" && ( + updateTask({ id: taskId, status })} + /> + )}
{/* Task Create Modal */} @@ -568,8 +568,8 @@ export const TabloDetailsPage = () => {

Accès client

- Le client recevra un email pour définir son mot de passe ou, s'il a déjà - un compte, une notification d'accès directe à ce tablo. + Le client recevra un email pour définir son mot de passe ou, s'il a déjà un + compte, une notification d'accès directe à ce tablo.

@@ -681,7 +681,9 @@ export const TabloDetailsPage = () => { ) : ( <>
-

Inviter un utilisateur

+

+ Inviter un utilisateur +

Utilisez le système d'invitation standard par email pour le moment

diff --git a/apps/main/src/pages/tasks.test.tsx b/apps/main/src/pages/tasks.test.tsx index e421f12..d5f3e5b 100644 --- a/apps/main/src/pages/tasks.test.tsx +++ b/apps/main/src/pages/tasks.test.tsx @@ -1,8 +1,8 @@ import { screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { TasksPage } from "./tasks"; import { renderWithProviders } from "../utils/testHelpers"; +import { TasksPage } from "./tasks"; const mutateUpdateTask = vi.fn(); const mutateDeleteTask = vi.fn(); diff --git a/biome.json b/biome.json index ef80f8d..cc68d4e 100644 --- a/biome.json +++ b/biome.json @@ -13,6 +13,12 @@ "apps/api/*.{ts,tsx,js,jsx,json}", "packages/ui/src/**/*", "packages/ui/*.{ts,tsx,js,jsx,json}", + "packages/tablo-views/src/**/*", + "packages/tablo-views/*.{ts,tsx,js,jsx,json}", + "packages/auth-ui/src/**/*", + "packages/auth-ui/*.{ts,tsx,js,jsx,json}", + "packages/chat-ui/src/**/*", + "packages/chat-ui/*.{ts,tsx,js,jsx,json}", "packages/shared/src/**/*", "packages/shared/*.{ts,tsx,js,jsx,json}", "packages/shared-types/src/**/*", @@ -298,6 +304,12 @@ "apps/api/*.{ts,tsx}", "packages/ui/src/**/*.{ts,tsx}", "packages/ui/*.{ts,tsx}", + "packages/tablo-views/src/**/*.{ts,tsx}", + "packages/tablo-views/*.{ts,tsx}", + "packages/auth-ui/src/**/*.{ts,tsx}", + "packages/auth-ui/*.{ts,tsx}", + "packages/chat-ui/src/**/*.{ts,tsx}", + "packages/chat-ui/*.{ts,tsx}", "packages/shared/src/**/*.{ts,tsx}", "packages/shared/*.{ts,tsx}", "packages/shared-types/src/**/*.{ts,tsx}", diff --git a/packages/auth-ui/src/AuthInfoBanner.tsx b/packages/auth-ui/src/AuthInfoBanner.tsx index a5554d2..c7b7aff 100644 --- a/packages/auth-ui/src/AuthInfoBanner.tsx +++ b/packages/auth-ui/src/AuthInfoBanner.tsx @@ -7,7 +7,8 @@ type AuthInfoBannerProps = { }; const variantStyles: Record = { - error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", + error: + "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800", success: "bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800", diff --git a/packages/chat-ui/src/chat-ui.css b/packages/chat-ui/src/chat-ui.css index 0398317..eff81d9 100644 --- a/packages/chat-ui/src/chat-ui.css +++ b/packages/chat-ui/src/chat-ui.css @@ -2,45 +2,82 @@ /* ─── Message entry ─────────────────────────────────────────────── */ @keyframes chat-message-enter { - from { opacity: 0; transform: translateY(8px); } - to { opacity: 1; transform: translateY(0); } + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: translateY(0); + } } /* ─── Toolbar entrance ──────────────────────────────────────────── */ @keyframes chat-toolbar-enter { - from { opacity: 0; transform: scale(0.95) translateY(4px); } - to { opacity: 1; transform: scale(1) translateY(0); } + from { + opacity: 0; + transform: scale(0.95) translateY(4px); + } + to { + opacity: 1; + transform: scale(1) translateY(0); + } } /* ─── Reaction pop ──────────────────────────────────────────────── */ @keyframes chat-reaction-pop { - 0% { transform: scale(0); opacity: 0; } - 70% { transform: scale(1.1); } - 100% { transform: scale(1); opacity: 1; } + 0% { + transform: scale(0); + opacity: 0; + } + 70% { + transform: scale(1.1); + } + 100% { + transform: scale(1); + opacity: 1; + } } /* ─── Typing indicator dots ─────────────────────────────────────── */ @keyframes chat-typing-pulse { - 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } - 30% { opacity: 1; transform: translateY(-4px); } + 0%, + 60%, + 100% { + opacity: 0.3; + transform: translateY(0); + } + 30% { + opacity: 1; + transform: translateY(-4px); + } } /* ─── Cursor blink (streaming) ──────────────────────────────────── */ @keyframes chat-cursor-blink { - 0%, 100% { opacity: 1; } - 50% { opacity: 0; } + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0; + } } /* ─── Read receipt status color transition ───────────────────────── */ @keyframes chat-status-read-in { - from { color: var(--color-muted-foreground); } - to { color: var(--color-primary); } + from { + color: var(--color-muted-foreground); + } + to { + color: var(--color-primary); + } } /* ─── Utility classes ───────────────────────────────────────────── */ @layer base { .chat-message { - animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1.0); + animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1); } .chat-typing-dot { @@ -56,7 +93,7 @@ } .chat-reaction-pop { - animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1.0); + animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1); } .chat-status-read { diff --git a/packages/chat-ui/src/components/chat.tsx b/packages/chat-ui/src/components/chat.tsx index a4e8549..4b58a8a 100644 --- a/packages/chat-ui/src/components/chat.tsx +++ b/packages/chat-ui/src/components/chat.tsx @@ -1,72 +1,71 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { + AlertCircle, + ArrowUp, Check, CheckCheck, - ArrowUp, ChevronDown, Clock, - AlertCircle, + Mic, + MoreHorizontal, + Paperclip, + Pause, + Pencil, + Pin, + // Plus, + Play, Reply, SmilePlus, - MoreHorizontal, - Pin, - Pencil, Trash2, - X, - Paperclip, // Image as ImageIcon, // Smile, Upload, - // Plus, - Play, - Pause, - Mic, -} from "lucide-react" -import { createPortal } from "react-dom" + X, +} from "lucide-react"; +import * as React from "react"; +import { createPortal } from "react-dom"; +import { + formatTimestamp, + groupMessages, + useAutoResize, + useAutoScroll, + useTypingIndicator, +} from "../hooks"; import type { - ChatUser, ChatConfig, ChatLabels, ChatMessageData, + ChatUser, MessageGroup, TypingUser, -} from "../types" -import { - groupMessages, - useAutoScroll, - useAutoResize, - useTypingIndicator, - formatTimestamp, -} from "../hooks" +} from "../types"; // ─── Context ────────────────────────────────────────────────────────────────── -const ChatContext = React.createContext(null) +const ChatContext = React.createContext(null); function useChatContext() { - const ctx = React.useContext(ChatContext) - if (!ctx) - throw new Error("Chat components must be wrapped in ") - return ctx + const ctx = React.useContext(ChatContext); + if (!ctx) throw new Error("Chat components must be wrapped in "); + return ctx; } // ─── ChatProvider ───────────────────────────────────────────────────────────── interface ChatProviderProps { - currentUser: ChatUser - dateFormat?: "relative" | "absolute" | "time-only" - messageGroupingInterval?: number - labels?: ChatLabels - onReactionAdd?: (messageId: string, emoji: string) => void - onReactionRemove?: (messageId: string, emoji: string) => void - onReply?: (message: ChatMessageData) => void - onEdit?: (message: ChatMessageData) => void - onDelete?: (messageId: string) => void - onPin?: (messageId: string) => void - children: React.ReactNode - style?: React.CSSProperties - className?: string + currentUser: ChatUser; + dateFormat?: "relative" | "absolute" | "time-only"; + messageGroupingInterval?: number; + labels?: ChatLabels; + onReactionAdd?: (messageId: string, emoji: string) => void; + onReactionRemove?: (messageId: string, emoji: string) => void; + onReply?: (message: ChatMessageData) => void; + onEdit?: (message: ChatMessageData) => void; + onDelete?: (messageId: string) => void; + onPin?: (messageId: string) => void; + children: React.ReactNode; + style?: React.CSSProperties; + className?: string; } function ChatProvider({ @@ -97,8 +96,19 @@ function ChatProvider({ onDelete, onPin, }), - [currentUser, dateFormat, messageGroupingInterval, labels, onReactionAdd, onReactionRemove, onReply, onEdit, onDelete, onPin] - ) + [ + currentUser, + dateFormat, + messageGroupingInterval, + labels, + onReactionAdd, + onReactionRemove, + onReply, + onEdit, + onDelete, + onPin, + ] + ); return ( @@ -106,19 +116,26 @@ function ChatProvider({ {children}
- ) + ); } // ─── Quick emoji picker (6 common reactions) ────────────────────────────────── -const QUICK_REACTIONS = ["\u{1F44D}", "\u{2764}\u{FE0F}", "\u{1F602}", "\u{1F62E}", "\u{1F64F}", "\u{1F525}"] +const QUICK_REACTIONS = [ + "\u{1F44D}", + "\u{2764}\u{FE0F}", + "\u{1F602}", + "\u{1F62E}", + "\u{1F64F}", + "\u{1F525}", +]; function QuickReactionPicker({ onSelect, onClose, }: { - onSelect: (emoji: string) => void - onClose: () => void + onSelect: (emoji: string) => void; + onClose: () => void; }) { return (
{ - onSelect(emoji) - onClose() + onSelect(emoji); + onClose(); }} className="flex size-8 items-center justify-center rounded-lg text-lg transition-transform hover:scale-125 hover:bg-accent" aria-label={`React with ${emoji}`} @@ -139,20 +156,20 @@ function QuickReactionPicker({ ))}
- ) + ); } // ─── ChatMessageActions (hover toolbar) ─────────────────────────────────────── interface ChatMessageActionsProps { - message: ChatMessageData - isOutgoing: boolean + message: ChatMessageData; + isOutgoing: boolean; } function ChatMessageActions({ message, isOutgoing }: ChatMessageActionsProps) { - const { onReply, onReactionAdd, onEdit, onDelete, onPin } = useChatContext() - const [showReactions, setShowReactions] = React.useState(false) - const [showMore, setShowMore] = React.useState(false) + const { onReply, onReactionAdd, onEdit, onDelete, onPin } = useChatContext(); + const [showReactions, setShowReactions] = React.useState(false); + const [showMore, setShowMore] = React.useState(false); return (
- onReactionAdd?.(message.id, emoji) - } + onSelect={(emoji) => onReactionAdd?.(message.id, emoji)} onClose={() => setShowReactions(false)} />
@@ -211,8 +226,8 @@ function ChatMessageActions({ message, isOutgoing }: ChatMessageActionsProps) { {isOutgoing && (
- ) + ); } // ─── ChatMessageReply (quoted reply inside bubble) ──────────────────────────── @@ -255,8 +270,8 @@ function ChatMessageReply({ replyTo, isOutgoing, }: { - replyTo: NonNullable - isOutgoing: boolean + replyTo: NonNullable; + isOutgoing: boolean; }) { // Outgoing bubbles set text color via --chat-bubble-outgoing-text which may // be white (Lunar, Midnight) or dark (Aurora, Ember). Using `text-inherit` @@ -290,63 +305,70 @@ function ChatMessageReply({
- ) + ); } // ─── ChatMessage ────────────────────────────────────────────────────────────── interface ChatMessageProps { - message: ChatMessageData - isOutgoing: boolean - position: "solo" | "first" | "middle" | "last" - showSender?: boolean - showAvatar?: boolean - className?: string + message: ChatMessageData; + isOutgoing: boolean; + position: "solo" | "first" | "middle" | "last"; + showSender?: boolean; + showAvatar?: boolean; + className?: string; } // ─── Voice Message ───────────────────────────────────────────────────────── -function ChatVoiceMessage({ voice, isOutgoing }: { voice: NonNullable; isOutgoing: boolean }) { - const [playing, setPlaying] = React.useState(false) - const [progress, setProgress] = React.useState(0) - const progressRef = React.useRef(0) +function ChatVoiceMessage({ + voice, + isOutgoing, +}: { + voice: NonNullable; + isOutgoing: boolean; +}) { + const [playing, setPlaying] = React.useState(false); + const [progress, setProgress] = React.useState(0); + const progressRef = React.useRef(0); React.useEffect(() => { - progressRef.current = progress - }, [progress]) + progressRef.current = progress; + }, [progress]); - const totalMins = Math.floor(voice.duration / 60) - const totalSecs = Math.floor(voice.duration % 60) - const elapsed = progress * voice.duration - const elapsedMins = Math.floor(elapsed / 60) - const elapsedSecs = Math.floor(elapsed % 60) - const timeLabel = playing || progress > 0 - ? `${elapsedMins}:${elapsedSecs.toString().padStart(2, "0")}` - : `${totalMins}:${totalSecs.toString().padStart(2, "0")}` + const totalMins = Math.floor(voice.duration / 60); + const totalSecs = Math.floor(voice.duration % 60); + const elapsed = progress * voice.duration; + const elapsedMins = Math.floor(elapsed / 60); + const elapsedSecs = Math.floor(elapsed % 60); + const timeLabel = + playing || progress > 0 + ? `${elapsedMins}:${elapsedSecs.toString().padStart(2, "0")}` + : `${totalMins}:${totalSecs.toString().padStart(2, "0")}`; - const progressIndex = Math.floor(progress * voice.waveform.length) + const progressIndex = Math.floor(progress * voice.waveform.length); React.useEffect(() => { - if (!playing) return - const fps = 20 - const step = 1 / (voice.duration * fps) + if (!playing) return; + const fps = 20; + const step = 1 / (voice.duration * fps); const id = setInterval(() => { - const next = progressRef.current + step + const next = progressRef.current + step; if (next >= 1) { - setProgress(0) - setPlaying(false) - clearInterval(id) + setProgress(0); + setPlaying(false); + clearInterval(id); } else { - setProgress(next) + setProgress(next); } - }, 1000 / fps) - return () => clearInterval(id) - }, [playing, voice.duration]) + }, 1000 / fps); + return () => clearInterval(id); + }, [playing, voice.duration]); const toggle = () => { - if (!playing && progress === 0) setProgress(0) - setPlaying((p) => !p) - } + if (!playing && progress === 0) setProgress(0); + setPlaying((p) => !p); + }; return (
@@ -364,7 +386,7 @@ function ChatVoiceMessage({ voice, isOutgoing }: { voice: NonNullable
{voice.waveform.map((v, i) => { - const played = i < progressIndex + const played = i < progressIndex; return (
- ) + ); })}
{timeLabel}
- ) + ); } function ChatMessage({ @@ -392,10 +414,10 @@ function ChatMessage({ showAvatar = false, className, }: ChatMessageProps) { - const timestamp = new Date(message.timestamp) - const { currentUser } = useChatContext() - const radiusClass = getBubbleRadius(isOutgoing, position) - const [lightboxImage, setLightboxImage] = React.useState(null) + const timestamp = new Date(message.timestamp); + const { currentUser } = useChatContext(); + const radiusClass = getBubbleRadius(isOutgoing, position); + const [lightboxImage, setLightboxImage] = React.useState(null); return (
{/* Quoted reply */} {message.replyTo && ( - + )} {/* Text content */} @@ -463,7 +480,12 @@ function ChatMessage({ {/* Images */} {message.images && message.images.length > 0 && ( -
+
{message.images.map((img, idx) => (
-

{file.name}

-

{file.size < 1024 ? `${file.size} B` : file.size < 1048576 ? `${(file.size / 1024).toFixed(0)} KB` : `${(file.size / 1048576).toFixed(1)} MB`}

+

+ {file.name} +

+

+ {file.size < 1024 + ? `${file.size} B` + : file.size < 1048576 + ? `${(file.size / 1024).toFixed(0)} KB` + : `${(file.size / 1048576).toFixed(1)} MB`} +

))} @@ -524,20 +556,27 @@ function ChatMessage({ className="chat-content-card mt-1.5 block hover:opacity-90 transition-opacity" > {message.linkPreview.image && ( - + )}
-

{message.linkPreview.title}

-

{message.linkPreview.description}

+

+ {message.linkPreview.title} +

+

+ {message.linkPreview.description} +

{message.linkPreview.url}

)} {/* Voice message */} - {message.voice && ( - - )} + {message.voice && } {/* Inline timestamp + status + edited label */}
- {message.isEdited && ( - edited - )} + {message.isEdited && edited} - {isOutgoing && message.status && ( - - )} + {isOutgoing && message.status && }
@@ -578,37 +613,36 @@ function ChatMessage({ {/* Read receipts (group chat) — small stacked avatars */} {message.readBy && message.readBy.length > 0 && ( - + )}
{/* Image lightbox */} - {lightboxImage && typeof document !== "undefined" && createPortal( -
setLightboxImage(null)} - > - - e.stopPropagation()} - /> -
, - document.body - )} + + e.stopPropagation()} + /> +
, + document.body + )}
- ) + ); } // ─── Bubble radius helper ───────────────────────────────────────────────────── @@ -620,50 +654,42 @@ function getBubbleRadius( if (isOutgoing) { switch (position) { case "solo": - return "rounded-[18px_18px_4px_18px]" + return "rounded-[18px_18px_4px_18px]"; case "first": - return "rounded-[18px_18px_4px_18px]" + return "rounded-[18px_18px_4px_18px]"; case "middle": - return "rounded-[18px_4px_4px_18px]" + return "rounded-[18px_4px_4px_18px]"; case "last": - return "rounded-[18px_4px_18px_18px]" + return "rounded-[18px_4px_18px_18px]"; } } else { switch (position) { case "solo": - return "rounded-[18px_18px_18px_4px]" + return "rounded-[18px_18px_18px_4px]"; case "first": - return "rounded-[18px_18px_18px_4px]" + return "rounded-[18px_18px_18px_4px]"; case "middle": - return "rounded-[4px_18px_18px_4px]" + return "rounded-[4px_18px_18px_4px]"; case "last": - return "rounded-[4px_18px_18px_18px]" + return "rounded-[4px_18px_18px_18px]"; } } } // ─── ChatMessageStatus ──────────────────────────────────────────────────────── -function ChatMessageStatus({ - status, -}: { - status: NonNullable -}) { +function ChatMessageStatus({ status }: { status: NonNullable }) { switch (status) { case "sending": - return + return ; case "sent": - return + return ; case "delivered": - return + return ; case "read": - return ( - - ) + return ; case "failed": - return ( - - ) + return ; } } @@ -675,37 +701,30 @@ function ChatMessageReactions({ isOutgoing, currentUserId, }: { - messageId: string - reactions: NonNullable - isOutgoing: boolean - currentUserId: string + messageId: string; + reactions: NonNullable; + isOutgoing: boolean; + currentUserId: string; }) { - const { onReactionAdd, onReactionRemove } = useChatContext() + const { onReactionAdd, onReactionRemove } = useChatContext(); return ( -
+
{reactions.map((r) => { - const hasReacted = r.userIds.includes(currentUserId) + const hasReacted = r.userIds.includes(currentUserId); return ( - ) + ); })} {/* Add reaction button — visible on hover */}
- ) + ); } // ─── ChatReadReceipts (group chat — stacked mini avatars) ───────────────────── @@ -744,20 +761,15 @@ function ChatReadReceipts({ readBy, isOutgoing, }: { - readBy: NonNullable - isOutgoing: boolean + readBy: NonNullable; + isOutgoing: boolean; }) { - const maxVisible = 3 - const visible = readBy.slice(0, maxVisible) - const overflow = readBy.length - maxVisible + const maxVisible = 3; + const visible = readBy.slice(0, maxVisible); + const overflow = readBy.length - maxVisible; return ( -
+
{visible.map((user) => (
{overflow > 0 && ( - - +{overflow} - + +{overflow} )}
- ) + ); } // ─── ChatMessageGroup ───────────────────────────────────────────────────────── interface ChatMessageGroupProps { - group: MessageGroup - className?: string + group: MessageGroup; + className?: string; } function ChatMessageGroup({ group, className }: ChatMessageGroupProps) { - const len = group.messages.length + const len = group.messages.length; return (
{group.messages.map((msg, i) => { const position: "solo" | "first" | "middle" | "last" = - len === 1 - ? "solo" - : i === 0 - ? "first" - : i === len - 1 - ? "last" - : "middle" + len === 1 ? "solo" : i === 0 ? "first" : i === len - 1 ? "last" : "middle"; return ( - ) + ); })}
- ) + ); } // ─── ChatDateSeparator ──────────────────────────────────────────────────────── interface ChatDateSeparatorProps { - label: string - className?: string + label: string; + className?: string; } function ChatDateSeparator({ label, className }: ChatDateSeparatorProps) { return ( -
+
{label}
- ) + ); } // ─── ChatSystemMessage ──────────────────────────────────────────────────────── interface ChatSystemMessageProps { - message: ChatMessageData - className?: string + message: ChatMessageData; + className?: string; } function ChatSystemMessage({ message, className }: ChatSystemMessageProps) { return ( -
+
{message.text || message.systemEvent}
- ) + ); } // ─── ChatTypingIndicator ────────────────────────────────────────────────────── interface ChatTypingIndicatorProps { - users: TypingUser[] - className?: string + users: TypingUser[]; + className?: string; } function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) { - const { labels } = useChatContext() - if (users.length === 0) return null + const { labels } = useChatContext(); + if (users.length === 0) return null; const label = users.length === 1 ? (labels?.typingOne?.replace("{{name}}", users[0]!.name) ?? `${users[0]!.name} is typing`) : users.length === 2 - ? (labels?.typingTwo?.replace("{{name1}}", users[0]!.name).replace("{{name2}}", users[1]!.name) ?? `${users[0]!.name} and ${users[1]!.name} are typing`) - : (labels?.typingMany ?? "Several people are typing") + ? (labels?.typingTwo + ?.replace("{{name1}}", users[0]!.name) + .replace("{{name2}}", users[1]!.name) ?? + `${users[0]!.name} and ${users[1]!.name} are typing`) + : (labels?.typingMany ?? "Several people are typing"); return ( -
+
{/* Avatar */}
{users[0]!.avatar ? ( @@ -915,9 +907,7 @@ function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) {
{/* Label */} - - {label} - + {label} {/* Dots bubble */}
@@ -936,37 +926,28 @@ function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) {
- ) + ); } // ─── ChatReplyPreview (bar above composer) ──────────────────────────────────── interface ChatReplyPreviewProps { - replyingTo: ChatMessageData - onCancel: () => void - className?: string + replyingTo: ChatMessageData; + onCancel: () => void; + className?: string; } -function ChatReplyPreview({ - replyingTo, - onCancel, - className, -}: ChatReplyPreviewProps) { +function ChatReplyPreview({ replyingTo, onCancel, className }: ChatReplyPreviewProps) { return (
{replyingTo.senderName} - - {replyingTo.text} - + {replyingTo.text}
- ) + ); } // ─── ChatMessages (scroll container) ────────────────────────────────────────── interface ChatMessagesProps { - messages: ChatMessageData[] - typingUsers?: TypingUser[] - className?: string - onLoadMore?: () => Promise - hasMore?: boolean + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + className?: string; + onLoadMore?: () => Promise; + hasMore?: boolean; } -function ChatMessages({ - messages, - typingUsers = [], - className, -}: ChatMessagesProps) { - const { currentUser, messageGroupingInterval, labels } = useChatContext() - const { containerRef, scrollToBottom, isAtBottom, unseenCount } = - useAutoScroll(messages) +function ChatMessages({ messages, typingUsers = [], className }: ChatMessagesProps) { + const { currentUser, messageGroupingInterval, labels } = useChatContext(); + const { containerRef, scrollToBottom, isAtBottom, unseenCount } = useAutoScroll(messages); const items = React.useMemo( () => groupMessages(messages, currentUser.id, messageGroupingInterval), [messages, currentUser.id, messageGroupingInterval] - ) + ); return ( -
+
{/* Scrollable area */}
{ switch (item.type) { case "date": - return ( - - ) + return ; case "system": - return ( - - ) + return ; case "group": return ( - ) + ); } })} {/* Typing indicator at the bottom */} - {typingUsers.length > 0 && ( - - )} + {typingUsers.length > 0 && }
@@ -1056,12 +1015,9 @@ function ChatMessages({ onClick={() => scrollToBottom("smooth")} className={cn( "absolute bottom-4 right-4 z-5 flex size-10 items-center justify-center rounded-full border border-border bg-background shadow-md transition-all duration-200", - isAtBottom - ? "pointer-events-none translate-y-2 opacity-0" - : "translate-y-0 opacity-100" + isAtBottom ? "pointer-events-none translate-y-2 opacity-0" : "translate-y-0 opacity-100" )} - aria-label={labels?.scrollToBottom ?? "Scroll to bottom" - } + aria-label={labels?.scrollToBottom ?? "Scroll to bottom"} > {/* Unread badge */} @@ -1072,26 +1028,20 @@ function ChatMessages({ )}
- ) + ); } // ─── File preview item ──────────────────────────────────────────────────────── interface FilePreviewItem { - file: File - id: string - preview?: string // data URL for images - progress?: number // 0-100 + file: File; + id: string; + preview?: string; // data URL for images + progress?: number; // 0-100 } -function ChatFilePreview({ - item, - onRemove, -}: { - item: FilePreviewItem - onRemove: () => void -}) { - const isImage = item.file.type.startsWith("image/") +function ChatFilePreview({ item, onRemove }: { item: FilePreviewItem; onRemove: () => void }) { + const isImage = item.file.type.startsWith("image/"); return (
@@ -1105,15 +1055,22 @@ function ChatFilePreview({
-

{item.file.name}

-

{(item.file.size / 1024).toFixed(0)} KB

+

+ {item.file.name} +

+

+ {(item.file.size / 1024).toFixed(0)} KB +

)} {/* Progress bar */} {item.progress !== undefined && item.progress < 100 && (
-
+
)} {/* Remove button */} @@ -1125,21 +1082,21 @@ function ChatFilePreview({
- ) + ); } // ─── ChatComposer ───────────────────────────────────────────────────────────── interface ChatComposerProps { - onSend?: (text: string) => void - onTyping?: (isTyping: boolean) => void - onFileUpload?: (files: File[]) => void - onVoiceRecord?: () => void - placeholder?: string - disabled?: boolean - replyingTo?: ChatMessageData | null - onCancelReply?: () => void - className?: string + onSend?: (text: string) => void; + onTyping?: (isTyping: boolean) => void; + onFileUpload?: (files: File[]) => void; + onVoiceRecord?: () => void; + placeholder?: string; + disabled?: boolean; + replyingTo?: ChatMessageData | null; + onCancelReply?: () => void; + className?: string; } function ChatComposer({ @@ -1153,103 +1110,112 @@ function ChatComposer({ onCancelReply, className, }: ChatComposerProps) { - const [value, setValue] = React.useState("") - const [files, setFiles] = React.useState([]) - const [isDragging, setIsDragging] = React.useState(false) + const [value, setValue] = React.useState(""); + const [files, setFiles] = React.useState([]); + const [isDragging, setIsDragging] = React.useState(false); // const [showAttachMenu, setShowAttachMenu] = React.useState(false) - const { textareaRef, resize } = useAutoResize({ maxRows: 6 }) - const { handleKeyDown: handleTypingKeyDown, stopTyping } = - useTypingIndicator({ onTypingChange: onTyping }) + const { textareaRef, resize } = useAutoResize({ maxRows: 6 }); + const { handleKeyDown: handleTypingKeyDown, stopTyping } = useTypingIndicator({ + onTypingChange: onTyping, + }); // const fileInputRef = React.useRef(null) // const imageInputRef = React.useRef(null) - const hasContent = value.trim().length > 0 || files.length > 0 + const hasContent = value.trim().length > 0 || files.length > 0; - const addFiles = React.useCallback((newFiles: FileList | File[]) => { - const arr = Array.from(newFiles) - const items: FilePreviewItem[] = arr.map((f) => ({ - file: f, - id: `${f.name}-${Date.now()}-${Math.random()}`, - progress: undefined, - })) + const addFiles = React.useCallback( + (newFiles: FileList | File[]) => { + const arr = Array.from(newFiles); + const items: FilePreviewItem[] = arr.map((f) => ({ + file: f, + id: `${f.name}-${Date.now()}-${Math.random()}`, + progress: undefined, + })); - // Generate image previews - items.forEach((item) => { - if (item.file.type.startsWith("image/")) { - const reader = new FileReader() - reader.onload = (e) => { - setFiles((prev) => - prev.map((f) => f.id === item.id ? { ...f, preview: e.target?.result as string } : f) - ) + // Generate image previews + items.forEach((item) => { + if (item.file.type.startsWith("image/")) { + const reader = new FileReader(); + reader.onload = (e) => { + setFiles((prev) => + prev.map((f) => + f.id === item.id ? { ...f, preview: e.target?.result as string } : f + ) + ); + }; + reader.readAsDataURL(item.file); } - reader.readAsDataURL(item.file) - } - }) + }); - setFiles((prev) => [...prev, ...items]) - onFileUpload?.(arr) - }, [onFileUpload]) + setFiles((prev) => [...prev, ...items]); + onFileUpload?.(arr); + }, + [onFileUpload] + ); const removeFile = React.useCallback((id: string) => { - setFiles((prev) => prev.filter((f) => f.id !== id)) - }, []) + setFiles((prev) => prev.filter((f) => f.id !== id)); + }, []); const handleSend = React.useCallback(() => { - const trimmed = value.trim() - if ((!trimmed && files.length === 0) || disabled) return - if (trimmed) onSend?.(trimmed) - setValue("") - setFiles([]) - stopTyping() - if (textareaRef.current) textareaRef.current.style.height = "auto" - }, [value, files, disabled, onSend, textareaRef, stopTyping]) + const trimmed = value.trim(); + if ((!trimmed && files.length === 0) || disabled) return; + if (trimmed) onSend?.(trimmed); + setValue(""); + setFiles([]); + stopTyping(); + if (textareaRef.current) textareaRef.current.style.height = "auto"; + }, [value, files, disabled, onSend, textareaRef, stopTyping]); const handleKeyDown = React.useCallback( (e: React.KeyboardEvent) => { - handleTypingKeyDown() - if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend() } - if (e.key === "Escape" && replyingTo) onCancelReply?.() + handleTypingKeyDown(); + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + handleSend(); + } + if (e.key === "Escape" && replyingTo) onCancelReply?.(); }, [handleSend, handleTypingKeyDown, replyingTo, onCancelReply] - ) + ); // Paste upload const handlePaste = React.useCallback( (e: React.ClipboardEvent) => { - const items = e.clipboardData?.items - if (!items) return - const imageFiles: File[] = [] + const items = e.clipboardData?.items; + if (!items) return; + const imageFiles: File[] = []; for (const item of Array.from(items)) { if (item.type.startsWith("image/")) { - const file = item.getAsFile() - if (file) imageFiles.push(file) + const file = item.getAsFile(); + if (file) imageFiles.push(file); } } if (imageFiles.length > 0) { - addFiles(imageFiles) + addFiles(imageFiles); } }, [addFiles] - ) + ); // Drag-and-drop handlers (on the composer container) const handleDragOver = React.useCallback((e: React.DragEvent) => { - e.preventDefault() - setIsDragging(true) - }, []) + e.preventDefault(); + setIsDragging(true); + }, []); const handleDragLeave = React.useCallback((e: React.DragEvent) => { - e.preventDefault() - setIsDragging(false) - }, []) + e.preventDefault(); + setIsDragging(false); + }, []); const handleDrop = React.useCallback( (e: React.DragEvent) => { - e.preventDefault() - setIsDragging(false) + e.preventDefault(); + setIsDragging(false); if (e.dataTransfer.files.length > 0) { - addFiles(e.dataTransfer.files) + addFiles(e.dataTransfer.files); } }, [addFiles] - ) + ); return (
{ setValue(e.target.value); resize() }} + onChange={(e) => { + setValue(e.target.value); + resize(); + }} onKeyDown={handleKeyDown} onPaste={handlePaste} placeholder={placeholder} @@ -1374,7 +1343,7 @@ function ChatComposer({
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── @@ -1394,7 +1363,7 @@ export { ChatTypingIndicator, ChatReplyPreview, ChatReadReceipts, -} +}; export type { ChatProviderProps, ChatMessageProps, @@ -1406,4 +1375,4 @@ export type { ChatMessageActionsProps, ChatTypingIndicatorProps, ChatReplyPreviewProps, -} +}; diff --git a/packages/chat-ui/src/components/features.tsx b/packages/chat-ui/src/components/features.tsx index b3589db..c058aed 100644 --- a/packages/chat-ui/src/components/features.tsx +++ b/packages/chat-ui/src/components/features.tsx @@ -1,33 +1,33 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { - X, - Search, - Pin, + ArrowDown, + ArrowUp, + Check, ChevronDown, ChevronRight, - ArrowUp, - ArrowDown, + Pin, + Search, Trash2, - Check, -} from "lucide-react" -import type { ChatMessageData } from "../types" -import { formatTimestamp } from "../hooks" + X, +} from "lucide-react"; +import * as React from "react"; +import { formatTimestamp } from "../hooks"; +import type { ChatMessageData } from "../types"; // ─── ChatForwardDialog ──────────────────────────────────────────────────────── interface Conversation { - id: string - title: string - avatar?: string + id: string; + title: string; + avatar?: string; } interface ChatForwardDialogProps { - message: ChatMessageData - conversations: Conversation[] - onForward: (targetIds: string[]) => void - onCancel: () => void - className?: string + message: ChatMessageData; + conversations: Conversation[]; + onForward: (targetIds: string[]) => void; + onCancel: () => void; + className?: string; } function ChatForwardDialog({ @@ -37,24 +37,24 @@ function ChatForwardDialog({ onCancel, className, }: ChatForwardDialogProps) { - const [query, setQuery] = React.useState("") - const [selected, setSelected] = React.useState>(new Set()) + const [query, setQuery] = React.useState(""); + const [selected, setSelected] = React.useState>(new Set()); - const filtered = conversations.filter((c) => - c.title.toLowerCase().includes(query.toLowerCase()) - ) + const filtered = conversations.filter((c) => c.title.toLowerCase().includes(query.toLowerCase())); const toggle = (id: string) => { setSelected((prev) => { - const next = new Set(prev) - if (next.has(id)) next.delete(id) - else next.add(id) - return next - }) - } + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }; return ( -
+
{/* Header */}
@@ -66,7 +66,9 @@ function ChatForwardDialog({ {/* Preview */}
- {message.senderName} + + {message.senderName} +

{message.text}

@@ -106,7 +108,10 @@ function ChatForwardDialog({ {/* Actions */}
-
- ) + ); } // ─── ChatEditComposer (inline edit mode) ────────────────────────────────────── interface ChatEditComposerProps { - message: ChatMessageData - onSave: (messageId: string, newText: string) => void - onCancel: () => void - className?: string + message: ChatMessageData; + onSave: (messageId: string, newText: string) => void; + onCancel: () => void; + className?: string; } -function ChatEditComposer({ - message, - onSave, - onCancel, - className, -}: ChatEditComposerProps) { - const [value, setValue] = React.useState(message.text || "") +function ChatEditComposer({ message, onSave, onCancel, className }: ChatEditComposerProps) { + const [value, setValue] = React.useState(message.text || ""); return (
{/* Edit bar */}
Editing message -
@@ -153,8 +156,11 @@ function ChatEditComposer({ value={value} onChange={(e) => setValue(e.target.value)} onKeyDown={(e) => { - if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSave(message.id, value.trim()) } - if (e.key === "Escape") onCancel() + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + onSave(message.id, value.trim()); + } + if (e.key === "Escape") onCancel(); }} rows={1} autoFocus @@ -169,14 +175,14 @@ function ChatEditComposer({
- ) + ); } // ─── ChatDeletedMessage (placeholder) ───────────────────────────────────────── interface ChatDeletedMessageProps { - deletedBy?: string - className?: string + deletedBy?: string; + className?: string; } function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) { @@ -187,17 +193,17 @@ function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) { {deletedBy ? `${deletedBy} deleted this message` : "This message was deleted"}
- ) + ); } // ─── ChatPinnedPanel ────────────────────────────────────────────────────────── interface ChatPinnedPanelProps { - pinnedMessages: ChatMessageData[] - onUnpin: (messageId: string) => void - onJumpTo: (messageId: string) => void - onClose: () => void - className?: string + pinnedMessages: ChatMessageData[]; + onUnpin: (messageId: string) => void; + onJumpTo: (messageId: string) => void; + onClose: () => void; + className?: string; } function ChatPinnedPanel({ @@ -227,17 +233,25 @@ function ChatPinnedPanel({ className="border-b border-border px-4 py-3 transition-colors hover:bg-accent" >
- {msg.senderName} + + {msg.senderName} + {formatTimestamp(new Date(msg.timestamp))}

{msg.text}

- -
@@ -250,27 +264,27 @@ function ChatPinnedPanel({ )}
- ) + ); } // ─── ChatNestedThread ───────────────────────────────────────────────────────── interface ThreadedMessage extends ChatMessageData { - parentId: string | null - children: ThreadedMessage[] - depth: number - votes?: number - userVote?: "up" | "down" | null - isCollapsed?: boolean + parentId: string | null; + children: ThreadedMessage[]; + depth: number; + votes?: number; + userVote?: "up" | "down" | null; + isCollapsed?: boolean; } interface ChatNestedThreadProps { - messages: ThreadedMessage[] - maxDepth?: number - onReply?: (parentId: string) => void - onVote?: (messageId: string, direction: "up" | "down") => void - showVotes?: boolean - className?: string + messages: ThreadedMessage[]; + maxDepth?: number; + onReply?: (parentId: string) => void; + onVote?: (messageId: string, direction: "up" | "down") => void; + showVotes?: boolean; + className?: string; } function ChatNestedThread({ @@ -294,7 +308,7 @@ function ChatNestedThread({ /> ))}
- ) + ); } function ThreadMessage({ @@ -304,29 +318,30 @@ function ThreadMessage({ onVote, showVotes, }: { - message: ThreadedMessage - maxDepth: number - onReply?: (parentId: string) => void - onVote?: (messageId: string, direction: "up" | "down") => void - showVotes: boolean + message: ThreadedMessage; + maxDepth: number; + onReply?: (parentId: string) => void; + onVote?: (messageId: string, direction: "up" | "down") => void; + showVotes: boolean; }) { - const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false) - const atMaxDepth = message.depth >= maxDepth + const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false); + const atMaxDepth = message.depth >= maxDepth; return (
{/* Thread connector line */} - {message.depth > 0 && ( -
- )} + {message.depth > 0 &&
} {/* Vote buttons */} {showVotes && (
@@ -335,7 +350,10 @@ function ThreadMessage({ @@ -353,7 +371,10 @@ function ThreadMessage({

{message.text}

{!atMaxDepth && ( - )} @@ -362,7 +383,11 @@ function ThreadMessage({ onClick={() => setCollapsed(!collapsed)} className="flex items-center gap-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground" > - {collapsed ? : } + {collapsed ? ( + + ) : ( + + )} {message.children.length} {message.children.length === 1 ? "reply" : "replies"} )} @@ -392,53 +417,63 @@ function ThreadMessage({ )}
- ) + ); } // ─── ChatSearch ─────────────────────────────────────────────────────────────── interface SearchResult { - messageId: string - conversationId?: string - conversationName?: string - senderName: string - snippet: string - timestamp: Date | number + messageId: string; + conversationId?: string; + conversationName?: string; + senderName: string; + snippet: string; + timestamp: Date | number; } interface ChatSearchProps { - onSearch: (query: string) => SearchResult[] | Promise - onSelect: (result: SearchResult) => void - onClose: () => void - className?: string + onSearch: (query: string) => SearchResult[] | Promise; + onSelect: (result: SearchResult) => void; + onClose: () => void; + className?: string; } function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) { - const [query, setQuery] = React.useState("") - const [results, setResults] = React.useState([]) - const inputRef = React.useRef(null) + const [query, setQuery] = React.useState(""); + const [results, setResults] = React.useState([]); + const inputRef = React.useRef(null); React.useEffect(() => { - inputRef.current?.focus() - }, []) + inputRef.current?.focus(); + }, []); React.useEffect(() => { - if (!query.trim()) { setResults([]); return } + if (!query.trim()) { + setResults([]); + return; + } const timeout = setTimeout(async () => { - const r = await onSearch(query) - setResults(r) - }, 200) - return () => clearTimeout(timeout) - }, [query, onSearch]) + const r = await onSearch(query); + setResults(r); + }, 200); + return () => clearTimeout(timeout); + }, [query, onSearch]); React.useEffect(() => { - const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose() } - document.addEventListener("keydown", handler) - return () => document.removeEventListener("keydown", handler) - }, [onClose]) + const handler = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + document.addEventListener("keydown", handler); + return () => document.removeEventListener("keydown", handler); + }, [onClose]); return ( -
+
{/* Search input */}
@@ -451,7 +486,9 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) placeholder="Search messages..." className="flex-1 bg-transparent text-[15px] text-foreground placeholder:text-muted-foreground/60 outline-none" /> - ESC + + ESC +
{/* Results */} @@ -459,13 +496,18 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) {results.map((r) => (
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── @@ -494,7 +536,7 @@ export { ChatPinnedPanel, ChatNestedThread, ChatSearch, -} +}; export type { Conversation, ChatForwardDialogProps, @@ -505,4 +547,4 @@ export type { ChatNestedThreadProps, SearchResult, ChatSearchProps, -} +}; diff --git a/packages/chat-ui/src/components/layouts.tsx b/packages/chat-ui/src/components/layouts.tsx index abc5ff5..d12e6e8 100644 --- a/packages/chat-ui/src/components/layouts.tsx +++ b/packages/chat-ui/src/components/layouts.tsx @@ -1,38 +1,43 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { - MessageSquare, - Search, - Phone, - X, - ChevronLeft, - Plus, - Minimize2, - Pin, - Ticket, - Clock, AlertCircle, CheckCircle2, + ChevronLeft, Circle, + Clock, + MessageSquare, + Minimize2, + Phone, + Pin, + Plus, + Search, + Ticket, User, -} from "lucide-react" -import type { ChatMessageData, ChatUser, TypingUser } from "../types" -import { ChatProvider, ChatMessages, ChatComposer } from "./chat" + X, +} from "lucide-react"; +import * as React from "react"; +import type { ChatMessageData, ChatUser, TypingUser } from "../types"; +import { ChatComposer, ChatMessages, ChatProvider } from "./chat"; // ─── Shared: ChatHeader ─────────────────────────────────────────────────────── interface ChatHeaderProps { - title: string - subtitle?: string - avatar?: React.ReactNode - actions?: React.ReactNode - onBack?: () => void - className?: string + title: string; + subtitle?: string; + avatar?: React.ReactNode; + actions?: React.ReactNode; + onBack?: () => void; + className?: string; } function ChatHeader({ title, subtitle, avatar, actions, onBack, className }: ChatHeaderProps) { return ( -
+
{onBack && (
- ) + ); } // ─── Shared: Sidebar conversation item ──────────────────────────────────────── interface SidebarConversation { - id: string - title: string - avatar?: string - lastMessage?: string - lastMessageTime?: string - unreadCount?: number - presence?: "online" | "away" | "offline" - isGroup?: boolean + id: string; + title: string; + avatar?: string; + lastMessage?: string; + lastMessageTime?: string; + unreadCount?: number; + presence?: "online" | "away" | "offline"; + isGroup?: boolean; } function ConversationItem({ @@ -66,9 +73,9 @@ function ConversationItem({ isActive, onClick, }: { - convo: SidebarConversation - isActive: boolean - onClick: () => void + convo: SidebarConversation; + isActive: boolean; + onClick: () => void; }) { return (
@@ -103,7 +112,7 @@ function ConversationItem({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -111,16 +120,16 @@ function ConversationItem({ // ═══════════════════════════════════════════════════════════════════════════════ interface FullMessengerProps { - currentUser: ChatUser - conversations: SidebarConversation[] - activeConversationId?: string - onSelectConversation: (id: string) => void - messages: ChatMessageData[] - typingUsers?: TypingUser[] - onSend: (text: string) => void - title?: string - subtitle?: string - className?: string + currentUser: ChatUser; + conversations: SidebarConversation[]; + activeConversationId?: string; + onSelectConversation: (id: string) => void; + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + onSend: (text: string) => void; + title?: string; + subtitle?: string; + className?: string; } function FullMessenger({ @@ -135,8 +144,8 @@ function FullMessenger({ subtitle, className, }: FullMessengerProps) { - const activeConvo = conversations.find((c) => c.id === activeConversationId) - const showingConvo = !!activeConvo + const activeConvo = conversations.find((c) => c.id === activeConversationId); + const showingConvo = !!activeConvo; return ( - - - + + +
} /> @@ -227,14 +242,16 @@ function FullMessenger({
-

Select a conversation

+

+ Select a conversation +

)}
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -242,14 +259,14 @@ function FullMessenger({ // ═══════════════════════════════════════════════════════════════════════════════ interface ChatWidgetProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - title?: string - subtitle?: string - greeting?: string - position?: "bottom-right" | "bottom-left" - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + title?: string; + subtitle?: string; + greeting?: string; + position?: "bottom-right" | "bottom-left"; + className?: string; } function ChatWidget({ @@ -261,11 +278,17 @@ function ChatWidget({ position = "bottom-right", className, }: ChatWidgetProps) { - const [isOpen, setIsOpen] = React.useState(false) + const [isOpen, setIsOpen] = React.useState(false); return ( -
+
{/* Chat window */} {isOpen && (
@@ -278,7 +301,10 @@ function ChatWidget({
} actions={ - } @@ -298,7 +324,7 @@ function ChatWidget({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -306,12 +332,12 @@ function ChatWidget({ // ═══════════════════════════════════════════════════════════════════════════════ interface InlineChatProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - placeholder?: string - maxHeight?: number - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + placeholder?: string; + maxHeight?: number; + className?: string; } function InlineChat({ @@ -324,12 +350,18 @@ function InlineChat({ }: InlineChatProps) { return ( -
+
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -337,23 +369,23 @@ function InlineChat({ // ═══════════════════════════════════════════════════════════════════════════════ interface Topic { - id: string - title: string - author: string - replyCount: number - lastActivity: string - isPinned?: boolean - tags?: string[] + id: string; + title: string; + author: string; + replyCount: number; + lastActivity: string; + isPinned?: boolean; + tags?: string[]; } interface ChatBoardProps { - currentUser: ChatUser - topics: Topic[] - activeTopic?: Topic - onSelectTopic: (id: string) => void - onBack?: () => void - children?: React.ReactNode - className?: string + currentUser: ChatUser; + topics: Topic[]; + activeTopic?: Topic; + onSelectTopic: (id: string) => void; + onBack?: () => void; + children?: React.ReactNode; + className?: string; } function ChatBoard({ @@ -370,16 +402,25 @@ function ChatBoard({
{activeTopic ? ( <> - +
{children}
) : ( <> - - } /> + + + + } + />
{topics.map((t) => (
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -420,12 +466,12 @@ function ChatBoard({ // ═══════════════════════════════════════════════════════════════════════════════ interface LiveChatProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - title?: string - viewerCount?: number - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + title?: string; + viewerCount?: number; + className?: string; } function LiveChat({ @@ -452,64 +498,67 @@ function LiveChat({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ // LAYOUT 7: SupportTickets (Help desk / ticket queue) // ═══════════════════════════════════════════════════════════════════════════════ -type TicketStatus = "open" | "in-progress" | "resolved" -type TicketPriority = "low" | "medium" | "high" | "urgent" +type TicketStatus = "open" | "in-progress" | "resolved"; +type TicketPriority = "low" | "medium" | "high" | "urgent"; interface SupportTicket { - id: string - subject: string - customerName: string - customerAvatar?: string - status: TicketStatus - priority: TicketPriority - category?: string - tags?: string[] - createdAt: string - updatedAt?: string - lastMessage?: string - unreadCount?: number - assignee?: string + id: string; + subject: string; + customerName: string; + customerAvatar?: string; + status: TicketStatus; + priority: TicketPriority; + category?: string; + tags?: string[]; + createdAt: string; + updatedAt?: string; + lastMessage?: string; + unreadCount?: number; + assignee?: string; } interface SupportTicketsProps { - currentUser: ChatUser - tickets: SupportTicket[] - activeTicketId?: string - onSelectTicket: (id: string) => void - messages: ChatMessageData[] - typingUsers?: TypingUser[] - onSend: (text: string) => void - statusFilter?: TicketStatus | "all" - onStatusFilterChange?: (status: TicketStatus | "all") => void - title?: string - className?: string + currentUser: ChatUser; + tickets: SupportTicket[]; + activeTicketId?: string; + onSelectTicket: (id: string) => void; + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + onSend: (text: string) => void; + statusFilter?: TicketStatus | "all"; + onStatusFilterChange?: (status: TicketStatus | "all") => void; + title?: string; + className?: string; } // ─── Internal helpers ──────────────────────────────────────────────────────── -const ticketStatusConfig: Record = { +const ticketStatusConfig: Record< + TicketStatus, + { icon: typeof Circle; label: string; color: string } +> = { open: { icon: Circle, label: "Open", color: "var(--color-chart-4)" }, "in-progress": { icon: Clock, label: "In Progress", color: "var(--color-primary)" }, resolved: { icon: CheckCircle2, label: "Resolved", color: "#22c55e" }, -} +}; const ticketPriorityColors: Record = { urgent: "var(--color-destructive)", high: "var(--color-chart-4)", medium: "var(--color-primary)", low: "var(--color-muted-foreground)", -} +}; function TicketStatusBadge({ status }: { status: TicketStatus }) { - const cfg = ticketStatusConfig[status] - const Icon = cfg.icon + const cfg = ticketStatusConfig[status]; + const Icon = cfg.icon; return ( {cfg.label} - ) + ); } function TicketPriorityBadge({ priority }: { priority: TicketPriority }) { - const color = ticketPriorityColors[priority] + const color = ticketPriorityColors[priority]; return ( {priority} - ) + ); } function TicketFilterTabs({ value, onChange, }: { - value: TicketStatus | "all" - onChange: (v: TicketStatus | "all") => void + value: TicketStatus | "all"; + onChange: (v: TicketStatus | "all") => void; }) { const tabs: { key: TicketStatus | "all"; label: string }[] = [ { key: "all", label: "All" }, { key: "open", label: "Open" }, { key: "in-progress", label: "Active" }, { key: "resolved", label: "Resolved" }, - ] + ]; return (
{tabs.map((t) => ( @@ -569,7 +618,7 @@ function TicketFilterTabs({ ))}
- ) + ); } function TicketItem({ @@ -577,11 +626,11 @@ function TicketItem({ isActive, onClick, }: { - ticket: SupportTicket - isActive: boolean - onClick: () => void + ticket: SupportTicket; + isActive: boolean; + onClick: () => void; }) { - const StatusIcon = ticketStatusConfig[ticket.status].icon + const StatusIcon = ticketStatusConfig[ticket.status].icon; return ( - ) + ); } // ─── Main component ────────────────────────────────────────────────────────── @@ -644,17 +693,17 @@ function SupportTickets({ title = "Support Tickets", className, }: SupportTicketsProps) { - const [internalFilter, setInternalFilter] = React.useState("all") - const filter = controlledFilter ?? internalFilter - const setFilter = onStatusFilterChange ?? setInternalFilter + const [internalFilter, setInternalFilter] = React.useState("all"); + const filter = controlledFilter ?? internalFilter; + const setFilter = onStatusFilterChange ?? setInternalFilter; - const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter) - const activeTicket = tickets.find((t) => t.id === activeTicketId) + const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter); + const activeTicket = tickets.find((t) => t.id === activeTicketId); - const openCount = tickets.filter((t) => t.status === "open").length - const activeCount = tickets.filter((t) => t.status === "in-progress").length + const openCount = tickets.filter((t) => t.status === "open").length; + const activeCount = tickets.filter((t) => t.status === "in-progress").length; - const showingTicket = !!activeTicket + const showingTicket = !!activeTicket; return (
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── -const ChatConversationItem = ConversationItem +const ChatConversationItem = ConversationItem; export { ChatHeader, @@ -787,7 +836,7 @@ export { TicketStatusBadge, TicketPriorityBadge, TicketFilterTabs, -} +}; export type { ChatHeaderProps, SidebarConversation, @@ -801,4 +850,4 @@ export type { TicketPriority, SupportTicket, SupportTicketsProps, -} +}; diff --git a/packages/chat-ui/src/hooks.ts b/packages/chat-ui/src/hooks.ts index 467abc4..89238b8 100644 --- a/packages/chat-ui/src/hooks.ts +++ b/packages/chat-ui/src/hooks.ts @@ -1,35 +1,21 @@ -import { - useRef, - useEffect, - useCallback, - useState, -} from "react" -import { - isToday, - isYesterday, - format, - isSameDay, - differenceInSeconds, -} from "date-fns" -import type { ChatMessageData, MessageListItem, MessageGroup } from "./types" +import { differenceInSeconds, format, isSameDay, isToday, isYesterday } from "date-fns"; +import { useCallback, useEffect, useRef, useState } from "react"; +import type { ChatMessageData, MessageGroup, MessageListItem } from "./types"; // ─── Date formatting ────────────────────────────────────────────────────────── export function formatDateLabel(date: Date): string { - if (isToday(date)) return "Today" - if (isYesterday(date)) return "Yesterday" - const now = new Date() - const diffDays = Math.floor( - (now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24) - ) - if (diffDays < 7) return format(date, "EEEE") // "Tuesday" - if (date.getFullYear() === now.getFullYear()) - return format(date, "MMMM d") // "March 18" - return format(date, "MMMM d, yyyy") // "March 18, 2026" + if (isToday(date)) return "Today"; + if (isYesterday(date)) return "Yesterday"; + const now = new Date(); + const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); + if (diffDays < 7) return format(date, "EEEE"); // "Tuesday" + if (date.getFullYear() === now.getFullYear()) return format(date, "MMMM d"); // "March 18" + return format(date, "MMMM d, yyyy"); // "March 18, 2026" } export function formatTimestamp(date: Date): string { - return format(date, "h:mm a") // "10:42 AM" + return format(date, "h:mm a"); // "10:42 AM" } // ─── Message grouping ───────────────────────────────────────────────────────── @@ -39,40 +25,40 @@ export function groupMessages( currentUserId: string, intervalSeconds: number = 120 ): MessageListItem[] { - if (messages.length === 0) return [] + if (messages.length === 0) return []; - const items: MessageListItem[] = [] - let currentGroup: MessageGroup | null = null - let lastDate: Date | null = null + const items: MessageListItem[] = []; + let currentGroup: MessageGroup | null = null; + let lastDate: Date | null = null; for (const msg of messages) { - const msgDate = new Date(msg.timestamp) + const msgDate = new Date(msg.timestamp); // System messages break groups if (msg.isSystem) { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) - currentGroup = null + items.push({ type: "group", group: currentGroup }); + currentGroup = null; } // Insert date separator if needed if (!lastDate || !isSameDay(lastDate, msgDate)) { - items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }) - lastDate = msgDate + items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }); + lastDate = msgDate; } - items.push({ type: "system", message: msg }) - continue + items.push({ type: "system", message: msg }); + continue; } // Insert date separator if needed if (!lastDate || !isSameDay(lastDate, msgDate)) { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) - currentGroup = null + items.push({ type: "group", group: currentGroup }); + currentGroup = null; } - items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }) - lastDate = msgDate + items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }); + lastDate = msgDate; } // Check if message should continue the current group @@ -82,16 +68,14 @@ export function groupMessages( currentGroup.messages.length > 0 && differenceInSeconds( msgDate, - new Date( - currentGroup.messages[currentGroup.messages.length - 1]!.timestamp - ) - ) <= intervalSeconds + new Date(currentGroup.messages[currentGroup.messages.length - 1]!.timestamp) + ) <= intervalSeconds; if (shouldGroup && currentGroup) { - currentGroup.messages.push(msg) + currentGroup.messages.push(msg); } else { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) + items.push({ type: "group", group: currentGroup }); } currentGroup = { senderId: msg.senderId, @@ -99,133 +83,126 @@ export function groupMessages( senderAvatar: msg.senderAvatar, messages: [msg], isOutgoing: msg.senderId === currentUserId, - } + }; } } if (currentGroup) { - items.push({ type: "group", group: currentGroup }) + items.push({ type: "group", group: currentGroup }); } - return items + return items; } // ─── Auto-scroll hook ───────────────────────────────────────────────────────── -export function useAutoScroll( - messages: ChatMessageData[], - opts?: { threshold?: number } -) { - const containerRef = useRef(null) - const [isAtBottom, setIsAtBottom] = useState(true) - const [unseenCount, setUnseenCount] = useState(0) - const prevLengthRef = useRef(messages.length) - const threshold = opts?.threshold ?? 100 +export function useAutoScroll(messages: ChatMessageData[], opts?: { threshold?: number }) { + const containerRef = useRef(null); + const [isAtBottom, setIsAtBottom] = useState(true); + const [unseenCount, setUnseenCount] = useState(0); + const prevLengthRef = useRef(messages.length); + const threshold = opts?.threshold ?? 100; - const scrollToBottom = useCallback( - (behavior: ScrollBehavior = "smooth") => { - const el = containerRef.current - if (!el) return - el.scrollTo({ top: el.scrollHeight, behavior }) - setUnseenCount(0) - }, - [] - ) + const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => { + const el = containerRef.current; + if (!el) return; + el.scrollTo({ top: el.scrollHeight, behavior }); + setUnseenCount(0); + }, []); // Track scroll position useEffect(() => { - const el = containerRef.current - if (!el) return + const el = containerRef.current; + if (!el) return; const handleScroll = () => { - const distanceFromBottom = - el.scrollHeight - el.scrollTop - el.clientHeight - const atBottom = distanceFromBottom <= threshold - setIsAtBottom(atBottom) - if (atBottom) setUnseenCount(0) - } + const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight; + const atBottom = distanceFromBottom <= threshold; + setIsAtBottom(atBottom); + if (atBottom) setUnseenCount(0); + }; - el.addEventListener("scroll", handleScroll, { passive: true }) - return () => el.removeEventListener("scroll", handleScroll) - }, [threshold]) + el.addEventListener("scroll", handleScroll, { passive: true }); + return () => el.removeEventListener("scroll", handleScroll); + }, [threshold]); // Auto-scroll when new messages arrive and user is at bottom useEffect(() => { - const newCount = messages.length - prevLengthRef.current - prevLengthRef.current = messages.length + const newCount = messages.length - prevLengthRef.current; + prevLengthRef.current = messages.length; - if (newCount <= 0) return + if (newCount <= 0) return; if (isAtBottom) { - scrollToBottom("smooth") + scrollToBottom("smooth"); } else { - setUnseenCount((c) => c + newCount) + setUnseenCount((c) => c + newCount); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [messages.length]) + }, [messages.length]); // Scroll to bottom on mount useEffect(() => { - scrollToBottom("instant") + scrollToBottom("instant"); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, []); - return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const + return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const; } // ─── Auto-resize textarea hook ──────────────────────────────────────────────── export function useAutoResize(opts?: { maxRows?: number }) { - const textareaRef = useRef(null) - const maxRows = opts?.maxRows ?? 6 + const textareaRef = useRef(null); + const maxRows = opts?.maxRows ?? 6; const resize = useCallback(() => { - const el = textareaRef.current - if (!el) return - el.style.height = "auto" - const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22 - const maxHeight = lineHeight * maxRows - el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px` - el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden" - }, [maxRows]) + const el = textareaRef.current; + if (!el) return; + el.style.height = "auto"; + const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22; + const maxHeight = lineHeight * maxRows; + el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`; + el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden"; + }, [maxRows]); - return { textareaRef, resize } as const + return { textareaRef, resize } as const; } // ─── Typing indicator hook ──────────────────────────────────────────────────── export function useTypingIndicator(opts?: { - onTypingChange?: (isTyping: boolean) => void - debounceMs?: number + onTypingChange?: (isTyping: boolean) => void; + debounceMs?: number; }) { - const [isTyping, setIsTyping] = useState(false) - const timeoutRef = useRef | null>(null) - const debounceMs = opts?.debounceMs ?? 2000 + const [isTyping, setIsTyping] = useState(false); + const timeoutRef = useRef | null>(null); + const debounceMs = opts?.debounceMs ?? 2000; const handleKeyDown = useCallback(() => { if (!isTyping) { - setIsTyping(true) - opts?.onTypingChange?.(true) + setIsTyping(true); + opts?.onTypingChange?.(true); } - if (timeoutRef.current) clearTimeout(timeoutRef.current) + if (timeoutRef.current) clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { - setIsTyping(false) - opts?.onTypingChange?.(false) - }, debounceMs) - }, [isTyping, debounceMs, opts]) + setIsTyping(false); + opts?.onTypingChange?.(false); + }, debounceMs); + }, [isTyping, debounceMs, opts]); const stopTyping = useCallback(() => { - if (timeoutRef.current) clearTimeout(timeoutRef.current) - setIsTyping(false) - opts?.onTypingChange?.(false) - }, [opts]) + if (timeoutRef.current) clearTimeout(timeoutRef.current); + setIsTyping(false); + opts?.onTypingChange?.(false); + }, [opts]); useEffect(() => { return () => { - if (timeoutRef.current) clearTimeout(timeoutRef.current) - } - }, []) + if (timeoutRef.current) clearTimeout(timeoutRef.current); + }; + }, []); - return { isTyping, handleKeyDown, stopTyping } as const + return { isTyping, handleKeyDown, stopTyping } as const; } diff --git a/packages/chat-ui/src/index.ts b/packages/chat-ui/src/index.ts index 2ea8fee..24721f7 100644 --- a/packages/chat-ui/src/index.ts +++ b/packages/chat-ui/src/index.ts @@ -1,114 +1,110 @@ // Core components -export { - ChatProvider, - ChatMessage, - ChatMessageGroup, - ChatDateSeparator, - ChatSystemMessage, - ChatMessages, - ChatComposer, - ChatMessageStatus, - ChatMessageReactions, - ChatMessageActions, - ChatMessageReply, - ChatTypingIndicator, - ChatReplyPreview, - ChatReadReceipts, -} from "./components/chat" -export type { - ChatProviderProps, - ChatMessageProps, - ChatMessageGroupProps, - ChatDateSeparatorProps, - ChatSystemMessageProps, - ChatMessagesProps, - ChatComposerProps, - ChatMessageActionsProps, - ChatTypingIndicatorProps, - ChatReplyPreviewProps, -} from "./components/chat" +export type { + ChatComposerProps, + ChatDateSeparatorProps, + ChatMessageActionsProps, + ChatMessageGroupProps, + ChatMessageProps, + ChatMessagesProps, + ChatProviderProps, + ChatReplyPreviewProps, + ChatSystemMessageProps, + ChatTypingIndicatorProps, +} from "./components/chat"; +export { + ChatComposer, + ChatDateSeparator, + ChatMessage, + ChatMessageActions, + ChatMessageGroup, + ChatMessageReactions, + ChatMessageReply, + ChatMessageStatus, + ChatMessages, + ChatProvider, + ChatReadReceipts, + ChatReplyPreview, + ChatSystemMessage, + ChatTypingIndicator, +} from "./components/chat"; +export type { + ChatDeletedMessageProps, + ChatEditComposerProps, + ChatForwardDialogProps, + ChatNestedThreadProps, + ChatPinnedPanelProps, + ChatSearchProps, + Conversation, + SearchResult, + ThreadedMessage, +} from "./components/features"; // Feature components export { - ChatForwardDialog, - ChatEditComposer, ChatDeletedMessage, - ChatPinnedPanel, + ChatEditComposer, + ChatForwardDialog, ChatNestedThread, + ChatPinnedPanel, ChatSearch, -} from "./components/features" +} from "./components/features"; export type { - Conversation, - ChatForwardDialogProps, - ChatEditComposerProps, - ChatDeletedMessageProps, - ChatPinnedPanelProps, - ThreadedMessage, - ChatNestedThreadProps, - SearchResult, - ChatSearchProps, -} from "./components/features" - -// Pre-built layouts -export { - ChatHeader, - ChatConversationItem, - FullMessenger, - ChatWidget, - InlineChat, - ChatBoard, - LiveChat, - SupportTickets, - TicketStatusBadge, - TicketPriorityBadge, - TicketFilterTabs, -} from "./components/layouts" -export type { - ChatHeaderProps, - SidebarConversation, - FullMessengerProps, - ChatWidgetProps, - InlineChatProps, - Topic, ChatBoardProps, + ChatHeaderProps, + ChatWidgetProps, + FullMessengerProps, + InlineChatProps, LiveChatProps, - TicketStatus, - TicketPriority, + SidebarConversation, SupportTicket, SupportTicketsProps, -} from "./components/layouts" - + TicketPriority, + TicketStatus, + Topic, +} from "./components/layouts"; +// Pre-built layouts +export { + ChatBoard, + ChatConversationItem, + ChatHeader, + ChatWidget, + FullMessenger, + InlineChat, + LiveChat, + SupportTickets, + TicketFilterTabs, + TicketPriorityBadge, + TicketStatusBadge, +} from "./components/layouts"; +// Hooks +export { + formatDateLabel, + formatTimestamp, + groupMessages, + useAutoResize, + useAutoScroll, + useTypingIndicator, +} from "./hooks"; +export type { FileValidationResult } from "./security"; // Security utilities export { - sanitizeUrl, displayHostname, + formatReactionCount, + isValidEmoji, + sanitizeFileName, + sanitizeSenderName, + sanitizeUrl, stripBidiOverrides, truncateMessage, - sanitizeSenderName, validateFile, - sanitizeFileName, - isValidEmoji, - formatReactionCount, -} from "./security" -export type { FileValidationResult } from "./security" - +} from "./security"; // Types export type { - ChatUser, + ChatConfig, ChatLabels, ChatMessageData, - ChatConfig, + ChatUser, MessageGroup, MessageListItem, TypingUser, -} from "./types" - -// Hooks -export { - groupMessages, - useAutoScroll, - useAutoResize, - useTypingIndicator, - formatTimestamp, - formatDateLabel, -} from "./hooks" +} from "./types"; diff --git a/packages/chat-ui/src/security.ts b/packages/chat-ui/src/security.ts index 40bab72..902e5f3 100644 --- a/packages/chat-ui/src/security.ts +++ b/packages/chat-ui/src/security.ts @@ -5,22 +5,22 @@ // ─── URL Sanitization ───────────────────────────────────────────────────────── -const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i +const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i; /** Sanitize a URL — only allow http, https, and mailto. Blocks javascript:, data:, etc. */ export function sanitizeUrl(url: string | undefined | null): string { - if (!url) return "#" - const trimmed = url.trim() - if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#" - return trimmed + if (!url) return "#"; + const trimmed = url.trim(); + if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#"; + return trimmed; } /** Extract hostname from a URL for display (prevents misleading long URLs) */ export function displayHostname(url: string): string { try { - return new URL(url).hostname + return new URL(url).hostname; } catch { - return url + return url; } } @@ -29,7 +29,7 @@ export function displayHostname(url: string): string { /** Strip bidi override characters that can disguise malicious content (RLO attacks) */ export function stripBidiOverrides(text: string): string { // Remove LRO, RLO, LRE, RLE, PDF, LRI, RLI, FSI, PDI - return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "") + return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, ""); } /** Truncate message text to prevent rendering DoS */ @@ -37,80 +37,97 @@ export function truncateMessage( text: string, maxLength: number = 10_000 ): { text: string; truncated: boolean } { - if (text.length <= maxLength) return { text, truncated: false } - return { text: text.slice(0, maxLength) + "\u2026", truncated: true } + if (text.length <= maxLength) return { text, truncated: false }; + return { text: `${text.slice(0, maxLength)}\u2026`, truncated: true }; } /** Sanitize sender name — strip bidi, truncate */ export function sanitizeSenderName(name: string): string { - return stripBidiOverrides(name).slice(0, 100) + return stripBidiOverrides(name).slice(0, 100); } // ─── File Validation ────────────────────────────────────────────────────────── const BLOCKED_EXTENSIONS = new Set([ - ".exe", ".bat", ".cmd", ".scr", ".pif", ".com", - ".js", ".jsx", ".ts", ".tsx", ".mjs", - ".html", ".htm", ".xhtml", + ".exe", + ".bat", + ".cmd", + ".scr", + ".pif", + ".com", + ".js", + ".jsx", + ".ts", + ".tsx", + ".mjs", + ".html", + ".htm", + ".xhtml", ".svg", - ".xml", ".xsl", ".xslt", - ".hta", ".vbs", ".vbe", ".wsf", ".wsh", - ".ps1", ".psm1", - ".sh", ".bash", -]) + ".xml", + ".xsl", + ".xslt", + ".hta", + ".vbs", + ".vbe", + ".wsf", + ".wsh", + ".ps1", + ".psm1", + ".sh", + ".bash", +]); -const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024 // 25MB +const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25MB export interface FileValidationResult { - valid: boolean - error?: string + valid: boolean; + error?: string; } -export function validateFile( - file: File, - opts?: { maxSize?: number } -): FileValidationResult { - const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE +export function validateFile(file: File, opts?: { maxSize?: number }): FileValidationResult { + const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE; // Check extension - const parts = file.name.split(".") - const ext = parts.length > 1 ? "." + parts[parts.length - 1]!.toLowerCase() : "" + const parts = file.name.split("."); + const ext = parts.length > 1 ? `.${parts[parts.length - 1]!.toLowerCase()}` : ""; if (BLOCKED_EXTENSIONS.has(ext)) { - return { valid: false, error: `File type ${ext} is not allowed` } + return { valid: false, error: `File type ${ext} is not allowed` }; } // Check size if (file.size > maxSize) { - const mbLimit = Math.round(maxSize / (1024 * 1024)) - return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` } + const mbLimit = Math.round(maxSize / (1024 * 1024)); + return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` }; } - return { valid: true } + return { valid: true }; } /** Sanitize a file name for display */ export function sanitizeFileName(name: string): string { - let clean = name.replace(/[/\\]/g, "_") // Remove path traversal - clean = clean.replace(/\0/g, "") // Remove null bytes - clean = stripBidiOverrides(clean) // Remove bidi overrides - if (clean.length > 100) clean = clean.slice(0, 97) + "..." - return clean + let clean = name.replace(/[/\\]/g, "_"); // Remove path traversal + clean = clean.replace(/\0/g, ""); // Remove null bytes + clean = stripBidiOverrides(clean); // Remove bidi overrides + if (clean.length > 100) clean = `${clean.slice(0, 97)}...`; + return clean; } // ─── Emoji Validation ───────────────────────────────────────────────────────── -const EMOJI_REGEX = /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u +const EMOJI_REGEX = + /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u; /** Validate that a string is a valid emoji (not arbitrary text) */ export function isValidEmoji(str: string): boolean { - return EMOJI_REGEX.test(str) && str.length <= 20 + return EMOJI_REGEX.test(str) && str.length <= 20; } // ─── Reaction Count Safety ──────────────────────────────────────────────────── /** Format reaction count for display (cap at 999+, floor at 0) */ export function formatReactionCount(count: number): string { - if (count <= 0) return "0" - if (count > 999) return "999+" - return String(count) + if (count <= 0) return "0"; + if (count > 999) return "999+"; + return String(count); } diff --git a/packages/chat-ui/src/types.ts b/packages/chat-ui/src/types.ts index 1a7da7e..201eb7b 100644 --- a/packages/chat-ui/src/types.ts +++ b/packages/chat-ui/src/types.ts @@ -1,84 +1,84 @@ export interface ChatUser { - id: string - name: string - avatar?: string - status?: "online" | "away" | "dnd" | "offline" + id: string; + name: string; + avatar?: string; + status?: "online" | "away" | "dnd" | "offline"; } export interface ChatMessageData { - id: string - senderId: string - senderName: string - senderAvatar?: string + id: string; + senderId: string; + senderName: string; + senderAvatar?: string; // Content - text?: string - images?: { url: string; width: number; height: number; alt?: string }[] - files?: { name: string; size: number; type: string; url: string }[] - voice?: { url: string; duration: number; waveform: number[] } + text?: string; + images?: { url: string; width: number; height: number; alt?: string }[]; + files?: { name: string; size: number; type: string; url: string }[]; + voice?: { url: string; duration: number; waveform: number[] }; linkPreview?: { - url: string - title: string - description: string - image?: string - } - code?: { language: string; code: string } + url: string; + title: string; + description: string; + image?: string; + }; + code?: { language: string; code: string }; // Metadata - timestamp: Date | number - status?: "sending" | "sent" | "delivered" | "read" | "failed" - replyTo?: { id: string; senderName: string; text: string } - reactions?: { emoji: string; userIds: string[]; count: number }[] - isEdited?: boolean - isPinned?: boolean - isSystem?: boolean - systemEvent?: string + timestamp: Date | number; + status?: "sending" | "sent" | "delivered" | "read" | "failed"; + replyTo?: { id: string; senderName: string; text: string }; + reactions?: { emoji: string; userIds: string[]; count: number }[]; + isEdited?: boolean; + isPinned?: boolean; + isSystem?: boolean; + systemEvent?: string; // Read receipts (group chat) — list of users who have read up to this message - readBy?: { userId: string; name: string; avatar?: string }[] + readBy?: { userId: string; name: string; avatar?: string }[]; } export interface ChatLabels { - composerPlaceholder?: string - typingOne?: string // e.g. "{{name}} is typing" - typingTwo?: string // e.g. "{{name1}} and {{name2}} are typing" - typingMany?: string // e.g. "Several people are typing" - scrollToBottom?: string + composerPlaceholder?: string; + typingOne?: string; // e.g. "{{name}} is typing" + typingTwo?: string; // e.g. "{{name1}} and {{name2}} are typing" + typingMany?: string; // e.g. "Several people are typing" + scrollToBottom?: string; } export interface ChatConfig { - currentUser: ChatUser - dateFormat?: "relative" | "absolute" | "time-only" - messageGroupingInterval?: number // seconds, default 120 - labels?: ChatLabels + currentUser: ChatUser; + dateFormat?: "relative" | "absolute" | "time-only"; + messageGroupingInterval?: number; // seconds, default 120 + labels?: ChatLabels; // Callbacks - onReactionAdd?: (messageId: string, emoji: string) => void - onReactionRemove?: (messageId: string, emoji: string) => void - onReply?: (message: ChatMessageData) => void - onEdit?: (message: ChatMessageData) => void - onDelete?: (messageId: string) => void - onPin?: (messageId: string) => void + onReactionAdd?: (messageId: string, emoji: string) => void; + onReactionRemove?: (messageId: string, emoji: string) => void; + onReply?: (message: ChatMessageData) => void; + onEdit?: (message: ChatMessageData) => void; + onDelete?: (messageId: string) => void; + onPin?: (messageId: string) => void; } /** A group of consecutive messages from the same sender within the grouping interval */ export interface MessageGroup { - senderId: string - senderName: string - senderAvatar?: string - messages: ChatMessageData[] - isOutgoing: boolean + senderId: string; + senderName: string; + senderAvatar?: string; + messages: ChatMessageData[]; + isOutgoing: boolean; } /** Items that can appear in the message list */ export type MessageListItem = | { type: "group"; group: MessageGroup } | { type: "date"; date: Date; label: string } - | { type: "system"; message: ChatMessageData } + | { type: "system"; message: ChatMessageData }; /** Typing state for one or more users */ export interface TypingUser { - id: string - name: string - avatar?: string + id: string; + name: string; + avatar?: string; } diff --git a/packages/shared/package.json b/packages/shared/package.json index 2c58350..61dce73 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -35,7 +35,7 @@ "react-dom": "19.0.0", "react-router-dom": "^7.9.4", "sonner": "^2.0.7", -"tailwind-merge": "^3.0.2", + "tailwind-merge": "^3.0.2", "ts-pattern": "^5.6.2", "zustand": "^5.0.5" }, diff --git a/packages/tablo-views/src/ChatMessages.tsx b/packages/tablo-views/src/ChatMessages.tsx index 896e34c..319a233 100644 --- a/packages/tablo-views/src/ChatMessages.tsx +++ b/packages/tablo-views/src/ChatMessages.tsx @@ -1,11 +1,7 @@ +import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui"; +import { ChatComposer, ChatMessages as ChatMessageList, ChatProvider } from "@xtablo/chat-ui"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { - ChatProvider, - ChatMessages as ChatMessageList, - ChatComposer, -} from "@xtablo/chat-ui"; -import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui"; interface ChatMessage { id: string; @@ -60,7 +56,7 @@ export function ChatMessages({ name: membersById.get(currentUserId)?.name ?? t("currentUserName"), avatar: membersById.get(currentUserId)?.avatar_url ?? undefined, }), - [currentUserId, membersById, t], + [currentUserId, membersById, t] ); const chatMessages = useMemo( @@ -77,7 +73,7 @@ export function ChatMessages({ status: msg.optimistic ? "sending" : undefined, }; }), - [messages, membersById, t], + [messages, membersById, t] ); const chatTypingUsers = useMemo( @@ -87,7 +83,7 @@ export function ChatMessages({ name: membersById.get(userId)?.name ?? t("defaultUserName"), avatar: membersById.get(userId)?.avatar_url ?? undefined, })), - [typingUsers, membersById, t], + [typingUsers, membersById, t] ); const chatLabels = useMemo( @@ -98,19 +94,12 @@ export function ChatMessages({ typingMany: t("typingMany"), scrollToBottom: t("scrollToBottom"), }), - [t], + [t] ); return ( - - + + { diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index 4f5f3ee..a8e190f 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -8,8 +8,8 @@ import { ChevronDownIcon, ChevronRightIcon, CircleCheckIcon, - PencilIcon, ListChecksIcon, + PencilIcon, PlusIcon, Trash2Icon, XIcon, @@ -178,11 +178,7 @@ export function EtapesSection({ required className="h-11 sm:h-9 sm:w-80" /> - @@ -390,10 +386,7 @@ export function EtapesSection({ : "hover:bg-gray-50 dark:hover:bg-gray-800" )} onClick={() => - onTaskStatusChange?.( - task.id, - task.status === "done" ? "todo" : "done" - ) + onTaskStatusChange?.(task.id, task.status === "done" ? "todo" : "done") } > {task.status === "done" ? ( diff --git a/packages/tablo-views/src/TabloDetailsShell.tsx b/packages/tablo-views/src/TabloDetailsShell.tsx index b0eae62..d9e2d91 100644 --- a/packages/tablo-views/src/TabloDetailsShell.tsx +++ b/packages/tablo-views/src/TabloDetailsShell.tsx @@ -49,7 +49,9 @@ export function TabloDetailsShell({

{tablo.name}

- {headerActions &&
{headerActions}
} + {headerActions && ( +
{headerActions}
+ )}
@@ -58,7 +60,8 @@ export function TabloDetailsShell({ key={item.key} className={cn( "flex items-center gap-2", - index < metadata.length - 1 && "sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4" + index < metadata.length - 1 && + "sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4" )} > {item.label} diff --git a/packages/tablo-views/src/TabloDiscussionSection.tsx b/packages/tablo-views/src/TabloDiscussionSection.tsx index 8973a7f..422d9ce 100644 --- a/packages/tablo-views/src/TabloDiscussionSection.tsx +++ b/packages/tablo-views/src/TabloDiscussionSection.tsx @@ -1,7 +1,7 @@ import type { UserTablo } from "@xtablo/shared/types/tablos.types"; import { useEffect } from "react"; -import { useChat } from "./hooks/useChat"; import { ChatMessages } from "./ChatMessages"; +import { useChat } from "./hooks/useChat"; interface Member { id: string; diff --git a/packages/tablo-views/src/TabloEventsSection.tsx b/packages/tablo-views/src/TabloEventsSection.tsx index 2781805..74e1686 100644 --- a/packages/tablo-views/src/TabloEventsSection.tsx +++ b/packages/tablo-views/src/TabloEventsSection.tsx @@ -46,7 +46,11 @@ interface TabloEventsSectionProps { isInvitingUser?: boolean; isCancellingInvite?: boolean; onCreateEvent?: () => void; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } diff --git a/packages/tablo-views/src/TabloFilesSection.tsx b/packages/tablo-views/src/TabloFilesSection.tsx index a96df14..7312d2f 100644 --- a/packages/tablo-views/src/TabloFilesSection.tsx +++ b/packages/tablo-views/src/TabloFilesSection.tsx @@ -490,13 +490,35 @@ interface TabloFilesSectionProps { canUploadFiles?: boolean; canManageFolders?: boolean; canDeleteFiles?: boolean; - onCreateFile?: (params: { tabloId: string; fileName: string; data: { content: string; contentType: string } }) => Promise; + onCreateFile?: (params: { + tabloId: string; + fileName: string; + data: { content: string; contentType: string }; + }) => Promise; onDeleteFile?: (params: { tabloId: string; fileName: string }) => Promise; onDownloadFile?: (params: { tabloId: string; fileName: string }) => Promise; - onCreateFolder?: (params: { tabloId: string; name: string; description: string; createdBy: string }) => Promise; - onUpdateFolder?: (params: { tabloId: string; folderId: string; name: string; description: string }) => Promise; - onDeleteFolder?: (params: { tabloId: string; folderId: string; folderName: string }) => Promise; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onCreateFolder?: (params: { + tabloId: string; + name: string; + description: string; + createdBy: string; + }) => Promise; + onUpdateFolder?: (params: { + tabloId: string; + folderId: string; + name: string; + description: string; + }) => Promise; + onDeleteFolder?: (params: { + tabloId: string; + folderId: string; + folderName: string; + }) => Promise; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 1839fe9..1ec3a4d 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -12,8 +12,8 @@ import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography" import { AlertTriangle, ListChecks } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; import { KanbanBoard } from "./components/kanban/KanbanBoard"; -import type { TabloMember } from "./components/kanban/types"; import { TaskModal } from "./components/kanban/TaskModal"; +import type { TabloMember } from "./components/kanban/types"; import { TabloHeaderActions } from "./TabloHeaderActions"; interface CurrentUser { @@ -39,8 +39,14 @@ interface TabloTasksSectionProps { onCreateTask?: (task: KanbanTaskInsert) => void; onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; onDeleteTask?: (taskId: string) => void; - onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onUpdateTaskPositions?: ( + updates: Array<{ id: string; position: number; status: TaskStatus }> + ) => void; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } @@ -245,7 +251,8 @@ export const TabloTasksSection = ({ {orphanedTasks.length} {pluralize("tâche", orphanedTasks.length)} sans Étape

- Associez {orphanedTasks.length > 1 ? "ces" : "cette"} {pluralize("tâche", orphanedTasks.length)} à une étape. + Associez {orphanedTasks.length > 1 ? "ces" : "cette"}{" "} + {pluralize("tâche", orphanedTasks.length)} à une étape.

diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index df1dd2b..9594934 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -1,4 +1,10 @@ -import type { Etape, KanbanTask, KanbanTaskInsert, KanbanTaskUpdate, TaskStatus } from "@xtablo/shared-types"; +import type { + Etape, + KanbanTask, + KanbanTaskInsert, + KanbanTaskUpdate, + TaskStatus, +} from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; import { DatePicker } from "@xtablo/ui/components/date-picker"; import { Input } from "@xtablo/ui/components/input"; @@ -74,11 +80,11 @@ export const TaskModal = ({ const selectedAssigneeLabel = assigneeId === "unassigned" ? "Non assigné" - : providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"; + : (providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"); const selectedEtapeLabel = etapeId === "none" ? "Aucune Étape" - : providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"; + : (providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"); useEffect(() => { if (!isOpen) { @@ -104,7 +110,15 @@ export const TaskModal = ({ setSelectedTabloId(tablos[0].id); } } - }, [isOpen, task, initialTabloId, allowTabloSelection, tablos, initialDueDate, defaultAssigneeId]); + }, [ + isOpen, + task, + initialTabloId, + allowTabloSelection, + tablos, + initialDueDate, + defaultAssigneeId, + ]); // Format Date to YYYY-MM-DD string for database storage const formatDateForDb = (date: Date | undefined): string | null => { diff --git a/packages/tablo-views/src/hooks/useChat.ts b/packages/tablo-views/src/hooks/useChat.ts index 1ff345f..3b0e455 100644 --- a/packages/tablo-views/src/hooks/useChat.ts +++ b/packages/tablo-views/src/hooks/useChat.ts @@ -1,5 +1,5 @@ -import { useCallback, useEffect, useRef, useState } from "react"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useCallback, useEffect, useRef, useState } from "react"; interface ChatMessage { id: string; @@ -31,7 +31,14 @@ function normalizeMessage(raw: RawApiMessage): ChatMessage { } type ServerMessage = - | { type: "message.new"; id: string; userId: string; text: string; createdAt: string; clientId: string } + | { + type: "message.new"; + id: string; + userId: string; + text: string; + createdAt: string; + clientId: string; + } | { type: "typing"; userId: string; isTyping: boolean } | { type: "presence.update"; userId: string; status: "online" | "offline" } | { type: "error"; code: string; message: string }; @@ -56,30 +63,33 @@ export function useChat(channelId: string | undefined) { const isTypingRef = useRef(false); // Fetch message history from REST endpoint - const fetchHistory = useCallback(async (before?: string) => { - if (!channelId || !token) return; + const fetchHistory = useCallback( + async (before?: string) => { + if (!channelId || !token) return; - const params = new URLSearchParams({ limit: "50" }); - if (before) params.set("before", before); + const params = new URLSearchParams({ limit: "50" }); + if (before) params.set("before", before); - const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, { - headers: { Authorization: `Bearer ${token}` }, - }); + const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, { + headers: { Authorization: `Bearer ${token}` }, + }); - if (!res.ok) return; + if (!res.ok) return; - const data = await res.json() as { messages: RawApiMessage[]; hasMore: boolean }; - const normalized = data.messages.map(normalizeMessage); - setHasMoreMessages(data.hasMore); + const data = (await res.json()) as { messages: RawApiMessage[]; hasMore: boolean }; + const normalized = data.messages.map(normalizeMessage); + setHasMoreMessages(data.hasMore); - if (before) { - // Prepend older messages - setMessages((prev) => [...normalized, ...prev]); - } else { - // Initial load - setMessages(normalized); - } - }, [channelId, token]); + if (before) { + // Prepend older messages + setMessages((prev) => [...normalized, ...prev]); + } else { + // Initial load + setMessages(normalized); + } + }, + [channelId, token] + ); // Load more (pagination) const loadMoreMessages = useCallback(() => { @@ -116,13 +126,16 @@ export function useChat(channelId: string | undefined) { if (withoutOptimistic.some((m) => m.id === msg.id)) { return withoutOptimistic; } - return [...withoutOptimistic, { - id: msg.id, - userId: msg.userId, - text: msg.text, - createdAt: msg.createdAt, - clientId: msg.clientId, - }]; + return [ + ...withoutOptimistic, + { + id: msg.id, + userId: msg.userId, + text: msg.text, + createdAt: msg.createdAt, + clientId: msg.clientId, + }, + ]; }); break; @@ -130,7 +143,9 @@ export function useChat(channelId: string | undefined) { if (msg.userId === session?.user?.id) break; setTypingUsers((prev) => msg.isTyping - ? prev.includes(msg.userId) ? prev : [...prev, msg.userId] + ? prev.includes(msg.userId) + ? prev + : [...prev, msg.userId] : prev.filter((id) => id !== msg.userId) ); break; @@ -138,7 +153,9 @@ export function useChat(channelId: string | undefined) { case "presence.update": setOnlineUsers((prev) => msg.status === "online" - ? prev.includes(msg.userId) ? prev : [...prev, msg.userId] + ? prev.includes(msg.userId) + ? prev + : [...prev, msg.userId] : prev.filter((id) => id !== msg.userId) ); break; @@ -182,33 +199,36 @@ export function useChat(channelId: string | undefined) { }, [channelId, token, fetchHistory]); // Send message - const sendMessage = useCallback((text: string) => { - if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return; + const sendMessage = useCallback( + (text: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return; - const clientId = crypto.randomUUID(); + const clientId = crypto.randomUUID(); - // Optimistic update - setMessages((prev) => [ - ...prev, - { - id: `optimistic-${clientId}`, - userId: session?.user?.id ?? "", - text, - createdAt: new Date().toISOString(), - clientId, - optimistic: true, - }, - ]); + // Optimistic update + setMessages((prev) => [ + ...prev, + { + id: `optimistic-${clientId}`, + userId: session?.user?.id ?? "", + text, + createdAt: new Date().toISOString(), + clientId, + optimistic: true, + }, + ]); - wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId })); + wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId })); - // Stop typing when sending - if (isTypingRef.current) { - wsRef.current.send(JSON.stringify({ type: "typing.stop" })); - isTypingRef.current = false; - clearTimeout(typingTimerRef.current); - } - }, [session?.user?.id]); + // Stop typing when sending + if (isTypingRef.current) { + wsRef.current.send(JSON.stringify({ type: "typing.stop" })); + isTypingRef.current = false; + clearTimeout(typingTimerRef.current); + } + }, + [session?.user?.id] + ); // Typing indicator const sendTyping = useCallback(() => { diff --git a/packages/tablo-views/src/hooks/useChatUnread.ts b/packages/tablo-views/src/hooks/useChatUnread.ts index ff7f806..0f3a2c8 100644 --- a/packages/tablo-views/src/hooks/useChatUnread.ts +++ b/packages/tablo-views/src/hooks/useChatUnread.ts @@ -19,7 +19,7 @@ export function useChatUnread() { headers: { Authorization: `Bearer ${token}` }, }); if (!res.ok) return []; - const json = await res.json() as { unread: UnreadCount[] }; + const json = (await res.json()) as { unread: UnreadCount[] }; return json.unread; }, enabled: !!token, diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index ab47c35..6e5a8f2 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -1,32 +1,29 @@ -export { TabloTasksSection } from "./TabloTasksSection"; -export { TabloFilesSection } from "./TabloFilesSection"; -export { TabloDiscussionSection } from "./TabloDiscussionSection"; -export { TabloEventsSection } from "./TabloEventsSection"; -export { EtapesSection } from "./EtapesSection"; -export { RoadmapSection } from "./RoadmapSection"; -export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; -export { TabloDetailsShell } from "./TabloDetailsShell"; -export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; -export { SingleTabloView } from "./single-tablo/SingleTabloView"; +// Sub-components +export { GanttChart } from "./components/gantt/GanttChart"; +export { KanbanBoard } from "./components/kanban/KanbanBoard"; +export { TaskModal } from "./components/kanban/TaskModal"; +// Types +export type { TabloMember } from "./components/kanban/types"; +export { EtapesSection } from "./EtapesSection"; +// Hooks +export { useChat } from "./hooks/useChat"; +export { useChatUnread } from "./hooks/useChatUnread"; +export { RoadmapSection } from "./RoadmapSection"; +export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; export { DEFAULT_OVERVIEW_LAYOUT, sanitizeOverviewLayout, } from "./single-tablo/overviewLayout"; -export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; export { moveBetweenZones, moveWithinZone } from "./single-tablo/overviewReorder"; -export { getSingleTabloStatusConfig } from "./single-tablo/shared"; +export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; +export { SingleTabloView } from "./single-tablo/SingleTabloView"; export type { SingleTabloTabId } from "./single-tablo/shared"; - -// Sub-components -export { GanttChart } from "./components/gantt/GanttChart"; -export { TaskModal } from "./components/kanban/TaskModal"; -export { KanbanBoard } from "./components/kanban/KanbanBoard"; - -// Hooks -export { useChat } from "./hooks/useChat"; -export { useChatUnread } from "./hooks/useChatUnread"; - -// Types -export type { TabloMember } from "./components/kanban/types"; +export { getSingleTabloStatusConfig } from "./single-tablo/shared"; export type { TabloDetailsShellMetadataItem, TabloDetailsShellTab } from "./TabloDetailsShell"; +export { TabloDetailsShell } from "./TabloDetailsShell"; +export { TabloDiscussionSection } from "./TabloDiscussionSection"; +export { TabloEventsSection } from "./TabloEventsSection"; +export { TabloFilesSection } from "./TabloFilesSection"; +export { TabloHeaderActions } from "./TabloHeaderActions"; +export { TabloTasksSection } from "./TabloTasksSection"; diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index a5646a9..e78262a 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -1,7 +1,13 @@ import { cn } from "@xtablo/shared"; import type { KanbanTask } from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; -import { FileIcon, GripVerticalIcon, LayoutPanelTopIcon, ListChecksIcon, RotateCcwIcon } from "lucide-react"; +import { + FileIcon, + GripVerticalIcon, + LayoutPanelTopIcon, + ListChecksIcon, + RotateCcwIcon, +} from "lucide-react"; import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout"; interface DraggedBlock { @@ -170,7 +176,12 @@ export function SingleTabloOverview({ )) )} {personalTaskCount > 5 && ( - )} @@ -231,11 +242,7 @@ export function SingleTabloOverview({ const block = renderBlockContent(blockId); return ( -
onBlockDrop(zone, index)} - > +
onBlockDrop(zone, index)}> Date: Sun, 19 Apr 2026 18:07:24 +0200 Subject: [PATCH 34/44] Remove label --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3fcca40..0ab814a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,6 @@ jobs: - self-hosted - linux - x64 - - xtablo-runner timeout-minutes: 45 From dd71653ad5ef28e42ad58279c5366ab1b94de18f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:31:13 +0200 Subject: [PATCH 35/44] ci: reduce workflow parallelism for self-hosted runner --- .github/workflows/ci.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ab814a..d917eb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,33 +23,33 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v5 with: version: 10.19.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version: 20 cache: pnpm - name: Install dependencies - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --child-concurrency=2 - name: Lint - run: pnpm lint + run: pnpm turbo run lint --concurrency=2 - name: Typecheck - run: pnpm typecheck + run: pnpm turbo run typecheck --concurrency=1 - name: Test main app - run: pnpm --filter @xtablo/main test + run: pnpm --filter @xtablo/main test -- --maxWorkers=1 --no-file-parallelism - name: Test clients app - run: pnpm --filter @xtablo/clients test + run: pnpm --filter @xtablo/clients test -- --maxWorkers=1 --no-file-parallelism - name: Typecheck API run: pnpm --filter @xtablo/api typecheck From 901c54169c12cef5351fc4f0d26da16bb5da4e10 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:50:27 +0200 Subject: [PATCH 36/44] fix: keep client test helpers compatible with es2020 --- apps/clients/src/test/testHelpers.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index 51ae585..fbbcf44 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -31,7 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; + const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); From 5d7dbc95fc461b45cbe984b6d448821424668a13 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 19:24:47 +0200 Subject: [PATCH 37/44] Use ES2022 in apps/clients --- apps/clients/src/test/testHelpers.tsx | 2 +- apps/clients/tsconfig.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index fbbcf44..51ae585 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -31,7 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") ? options.testUser : defaultUser; + const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index 2431c00..f763816 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { - "target": "ES2020", + "target": "ES2022", "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], + "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client"], "module": "ESNext", "skipLibCheck": true, From 246755d7c4dbd4c756d62ddb60ed794d28ee8f15 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:35:42 +0200 Subject: [PATCH 38/44] Fix react rendering issue --- apps/api/README.md | 51 +++ apps/main/src/pages/planning.test.tsx | 145 ++++++++ apps/main/src/pages/planning.tsx | 466 +++++++++++++------------- 3 files changed, 433 insertions(+), 229 deletions(-) create mode 100644 apps/main/src/pages/planning.test.tsx diff --git a/apps/api/README.md b/apps/api/README.md index cfb930a..124ccb9 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -88,3 +88,54 @@ See `.env.example` for required environment variables. ## Deployment The API is deployed to Google Cloud Run. See `cloudbuild.yaml` for deployment configuration. + +## Dokploy Deployment + +Prefer a Dokploy `Application` instead of a Compose service. + +Dokploy supports Dockerfile-based applications directly, which fits this API better than maintaining a dedicated compose wrapper. Configure the application like this: + +- Build Type: `Dockerfile` +- Dockerfile Path: `apps/api/Dockerfile` +- Docker Context Path: `.` +- Docker Build Stage: `final` +- Port: `8080` +- Run Command: leave empty and use the image `CMD` + +Set these Dokploy environment variables: + +- `NODE_ENV` +- `DD_SERVICE=xtablo-api` +- `DD_ENV` +- `DD_VERSION` +- `DD_LOGS_INJECTION=true` +- `SUPABASE_URL` +- `SUPABASE_SERVICE_ROLE_KEY` +- `SUPABASE_CONNECTION_STRING` +- `SUPABASE_CA_CERT` +- `STRIPE_SECRET_KEY` +- `STRIPE_WEBHOOK_SECRET` +- `STRIPE_SOLO_PRICE_ID` +- `STRIPE_TEAM_PRICE_ID` +- `STRIPE_FOUNDER_PRICE_ID` +- `EMAIL_USER` +- `EMAIL_CLIENT_ID` +- `EMAIL_CLIENT_SECRET` +- `EMAIL_REFRESH_TOKEN` +- `R2_ACCOUNT_ID` +- `R2_ACCESS_KEY_ID` +- `R2_SECRET_ACCESS_KEY` +- `TASKS_SECRET` + +For Datadog logs, the Dokploy host should already run a Datadog Agent with Docker log collection enabled. Then add these Docker Swarm labels in Dokploy `Advanced Settings -> Swarm Settings -> Labels`: + +- `com.datadoghq.tags.service=xtablo-api` +- `com.datadoghq.tags.env=${DD_ENV}` +- `com.datadoghq.tags.version=${DD_VERSION}` +- `com.datadoghq.ad.logs=[{"source":"nodejs","service":"xtablo-api"}]` + +This gives you: + +- container logs in Datadog with `source: nodejs` +- service tagging as `xtablo-api` +- APM/log correlation via `dd-trace` plus `DD_LOGS_INJECTION=true` diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx new file mode 100644 index 0000000..d4bf8f6 --- /dev/null +++ b/apps/main/src/pages/planning.test.tsx @@ -0,0 +1,145 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, render, screen, waitFor } from "@testing-library/react"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import { I18nextProvider } from "react-i18next"; +import { createMemoryRouter, RouterProvider } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import testI18n from "../i18n.test"; +import { TestUserStoreProvider, type User } from "../providers/UserStoreProvider"; +import { PlanningPage } from "./planning"; + +vi.mock("../hooks/events", () => ({ + useDeleteEvent: () => ({ mutate: vi.fn(), isPending: false }), + useEventsByTablo: () => ({ + data: [ + { + event_id: "event-1", + tablo_id: "tablo-1", + tablo_name: "Tablo Alpha", + tablo_color: "bg-blue-500", + start_date: "2026-04-22", + start_time: "09:00:00", + end_time: "10:00:00", + title: "Kickoff", + description: "Planning event", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tablos", () => ({ + useGetAllTabloAccess: () => ({ + data: [{ tablo_id: "tablo-1", is_admin: true }], + }), + useTablosList: () => ({ + data: [{ id: "tablo-1", name: "Tablo Alpha" }], + isLoading: false, + }), +})); + +vi.mock("../providers/UserStoreProvider", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useIsReadOnlyUser: () => false, + }; +}); + +vi.mock("../components/EventModal", () => ({ + EventModal: () =>
, +})); + +const testUser: User = { + id: "user-1", + short_user_id: "u1", + name: "John Doe", + first_name: "John", + last_name: "Doe", + email: "john@example.com", + avatar_url: null, + is_temporary: false, + is_client: false, + client_onboarded_at: null, + last_signed_in: null, + plan: "none", + created_at: new Date("2026-01-01").toISOString(), +}; + +const createTestRouter = (initialEntry: string) => + createMemoryRouter( + [ + { + path: "/planning", + element: , + }, + { + path: "/tasks", + element:
Tasks page
, + }, + ], + { initialEntries: [initialEntry] } + ); + +const renderPlanningRouter = (initialEntry: string) => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + const router = createTestRouter(initialEntry); + + return { + router, + ...render( + + + + + + + + + + + + ), + }; +}; + +describe("PlanningPage", () => { + beforeEach(() => { + testI18n.changeLanguage("fr"); + }); + + it("does not throw when leaving the planning page from the events tab", async () => { + const { router } = renderPlanningRouter("/planning?tab=events"); + + expect(screen.getByText("Événements")).toBeInTheDocument(); + + await act(async () => { + await expect(router.navigate("/tasks")).resolves.toBeUndefined(); + }); + + await waitFor(() => { + expect(screen.getByText("Tasks page")).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/main/src/pages/planning.tsx b/apps/main/src/pages/planning.tsx index 58ea4f4..e5e7d38 100644 --- a/apps/main/src/pages/planning.tsx +++ b/apps/main/src/pages/planning.tsx @@ -1055,254 +1055,262 @@ export const PlanningPage = () => { ); }; - if (currentTab === "events") { - return ( -
- {renderEventsView()} - setIsCreateEventOpen(false)} - defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} - defaultDate={currentDate} - /> - -
- ); - } - return (
-
- {/* Sidebar */} -
-
- {/* Tablo Selector */} -
- setSelectedTabloId(value)} + disabled={tablosLoading} + > + + + + + {t("planning:allTablos")} + {tablos?.map((tablo) => ( + + {tablo.name} + + ))} + + +
+ + + + + +
- - - - - -
- - {/* Mini Calendar */} -
-
- {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()} -
-
- {dayNamesShort.map((day) => ( -
- {day.slice(0, 1)} -
- ))} - {getDaysInMonth(currentDate).map((day, index) => ( -
{ - if (day) { - navigateToCreateEvent(day, selectedTabloId); - } - }} - > - {day ? day.getDate() : ""} -
- ))} -
-
-
- - {/* Main Content */} -
- {/* Header */} -
-
-
- {t("planning:title")} - -
- - -
- {getViewTitle()} + {/* Mini Calendar */} +
+
+ {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
+
+ {dayNamesShort.map((day) => ( +
+ {day.slice(0, 1)} +
+ ))} + {getDaysInMonth(currentDate).map((day, index) => ( +
{ + if (day) { + navigateToCreateEvent(day, selectedTabloId); + } + }} + > + {day ? day.getDate() : ""} +
+ ))} +
+
+
-
- -
- {(["month", "week", "day"] as ViewType[]).map((view) => ( - +
+ - ))} + +
+ {getViewTitle()} +
+ +
+ +
+ {(["month", "week", "day"] as ViewType[]).map((view) => ( + + ))} +
-
- {/* Calendar Views */} -
- {tabloEventsLoading ? ( -
- Loading... - {t("planning:loadingEvents")} -
- ) : ( - <> - {currentView === "month" && renderMonthView()} - {currentView === "week" && renderWeekView()} - {currentView === "day" && renderDayView()} - - )} + {/* Calendar Views */} +
+ {tabloEventsLoading ? ( +
+ Loading... + {t("planning:loadingEvents")} +
+ ) : ( + <> + {currentView === "month" && renderMonthView()} + {currentView === "week" && renderWeekView()} + {currentView === "day" && renderDayView()} + + )} +
-
+ )} + + setIsCreateEventOpen(false)} + defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} + defaultDate={currentDate} + /> {isImportModalOpen && setIsImportModalOpen(false)} />} - + {isWebcalModalOpen && ( + + )}
); }; From fd5137e91e1ecf1ae455feeaa676faa8cae4ab2d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:35:42 +0200 Subject: [PATCH 39/44] Fix react rendering issue --- apps/api/README.md | 51 +++ apps/main/src/pages/planning.test.tsx | 145 ++++++++ apps/main/src/pages/planning.tsx | 466 +++++++++++++------------- 3 files changed, 433 insertions(+), 229 deletions(-) create mode 100644 apps/main/src/pages/planning.test.tsx diff --git a/apps/api/README.md b/apps/api/README.md index cfb930a..124ccb9 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -88,3 +88,54 @@ See `.env.example` for required environment variables. ## Deployment The API is deployed to Google Cloud Run. See `cloudbuild.yaml` for deployment configuration. + +## Dokploy Deployment + +Prefer a Dokploy `Application` instead of a Compose service. + +Dokploy supports Dockerfile-based applications directly, which fits this API better than maintaining a dedicated compose wrapper. Configure the application like this: + +- Build Type: `Dockerfile` +- Dockerfile Path: `apps/api/Dockerfile` +- Docker Context Path: `.` +- Docker Build Stage: `final` +- Port: `8080` +- Run Command: leave empty and use the image `CMD` + +Set these Dokploy environment variables: + +- `NODE_ENV` +- `DD_SERVICE=xtablo-api` +- `DD_ENV` +- `DD_VERSION` +- `DD_LOGS_INJECTION=true` +- `SUPABASE_URL` +- `SUPABASE_SERVICE_ROLE_KEY` +- `SUPABASE_CONNECTION_STRING` +- `SUPABASE_CA_CERT` +- `STRIPE_SECRET_KEY` +- `STRIPE_WEBHOOK_SECRET` +- `STRIPE_SOLO_PRICE_ID` +- `STRIPE_TEAM_PRICE_ID` +- `STRIPE_FOUNDER_PRICE_ID` +- `EMAIL_USER` +- `EMAIL_CLIENT_ID` +- `EMAIL_CLIENT_SECRET` +- `EMAIL_REFRESH_TOKEN` +- `R2_ACCOUNT_ID` +- `R2_ACCESS_KEY_ID` +- `R2_SECRET_ACCESS_KEY` +- `TASKS_SECRET` + +For Datadog logs, the Dokploy host should already run a Datadog Agent with Docker log collection enabled. Then add these Docker Swarm labels in Dokploy `Advanced Settings -> Swarm Settings -> Labels`: + +- `com.datadoghq.tags.service=xtablo-api` +- `com.datadoghq.tags.env=${DD_ENV}` +- `com.datadoghq.tags.version=${DD_VERSION}` +- `com.datadoghq.ad.logs=[{"source":"nodejs","service":"xtablo-api"}]` + +This gives you: + +- container logs in Datadog with `source: nodejs` +- service tagging as `xtablo-api` +- APM/log correlation via `dd-trace` plus `DD_LOGS_INJECTION=true` diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx new file mode 100644 index 0000000..d4bf8f6 --- /dev/null +++ b/apps/main/src/pages/planning.test.tsx @@ -0,0 +1,145 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, render, screen, waitFor } from "@testing-library/react"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import { I18nextProvider } from "react-i18next"; +import { createMemoryRouter, RouterProvider } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import testI18n from "../i18n.test"; +import { TestUserStoreProvider, type User } from "../providers/UserStoreProvider"; +import { PlanningPage } from "./planning"; + +vi.mock("../hooks/events", () => ({ + useDeleteEvent: () => ({ mutate: vi.fn(), isPending: false }), + useEventsByTablo: () => ({ + data: [ + { + event_id: "event-1", + tablo_id: "tablo-1", + tablo_name: "Tablo Alpha", + tablo_color: "bg-blue-500", + start_date: "2026-04-22", + start_time: "09:00:00", + end_time: "10:00:00", + title: "Kickoff", + description: "Planning event", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tablos", () => ({ + useGetAllTabloAccess: () => ({ + data: [{ tablo_id: "tablo-1", is_admin: true }], + }), + useTablosList: () => ({ + data: [{ id: "tablo-1", name: "Tablo Alpha" }], + isLoading: false, + }), +})); + +vi.mock("../providers/UserStoreProvider", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useIsReadOnlyUser: () => false, + }; +}); + +vi.mock("../components/EventModal", () => ({ + EventModal: () =>
, +})); + +const testUser: User = { + id: "user-1", + short_user_id: "u1", + name: "John Doe", + first_name: "John", + last_name: "Doe", + email: "john@example.com", + avatar_url: null, + is_temporary: false, + is_client: false, + client_onboarded_at: null, + last_signed_in: null, + plan: "none", + created_at: new Date("2026-01-01").toISOString(), +}; + +const createTestRouter = (initialEntry: string) => + createMemoryRouter( + [ + { + path: "/planning", + element: , + }, + { + path: "/tasks", + element:
Tasks page
, + }, + ], + { initialEntries: [initialEntry] } + ); + +const renderPlanningRouter = (initialEntry: string) => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + const router = createTestRouter(initialEntry); + + return { + router, + ...render( + + + + + + + + + + + + ), + }; +}; + +describe("PlanningPage", () => { + beforeEach(() => { + testI18n.changeLanguage("fr"); + }); + + it("does not throw when leaving the planning page from the events tab", async () => { + const { router } = renderPlanningRouter("/planning?tab=events"); + + expect(screen.getByText("Événements")).toBeInTheDocument(); + + await act(async () => { + await expect(router.navigate("/tasks")).resolves.toBeUndefined(); + }); + + await waitFor(() => { + expect(screen.getByText("Tasks page")).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/main/src/pages/planning.tsx b/apps/main/src/pages/planning.tsx index 58ea4f4..e5e7d38 100644 --- a/apps/main/src/pages/planning.tsx +++ b/apps/main/src/pages/planning.tsx @@ -1055,254 +1055,262 @@ export const PlanningPage = () => { ); }; - if (currentTab === "events") { - return ( -
- {renderEventsView()} - setIsCreateEventOpen(false)} - defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} - defaultDate={currentDate} - /> - -
- ); - } - return (
-
- {/* Sidebar */} -
-
- {/* Tablo Selector */} -
- setSelectedTabloId(value)} + disabled={tablosLoading} + > + + + + + {t("planning:allTablos")} + {tablos?.map((tablo) => ( + + {tablo.name} + + ))} + + +
+ + + + + +
- - - - - -
- - {/* Mini Calendar */} -
-
- {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()} -
-
- {dayNamesShort.map((day) => ( -
- {day.slice(0, 1)} -
- ))} - {getDaysInMonth(currentDate).map((day, index) => ( -
{ - if (day) { - navigateToCreateEvent(day, selectedTabloId); - } - }} - > - {day ? day.getDate() : ""} -
- ))} -
-
-
- - {/* Main Content */} -
- {/* Header */} -
-
-
- {t("planning:title")} - -
- - -
- {getViewTitle()} + {/* Mini Calendar */} +
+
+ {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
+
+ {dayNamesShort.map((day) => ( +
+ {day.slice(0, 1)} +
+ ))} + {getDaysInMonth(currentDate).map((day, index) => ( +
{ + if (day) { + navigateToCreateEvent(day, selectedTabloId); + } + }} + > + {day ? day.getDate() : ""} +
+ ))} +
+
+
-
- -
- {(["month", "week", "day"] as ViewType[]).map((view) => ( - +
+ - ))} + +
+ {getViewTitle()} +
+ +
+ +
+ {(["month", "week", "day"] as ViewType[]).map((view) => ( + + ))} +
-
- {/* Calendar Views */} -
- {tabloEventsLoading ? ( -
- Loading... - {t("planning:loadingEvents")} -
- ) : ( - <> - {currentView === "month" && renderMonthView()} - {currentView === "week" && renderWeekView()} - {currentView === "day" && renderDayView()} - - )} + {/* Calendar Views */} +
+ {tabloEventsLoading ? ( +
+ Loading... + {t("planning:loadingEvents")} +
+ ) : ( + <> + {currentView === "month" && renderMonthView()} + {currentView === "week" && renderWeekView()} + {currentView === "day" && renderDayView()} + + )} +
-
+ )} + + setIsCreateEventOpen(false)} + defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} + defaultDate={currentDate} + /> {isImportModalOpen && setIsImportModalOpen(false)} />} - + {isWebcalModalOpen && ( + + )}
); }; From 3c90ba232cea8b9d51fbfdc23b4de9931a6e83ae Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:39:13 +0200 Subject: [PATCH 40/44] fix test --- apps/main/src/pages/planning.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx index d4bf8f6..c3ba6c0 100644 --- a/apps/main/src/pages/planning.test.tsx +++ b/apps/main/src/pages/planning.test.tsx @@ -61,7 +61,6 @@ const testUser: User = { avatar_url: null, is_temporary: false, is_client: false, - client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date("2026-01-01").toISOString(), From 222c61339f51fb573b199fa73543755fadcb9e60 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 22:13:30 +0200 Subject: [PATCH 41/44] feat: add datadog frontend sourcemap uploads --- .github/workflows/frontend-sourcemaps.yml | 74 +++ apps/clients/src/setupTests.ts | 34 +- apps/clients/src/vite-env.d.ts | 9 + apps/clients/src/viteConfig.test.ts | 13 + apps/clients/vite.config.ts | 3 + apps/external/package.json | 1 + apps/external/src/setupTests.ts | 1 + apps/external/src/vite-env.d.ts | 8 + apps/external/src/viteConfig.test.ts | 13 + apps/external/vite.config.ts | 7 +- apps/main/src/lib/rum.test.ts | 35 ++ apps/main/src/lib/rum.ts | 3 +- apps/main/src/setupTests.ts | 36 +- apps/main/src/vite-env.d.ts | 8 + apps/main/src/viteConfig.test.ts | 13 + apps/main/vite.config.ts | 3 + ...026-04-22-datadog-rum-sourcemaps-via-ci.md | 467 ++++++++++++++++ ...22-datadog-rum-sourcemaps-via-ci-design.md | 99 ++++ package.json | 1 + pnpm-lock.yaml | 502 +++++++++++++++++- 20 files changed, 1290 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/frontend-sourcemaps.yml create mode 100644 apps/clients/src/vite-env.d.ts create mode 100644 apps/clients/src/viteConfig.test.ts create mode 100644 apps/external/src/setupTests.ts create mode 100644 apps/external/src/viteConfig.test.ts create mode 100644 apps/main/src/lib/rum.test.ts create mode 100644 apps/main/src/viteConfig.test.ts create mode 100644 docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md create mode 100644 docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml new file mode 100644 index 0000000..38247ee --- /dev/null +++ b/.github/workflows/frontend-sourcemaps.yml @@ -0,0 +1,74 @@ +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - name: Check out repository + uses: actions/checkout@v6 + + - name: Set up pnpm + uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Validate Datadog secrets + run: | + test -n "$DATADOG_API_KEY" + test -n "$DATADOG_SITE" + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 23c7532..bfff6cc 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -13,19 +13,23 @@ global.ResizeObserver = class ResizeObserver { disconnect() {} }; -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/clients/src/vite-env.d.ts b/apps/clients/src/vite-env.d.ts new file mode 100644 index 0000000..f9164af --- /dev/null +++ b/apps/clients/src/vite-env.d.ts @@ -0,0 +1,9 @@ +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts new file mode 100644 index 0000000..5583270 --- /dev/null +++ b/apps/clients/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 7b36df3..8d83ea9 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -13,6 +13,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false }, define: process.env.VITEST ? { diff --git a/apps/external/package.json b/apps/external/package.json index b93d5b1..fa37897 100644 --- a/apps/external/package.json +++ b/apps/external/package.json @@ -27,6 +27,7 @@ "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/external/src/setupTests.ts b/apps/external/src/setupTests.ts new file mode 100644 index 0000000..3115856 --- /dev/null +++ b/apps/external/src/setupTests.ts @@ -0,0 +1 @@ +// Intentionally minimal test setup so Vitest can honor the configured setupFiles path. diff --git a/apps/external/src/vite-env.d.ts b/apps/external/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/external/src/vite-env.d.ts +++ b/apps/external/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts new file mode 100644 index 0000000..b3831b7 --- /dev/null +++ b/apps/external/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/external/vite.config.ts b/apps/external/vite.config.ts index 8bd72da..c4f1e6b 100644 --- a/apps/external/vite.config.ts +++ b/apps/external/vite.config.ts @@ -3,13 +3,9 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import tailwindcss from "@tailwindcss/vite"; import react from "@vitejs/plugin-react"; -import { dirname } from "path"; -import { fileURLToPath } from "url"; import { defineConfig, PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; -const __dirname = dirname(fileURLToPath(import.meta.url)); - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const plugins: PluginOption[] = [ @@ -26,6 +22,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/apps/main/src/lib/rum.test.ts b/apps/main/src/lib/rum.test.ts new file mode 100644 index 0000000..f468c19 --- /dev/null +++ b/apps/main/src/lib/rum.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); diff --git a/apps/main/src/lib/rum.ts b/apps/main/src/lib/rum.ts index 948e6f2..e2a49ca 100644 --- a/apps/main/src/lib/rum.ts +++ b/apps/main/src/lib/rum.ts @@ -13,9 +13,8 @@ datadogRum.init({ site: "datadoghq.com", service: "xtablo-ui", env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, - // Specify a version number to identify the deployed version of your application in Datadog - // version: '1.0.0', sessionSampleRate: 100, sessionReplaySampleRate: 80, defaultPrivacyLevel: "mask-user-input", diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 1fa4e83..36149d2 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -21,20 +21,24 @@ global.ResizeObserver = class ResizeObserver { } }; -// Mock scrollIntoView for Radix UI components -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +// Mock scroll APIs for DOM-oriented tests without breaking node-environment suites. +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), // deprecated - removeListener: vi.fn(), // deprecated - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), // deprecated + removeListener: vi.fn(), // deprecated + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/main/src/vite-env.d.ts b/apps/main/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/main/src/vite-env.d.ts +++ b/apps/main/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts new file mode 100644 index 0000000..3a15668 --- /dev/null +++ b/apps/main/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/main/vite.config.ts b/apps/main/vite.config.ts index 59e1e45..10802fc 100644 --- a/apps/main/vite.config.ts +++ b/apps/main/vite.config.ts @@ -43,6 +43,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md new file mode 100644 index 0000000..ac7edbd --- /dev/null +++ b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md @@ -0,0 +1,467 @@ +# Datadog RUM Sourcemaps Via CI Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Generate private frontend sourcemaps for Datadog RUM/Error Tracking, upload them from GitHub Actions, and keep `.map` files out of deployed frontend assets. + +**Architecture:** Add an explicit release-version contract to the main app’s RUM init, enable hidden sourcemaps in all Vite frontends, and create a frontend CI workflow that builds each app, uploads sourcemaps with matching Datadog metadata, and removes `.map` files before any deploy step consumes the build output. + +**Tech Stack:** React 19, Vite 6, Vitest, GitHub Actions, Datadog CI CLI, Cloudflare/Wrangler deploy targets, pnpm workspaces. + +**Spec:** `docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md` + +--- + +## File Structure + +### New files + +- `.github/workflows/frontend-sourcemaps.yml` — GitHub Actions workflow that builds the frontend apps on a self-hosted runner and uploads sourcemaps to Datadog. +- `apps/clients/src/vite-env.d.ts` — Vite env typings for client-specific build variables, including `VITE_APP_VERSION`. +- `apps/main/src/lib/rum.test.ts` — regression test for Datadog RUM init config. +- `apps/main/vite.config.test.ts` — production sourcemap config test for `apps/main`. +- `apps/clients/vite.config.test.ts` — production sourcemap config test for `apps/clients`. +- `apps/external/vite.config.test.ts` — production sourcemap config test for `apps/external`. + +### Modified files + +- `package.json` — add `@datadog/datadog-ci` to root dev dependencies. +- `apps/main/src/lib/rum.ts` — add `version: import.meta.env.VITE_APP_VERSION`. +- `apps/main/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/external/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/main/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/clients/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/external/vite.config.ts` — enable hidden sourcemaps for non-test builds. + +--- + +## Chunk 1: Runtime Release Metadata + +### Task 1: Wire Datadog RUM version in `apps/main` + +**Files:** +- Create: `apps/main/src/lib/rum.test.ts` +- Modify: `apps/main/src/lib/rum.ts` +- Modify: `apps/main/src/vite-env.d.ts` + +- [ ] **Step 1: Write the failing RUM init test** + +Create `apps/main/src/lib/rum.test.ts`: + +```typescript +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +``` + +Expected: FAIL because `version` is not set in `datadogRum.init`. + +- [ ] **Step 3: Add the runtime version** + +Update `apps/main/src/lib/rum.ts`: + +```typescript + service: "xtablo-ui", + env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, +``` + +Update `apps/main/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 4: Run the test to verify it passes** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add apps/main/src/lib/rum.ts apps/main/src/lib/rum.test.ts apps/main/src/vite-env.d.ts +git commit -m "feat: add Datadog release version to main rum config" +``` + +--- + +## Chunk 2: Hidden Sourcemaps In All Vite Frontends + +### Task 2: Add production sourcemap config tests + +**Files:** +- Create: `apps/main/vite.config.test.ts` +- Create: `apps/clients/vite.config.test.ts` +- Create: `apps/external/vite.config.test.ts` + +- [ ] **Step 1: Write the failing config test for `apps/main`** + +Create `apps/main/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 2: Write the failing config test for `apps/clients`** + +Create `apps/clients/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 3: Write the failing config test for `apps/external`** + +Create `apps/external/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 4: Run the tests to verify they fail** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +``` + +Expected: FAIL because `build.sourcemap` is not configured. + +- [ ] **Step 5: Implement hidden sourcemaps in all three Vite configs** + +Update: +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Add the same build section in each returned config: + +```typescript + build: { + sourcemap: mode === "test" ? false : "hidden", + }, +``` + +Keep it alongside the existing `plugins`, `server`, `define`, and `test` sections. + +- [ ] **Step 6: Add env typing for the remaining apps** + +Create `apps/clients/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +Update `apps/external/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 7: Run the tests and typechecks** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 8: Commit** + +```bash +git add apps/main/vite.config.ts apps/main/vite.config.test.ts apps/clients/vite.config.ts apps/clients/vite.config.test.ts apps/clients/src/vite-env.d.ts apps/external/vite.config.ts apps/external/vite.config.test.ts apps/external/src/vite-env.d.ts +git commit -m "build: enable hidden sourcemaps for frontend apps" +``` + +--- + +## Chunk 3: Datadog CI Upload Workflow + +### Task 3: Add pinned Datadog CLI and frontend sourcemap workflow + +**Files:** +- Create: `.github/workflows/frontend-sourcemaps.yml` +- Modify: `package.json` + +- [ ] **Step 1: Add the Datadog CLI dependency** + +Update root `package.json`: + +```json + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^3.21.0", + "turbo": "^2.5.8", + "typescript": "^5.7.0" + } +``` + +- [ ] **Step 2: Install dependencies and verify lockfile changes** + +Run: + +```bash +pnpm install +``` + +Expected: `pnpm-lock.yaml` updates with `@datadog/datadog-ci`. + +- [ ] **Step 3: Create the workflow** + +Create `.github/workflows/frontend-sourcemaps.yml`: + +```yaml +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete +``` + +- [ ] **Step 4: Validate the workflow file structure** + +Run: + +```bash +rg -n "datadog-ci sourcemaps upload|RELEASE_VERSION|find .*\\.map" .github/workflows/frontend-sourcemaps.yml +``` + +Expected: one upload and one cleanup step for each frontend app. + +- [ ] **Step 5: Commit** + +```bash +git add package.json pnpm-lock.yaml .github/workflows/frontend-sourcemaps.yml +git commit -m "ci: upload frontend sourcemaps to Datadog" +``` + +--- + +## Chunk 4: End-To-End Verification + +### Task 4: Prove builds emit hidden sourcemaps and cleanup works + +**Files:** +- No new source files + +- [ ] **Step 1: Build each frontend locally with a release version** + +Run: + +```bash +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/main build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/clients build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/external build +``` + +Expected: each `dist/` contains built assets and `.map` files, but the generated JS bundles do not include public `sourceMappingURL` comments. + +- [ ] **Step 2: Verify `.map` files exist before cleanup** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: at least one sourcemap per app. + +- [ ] **Step 3: Simulate CI cleanup locally** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' -delete +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: no output from the second command. + +- [ ] **Step 4: Run the targeted regression suite** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git status --short +``` + +Expected: clean worktree before opening the implementation PR. diff --git a/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md new file mode 100644 index 0000000..6e247b0 --- /dev/null +++ b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md @@ -0,0 +1,99 @@ +# Datadog RUM Sourcemaps Via CI Design + +**Goal:** Deobfuscate frontend RUM and Error Tracking stack traces in Datadog for the Xtablo frontends by generating sourcemaps during build, uploading them in CI, and keeping `.map` files off the public CDN. + +## Current State + +- `apps/main` initializes Datadog RUM in [apps/main/src/lib/rum.ts](/Users/arthur.belleville/Documents/perso/projects/xtablo-source/apps/main/src/lib/rum.ts) with `service: "xtablo-ui"` and `env: import.meta.env.MODE`, but no explicit release version. +- `apps/main`, `apps/clients`, and `apps/external` are Vite frontends with production Cloudflare deployments. +- None of the three Vite configs currently emit production sourcemaps. +- On this branch there is no tracked GitHub Actions workflow yet, so CI wiring must be introduced as part of the implementation. + +## Decision + +Use Datadog’s recommended CI upload flow: + +1. Build each frontend with Vite `build.sourcemap: "hidden"`. +2. Upload generated sourcemaps from CI with `datadog-ci sourcemaps upload`. +3. Use a release version derived from the CI commit SHA. +4. Remove all `.map` files from `dist/` before deploy packaging so they are never publicly served. + +This keeps sourcemaps private while still enabling unminified stack traces in Datadog. + +Sources: +- Datadog CI sourcemap upload guide: https://docs.datadoghq.com/real_user_monitoring/guide/upload-javascript-source-maps/?tab=vite +- Vite `build.sourcemap` docs: https://vite.dev/config/build-options.html + +## Runtime Contract + +Datadog matches sourcemaps against browser events by `service` and `version`. + +- `apps/main` must emit `version: import.meta.env.VITE_APP_VERSION` in its RUM initialization. +- CI must upload sourcemaps for `apps/main` using: + - `service=xtablo-ui` + - `release-version=$GITHUB_SHA` +- `apps/clients` and `apps/external` should use the same CI release version convention now, even though they do not currently emit RUM events. This keeps the deployment contract consistent and avoids another pipeline change when browser monitoring is enabled there. + +## Public Asset Prefixes + +The Datadog upload command must use the real production asset prefixes: + +- `apps/main`: `https://app.xtablo.com/assets` +- `apps/clients`: `https://clients.xtablo.com/assets` +- `apps/external`: `https://embed.xtablo.com/assets` + +These prefixes must match the actual URLs used by the deployed JS bundles. + +## Implementation Shape + +### Frontend code + +- `apps/main/src/lib/rum.ts` + - add `version: import.meta.env.VITE_APP_VERSION` +- `apps/main/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` +- `apps/clients/src/vite-env.d.ts` + - create and declare `VITE_APP_VERSION` +- `apps/external/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` + +### Build config + +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Each should emit hidden sourcemaps for non-test builds. + +### CI + +- Add GitHub Actions workflow for frontend builds on self-hosted runners. +- Add `@datadog/datadog-ci` as a root dev dependency so the workflow can run a pinned CLI version from the repo. +- After each frontend build: + - upload sourcemaps to Datadog + - delete `dist/**/*.map` + +## Secrets And CI Inputs + +The workflow needs: + +- `DATADOG_API_KEY` +- `DATADOG_SITE` +- release version from `github.sha` + +The workflow should fail fast if Datadog secrets are missing on the deployment path where sourcemap upload is required. + +## Verification + +- Unit test for `apps/main` RUM init to assert `version` is wired from env. +- Vite config tests or config assertions for all three apps to verify production builds use `sourcemap: "hidden"`. +- CI workflow smoke verification: + - build the apps + - run sourcemap upload + - confirm `.map` files are removed from `dist` + +## Non-Goals + +- Enabling Datadog RUM in `apps/clients` or `apps/external` right now. +- Serving sourcemaps publicly. +- Changing app deployment hosts or CDN paths. diff --git a/package.json b/package.json index 5366d4f..5dd27ce 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^4.3.0", "turbo": "^2.5.8", "typescript": "^5.7.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e797dbd..68d2284 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: '@biomejs/biome': specifier: 2.2.5 version: 2.2.5 + '@datadog/datadog-ci': + specifier: ^4.3.0 + version: 4.4.0(@types/node@22.18.12) turbo: specifier: ^2.5.8 version: 2.5.8 @@ -89,7 +92,7 @@ importers: version: 2.2.5 '@datadog/datadog-ci-base': specifier: ^4.0.2 - version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@datadog/datadog-ci-plugin-cloud-run': specifier: ^4.0.2 version: 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) @@ -318,6 +321,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) @@ -1944,11 +1950,84 @@ packages: '@datadog/datadog-ci-plugin-synthetics': optional: true + '@datadog/datadog-ci-base@4.4.0': + resolution: {integrity: sha512-sFssfj3EQKBiD9SkVYzhkzHZEQqmnsMGXKYKoLLTFcTmRbaePItx/1Sa3KzFVIWBhZQSpYoJt3VZ7+cagCShLA==} + peerDependencies: + '@datadog/datadog-ci-plugin-aas': 4.4.0 + '@datadog/datadog-ci-plugin-cloud-run': 4.4.0 + '@datadog/datadog-ci-plugin-container-app': 4.4.0 + '@datadog/datadog-ci-plugin-deployment': 4.4.0 + '@datadog/datadog-ci-plugin-dora': 4.4.0 + '@datadog/datadog-ci-plugin-gate': 4.4.0 + '@datadog/datadog-ci-plugin-lambda': 4.4.0 + '@datadog/datadog-ci-plugin-sarif': 4.4.0 + '@datadog/datadog-ci-plugin-sbom': 4.4.0 + '@datadog/datadog-ci-plugin-stepfunctions': 4.4.0 + '@datadog/datadog-ci-plugin-synthetics': 4.4.0 + peerDependenciesMeta: + '@datadog/datadog-ci-plugin-aas': + optional: true + '@datadog/datadog-ci-plugin-cloud-run': + optional: true + '@datadog/datadog-ci-plugin-container-app': + optional: true + '@datadog/datadog-ci-plugin-deployment': + optional: true + '@datadog/datadog-ci-plugin-dora': + optional: true + '@datadog/datadog-ci-plugin-gate': + optional: true + '@datadog/datadog-ci-plugin-lambda': + optional: true + '@datadog/datadog-ci-plugin-sarif': + optional: true + '@datadog/datadog-ci-plugin-sbom': + optional: true + '@datadog/datadog-ci-plugin-stepfunctions': + optional: true + '@datadog/datadog-ci-plugin-synthetics': + optional: true + '@datadog/datadog-ci-plugin-cloud-run@4.1.2': resolution: {integrity: sha512-HKVZ7SSjzskdVqIrf16bqmgeRrxscoRkgh9ILfni3D/GoXpG3DFaZPs7pXJR6igjBeZMclLjtolqMyyWy7DCLQ==} peerDependencies: '@datadog/datadog-ci-base': 4.1.2 + '@datadog/datadog-ci-plugin-deployment@4.4.0': + resolution: {integrity: sha512-u9FtFw2TKRF74wwcuM8tWseWTrLKZZ/Lwq1Fz+LtAGHTJ5675WuIhGNnSxbrKU4f2VsaFp+eUIsetcqbuUerXw==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-dora@4.4.0': + resolution: {integrity: sha512-DuyKfiwxZoNu5dlMPZNq6DYlafR/3kpaqS0q9KfGStnu1LwS5YTREuZgssNkyYWnF6qZN80x1l7E/ubaAFVYOg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-gate@4.4.0': + resolution: {integrity: sha512-bR5AY5p5/5jQuZtcuEPJrEpL1WhJiXhfPwuc9OhGN0ny4/98S3Hg02aQ9aoloFipsBgEN3W5XhrWH6Pn1jSI5w==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sarif@4.4.0': + resolution: {integrity: sha512-kgExnC/ReiGKr9R6SxaXr62lp2fYJQ4i8c9x4/GqDpNbLENQdsqBmxs6h1/N3xkdt3/p3RZlMcAhIytLYDkBAA==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sbom@4.4.0': + resolution: {integrity: sha512-bBsgIBBT0KsWqLcIMuf692PGjMNjG6OKNUjuPZOWbuToyKKnpRRkMDrX9KvUWVXuMKfDEp7i2PYw/2fQm5DXHg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-synthetics@4.4.0': + resolution: {integrity: sha512-SpGdOZUSjEVZZD/hopPKuXnOP6ZRl0nnZ8i5ffVIxohlMwn5y0vMWjjkDohk24M+2QBDUnMe4sNXW4YP1aeSWg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci@4.4.0': + resolution: {integrity: sha512-vpQPcz+FRgDhPoHg9aXtTeaVe6Dhky6q1vG9TmOWDX39Pjf/Wz1LEY94uWvK6miC8orHf6RtIGOSxsycRNde7g==} + engines: {node: '>=18'} + hasBin: true + '@datadog/flagging-core@0.1.0-preview.13': resolution: {integrity: sha512-DfQYeBgGvCerKx6coRiXMt0aXWJB8kRIsJhfdTKyejS9rfp6ZBjWc6dctKzhwMAQdpBiN42MEVXNt4Pdcmj1WA==} peerDependencies: @@ -4999,6 +5078,9 @@ packages: '@types/use-sync-external-store@0.0.6': resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@types/uuid@9.0.8': + resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==} + '@types/whatwg-mimetype@3.0.2': resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} @@ -5298,6 +5380,14 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} @@ -5391,6 +5481,13 @@ packages: resolution: {integrity: sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==} engines: {node: '>=8'} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + + assert-plus@1.0.0: + resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} + engines: {node: '>=0.8'} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -5496,6 +5593,9 @@ packages: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} @@ -5540,6 +5640,10 @@ packages: buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + busboy@1.6.0: resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} engines: {node: '>=10.16.0'} @@ -5737,6 +5841,10 @@ packages: resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==} engines: {node: '>= 0.10'} + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + create-jest@29.7.0: resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -5778,6 +5886,10 @@ packages: csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} + dashdash@1.14.1: + resolution: {integrity: sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==} + engines: {node: '>=0.10'} + data-uri-to-buffer@4.0.1: resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} engines: {node: '>= 12'} @@ -5974,6 +6086,9 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + ecc-jsbn@0.1.2: + resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} + ecdsa-sig-formatter@1.0.11: resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==} @@ -6207,6 +6322,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-levenshtein@3.0.0: + resolution: {integrity: sha512-hKKNajm46uNmTlhHSyZkmToAc56uZJwYq7yrciZjqOxnlfQwERDQJmHPUp7m1m9wx8vgOe8IaCKZ5Kv2k1DdCQ==} + fast-png@6.4.0: resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} @@ -6221,6 +6339,10 @@ packages: resolution: {integrity: sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==} hasBin: true + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -6386,6 +6508,12 @@ packages: resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==} engines: {node: '>= 14'} + get-value@4.0.1: + resolution: {integrity: sha512-QTDzwunK3V+VlJJlL0BlCzebAaE8OSlUC+UVd80PiekTw1gpzQSb3cfEQB2LYFWr1lbWfbdqL4pjAoJDPCLxhQ==} + + getpass@0.1.7: + resolution: {integrity: sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==} + glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -6402,6 +6530,11 @@ packages: deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + glob@11.0.3: resolution: {integrity: sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==} engines: {node: 20 || >=22} @@ -6804,9 +6937,17 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} + is-plain-object@2.0.4: + resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} + engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-primitive@3.0.1: + resolution: {integrity: sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==} + engines: {node: '>=0.10.0'} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -6868,6 +7009,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + isobject@3.0.1: + resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} + engines: {node: '>=0.10.0'} + isomorphic.js@0.2.5: resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} @@ -7074,6 +7219,13 @@ packages: resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} hasBin: true + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + jsbn@0.1.1: + resolution: {integrity: sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==} + jsdom@20.0.3: resolution: {integrity: sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==} engines: {node: '>=14'} @@ -7573,6 +7725,9 @@ packages: mutexify@1.4.0: resolution: {integrity: sha512-pbYSsOrSB/AKN5h/WzzLRMFgZhClWccf2XIB4RSMC8JbquiB0e0/SH5AIfdQMdyHmYtv4seU7yV/TvAwPLJ1Yg==} + nan@2.26.2: + resolution: {integrity: sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -7754,6 +7909,9 @@ packages: package-manager-detector@1.5.0: resolution: {integrity: sha512-uBj69dVlYe/+wxj8JOpr97XfsxH/eumMt6HqjNTmJDf/6NO9s+0uxeOneIz3AsPt2m6y9PqzDzd3ATcU17MNfw==} + packageurl-js@2.0.1: + resolution: {integrity: sha512-N5ixXjzTy4QDQH0Q9YFjqIWd6zH6936Djpl2m9QNFmDv5Fum8q8BjkpAcHNMzOFE0IwQrFhJWex3AN6kS0OSwg==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -8527,6 +8685,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.6.0: + resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} + engines: {node: '>=11.0.0'} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -8564,6 +8726,10 @@ packages: resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} engines: {node: '>= 0.4'} + set-value@4.1.0: + resolution: {integrity: sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==} + engines: {node: '>=11.0'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -8702,6 +8868,15 @@ packages: resolution: {integrity: sha512-UXhXR2869FQaD+GMly8jAMCRZ94nU5KcrFetZfWEMd+LVVG6y0ExgHAhatEcKZ/wk8YcKPdi+hiD2wm75lq3/Q==} engines: {node: '>=4.0.0'} + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + + sshpk@1.16.1: + resolution: {integrity: sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==} + engines: {node: '>=0.10.0'} + hasBin: true + stack-utils@2.0.6: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} @@ -9074,6 +9249,9 @@ packages: tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -9617,6 +9795,18 @@ packages: resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + ws@7.5.10: + resolution: {integrity: sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==} + engines: {node: '>=8.3.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ^5.0.2 + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + ws@8.18.0: resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} engines: {node: '>=10.0.0'} @@ -9645,6 +9835,14 @@ packages: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} + xml2js@0.5.0: + resolution: {integrity: sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} @@ -9675,6 +9873,9 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yamux-js@0.1.2: + resolution: {integrity: sha512-bhsPlPZ9xB4Dawyf6nkS58u4F3IvGCaybkEKGnneUeepcI7MPoG3Tt6SaKCU5x/kP2/2w20Qm/GqbpwAM16vYw==} + yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -11283,7 +11484,7 @@ snapshots: '@datadog/browser-core': 6.22.0 '@datadog/browser-rum-core': 6.22.0 - '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23)': + '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23)': dependencies: '@antfu/install-pkg': 1.1.0 '@types/datadog-metrics': 0.6.1 @@ -11308,13 +11509,54 @@ snapshots: upath: 2.0.1 optionalDependencies: '@datadog/datadog-ci-plugin-cloud-run': 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + transitivePeerDependencies: + - '@types/node' + - supports-color + + '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12)': + dependencies: + '@antfu/install-pkg': 1.1.0 + '@types/datadog-metrics': 0.6.1 + async-retry: 1.3.1 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + datadog-metrics: 0.9.3 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + glob: 10.5.0 + inquirer: 8.2.7(@types/node@22.18.12) + jest-diff: 30.2.0 + jszip: 3.10.1 + proxy-agent: 6.5.0 + semver: 7.7.3 + simple-git: 3.16.0 + terminal-link: 2.1.1 + tiny-async-pool: 2.1.0 + typanion: 3.14.0 + upath: 2.0.1 + optionalDependencies: + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) transitivePeerDependencies: - '@types/node' - supports-color '@datadog/datadog-ci-plugin-cloud-run@4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23)': dependencies: - '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@google-cloud/logging': 11.2.1 '@google-cloud/run': 3.0.1 chalk: 3.0.0 @@ -11329,6 +11571,119 @@ snapshots: - encoding - supports-color + '@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@types/uuid': 9.0.8 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + + '@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + form-data: 4.0.4 + simple-git: 3.16.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + packageurl-js: 2.0.1 + simple-git: 3.16.0 + upath: 2.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-levenshtein: 3.0.0 + get-value: 4.0.1 + ora: 5.4.1 + set-value: 4.1.0 + ssh2: 1.17.0 + sshpk: 1.16.1 + upath: 2.0.1 + ws: 7.5.10 + xml2js: 0.5.0 + yamux-js: 0.1.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + '@datadog/datadog-ci@4.4.0(@types/node@22.18.12)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + js-yaml: 4.1.1 + semver: 7.7.3 + simple-git: 3.16.0 + typanion: 3.14.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - '@datadog/datadog-ci-plugin-aas' + - '@datadog/datadog-ci-plugin-cloud-run' + - '@datadog/datadog-ci-plugin-container-app' + - '@datadog/datadog-ci-plugin-lambda' + - '@datadog/datadog-ci-plugin-stepfunctions' + - '@types/node' + - bufferutil + - debug + - supports-color + - utf-8-validate + '@datadog/flagging-core@0.1.0-preview.13(@openfeature/core@1.9.1)': dependencies: '@openfeature/core': 1.9.1 @@ -11912,6 +12267,13 @@ snapshots: optionalDependencies: '@types/node': 20.19.23 + '@inquirer/external-editor@1.0.2(@types/node@22.18.12)': + dependencies: + chardet: 2.1.1 + iconv-lite: 0.7.0 + optionalDependencies: + '@types/node': 22.18.12 + '@internationalized/date@3.10.0': dependencies: '@swc/helpers': 0.5.17 @@ -14885,6 +15247,8 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} + '@types/uuid@9.0.8': {} + '@types/whatwg-mimetype@3.0.2': {} '@types/ws@8.18.1': @@ -15258,6 +15622,10 @@ snapshots: agent-base@7.1.4: {} + ajv-formats@2.1.1(ajv@8.18.0): + optionalDependencies: + ajv: 8.18.0 + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 @@ -15374,6 +15742,12 @@ snapshots: arrify@2.0.1: {} + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + + assert-plus@1.0.0: {} + assertion-error@2.0.1: {} ast-types@0.13.4: @@ -15506,6 +15880,10 @@ snapshots: basic-ftp@5.0.5: {} + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + bignumber.js@9.3.1: {} bl@4.1.0: @@ -15560,6 +15938,9 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 + buildcheck@0.0.7: + optional: true + busboy@1.6.0: dependencies: streamsearch: 1.1.0 @@ -15730,6 +16111,12 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.26.2 + optional: true + create-jest@29.7.0(@types/node@22.18.12)(ts-node@10.9.2(@types/node@22.18.12)(typescript@5.9.3)): dependencies: '@jest/types': 29.6.3 @@ -15776,6 +16163,10 @@ snapshots: csstype@3.1.3: {} + dashdash@1.14.1: + dependencies: + assert-plus: 1.0.0 + data-uri-to-buffer@4.0.1: {} data-uri-to-buffer@6.0.2: {} @@ -15984,6 +16375,11 @@ snapshots: eastasianwidth@0.2.0: {} + ecc-jsbn@0.1.2: + dependencies: + jsbn: 0.1.1 + safer-buffer: 2.1.2 + ecdsa-sig-formatter@1.0.11: dependencies: safe-buffer: 5.2.1 @@ -16355,6 +16751,10 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-levenshtein@3.0.0: + dependencies: + fastest-levenshtein: 1.0.16 + fast-png@6.4.0: dependencies: '@types/pako': 2.0.4 @@ -16371,6 +16771,8 @@ snapshots: dependencies: strnum: 2.1.1 + fastest-levenshtein@1.0.16: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -16562,6 +16964,12 @@ snapshots: transitivePeerDependencies: - supports-color + get-value@4.0.1: {} + + getpass@0.1.7: + dependencies: + assert-plus: 1.0.0 + glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -16581,6 +16989,15 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.5 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + glob@11.0.3: dependencies: foreground-child: 3.3.1 @@ -17017,6 +17434,26 @@ snapshots: transitivePeerDependencies: - '@types/node' + inquirer@8.2.7(@types/node@22.18.12): + dependencies: + '@inquirer/external-editor': 1.0.2(@types/node@22.18.12) + ansi-escapes: 4.3.2 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-width: 3.0.0 + figures: 3.2.0 + lodash: 4.17.21 + mute-stream: 0.0.8 + ora: 5.4.1 + run-async: 2.4.1 + rxjs: 7.8.2 + string-width: 4.2.3 + strip-ansi: 6.0.1 + through: 2.3.8 + wrap-ansi: 6.2.0 + transitivePeerDependencies: + - '@types/node' + internal-slot@1.1.0: dependencies: es-errors: 1.3.0 @@ -17125,8 +17562,14 @@ snapshots: is-plain-obj@4.1.0: {} + is-plain-object@2.0.4: + dependencies: + isobject: 3.0.1 + is-potential-custom-element-name@1.0.1: {} + is-primitive@3.0.1: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -17182,6 +17625,8 @@ snapshots: isexe@2.0.0: {} + isobject@3.0.1: {} + isomorphic.js@0.2.5: {} istanbul-lib-coverage@3.2.2: {} @@ -17598,6 +18043,12 @@ snapshots: dependencies: argparse: 2.0.1 + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + jsbn@0.1.1: {} + jsdom@20.0.3: dependencies: abab: 2.0.6 @@ -18271,6 +18722,9 @@ snapshots: dependencies: queue-tick: 1.0.1 + nan@2.26.2: + optional: true + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -18454,6 +18908,8 @@ snapshots: package-manager-detector@1.5.0: {} + packageurl-js@2.0.1: {} + pako@1.0.11: {} pako@2.1.0: {} @@ -19343,6 +19799,8 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.6.0: {} + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -19383,6 +19841,11 @@ snapshots: es-errors: 1.3.0 es-object-atoms: 1.1.1 + set-value@4.1.0: + dependencies: + is-plain-object: 2.0.4 + is-primitive: 3.0.1 + setimmediate@1.0.5: {} sharp@0.33.5: @@ -19573,6 +20036,26 @@ snapshots: sql-template-strings@2.2.2: {} + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.26.2 + + sshpk@1.16.1: + dependencies: + asn1: 0.2.6 + assert-plus: 1.0.0 + bcrypt-pbkdf: 1.0.2 + dashdash: 1.14.1 + ecc-jsbn: 0.1.2 + getpass: 0.1.7 + jsbn: 0.1.1 + safer-buffer: 2.1.2 + tweetnacl: 0.14.5 + stack-utils@2.0.6: dependencies: escape-string-regexp: 2.0.0 @@ -19958,6 +20441,8 @@ snapshots: tw-animate-css@1.4.0: {} + tweetnacl@0.14.5: {} + typanion@3.14.0: {} type-check@0.4.0: @@ -20634,12 +21119,21 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 3.0.7 + ws@7.5.10: {} + ws@8.18.0: {} ws@8.18.3: {} xml-name-validator@4.0.0: {} + xml2js@0.5.0: + dependencies: + sax: 1.6.0 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + xmlchars@2.2.0: {} xtend@4.0.2: {} @@ -20662,6 +21156,8 @@ snapshots: yallist@3.1.1: {} + yamux-js@0.1.2: {} + yargs-parser@21.1.1: {} yargs@17.7.2: From 0b0c3800802fb432e6017209b2b8773b400309e1 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 22:20:13 +0200 Subject: [PATCH 42/44] feat: add datadog frontend sourcemap uploads --- .github/workflows/frontend-sourcemaps.yml | 74 +++ apps/clients/src/setupTests.ts | 34 +- apps/clients/src/vite-env.d.ts | 9 + apps/clients/src/viteConfig.test.ts | 13 + apps/clients/vite.config.ts | 3 + apps/external/package.json | 1 + apps/external/src/setupTests.ts | 1 + apps/external/src/vite-env.d.ts | 8 + apps/external/src/viteConfig.test.ts | 13 + apps/external/vite.config.ts | 7 +- apps/main/src/lib/rum.test.ts | 35 ++ apps/main/src/lib/rum.ts | 3 +- apps/main/src/setupTests.ts | 36 +- apps/main/src/vite-env.d.ts | 8 + apps/main/src/viteConfig.test.ts | 13 + apps/main/vite.config.ts | 3 + ...026-04-22-datadog-rum-sourcemaps-via-ci.md | 467 ++++++++++++++++ ...22-datadog-rum-sourcemaps-via-ci-design.md | 99 ++++ package.json | 1 + pnpm-lock.yaml | 502 +++++++++++++++++- 20 files changed, 1290 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/frontend-sourcemaps.yml create mode 100644 apps/clients/src/vite-env.d.ts create mode 100644 apps/clients/src/viteConfig.test.ts create mode 100644 apps/external/src/setupTests.ts create mode 100644 apps/external/src/viteConfig.test.ts create mode 100644 apps/main/src/lib/rum.test.ts create mode 100644 apps/main/src/viteConfig.test.ts create mode 100644 docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md create mode 100644 docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml new file mode 100644 index 0000000..38247ee --- /dev/null +++ b/.github/workflows/frontend-sourcemaps.yml @@ -0,0 +1,74 @@ +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - name: Check out repository + uses: actions/checkout@v6 + + - name: Set up pnpm + uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Validate Datadog secrets + run: | + test -n "$DATADOG_API_KEY" + test -n "$DATADOG_SITE" + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 00791b7..d54e5d0 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -19,19 +19,23 @@ global.ResizeObserver = class ResizeObserver { } }; -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/clients/src/vite-env.d.ts b/apps/clients/src/vite-env.d.ts new file mode 100644 index 0000000..f9164af --- /dev/null +++ b/apps/clients/src/vite-env.d.ts @@ -0,0 +1,9 @@ +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts new file mode 100644 index 0000000..5583270 --- /dev/null +++ b/apps/clients/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 8fbd39f..db6ef09 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -17,6 +17,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false }, define: process.env.VITEST ? { diff --git a/apps/external/package.json b/apps/external/package.json index b93d5b1..fa37897 100644 --- a/apps/external/package.json +++ b/apps/external/package.json @@ -27,6 +27,7 @@ "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/external/src/setupTests.ts b/apps/external/src/setupTests.ts new file mode 100644 index 0000000..3115856 --- /dev/null +++ b/apps/external/src/setupTests.ts @@ -0,0 +1 @@ +// Intentionally minimal test setup so Vitest can honor the configured setupFiles path. diff --git a/apps/external/src/vite-env.d.ts b/apps/external/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/external/src/vite-env.d.ts +++ b/apps/external/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts new file mode 100644 index 0000000..b3831b7 --- /dev/null +++ b/apps/external/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/external/vite.config.ts b/apps/external/vite.config.ts index 8bd72da..c4f1e6b 100644 --- a/apps/external/vite.config.ts +++ b/apps/external/vite.config.ts @@ -3,13 +3,9 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import tailwindcss from "@tailwindcss/vite"; import react from "@vitejs/plugin-react"; -import { dirname } from "path"; -import { fileURLToPath } from "url"; import { defineConfig, PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; -const __dirname = dirname(fileURLToPath(import.meta.url)); - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const plugins: PluginOption[] = [ @@ -26,6 +22,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/apps/main/src/lib/rum.test.ts b/apps/main/src/lib/rum.test.ts new file mode 100644 index 0000000..f468c19 --- /dev/null +++ b/apps/main/src/lib/rum.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); diff --git a/apps/main/src/lib/rum.ts b/apps/main/src/lib/rum.ts index 948e6f2..e2a49ca 100644 --- a/apps/main/src/lib/rum.ts +++ b/apps/main/src/lib/rum.ts @@ -13,9 +13,8 @@ datadogRum.init({ site: "datadoghq.com", service: "xtablo-ui", env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, - // Specify a version number to identify the deployed version of your application in Datadog - // version: '1.0.0', sessionSampleRate: 100, sessionReplaySampleRate: 80, defaultPrivacyLevel: "mask-user-input", diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 1fa4e83..36149d2 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -21,20 +21,24 @@ global.ResizeObserver = class ResizeObserver { } }; -// Mock scrollIntoView for Radix UI components -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +// Mock scroll APIs for DOM-oriented tests without breaking node-environment suites. +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), // deprecated - removeListener: vi.fn(), // deprecated - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), // deprecated + removeListener: vi.fn(), // deprecated + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/main/src/vite-env.d.ts b/apps/main/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/main/src/vite-env.d.ts +++ b/apps/main/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts new file mode 100644 index 0000000..3a15668 --- /dev/null +++ b/apps/main/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/main/vite.config.ts b/apps/main/vite.config.ts index 59e1e45..10802fc 100644 --- a/apps/main/vite.config.ts +++ b/apps/main/vite.config.ts @@ -43,6 +43,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md new file mode 100644 index 0000000..ac7edbd --- /dev/null +++ b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md @@ -0,0 +1,467 @@ +# Datadog RUM Sourcemaps Via CI Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Generate private frontend sourcemaps for Datadog RUM/Error Tracking, upload them from GitHub Actions, and keep `.map` files out of deployed frontend assets. + +**Architecture:** Add an explicit release-version contract to the main app’s RUM init, enable hidden sourcemaps in all Vite frontends, and create a frontend CI workflow that builds each app, uploads sourcemaps with matching Datadog metadata, and removes `.map` files before any deploy step consumes the build output. + +**Tech Stack:** React 19, Vite 6, Vitest, GitHub Actions, Datadog CI CLI, Cloudflare/Wrangler deploy targets, pnpm workspaces. + +**Spec:** `docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md` + +--- + +## File Structure + +### New files + +- `.github/workflows/frontend-sourcemaps.yml` — GitHub Actions workflow that builds the frontend apps on a self-hosted runner and uploads sourcemaps to Datadog. +- `apps/clients/src/vite-env.d.ts` — Vite env typings for client-specific build variables, including `VITE_APP_VERSION`. +- `apps/main/src/lib/rum.test.ts` — regression test for Datadog RUM init config. +- `apps/main/vite.config.test.ts` — production sourcemap config test for `apps/main`. +- `apps/clients/vite.config.test.ts` — production sourcemap config test for `apps/clients`. +- `apps/external/vite.config.test.ts` — production sourcemap config test for `apps/external`. + +### Modified files + +- `package.json` — add `@datadog/datadog-ci` to root dev dependencies. +- `apps/main/src/lib/rum.ts` — add `version: import.meta.env.VITE_APP_VERSION`. +- `apps/main/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/external/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/main/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/clients/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/external/vite.config.ts` — enable hidden sourcemaps for non-test builds. + +--- + +## Chunk 1: Runtime Release Metadata + +### Task 1: Wire Datadog RUM version in `apps/main` + +**Files:** +- Create: `apps/main/src/lib/rum.test.ts` +- Modify: `apps/main/src/lib/rum.ts` +- Modify: `apps/main/src/vite-env.d.ts` + +- [ ] **Step 1: Write the failing RUM init test** + +Create `apps/main/src/lib/rum.test.ts`: + +```typescript +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +``` + +Expected: FAIL because `version` is not set in `datadogRum.init`. + +- [ ] **Step 3: Add the runtime version** + +Update `apps/main/src/lib/rum.ts`: + +```typescript + service: "xtablo-ui", + env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, +``` + +Update `apps/main/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 4: Run the test to verify it passes** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add apps/main/src/lib/rum.ts apps/main/src/lib/rum.test.ts apps/main/src/vite-env.d.ts +git commit -m "feat: add Datadog release version to main rum config" +``` + +--- + +## Chunk 2: Hidden Sourcemaps In All Vite Frontends + +### Task 2: Add production sourcemap config tests + +**Files:** +- Create: `apps/main/vite.config.test.ts` +- Create: `apps/clients/vite.config.test.ts` +- Create: `apps/external/vite.config.test.ts` + +- [ ] **Step 1: Write the failing config test for `apps/main`** + +Create `apps/main/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 2: Write the failing config test for `apps/clients`** + +Create `apps/clients/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 3: Write the failing config test for `apps/external`** + +Create `apps/external/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 4: Run the tests to verify they fail** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +``` + +Expected: FAIL because `build.sourcemap` is not configured. + +- [ ] **Step 5: Implement hidden sourcemaps in all three Vite configs** + +Update: +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Add the same build section in each returned config: + +```typescript + build: { + sourcemap: mode === "test" ? false : "hidden", + }, +``` + +Keep it alongside the existing `plugins`, `server`, `define`, and `test` sections. + +- [ ] **Step 6: Add env typing for the remaining apps** + +Create `apps/clients/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +Update `apps/external/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 7: Run the tests and typechecks** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 8: Commit** + +```bash +git add apps/main/vite.config.ts apps/main/vite.config.test.ts apps/clients/vite.config.ts apps/clients/vite.config.test.ts apps/clients/src/vite-env.d.ts apps/external/vite.config.ts apps/external/vite.config.test.ts apps/external/src/vite-env.d.ts +git commit -m "build: enable hidden sourcemaps for frontend apps" +``` + +--- + +## Chunk 3: Datadog CI Upload Workflow + +### Task 3: Add pinned Datadog CLI and frontend sourcemap workflow + +**Files:** +- Create: `.github/workflows/frontend-sourcemaps.yml` +- Modify: `package.json` + +- [ ] **Step 1: Add the Datadog CLI dependency** + +Update root `package.json`: + +```json + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^3.21.0", + "turbo": "^2.5.8", + "typescript": "^5.7.0" + } +``` + +- [ ] **Step 2: Install dependencies and verify lockfile changes** + +Run: + +```bash +pnpm install +``` + +Expected: `pnpm-lock.yaml` updates with `@datadog/datadog-ci`. + +- [ ] **Step 3: Create the workflow** + +Create `.github/workflows/frontend-sourcemaps.yml`: + +```yaml +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete +``` + +- [ ] **Step 4: Validate the workflow file structure** + +Run: + +```bash +rg -n "datadog-ci sourcemaps upload|RELEASE_VERSION|find .*\\.map" .github/workflows/frontend-sourcemaps.yml +``` + +Expected: one upload and one cleanup step for each frontend app. + +- [ ] **Step 5: Commit** + +```bash +git add package.json pnpm-lock.yaml .github/workflows/frontend-sourcemaps.yml +git commit -m "ci: upload frontend sourcemaps to Datadog" +``` + +--- + +## Chunk 4: End-To-End Verification + +### Task 4: Prove builds emit hidden sourcemaps and cleanup works + +**Files:** +- No new source files + +- [ ] **Step 1: Build each frontend locally with a release version** + +Run: + +```bash +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/main build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/clients build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/external build +``` + +Expected: each `dist/` contains built assets and `.map` files, but the generated JS bundles do not include public `sourceMappingURL` comments. + +- [ ] **Step 2: Verify `.map` files exist before cleanup** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: at least one sourcemap per app. + +- [ ] **Step 3: Simulate CI cleanup locally** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' -delete +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: no output from the second command. + +- [ ] **Step 4: Run the targeted regression suite** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git status --short +``` + +Expected: clean worktree before opening the implementation PR. diff --git a/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md new file mode 100644 index 0000000..6e247b0 --- /dev/null +++ b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md @@ -0,0 +1,99 @@ +# Datadog RUM Sourcemaps Via CI Design + +**Goal:** Deobfuscate frontend RUM and Error Tracking stack traces in Datadog for the Xtablo frontends by generating sourcemaps during build, uploading them in CI, and keeping `.map` files off the public CDN. + +## Current State + +- `apps/main` initializes Datadog RUM in [apps/main/src/lib/rum.ts](/Users/arthur.belleville/Documents/perso/projects/xtablo-source/apps/main/src/lib/rum.ts) with `service: "xtablo-ui"` and `env: import.meta.env.MODE`, but no explicit release version. +- `apps/main`, `apps/clients`, and `apps/external` are Vite frontends with production Cloudflare deployments. +- None of the three Vite configs currently emit production sourcemaps. +- On this branch there is no tracked GitHub Actions workflow yet, so CI wiring must be introduced as part of the implementation. + +## Decision + +Use Datadog’s recommended CI upload flow: + +1. Build each frontend with Vite `build.sourcemap: "hidden"`. +2. Upload generated sourcemaps from CI with `datadog-ci sourcemaps upload`. +3. Use a release version derived from the CI commit SHA. +4. Remove all `.map` files from `dist/` before deploy packaging so they are never publicly served. + +This keeps sourcemaps private while still enabling unminified stack traces in Datadog. + +Sources: +- Datadog CI sourcemap upload guide: https://docs.datadoghq.com/real_user_monitoring/guide/upload-javascript-source-maps/?tab=vite +- Vite `build.sourcemap` docs: https://vite.dev/config/build-options.html + +## Runtime Contract + +Datadog matches sourcemaps against browser events by `service` and `version`. + +- `apps/main` must emit `version: import.meta.env.VITE_APP_VERSION` in its RUM initialization. +- CI must upload sourcemaps for `apps/main` using: + - `service=xtablo-ui` + - `release-version=$GITHUB_SHA` +- `apps/clients` and `apps/external` should use the same CI release version convention now, even though they do not currently emit RUM events. This keeps the deployment contract consistent and avoids another pipeline change when browser monitoring is enabled there. + +## Public Asset Prefixes + +The Datadog upload command must use the real production asset prefixes: + +- `apps/main`: `https://app.xtablo.com/assets` +- `apps/clients`: `https://clients.xtablo.com/assets` +- `apps/external`: `https://embed.xtablo.com/assets` + +These prefixes must match the actual URLs used by the deployed JS bundles. + +## Implementation Shape + +### Frontend code + +- `apps/main/src/lib/rum.ts` + - add `version: import.meta.env.VITE_APP_VERSION` +- `apps/main/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` +- `apps/clients/src/vite-env.d.ts` + - create and declare `VITE_APP_VERSION` +- `apps/external/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` + +### Build config + +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Each should emit hidden sourcemaps for non-test builds. + +### CI + +- Add GitHub Actions workflow for frontend builds on self-hosted runners. +- Add `@datadog/datadog-ci` as a root dev dependency so the workflow can run a pinned CLI version from the repo. +- After each frontend build: + - upload sourcemaps to Datadog + - delete `dist/**/*.map` + +## Secrets And CI Inputs + +The workflow needs: + +- `DATADOG_API_KEY` +- `DATADOG_SITE` +- release version from `github.sha` + +The workflow should fail fast if Datadog secrets are missing on the deployment path where sourcemap upload is required. + +## Verification + +- Unit test for `apps/main` RUM init to assert `version` is wired from env. +- Vite config tests or config assertions for all three apps to verify production builds use `sourcemap: "hidden"`. +- CI workflow smoke verification: + - build the apps + - run sourcemap upload + - confirm `.map` files are removed from `dist` + +## Non-Goals + +- Enabling Datadog RUM in `apps/clients` or `apps/external` right now. +- Serving sourcemaps publicly. +- Changing app deployment hosts or CDN paths. diff --git a/package.json b/package.json index 5366d4f..5dd27ce 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^4.3.0", "turbo": "^2.5.8", "typescript": "^5.7.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 240d4f4..6337b4e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: '@biomejs/biome': specifier: 2.2.5 version: 2.2.5 + '@datadog/datadog-ci': + specifier: ^4.3.0 + version: 4.4.0(@types/node@22.18.12) turbo: specifier: ^2.5.8 version: 2.5.8 @@ -89,7 +92,7 @@ importers: version: 2.2.5 '@datadog/datadog-ci-base': specifier: ^4.0.2 - version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@datadog/datadog-ci-plugin-cloud-run': specifier: ^4.0.2 version: 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) @@ -321,6 +324,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) @@ -1987,11 +1993,84 @@ packages: '@datadog/datadog-ci-plugin-synthetics': optional: true + '@datadog/datadog-ci-base@4.4.0': + resolution: {integrity: sha512-sFssfj3EQKBiD9SkVYzhkzHZEQqmnsMGXKYKoLLTFcTmRbaePItx/1Sa3KzFVIWBhZQSpYoJt3VZ7+cagCShLA==} + peerDependencies: + '@datadog/datadog-ci-plugin-aas': 4.4.0 + '@datadog/datadog-ci-plugin-cloud-run': 4.4.0 + '@datadog/datadog-ci-plugin-container-app': 4.4.0 + '@datadog/datadog-ci-plugin-deployment': 4.4.0 + '@datadog/datadog-ci-plugin-dora': 4.4.0 + '@datadog/datadog-ci-plugin-gate': 4.4.0 + '@datadog/datadog-ci-plugin-lambda': 4.4.0 + '@datadog/datadog-ci-plugin-sarif': 4.4.0 + '@datadog/datadog-ci-plugin-sbom': 4.4.0 + '@datadog/datadog-ci-plugin-stepfunctions': 4.4.0 + '@datadog/datadog-ci-plugin-synthetics': 4.4.0 + peerDependenciesMeta: + '@datadog/datadog-ci-plugin-aas': + optional: true + '@datadog/datadog-ci-plugin-cloud-run': + optional: true + '@datadog/datadog-ci-plugin-container-app': + optional: true + '@datadog/datadog-ci-plugin-deployment': + optional: true + '@datadog/datadog-ci-plugin-dora': + optional: true + '@datadog/datadog-ci-plugin-gate': + optional: true + '@datadog/datadog-ci-plugin-lambda': + optional: true + '@datadog/datadog-ci-plugin-sarif': + optional: true + '@datadog/datadog-ci-plugin-sbom': + optional: true + '@datadog/datadog-ci-plugin-stepfunctions': + optional: true + '@datadog/datadog-ci-plugin-synthetics': + optional: true + '@datadog/datadog-ci-plugin-cloud-run@4.1.2': resolution: {integrity: sha512-HKVZ7SSjzskdVqIrf16bqmgeRrxscoRkgh9ILfni3D/GoXpG3DFaZPs7pXJR6igjBeZMclLjtolqMyyWy7DCLQ==} peerDependencies: '@datadog/datadog-ci-base': 4.1.2 + '@datadog/datadog-ci-plugin-deployment@4.4.0': + resolution: {integrity: sha512-u9FtFw2TKRF74wwcuM8tWseWTrLKZZ/Lwq1Fz+LtAGHTJ5675WuIhGNnSxbrKU4f2VsaFp+eUIsetcqbuUerXw==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-dora@4.4.0': + resolution: {integrity: sha512-DuyKfiwxZoNu5dlMPZNq6DYlafR/3kpaqS0q9KfGStnu1LwS5YTREuZgssNkyYWnF6qZN80x1l7E/ubaAFVYOg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-gate@4.4.0': + resolution: {integrity: sha512-bR5AY5p5/5jQuZtcuEPJrEpL1WhJiXhfPwuc9OhGN0ny4/98S3Hg02aQ9aoloFipsBgEN3W5XhrWH6Pn1jSI5w==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sarif@4.4.0': + resolution: {integrity: sha512-kgExnC/ReiGKr9R6SxaXr62lp2fYJQ4i8c9x4/GqDpNbLENQdsqBmxs6h1/N3xkdt3/p3RZlMcAhIytLYDkBAA==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sbom@4.4.0': + resolution: {integrity: sha512-bBsgIBBT0KsWqLcIMuf692PGjMNjG6OKNUjuPZOWbuToyKKnpRRkMDrX9KvUWVXuMKfDEp7i2PYw/2fQm5DXHg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-synthetics@4.4.0': + resolution: {integrity: sha512-SpGdOZUSjEVZZD/hopPKuXnOP6ZRl0nnZ8i5ffVIxohlMwn5y0vMWjjkDohk24M+2QBDUnMe4sNXW4YP1aeSWg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci@4.4.0': + resolution: {integrity: sha512-vpQPcz+FRgDhPoHg9aXtTeaVe6Dhky6q1vG9TmOWDX39Pjf/Wz1LEY94uWvK6miC8orHf6RtIGOSxsycRNde7g==} + engines: {node: '>=18'} + hasBin: true + '@datadog/flagging-core@0.1.0-preview.13': resolution: {integrity: sha512-DfQYeBgGvCerKx6coRiXMt0aXWJB8kRIsJhfdTKyejS9rfp6ZBjWc6dctKzhwMAQdpBiN42MEVXNt4Pdcmj1WA==} peerDependencies: @@ -5042,6 +5121,9 @@ packages: '@types/use-sync-external-store@0.0.6': resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@types/uuid@9.0.8': + resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==} + '@types/whatwg-mimetype@3.0.2': resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} @@ -5341,6 +5423,14 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} @@ -5434,6 +5524,13 @@ packages: resolution: {integrity: sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==} engines: {node: '>=8'} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + + assert-plus@1.0.0: + resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} + engines: {node: '>=0.8'} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -5539,6 +5636,9 @@ packages: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} @@ -5583,6 +5683,10 @@ packages: buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + busboy@1.6.0: resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} engines: {node: '>=10.16.0'} @@ -5780,6 +5884,10 @@ packages: resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==} engines: {node: '>= 0.10'} + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + create-jest@29.7.0: resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -5821,6 +5929,10 @@ packages: csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} + dashdash@1.14.1: + resolution: {integrity: sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==} + engines: {node: '>=0.10'} + data-uri-to-buffer@4.0.1: resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} engines: {node: '>= 12'} @@ -6017,6 +6129,9 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + ecc-jsbn@0.1.2: + resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} + ecdsa-sig-formatter@1.0.11: resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==} @@ -6250,6 +6365,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-levenshtein@3.0.0: + resolution: {integrity: sha512-hKKNajm46uNmTlhHSyZkmToAc56uZJwYq7yrciZjqOxnlfQwERDQJmHPUp7m1m9wx8vgOe8IaCKZ5Kv2k1DdCQ==} + fast-png@6.4.0: resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} @@ -6264,6 +6382,10 @@ packages: resolution: {integrity: sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==} hasBin: true + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -6429,6 +6551,12 @@ packages: resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==} engines: {node: '>= 14'} + get-value@4.0.1: + resolution: {integrity: sha512-QTDzwunK3V+VlJJlL0BlCzebAaE8OSlUC+UVd80PiekTw1gpzQSb3cfEQB2LYFWr1lbWfbdqL4pjAoJDPCLxhQ==} + + getpass@0.1.7: + resolution: {integrity: sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==} + glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -6445,6 +6573,11 @@ packages: deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + glob@11.0.3: resolution: {integrity: sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==} engines: {node: 20 || >=22} @@ -6847,9 +6980,17 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} + is-plain-object@2.0.4: + resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} + engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-primitive@3.0.1: + resolution: {integrity: sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==} + engines: {node: '>=0.10.0'} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -6911,6 +7052,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + isobject@3.0.1: + resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} + engines: {node: '>=0.10.0'} + isomorphic.js@0.2.5: resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} @@ -7117,6 +7262,13 @@ packages: resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} hasBin: true + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + jsbn@0.1.1: + resolution: {integrity: sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==} + jsdom@20.0.3: resolution: {integrity: sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==} engines: {node: '>=14'} @@ -7616,6 +7768,9 @@ packages: mutexify@1.4.0: resolution: {integrity: sha512-pbYSsOrSB/AKN5h/WzzLRMFgZhClWccf2XIB4RSMC8JbquiB0e0/SH5AIfdQMdyHmYtv4seU7yV/TvAwPLJ1Yg==} + nan@2.26.2: + resolution: {integrity: sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -7797,6 +7952,9 @@ packages: package-manager-detector@1.5.0: resolution: {integrity: sha512-uBj69dVlYe/+wxj8JOpr97XfsxH/eumMt6HqjNTmJDf/6NO9s+0uxeOneIz3AsPt2m6y9PqzDzd3ATcU17MNfw==} + packageurl-js@2.0.1: + resolution: {integrity: sha512-N5ixXjzTy4QDQH0Q9YFjqIWd6zH6936Djpl2m9QNFmDv5Fum8q8BjkpAcHNMzOFE0IwQrFhJWex3AN6kS0OSwg==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -8570,6 +8728,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.6.0: + resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} + engines: {node: '>=11.0.0'} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -8607,6 +8769,10 @@ packages: resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} engines: {node: '>= 0.4'} + set-value@4.1.0: + resolution: {integrity: sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==} + engines: {node: '>=11.0'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -8745,6 +8911,15 @@ packages: resolution: {integrity: sha512-UXhXR2869FQaD+GMly8jAMCRZ94nU5KcrFetZfWEMd+LVVG6y0ExgHAhatEcKZ/wk8YcKPdi+hiD2wm75lq3/Q==} engines: {node: '>=4.0.0'} + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + + sshpk@1.16.1: + resolution: {integrity: sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==} + engines: {node: '>=0.10.0'} + hasBin: true + stack-utils@2.0.6: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} @@ -9117,6 +9292,9 @@ packages: tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -9660,6 +9838,18 @@ packages: resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + ws@7.5.10: + resolution: {integrity: sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==} + engines: {node: '>=8.3.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ^5.0.2 + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + ws@8.18.0: resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} engines: {node: '>=10.0.0'} @@ -9688,6 +9878,14 @@ packages: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} + xml2js@0.5.0: + resolution: {integrity: sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} @@ -9718,6 +9916,9 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yamux-js@0.1.2: + resolution: {integrity: sha512-bhsPlPZ9xB4Dawyf6nkS58u4F3IvGCaybkEKGnneUeepcI7MPoG3Tt6SaKCU5x/kP2/2w20Qm/GqbpwAM16vYw==} + yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -11326,7 +11527,7 @@ snapshots: '@datadog/browser-core': 6.22.0 '@datadog/browser-rum-core': 6.22.0 - '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23)': + '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23)': dependencies: '@antfu/install-pkg': 1.1.0 '@types/datadog-metrics': 0.6.1 @@ -11351,13 +11552,54 @@ snapshots: upath: 2.0.1 optionalDependencies: '@datadog/datadog-ci-plugin-cloud-run': 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + transitivePeerDependencies: + - '@types/node' + - supports-color + + '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12)': + dependencies: + '@antfu/install-pkg': 1.1.0 + '@types/datadog-metrics': 0.6.1 + async-retry: 1.3.1 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + datadog-metrics: 0.9.3 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + glob: 10.5.0 + inquirer: 8.2.7(@types/node@22.18.12) + jest-diff: 30.2.0 + jszip: 3.10.1 + proxy-agent: 6.5.0 + semver: 7.7.3 + simple-git: 3.16.0 + terminal-link: 2.1.1 + tiny-async-pool: 2.1.0 + typanion: 3.14.0 + upath: 2.0.1 + optionalDependencies: + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) transitivePeerDependencies: - '@types/node' - supports-color '@datadog/datadog-ci-plugin-cloud-run@4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23)': dependencies: - '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@google-cloud/logging': 11.2.1 '@google-cloud/run': 3.0.1 chalk: 3.0.0 @@ -11372,6 +11614,119 @@ snapshots: - encoding - supports-color + '@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@types/uuid': 9.0.8 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + + '@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + form-data: 4.0.4 + simple-git: 3.16.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + packageurl-js: 2.0.1 + simple-git: 3.16.0 + upath: 2.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-levenshtein: 3.0.0 + get-value: 4.0.1 + ora: 5.4.1 + set-value: 4.1.0 + ssh2: 1.17.0 + sshpk: 1.16.1 + upath: 2.0.1 + ws: 7.5.10 + xml2js: 0.5.0 + yamux-js: 0.1.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + '@datadog/datadog-ci@4.4.0(@types/node@22.18.12)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + js-yaml: 4.1.1 + semver: 7.7.3 + simple-git: 3.16.0 + typanion: 3.14.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - '@datadog/datadog-ci-plugin-aas' + - '@datadog/datadog-ci-plugin-cloud-run' + - '@datadog/datadog-ci-plugin-container-app' + - '@datadog/datadog-ci-plugin-lambda' + - '@datadog/datadog-ci-plugin-stepfunctions' + - '@types/node' + - bufferutil + - debug + - supports-color + - utf-8-validate + '@datadog/flagging-core@0.1.0-preview.13(@openfeature/core@1.9.1)': dependencies: '@openfeature/core': 1.9.1 @@ -11955,6 +12310,13 @@ snapshots: optionalDependencies: '@types/node': 20.19.23 + '@inquirer/external-editor@1.0.2(@types/node@22.18.12)': + dependencies: + chardet: 2.1.1 + iconv-lite: 0.7.0 + optionalDependencies: + '@types/node': 22.18.12 + '@internationalized/date@3.10.0': dependencies: '@swc/helpers': 0.5.17 @@ -14928,6 +15290,8 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} + '@types/uuid@9.0.8': {} + '@types/whatwg-mimetype@3.0.2': {} '@types/ws@8.18.1': @@ -15301,6 +15665,10 @@ snapshots: agent-base@7.1.4: {} + ajv-formats@2.1.1(ajv@8.18.0): + optionalDependencies: + ajv: 8.18.0 + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 @@ -15417,6 +15785,12 @@ snapshots: arrify@2.0.1: {} + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + + assert-plus@1.0.0: {} + assertion-error@2.0.1: {} ast-types@0.13.4: @@ -15549,6 +15923,10 @@ snapshots: basic-ftp@5.0.5: {} + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + bignumber.js@9.3.1: {} bl@4.1.0: @@ -15603,6 +15981,9 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 + buildcheck@0.0.7: + optional: true + busboy@1.6.0: dependencies: streamsearch: 1.1.0 @@ -15773,6 +16154,12 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.26.2 + optional: true + create-jest@29.7.0(@types/node@22.18.12)(ts-node@10.9.2(@types/node@22.18.12)(typescript@5.9.3)): dependencies: '@jest/types': 29.6.3 @@ -15819,6 +16206,10 @@ snapshots: csstype@3.1.3: {} + dashdash@1.14.1: + dependencies: + assert-plus: 1.0.0 + data-uri-to-buffer@4.0.1: {} data-uri-to-buffer@6.0.2: {} @@ -16027,6 +16418,11 @@ snapshots: eastasianwidth@0.2.0: {} + ecc-jsbn@0.1.2: + dependencies: + jsbn: 0.1.1 + safer-buffer: 2.1.2 + ecdsa-sig-formatter@1.0.11: dependencies: safe-buffer: 5.2.1 @@ -16398,6 +16794,10 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-levenshtein@3.0.0: + dependencies: + fastest-levenshtein: 1.0.16 + fast-png@6.4.0: dependencies: '@types/pako': 2.0.4 @@ -16414,6 +16814,8 @@ snapshots: dependencies: strnum: 2.1.1 + fastest-levenshtein@1.0.16: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -16605,6 +17007,12 @@ snapshots: transitivePeerDependencies: - supports-color + get-value@4.0.1: {} + + getpass@0.1.7: + dependencies: + assert-plus: 1.0.0 + glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -16624,6 +17032,15 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.5 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + glob@11.0.3: dependencies: foreground-child: 3.3.1 @@ -17060,6 +17477,26 @@ snapshots: transitivePeerDependencies: - '@types/node' + inquirer@8.2.7(@types/node@22.18.12): + dependencies: + '@inquirer/external-editor': 1.0.2(@types/node@22.18.12) + ansi-escapes: 4.3.2 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-width: 3.0.0 + figures: 3.2.0 + lodash: 4.17.21 + mute-stream: 0.0.8 + ora: 5.4.1 + run-async: 2.4.1 + rxjs: 7.8.2 + string-width: 4.2.3 + strip-ansi: 6.0.1 + through: 2.3.8 + wrap-ansi: 6.2.0 + transitivePeerDependencies: + - '@types/node' + internal-slot@1.1.0: dependencies: es-errors: 1.3.0 @@ -17168,8 +17605,14 @@ snapshots: is-plain-obj@4.1.0: {} + is-plain-object@2.0.4: + dependencies: + isobject: 3.0.1 + is-potential-custom-element-name@1.0.1: {} + is-primitive@3.0.1: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -17225,6 +17668,8 @@ snapshots: isexe@2.0.0: {} + isobject@3.0.1: {} + isomorphic.js@0.2.5: {} istanbul-lib-coverage@3.2.2: {} @@ -17641,6 +18086,12 @@ snapshots: dependencies: argparse: 2.0.1 + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + jsbn@0.1.1: {} + jsdom@20.0.3: dependencies: abab: 2.0.6 @@ -18314,6 +18765,9 @@ snapshots: dependencies: queue-tick: 1.0.1 + nan@2.26.2: + optional: true + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -18497,6 +18951,8 @@ snapshots: package-manager-detector@1.5.0: {} + packageurl-js@2.0.1: {} + pako@1.0.11: {} pako@2.1.0: {} @@ -19386,6 +19842,8 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.6.0: {} + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -19426,6 +19884,11 @@ snapshots: es-errors: 1.3.0 es-object-atoms: 1.1.1 + set-value@4.1.0: + dependencies: + is-plain-object: 2.0.4 + is-primitive: 3.0.1 + setimmediate@1.0.5: {} sharp@0.33.5: @@ -19616,6 +20079,26 @@ snapshots: sql-template-strings@2.2.2: {} + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.26.2 + + sshpk@1.16.1: + dependencies: + asn1: 0.2.6 + assert-plus: 1.0.0 + bcrypt-pbkdf: 1.0.2 + dashdash: 1.14.1 + ecc-jsbn: 0.1.2 + getpass: 0.1.7 + jsbn: 0.1.1 + safer-buffer: 2.1.2 + tweetnacl: 0.14.5 + stack-utils@2.0.6: dependencies: escape-string-regexp: 2.0.0 @@ -20001,6 +20484,8 @@ snapshots: tw-animate-css@1.4.0: {} + tweetnacl@0.14.5: {} + typanion@3.14.0: {} type-check@0.4.0: @@ -20677,12 +21162,21 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 3.0.7 + ws@7.5.10: {} + ws@8.18.0: {} ws@8.18.3: {} xml-name-validator@4.0.0: {} + xml2js@0.5.0: + dependencies: + sax: 1.6.0 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + xmlchars@2.2.0: {} xtend@4.0.2: {} @@ -20705,6 +21199,8 @@ snapshots: yallist@3.1.1: {} + yamux-js@0.1.2: {} + yargs-parser@21.1.1: {} yargs@17.7.2: From 38a471e98a9b15659ceeb8a2e191589d56cf659e Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 23 Apr 2026 19:29:12 +0200 Subject: [PATCH 43/44] Set site --- .github/workflows/frontend-sourcemaps.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml index 38247ee..70ab116 100644 --- a/.github/workflows/frontend-sourcemaps.yml +++ b/.github/workflows/frontend-sourcemaps.yml @@ -15,7 +15,7 @@ jobs: - x64 env: DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} - DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + DATADOG_SITE: datadoghq.com RELEASE_VERSION: ${{ github.sha }} steps: - name: Check out repository From e4576b6363aeca9312f76f932f5c940649ae4de4 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 23 Apr 2026 19:32:58 +0200 Subject: [PATCH 44/44] Fix lint --- apps/clients/src/viteConfig.test.ts | 7 ++++++- apps/external/src/viteConfig.test.ts | 7 ++++++- apps/main/src/viteConfig.test.ts | 7 ++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts index 5583270..dad6799 100644 --- a/apps/clients/src/viteConfig.test.ts +++ b/apps/clients/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("clients vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); }); diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts index b3831b7..1c95586 100644 --- a/apps/external/src/viteConfig.test.ts +++ b/apps/external/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("external vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); }); diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts index 3a15668..7242369 100644 --- a/apps/main/src/viteConfig.test.ts +++ b/apps/main/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("main vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); });