diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..47e4b42 --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,8 @@ +# The Worker's secrets for `pnpm dev:worker` / `pnpm preview` (wrangler dev +# reads .dev.vars). Copy to .dev.vars. Deployed, the service-role key is the +# Supabase root's output and the deploy stores it; never commit it. +SUPABASE_SERVICE_ROLE_KEY= +# Optional: Postmark inbound email (worker/functions/postmark). +POSTMARK_WEBHOOK_USER= +POSTMARK_WEBHOOK_PASSWORD= +POSTMARK_WEBHOOK_AUTHORIZED_IPS= diff --git a/apps/web/.env.development b/apps/web/.env.development new file mode 100644 index 0000000..3e1f36a --- /dev/null +++ b/apps/web/.env.development @@ -0,0 +1,7 @@ +SKIP_PREFLIGHT_CHECK=true + +VITE_SUPABASE_URL=http://127.0.0.1:54321 +VITE_SB_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH +VITE_IS_DEMO=false + +VITE_ATTACHMENTS_BUCKET=attachments diff --git a/apps/web/.gitignore b/apps/web/.gitignore new file mode 100644 index 0000000..b13fe97 --- /dev/null +++ b/apps/web/.gitignore @@ -0,0 +1,5 @@ +# local state wrangler and the PWA plugin write +.wrangler/ +dev-dist/ +.dev.vars +.env.local diff --git a/apps/web/CHANGELOG.md b/apps/web/CHANGELOG.md new file mode 100644 index 0000000..d28acbf --- /dev/null +++ b/apps/web/CHANGELOG.md @@ -0,0 +1,238 @@ +## v1.6.0 - 2026-09-22 + +## What's Changed + +* Add i18n support by @WiXSL in #183 +* Turn mobile settings dialog into a page by @fzaninotto in #206 +* Make currency configurable by @fzaninotto in #210 +* Improve font legibility by @fzaninotto in #211 +* Add infinite pagination to the activity log by @fzaninotto in #212 +* Add declarative database schemas by @fzaninotto in #213 +* Add bulk contact tagging by @WiXSL in #224 +* Add contact status sidebar by @WiXSL in #239 +* Add infinite scroll to contact and deal notes by @WiXSL in #241 +* Add grow on focus to the note input in contact show view by @fzaninotto in #253 +* Add a Task list MCP app by @fzaninotto in #274 +* Add a changelog page by @erwanMarmelab in #281 +* Add ability to filter contacts by any account manager by @pysnooLab in #344 +* Attach forwarded emails sent from a sale's secondary address by @pysnooLab in #345 +* Add ability to import data from a CSV file by @erwanMarmelab in #348 +* Add pull-to-refresh on mobile by @erwanMarmelab in #349 +* Fix Supabase security advisor warnings about views and functions by @slax57 in #199 +* Fix companies being created from blacklisted mail provider addresses on inbound mail by @ThieryMichel in #200 +* Fix note form initialization by @ThieryMichel in #202 +* Fix contact names extracted from inbound email not being capitalized by @ThieryMichel in #214 +* Fix notes pagination race condition on mobile by @WiXSL in #216 +* Fix ContactShow task count translation flicker by @WiXSL in #217 +* Fix inbound email contact matching to be case-insensitive and improve company creation by @slax57 in #219 +* Fix phone/email default values not clearing on submit when untouched by @ThieryMichel in #220 +* Fix missing i18n keys by @slax57 in #221 +* Fix supabase-remote-init project status check by @ThieryMichel in #229 +* Fix empty notes being allowed by @WiXSL in #230 +* Fix missing markdown styles by @slax57 in #231 +* Fix deal Kanban bug by @ThieryMichel in #235 +* Fix autocomplete input filtering with cmdk by adding a keyword field by @ThieryMichel in #237 +* Fix choice list scrolling to the bottom while filtering by @ThieryMichel in #240 +* Fix company selector overflow in the Deal form by @slax57 in #245 +* Fix mobile note edition user experience by @fzaninotto in #252 +* Fix missing grants for views in migrations by @jonathanarnault in #292 +* Fix add-note button overflowing in French by @jonathanarnault in #295 +* Fix initial Login page shows username/password fields even though VITE_DISABLE_EMAIL_PASSWORD_AUTHENTICATION is true by @fzaninotto in #334 +* Fix invalid logo URL during OAuth by @fzaninotto in #335 +* Bump various dependencies (hono, devalue, h3, flatted, smol-toml, astro, dompurify) by @dependabot[bot] in #203, #205, #222, #223, #227, #233, #234, #238, #254, #256, #257, #270, #271, #279, #282, #283, #300 +* Bump Playwright to the latest version by @erwanMarmelab in #290 +* [Doc] Add documentation about the Supabase REST API by @ThieryMichel in #195 +* [Doc] Document how to use a custom SMTP server by @slax57 in #201 +* [Doc] Add developer documentation for the agentic harness by @pysnooLab in #314 +* [Doc] Add an asciinema recording for the harness by @pysnooLab in #319 +* [Doc] Add a User Profile page to the user documentation by @pysnooLab in #339 +* [Doc] Document the Shadcn registry for users and contributors by @pysnooLab in #346 +* [Chore] Add browser-based integration tests and Storybook by @WiXSL in #198 +* [Chore] Set up e2e tests by @ThieryMichel in #204 +* [Chore] Refactor integration tests by @fzaninotto in #225 +* [Chore] Update NoteInputs stories to use the new StoryWrapper by @ThieryMichel in #236 +* [Chore] Reduce unit test verbosity by @ThieryMichel in #243 +* [Chore] Speed up e2e tests by @ThieryMichel in #244 +* [Chore] Fix the dismiss-toast e2e helper targeting the wrong close button by @jonathanarnault in #287 +* [Chore] Add Claude agents, skills, and rules by @jonathanarnault in #289 +* [Chore] Add a delete-resource skill by @erwanMarmelab in #294 +* [Chore] Upgrade Shadcn Admin Kit to v1.6.0 by @fzaninotto in #296 +* [Chore] Add the update-branding skill by @erwanMarmelab in #297 +* [Chore] Improve Claude hooks code quality by @jonathanarnault in #298 +* [Chore] Improve the agentic factory by @erwanMarmelab in #299 +* [Chore] Use subagents instead of agent teams to reduce costs by @jonathanarnault in #302 +* [Chore] Add the Ponytail plugin by @erwanMarmelab in #304 +* [Chore] Improve dev containers by @jonathanarnault in #306 +* [Chore] Improve agents and efforts by @erwanMarmelab in #308 +* [Chore] Allow committing on branches other than main by @jonathanarnault in #309 +* [Chore] Add a TypeScript LSP for Claude by @jonathanarnault in #310 +* [Chore] Rewrite skills by @pysnooLab in #311 +* [Chore] Simplify CLAUDE.md and add a way to bypass the harness for development by @pysnooLab in #312 +* [Chore] Add Docker-in-Docker support for dev containers by @jonathanarnault in #313 +* [Chore] Use Playwright with agents by @erwanMarmelab in #315 +* [Chore] Fix harness regressions by @pysnooLab in #316 +* [Chore] Remove graphify reference by @jonathanarnault in #317 +* [Chore] Add harness command support by @pysnooLab in #321 +* [Chore] Consolidate the harness by @pysnooLab in #331 + +## New Contributors +* @pysnooLab made their first contribution in https://github.com/marmelab/atomic-crm/pull/312 + +**Full Changelog**: https://github.com/marmelab/atomic-crm/compare/v1.5.0...v1.6.0 + +## v1.5.0 - 2026-03-10 + +Read about the updates online: [Atomic CRM March 2026 Updates](https://marmelab.com/blog/2026/03/13/atomic-crm-march-updates.html) + +## Breaking Change + +* table `contactNotes` has been renamed `contact_notes` +* table `dealNotes` has been renamed `deal_notes` +* column `stateAbbr` in table `companies` has been renamed `state_abbr` + +You must run the migration to update your database schema: + +``` +make supabase-migrate-database +``` + +## What's Changed + +* Replace React Admin with Shadcn Admin Kit by @Madeorsk in #104 +* Add SSO support and documentation by @djhi in #159, #161 +* Add Settings page by @fzaninotto in #162 +* Add mail forwarding by @ThieryMichel in #185 +* Add ability to import data from another CRM by @djhi in #133 +* Add support for attachments in inbound emails by @slax57 in #158 +* Add mobile app by @slax57 in #134 +* Add support for multiple emails and phone numbers per contact by @slax57 in #80 +* Add new fields to JSON import by @slax57 in #179 +* Add ability to load older notes on demand by @ThieryMichel in #177 +* Add custom telemetry by @djhi in #79 +* Add a confirmation page when the first user needs to confirm their email by @Madeorsk in #155 +* Add access control by @djhi in #70 +* Fix consistency in table and field names by @djhi in #136 +* Fix dates sometimes appearing shifted by 1 day by @ThieryMichel in #190 +* Fix error message when user creation fails by @Madeorsk in #151 +* Fix note list performance on mobile by @fzaninotto in #160 +* Fix attachment previews by @djhi in #154 +* Fix RLS policies on the sales table by @djhi in #74 +* Fix on-the-fly company creation by @fzaninotto in #120 +* Fix Deal list error by @djhi in #122 +* Fix New Task dialog closing even if task is invalid by @fzaninotto in #85 +* Fix signup error notification not being displayed by @WiXSL in #132 +* Fix password recovery email sent notification not showing by @WiXSL in #165 +* Fix Supabase authentication system for edge functions by @Madeorsk in #152 +* Fix JWT locally by @Madeorsk in #153 +* Fix mobile sheets height on Google Pixel devices by @slax57 in #172 +* Fix mobile note/task/contact headers to use ellipsis by @WiXSL in #176 +* Fix contact edit sheet header truncation on mobile by @WiXSL in #178 +* Fix DateInput and DateTimeInput on mobile Safari by @slax57 in #180 +* Fix ContactInput options cannot be scrolled on mobile by @slax57 in #181 +* Fix note attachment deletion on note remove by @WiXSL in #171 +* Fix remote init script by asking for org and region by @ThieryMichel in #191 +* Fix supabase-remote-init and prod-start scripts by @slax57 in #143 +* Fix Atomic registry components imports by @djhi in #118 +* Fix registry.json missing files and dependencies by @slax57 in #197 +* Fix UI contact component search input and icon contact filter by @mpsalunggg in #107 +* Fix typos and remove unused imports by @eithe in #69 +* Bump various dependencies (rollup, vitest, hono, lodash, dompurify, qs, devalue, storybook, minimatch, @modelcontextprotocol/sdk) by @dependabot[bot] in #67, #87, #130, #135, #137, #138, #142, #148, #149, #157, #166, #173, #174, #186, #187, #188, #189, #194, #196 +* [Doc] Improve documentation about initial production setup by @djhi in #77 +* [Doc] Document email setup by @djhi in #71 +* [Doc] Add Starlight documentation by @jonathanarnault in #110 +* [Doc] Fix documentation links by @main-uk in #116, @djhi in #127 +* [Doc] Add getting started link to menu and fix logo size by @jonathanarnault in #111 +* [Chore] Refactor remote init script by @djhi in #76 +* [Chore] Add registry file for Atomic CRM by @jonathanarnault in #115 +* [Chore] Add a build-lib command to publish an atomic-crm node module by @ThieryMichel in #66 +* [Chore] Allow TS sourcemaps in production by @djhi in #88 +* [Chore] Improve GitHub community standards by @arimet in #73 + +## New Contributors +* @dependabot[bot] made their first contribution in https://github.com/marmelab/atomic-crm/pull/67 +* @eithe made their first contribution in https://github.com/marmelab/atomic-crm/pull/69 +* @djhi made their first contribution in https://github.com/marmelab/atomic-crm/pull/70 +* @SxMShaDoW made their first contribution in https://github.com/marmelab/atomic-crm/pull/78 +* @fzaninotto made their first contribution in https://github.com/marmelab/atomic-crm/pull/85 +* @anthonycmain made their first contribution in https://github.com/marmelab/atomic-crm/pull/86 +* @0xflotus made their first contribution in https://github.com/marmelab/atomic-crm/pull/93 +* @erwanMarmelab made their first contribution in https://github.com/marmelab/atomic-crm/pull/96 +* @Madeorsk made their first contribution in https://github.com/marmelab/atomic-crm/pull/104 +* @mpsalunggg made their first contribution in https://github.com/marmelab/atomic-crm/pull/107 +* @main-uk made their first contribution in https://github.com/marmelab/atomic-crm/pull/116 +* @CMiksche made their first contribution in https://github.com/marmelab/atomic-crm/pull/123 +* @WiXSL made their first contribution in https://github.com/marmelab/atomic-crm/pull/132 + +**Full Changelog**: https://github.com/marmelab/atomic-crm/compare/v1.0.0...v1.5.0 + +## v1.0.0 - 2026-03-10 + +## What's Changed +* Fix(ops): Upgrade packages by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/1 +* Feat(signup): Add user signup support by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/3 +* Feat(upload): Send files to storage supabase by @arimet in https://github.com/marmelab/atomic-crm/pull/4 +* Fix(db): Add missing row policies to database by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/5 +* Feat(crm): Backport demo features to atomic-crm by @arimet in https://github.com/marmelab/atomic-crm/pull/7 +* Feat(database): Update columns to match the CRM demo types by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/2 +* Feat(supabase): Update init project script by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/6 +* Feat(atomic): Create view for companies and contact + ban users by @arimet in https://github.com/marmelab/atomic-crm/pull/10 +* Feat(crm): Add supabase deploy scripts by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/9 +* Feat(ops): Add deploy script by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/8 +* Feat(ops): Add CI/CD pipeline by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/11 +* Fix(init): Remove login required notification if crm is not initialized by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/13 +* Feat(crm): Set isImage into dataProvider by @arimet in https://github.com/marmelab/atomic-crm/pull/12 +* Fix(crm): Handle tags for Contact export by @arimet in https://github.com/marmelab/atomic-crm/pull/15 +* Fix(crm): Set phone number into split fields + update getCompanyAvatar by @arimet in https://github.com/marmelab/atomic-crm/pull/14 +* Fix(contacts): Return all sales in sales selector by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/16 +* Fix(crm): Date validation + refactor uploadToBucket by @arimet in https://github.com/marmelab/atomic-crm/pull/19 +* Fix(contact): Display LinkedIn profile as URL label in contact aside by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/18 +* Fix(ops): GitHub pages were not pushed as expected by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/22 +* Fix(crm): Apply suggestions from reviews by @arimet in https://github.com/marmelab/atomic-crm/pull/21 +* Fix(ops): Github pages were not pushed as expected by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/24 +* Fix(setting): Update current user information in supabase by @arimet in https://github.com/marmelab/atomic-crm/pull/23 +* Feat(auth): Add reset-password for Sales by @arimet in https://github.com/marmelab/atomic-crm/pull/26 +* Fix(crm): Handle deploy for Browser Router by @arimet in https://github.com/marmelab/atomic-crm/pull/30 +* Fix(views): Add security invokers to views to avoid data leak by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/29 +* Fix(deploy) by @arimet in https://github.com/marmelab/atomic-crm/pull/31 +* Fix(deploy): Add supabase project url and anon key to CI/CD by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/32 +* Fix(login): Fix admin base name by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/33 +* Fix: Search contact + improve import contact. by @arimet in https://github.com/marmelab/atomic-crm/pull/28 +* Feat(task): Associate task to an sales_id + improve documentation by @arimet in https://github.com/marmelab/atomic-crm/pull/25 +* Fix(migrations): recreate contact_summary view in remove acquisition migration by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/35 +* Feat(crm): Replace browserRouter with HashRouter and handle reset cal… by @arimet in https://github.com/marmelab/atomic-crm/pull/36 +* Feat(auth): Update supabase password via CRM UI by @arimet in https://github.com/marmelab/atomic-crm/pull/34 +* Feat(dataProvider): Add supabase to fakerest filter adapter by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/20 +* Fix(deals): Company name was not displayed in deal show modal by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/38 +* Fix(macOS): Update package lock to include rollup native binaries by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/41 +* Add fake rest provider by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/27 +* Feat(ops): Add option to deploy to another repository by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/37 +* Feat(UI): Improve Dashboard and display Empty Pages only if no filters are present by @arimet in https://github.com/marmelab/atomic-crm/pull/40 +* Feat(doc): Add linked supabase configuration guide by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/39 +* Fix(ux): Reduce initial loading time by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/42 +* Feat(mail): Add contact note via email by @slax57 in https://github.com/marmelab/atomic-crm/pull/17 +* Fix(perf): Logout user if db has been reset and improve login page load performance by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/45 +* Sec(init_state): init_state view is no longer leaking sales count by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/46 +* fix(crm): Fix signup page logo color by @slax57 in https://github.com/marmelab/atomic-crm/pull/44 +* Fix(avatar): Avatar upload does not fail anymore if no change in file… by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/48 +* Feat(auth): Handle resetPassword and Invite user by @arimet in https://github.com/marmelab/atomic-crm/pull/43 +* Feat(auth): For reseting user password, send reset email by @arimet in https://github.com/marmelab/atomic-crm/pull/47 +* Fix(ops): Update cross deploy documentation by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/50 +* Fix(import): tags and companies are no loger duplicated during imports by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/53 +* fix(mail): Support recipient with empty Name by @slax57 in https://github.com/marmelab/atomic-crm/pull/52 +* Feat(crm): Update mail templates by @arimet in https://github.com/marmelab/atomic-crm/pull/51 +* fix(login): Fix user is not automatically logged in after signup by @slax57 in https://github.com/marmelab/atomic-crm/pull/49 +* Fix(note): Improve note spacing by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/55 +* Fix(mail): Add debug log when creating a user and add documentation about email rate limit by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/56 +* Feat(task): Display Tasks for curent calendar week and not for seven … by @arimet in https://github.com/marmelab/atomic-crm/pull/54 +* Feat(setting): Display inboud email for user by @arimet in https://github.com/marmelab/atomic-crm/pull/59 +* Fix(avatar): Avatar deletion is now persisted as expected by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/57 +* Fix(contact): Update last_seen when a note is added to the contact by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/58 +* Feat(mailing): Add support for multiple recipients and fix some typos in mails by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/60 +* Feat(tasks): Update contact last seen when creating a task by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/61 +* Feat(task): Add task edit support by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/63 +* Feat(doc): Improve documentation by @jonathanarnault in https://github.com/marmelab/atomic-crm/pull/64 +* skip gh action task when needed secrets are missing by @ThieryMichel in https://github.com/marmelab/atomic-crm/pull/65 + + +**Full Changelog**: https://github.com/marmelab/atomic-crm/commits/v1.0.0 + diff --git a/apps/web/LICENSE.md b/apps/web/LICENSE.md new file mode 100644 index 0000000..7d10cba --- /dev/null +++ b/apps/web/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024-present, Francois Zaninotto, Marmelab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/web/build-env.ts b/apps/web/build-env.ts new file mode 100644 index 0000000..9c84d77 --- /dev/null +++ b/apps/web/build-env.ts @@ -0,0 +1,54 @@ +// What a production build inlines: the Supabase project the browser talks to, +// read from the `vars` of the wrangler.jsonc beside this file — committed as +// the fixture render of wrangler.template.jsonc, and re-rendered from the +// environment's wiring document by every Orun lane before it builds +// (component.yaml) — so the bundle and the Worker get the same URL and key +// from one place. A VITE_* value already in the environment (or .env.local) +// wins, as it does upstream. +import fs from "node:fs"; + +export function stripJsonc(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === '"') { + let j = i + 1; + while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1; + out += text.slice(i, j + 1); + i = j; + } else if (c === "/" && text[i + 1] === "/") { + while (i < text.length && text[i] !== "\n") i++; + out += "\n"; + } else if (c === "/" && text[i + 1] === "*") { + i = text.indexOf("*/", i + 2); + if (i < 0) break; + i++; + } else { + out += c; + } + } + return out.replace(/,(\s*[}\]])/g, "$1"); +} + +const FROM_WRANGLER = { + VITE_SUPABASE_URL: "SUPABASE_URL", + VITE_SB_PUBLISHABLE_KEY: "SB_PUBLISHABLE_KEY", +} as const; + +export function supabaseBuildEnv( + env: Record, + wranglerConfig: string, +): Record { + let vars: Record = {}; + try { + vars = JSON.parse(stripJsonc(fs.readFileSync(wranglerConfig, "utf8"))).vars ?? {}; + } catch { + vars = {}; + } + const out: Record = {}; + for (const [key, from] of Object.entries(FROM_WRANGLER)) { + const value = env[key] || vars[from]; + if (typeof value === "string" && value.length > 0) out[key] = value; + } + return out; +} diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..5d7f07c --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,70 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: web + description: The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment + +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: product + path: apps/web + lane: isolated + change: + inputs: + - pnpm-lock.yaml + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # wrangler bundles the Worker from its source on deploy; the build is the + # single-page app. + workerEntrypoint: worker/index.ts + assetsDir: dist + + workerName: atomic-crm-web + environmentAwareWorkerName: true + + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # Render wrangler.jsonc for this environment (dev from the fixture), then + # build the app — which inlines the project's URL and publishable key from + # that render (vite.config.ts) — then hand the Worker its secrets. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components supabase,cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret SUPABASE_SERVICE_ROLE_KEY --secret POSTMARK_WEBHOOK_USER --secret POSTMARK_WEBHOOK_PASSWORD --secret POSTMARK_WEBHOOK_AUTHORIZED_IPS --worker "atomic-crm-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc + + smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q '
' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true' && test \"$(curl -s -o /dev/null -w '%{http_code}' -X PATCH \"${DEPLOYED_URL}/functions/v1/update_password\")\" = 401" + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 0000000..13e1db0 --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} diff --git a/apps/web/demo/App.tsx b/apps/web/demo/App.tsx new file mode 100644 index 0000000..980a568 --- /dev/null +++ b/apps/web/demo/App.tsx @@ -0,0 +1,16 @@ +import { CRM } from "@/components/crm/root/CRM"; +import { + authProvider, + dataProvider, +} from "@/components/crm/providers/fakerest"; +import { memoryStore } from "ra-core"; + +const App = () => ( + +); + +export default App; diff --git a/apps/web/demo/main.tsx b/apps/web/demo/main.tsx new file mode 100644 index 0000000..72d9bd7 --- /dev/null +++ b/apps/web/demo/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import "../src/index.css"; +import App from "./App.tsx"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md new file mode 100644 index 0000000..4779d11 --- /dev/null +++ b/apps/web/docs/architecture.md @@ -0,0 +1,31 @@ +# web — architecture + +One Worker per environment, `atomic-crm-web-`. + +``` +browser ──▶ Static Assets (dist/: the React-Admin SPA, hash-routed) + │ + ├──▶ Supabase project: Auth, PostgREST (the data provider), Storage + │ + └──▶ /functions/v1/ ──▶ this Worker (worker/index.ts) + ├─ users, update_password, delete_note_attachments, postmark + │ └─▶ Supabase admin API (service-role key, a Worker secret) + └─ merge_contacts, mcp + └─▶ Postgres through Hyperdrive (HYPERDRIVE binding) +``` + +- **The SPA** is upstream's (`src/`), built by Vite. A build inlines the + project's URL and publishable key from the `vars` of the rendered + `wrangler.jsonc` (`build-env.ts`), so the bundle and the Worker always + name the same project. +- **The edge functions** are upstream's `supabase/functions`, in + `worker/functions`, nearly verbatim: `Deno.env.get` and `Deno.serve` come + from a two-function shim (`worker/functions/_shared/deno.ts`) and the + `jsr:`/`npm:` imports are npm packages. The Supabase client's `fetch` sends + `/functions/v1/*` to the page's own origin, so `supabase.functions.invoke` + reaches them unchanged. +- **Postgres** is reached per request (Kysely over `pg` for + `merge_contacts`, one client per query for the MCP server): a Worker may not + reuse a socket another request opened, and Hyperdrive is the pool. +- `run_worker_first` sends only `/functions/*` and `/api/*` to the Worker; + every other path is a file, or `index.html`. diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md new file mode 100644 index 0000000..5224d66 --- /dev/null +++ b/apps/web/docs/overview.md @@ -0,0 +1,20 @@ +# web + +The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment + +A Cloudflare Worker with Static Assets, deployed per environment by its CI lane. + +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md new file mode 100644 index 0000000..ea9ee8f --- /dev/null +++ b/apps/web/docs/runbook.md @@ -0,0 +1,15 @@ +# web — runbook + +| Symptom | Check | Fix | +|---|---|---| +| The deploy's smoke test fails on `/` | `curl -s https:/// \| grep 'id="root"'` | the build did not produce `dist/`: read the lane's `build-app` step | +| `/api/health` says `"supabase": false` | the rendered `wrangler.jsonc` `vars` | the Supabase root has not applied for this environment, or its `WIRING_SUPABASE` secret is missing: re-run the `supabase` lane | +| `/api/health` says `"admin": false`; inviting a user or resetting a password fails | `wrangler secret list --name atomic-crm-web-` | the deploy found no `SUPABASE_SERVICE_ROLE_KEY`: re-run the `supabase` lane, then this one | +| `/api/health` says `"database": false`; merging contacts fails | the `hyperdrive` block of the rendered config | re-run `cloudflare-hyperdrive`, then this lane | +| Sign-in works but every list is empty | the browser console: PostgREST 401/42501 | the schema is not applied: re-run `db-migrate` | +| `/functions/v1/postmark` answers 503 | — | inbound email is optional: store `POSTMARK_WEBHOOK_USER`, `POSTMARK_WEBHOOK_PASSWORD` and `POSTMARK_WEBHOOK_AUTHORIZED_IPS` as Orun secrets and redeploy | + +Local: `pnpm --filter @app/web preview` builds the app and serves it with the +Worker under `wrangler dev` on :8787 (secrets from `.dev.vars`, see +`.dev.vars.example`); `pnpm --filter @app/web dev:demo` runs upstream's +FakeRest demo with no Supabase at all. diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js new file mode 100644 index 0000000..4452d7f --- /dev/null +++ b/apps/web/eslint.config.js @@ -0,0 +1,74 @@ +// For more info, see https://github.com/storybookjs/eslint-plugin-storybook#configuration-flat-config-format +import js from "@eslint/js"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import globals from "globals"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { ignores: ["dist", "dev-dist", ".wrangler", "node_modules"] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ["**/*.{ts,tsx,mjs}"], + ignores: ["**/node_modules/**", "**/dist/**", "**/.astro/**"], + languageOptions: { + ecmaVersion: 2020, + }, + plugins: { + "react-hooks": reactHooks, + "react-refresh": reactRefresh, + }, + rules: { + ...reactHooks.configs.recommended.rules, + "react-refresh/only-export-components": [ + "warn", + { allowConstantExport: true }, + ], + "@typescript-eslint/no-unused-vars": [ + "error", + { + varsIgnorePattern: "^_", + argsIgnorePattern: "^_", + }, + ], + "no-console": ["error", { allow: ["warn", "error"] }], + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/consistent-type-imports": "warn", + }, + }, + { + files: ["**/*.{ts,tsx}"], + languageOptions: { + globals: globals.browser, + }, + }, + { + // Node scripts and Claude Code hooks. TypeScript files rely on the + // compiler for undefined identifiers; plain JS needs no-undef back on. + files: ["**/*.mjs"], + languageOptions: { + globals: globals.node, + }, + rules: { + "no-undef": "error", + }, + }, + { + files: [ + "src/components/admin/*.{ts,tsx}", + "src/hooks/*.{ts,tsx}", + "src/lib/*.{ts,tsx}", + ], + rules: { + "@typescript-eslint/no-explicit-any": "error", + "@typescript-eslint/consistent-type-imports": "off", + }, + }, + { + files: ["src/components/ui/*.{ts,tsx}"], + rules: { + "react-refresh/only-export-components": "off", + "@typescript-eslint/consistent-type-imports": "off", + }, + }, +); diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..0cdf08a --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + Atomic CRM + + + + +
+
+
Loading...
+
+
+ + + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..f8fb835 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,125 @@ +{ + "name": "@app/web", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite --force", + "dev:worker": "wrangler dev --port 8787", + "dev:demo": "vite --config vite.demo.config.ts --force", + "build": "vite build", + "build:demo": "vite build --config vite.demo.config.ts", + "preview": "vite build && wrangler dev --port 8787", + "typecheck": "tsc --noEmit -p tsconfig.app.json && tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.worker.json", + "lint": "eslint .", + "wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage", + "deploy": "wrangler deploy" + }, + "dependencies": { + "@fontsource-variable/inter": "5.2.8", + "@hello-pangea/dnd": "18.0.1", + "@modelcontextprotocol/server": "2.3.1", + "@nivo/bar": "0.99.0", + "@radix-ui/react-accordion": "1.2.20", + "@radix-ui/react-avatar": "1.2.6", + "@radix-ui/react-checkbox": "1.3.11", + "@radix-ui/react-dialog": "1.1.23", + "@radix-ui/react-dropdown-menu": "2.1.24", + "@radix-ui/react-label": "2.1.15", + "@radix-ui/react-navigation-menu": "1.2.22", + "@radix-ui/react-popover": "1.1.23", + "@radix-ui/react-progress": "1.1.16", + "@radix-ui/react-radio-group": "1.4.7", + "@radix-ui/react-select": "2.3.7", + "@radix-ui/react-separator": "1.1.15", + "@radix-ui/react-slot": "1.3.3", + "@radix-ui/react-switch": "1.3.7", + "@radix-ui/react-tabs": "1.1.21", + "@radix-ui/react-toggle": "1.1.18", + "@radix-ui/react-toggle-group": "1.1.19", + "@radix-ui/react-tooltip": "1.2.16", + "@streamparser/json-whatwg": "0.0.22", + "@supabase/middleware": "1.0.0", + "@supabase/server": "1.9.1", + "@supabase/supabase-js": "2.100.0", + "@tanstack/query-async-storage-persister": "5.95.2", + "@tanstack/react-query": "5.101.4", + "@tanstack/react-query-persist-client": "5.95.2", + "@types/qs": "6.15.0", + "base64-arraybuffer": "^1.0.2", + "class-variance-authority": "0.7.1", + "clsx": "2.1.1", + "cmdk": "1.1.1", + "cropperjs": "1.6.2", + "date-fns": "3.6.0", + "diacritic": "0.0.2", + "dompurify": "3.4.17", + "faker": "5.5.3", + "inflection": "3.0.2", + "jose": "6.2.2", + "json-stream-es": "1.2.1", + "jsonexport": "3.2.0", + "kysely": "0.27.2", + "lodash": "4.18.1", + "lucide-react": "0.542.0", + "marked": "17.0.5", + "mime": "4.1.0", + "ms": "2.1.3", + "next-themes": "0.4.6", + "papaparse": "5.5.3", + "pg": "8.23.1", + "pgsql-ast-parser": "12.0.2", + "qs": "6.16.1", + "query-string": "7.1.3", + "ra-core": "5.15.5", + "ra-data-fakerest": "5.15.5", + "ra-i18n-polyglot": "5.15.5", + "ra-language-english": "5.15.5", + "ra-language-french": "5.15.5", + "ra-supabase-core": "3.5.2", + "ra-supabase-language-english": "3.5.0", + "ra-supabase-language-french": "3.5.0", + "radix-ui": "1.6.7", + "react": "19.2.4", + "react-cropper": "2.3.3", + "react-dom": "19.2.4", + "react-dropzone": "14.4.1", + "react-error-boundary": "6.1.6", + "react-hook-form": "7.83.0", + "react-router": "7.18.2", + "react-router-dom": "7.18.2", + "sonner": "2.0.7", + "tailwind-merge": "3.6.0", + "tailwindcss": "4.2.2", + "tldts": "7.0.27", + "tw-animate-css": "1.4.0", + "vaul": "1.1.2", + "zod": "4.6.5" + }, + "devDependencies": { + "@cloudflare/workers-types": "^5.20261006.1", + "@eslint/js": "9.39.4", + "@tailwindcss/vite": "4.2.2", + "@types/dompurify": "3.0.5", + "@types/faker": "5.5.9", + "@types/jsonexport": "3.0.5", + "@types/lodash": "4.17.24", + "@types/ms": "2.1.0", + "@types/node": "22.20.1", + "@types/papaparse": "5.5.2", + "@types/pg": "^8.15.6", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@vitejs/plugin-react": "6.0.1", + "eslint": "9.39.4", + "eslint-plugin-react-hooks": "5.2.0", + "eslint-plugin-react-refresh": "0.4.26", + "globals": "16.5.0", + "typescript": "5.8.3", + "typescript-eslint": "8.57.2", + "vite": "8.3.5", + "vite-plugin-pwa": "1.3.0", + "vite-plugin-simple-html": "1.1.0", + "wrangler": "^4.151.0" + } +} diff --git a/apps/web/public/appIcon/100.png b/apps/web/public/appIcon/100.png new file mode 100644 index 0000000..ad942bc Binary files /dev/null and b/apps/web/public/appIcon/100.png differ diff --git a/apps/web/public/appIcon/1024.png b/apps/web/public/appIcon/1024.png new file mode 100644 index 0000000..0d332d3 Binary files /dev/null and b/apps/web/public/appIcon/1024.png differ diff --git a/apps/web/public/appIcon/114.png b/apps/web/public/appIcon/114.png new file mode 100644 index 0000000..aedabf6 Binary files /dev/null and b/apps/web/public/appIcon/114.png differ diff --git a/apps/web/public/appIcon/120.png b/apps/web/public/appIcon/120.png new file mode 100644 index 0000000..32ae110 Binary files /dev/null and b/apps/web/public/appIcon/120.png differ diff --git a/apps/web/public/appIcon/128.png b/apps/web/public/appIcon/128.png new file mode 100644 index 0000000..5b27872 Binary files /dev/null and b/apps/web/public/appIcon/128.png differ diff --git a/apps/web/public/appIcon/144.png b/apps/web/public/appIcon/144.png new file mode 100644 index 0000000..82de8cd Binary files /dev/null and b/apps/web/public/appIcon/144.png differ diff --git a/apps/web/public/appIcon/152.png b/apps/web/public/appIcon/152.png new file mode 100644 index 0000000..3b1f979 Binary files /dev/null and b/apps/web/public/appIcon/152.png differ diff --git a/apps/web/public/appIcon/16.png b/apps/web/public/appIcon/16.png new file mode 100644 index 0000000..51408fb Binary files /dev/null and b/apps/web/public/appIcon/16.png differ diff --git a/apps/web/public/appIcon/167.png b/apps/web/public/appIcon/167.png new file mode 100644 index 0000000..330d05b Binary files /dev/null and b/apps/web/public/appIcon/167.png differ diff --git a/apps/web/public/appIcon/180.png b/apps/web/public/appIcon/180.png new file mode 100644 index 0000000..16dc51a Binary files /dev/null and b/apps/web/public/appIcon/180.png differ diff --git a/apps/web/public/appIcon/192.png b/apps/web/public/appIcon/192.png new file mode 100644 index 0000000..0ad4253 Binary files /dev/null and b/apps/web/public/appIcon/192.png differ diff --git a/apps/web/public/appIcon/20.png b/apps/web/public/appIcon/20.png new file mode 100644 index 0000000..668b727 Binary files /dev/null and b/apps/web/public/appIcon/20.png differ diff --git a/apps/web/public/appIcon/256.png b/apps/web/public/appIcon/256.png new file mode 100644 index 0000000..9d6dacf Binary files /dev/null and b/apps/web/public/appIcon/256.png differ diff --git a/apps/web/public/appIcon/29.png b/apps/web/public/appIcon/29.png new file mode 100644 index 0000000..527fcee Binary files /dev/null and b/apps/web/public/appIcon/29.png differ diff --git a/apps/web/public/appIcon/32.png b/apps/web/public/appIcon/32.png new file mode 100644 index 0000000..e775ae9 Binary files /dev/null and b/apps/web/public/appIcon/32.png differ diff --git a/apps/web/public/appIcon/40.png b/apps/web/public/appIcon/40.png new file mode 100644 index 0000000..3fa5f29 Binary files /dev/null and b/apps/web/public/appIcon/40.png differ diff --git a/apps/web/public/appIcon/50.png b/apps/web/public/appIcon/50.png new file mode 100644 index 0000000..1777238 Binary files /dev/null and b/apps/web/public/appIcon/50.png differ diff --git a/apps/web/public/appIcon/512.png b/apps/web/public/appIcon/512.png new file mode 100644 index 0000000..ed6f8f1 Binary files /dev/null and b/apps/web/public/appIcon/512.png differ diff --git a/apps/web/public/appIcon/57.png b/apps/web/public/appIcon/57.png new file mode 100644 index 0000000..86221b5 Binary files /dev/null and b/apps/web/public/appIcon/57.png differ diff --git a/apps/web/public/appIcon/58.png b/apps/web/public/appIcon/58.png new file mode 100644 index 0000000..3c25f81 Binary files /dev/null and b/apps/web/public/appIcon/58.png differ diff --git a/apps/web/public/appIcon/60.png b/apps/web/public/appIcon/60.png new file mode 100644 index 0000000..105ab7a Binary files /dev/null and b/apps/web/public/appIcon/60.png differ diff --git a/apps/web/public/appIcon/64.png b/apps/web/public/appIcon/64.png new file mode 100644 index 0000000..2ee39be Binary files /dev/null and b/apps/web/public/appIcon/64.png differ diff --git a/apps/web/public/appIcon/72.png b/apps/web/public/appIcon/72.png new file mode 100644 index 0000000..6fc94a3 Binary files /dev/null and b/apps/web/public/appIcon/72.png differ diff --git a/apps/web/public/appIcon/76.png b/apps/web/public/appIcon/76.png new file mode 100644 index 0000000..fd69c1d Binary files /dev/null and b/apps/web/public/appIcon/76.png differ diff --git a/apps/web/public/appIcon/80.png b/apps/web/public/appIcon/80.png new file mode 100644 index 0000000..ce68015 Binary files /dev/null and b/apps/web/public/appIcon/80.png differ diff --git a/apps/web/public/appIcon/87.png b/apps/web/public/appIcon/87.png new file mode 100644 index 0000000..d02bb32 Binary files /dev/null and b/apps/web/public/appIcon/87.png differ diff --git a/apps/web/public/appIcon/maskable_icon.png b/apps/web/public/appIcon/maskable_icon.png new file mode 100644 index 0000000..5a0b8bd Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x128.png b/apps/web/public/appIcon/maskable_icon_x128.png new file mode 100644 index 0000000..804c8d2 Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x128.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x192.png b/apps/web/public/appIcon/maskable_icon_x192.png new file mode 100644 index 0000000..fb6d8c2 Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x192.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x384.png b/apps/web/public/appIcon/maskable_icon_x384.png new file mode 100644 index 0000000..669d06e Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x384.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x48.png b/apps/web/public/appIcon/maskable_icon_x48.png new file mode 100644 index 0000000..f35b2ee Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x48.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x512.png b/apps/web/public/appIcon/maskable_icon_x512.png new file mode 100644 index 0000000..7ce9a0e Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x512.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x72.png b/apps/web/public/appIcon/maskable_icon_x72.png new file mode 100644 index 0000000..a194dd8 Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x72.png differ diff --git a/apps/web/public/appIcon/maskable_icon_x96.png b/apps/web/public/appIcon/maskable_icon_x96.png new file mode 100644 index 0000000..62cb667 Binary files /dev/null and b/apps/web/public/appIcon/maskable_icon_x96.png differ diff --git a/apps/web/public/auth-callback.html b/apps/web/public/auth-callback.html new file mode 100644 index 0000000..b129008 --- /dev/null +++ b/apps/web/public/auth-callback.html @@ -0,0 +1,141 @@ + + + + + + + + + + Atomic CRM + + + + + +
+
+
Loading...
+
+
+ + + diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico new file mode 100644 index 0000000..fc12fe2 Binary files /dev/null and b/apps/web/public/favicon.ico differ diff --git a/apps/web/public/img/adding-users.png b/apps/web/public/img/adding-users.png new file mode 100644 index 0000000..b078003 Binary files /dev/null and b/apps/web/public/img/adding-users.png differ diff --git a/apps/web/public/img/empty.svg b/apps/web/public/img/empty.svg new file mode 100644 index 0000000..a00b838 --- /dev/null +++ b/apps/web/public/img/empty.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/logos/logo_atomic_crm.svg b/apps/web/public/logos/logo_atomic_crm.svg new file mode 100644 index 0000000..331b46b --- /dev/null +++ b/apps/web/public/logos/logo_atomic_crm.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/apps/web/public/manifest.json b/apps/web/public/manifest.json new file mode 100644 index 0000000..0d90526 --- /dev/null +++ b/apps/web/public/manifest.json @@ -0,0 +1,74 @@ +{ + "short_name": "Atomic CRM", + "name": "Atomic CRM", + "icons": [ + { + "src": "favicon.ico", + "sizes": "48x48 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "appIcon/192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "appIcon/512.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "purpose": "maskable", + "sizes": "1024x1024", + "src": "appIcon/maskable_icon.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "512x512", + "src": "appIcon/maskable_icon_x512.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "384x384", + "src": "appIcon/maskable_icon_x384.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "192x192", + "src": "appIcon/maskable_icon_x192.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "128x128", + "src": "appIcon/maskable_icon_x128.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "96x96", + "src": "appIcon/maskable_icon_x96.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "72x72", + "src": "appIcon/maskable_icon_x72.png", + "type": "image/png" + }, + { + "purpose": "maskable", + "sizes": "48x48", + "src": "appIcon/maskable_icon_x48.png", + "type": "image/png" + } + ], + "start_url": ".", + "display": "standalone", + "orientation": "portrait", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/apps/web/public/robots.txt b/apps/web/public/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/apps/web/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/apps/web/src/App.css b/apps/web/src/App.css new file mode 100644 index 0000000..b9d355d --- /dev/null +++ b/apps/web/src/App.css @@ -0,0 +1,42 @@ +#root { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx new file mode 100644 index 0000000..d5f4270 --- /dev/null +++ b/apps/web/src/App.tsx @@ -0,0 +1,36 @@ +import { CRM } from "@/components/crm/root/CRM"; + +/** + * Application entry point + * + * Customize Atomic CRM by passing props to the CRM component: + * - companySectors + * - darkTheme + * - dealCategories + * - dealPipelineStatuses + * - dealStages + * - lightTheme + * - darkModeLogo / lightModeLogo + * - noteStatuses + * - taskTypes + * - title + * ... as well as all the props accepted by shadcn-admin-kit's component. + * + * Logos must be an imported asset, an absolute URL, or a data URI — never a + * route-relative path like "./img/logo.png", which breaks on nested routes. + * + * @example + * import logoDark from "./logo-dark.svg"; + * import logoLight from "./logo-light.svg"; + * + * const App = () => ( + * + * ); + */ +const App = () => ; + +export default App; diff --git a/apps/web/src/assets/react.svg b/apps/web/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/apps/web/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/components/admin/Readme.md b/apps/web/src/components/admin/Readme.md new file mode 100644 index 0000000..c383290 --- /dev/null +++ b/apps/web/src/components/admin/Readme.md @@ -0,0 +1,40 @@ +# Admin Components + +The components in this directory come from [Shadcn Admin Kit](https://marmelab.com/shadcn-admin-kit/). They are application building blocks providing solution to usual single-page apps needs, including: + +- data fetching, +- lists and data tables, +- forms & validation, +- authentication, +- search & filtering, +- i18n, +- theming, +- loading and error management. +- rapid CRUD generation, +- ralationship management, +- roles & permissions, +- optimistic UI, +- undo functionality, +- bulk actions, +- user preferences, +- notifications, +- and more. + +These components are built on top of [TanStack Query](https://tanstack.com/query/latest), [React Hook Form](https://react-hook-form.com/), [React Router](https://reactrouter.com/), [ra-core](https://marmelab.com/ra-core/), [Radix UI](https://www.radix-ui.com/) and [Shadcn UI](https://ui.shadcn.com/). + +## Documentation + +You can find the documentation for these components on the [Shadcn Admin Kit website](https://marmelab.com/shadcn-admin-kit/docs). + +## Customization + +In Atomic CRM, these components are sometimes slightly modified to fit the look and feel of the application. You can customize them further by editing the source files in this directory. + +## Updates + +Shadcn Admin Kit components are actively maintained and updated. To update the components in Atomic CRM, type the following command: + +``` +npx shadcn@latest add -o https://marmelab.com/shadcn-admin-kit/r/admin.json +``` + diff --git a/apps/web/src/components/admin/access-denied.tsx b/apps/web/src/components/admin/access-denied.tsx new file mode 100644 index 0000000..0c52629 --- /dev/null +++ b/apps/web/src/components/admin/access-denied.tsx @@ -0,0 +1,19 @@ +import { Lock } from "lucide-react"; +import { Translate } from "ra-core"; + +/** + * Page displayed when the current user doesn't have the permissions to access a page. + * + * Used by default by ``, and can be passed to ``. + */ +export const AccessDenied = () => ( +
+ +

+ +

+

+ +

+
+); diff --git a/apps/web/src/components/admin/admin.tsx b/apps/web/src/components/admin/admin.tsx new file mode 100644 index 0000000..038f6c3 --- /dev/null +++ b/apps/web/src/components/admin/admin.tsx @@ -0,0 +1,154 @@ +import { + CoreAdminUI, + type CoreAdminUIProps, + CoreAdminContext, + type CoreAdminContextProps, + type CoreAdminProps, + localStorageStore, +} from "ra-core"; +import { i18nProvider as defaultI18nProvider } from "@/lib/i18nProvider"; +import { AccessDenied } from "@/components/admin/access-denied"; +import { Layout } from "@/components/admin/layout"; +import { LoginPage } from "@/components/admin/login-page"; +import { NotFound } from "@/components/admin/not-found"; +import { Ready } from "@/components/admin/ready"; +import { ThemeProvider } from "@/components/admin/theme-provider"; +import { AuthCallback } from "@/components/admin/authentication"; +import { useEffect } from "react"; + +const defaultStore = localStorageStore(); + +/** + * Context provider for the Admin component. + * + * Wraps CoreAdminContext to provide core admin functionality including data provider, + * auth provider, i18n provider, and store access to child components. + * + * @internal + */ +const AdminContext = (props: CoreAdminContextProps) => ( + +); + +/** + * UI component for the Admin application. + * + * Wraps CoreAdminUI with theme provider and handles telemetry reporting. + * Provides the main layout, login page, ready page, and authentication callback. + * + * @internal + */ +const AdminUI = (props: CoreAdminUIProps) => { + const { disableTelemetry = false, ...rest } = props; + + useEffect(() => { + if ( + disableTelemetry || + process.env.NODE_ENV !== "production" || + typeof window === "undefined" || + typeof window.location === "undefined" || + typeof Image === "undefined" + ) { + return; + } + const img = new Image(); + img.src = `https://shadcn-admin-kit-telemetry.marmelab.com/shadcn-admin-kit-telemetry?domain=${window.location.hostname}`; + }, [disableTelemetry]); + + return ( + + + + ); +}; + +/** + * Root component of a shadcn-admin-kit application. + * + * Creates context providers to allow its children to access the app configuration. + * Renders the main routes and layout, and delegates content area rendering to Resource children. + * Combines AdminContext and AdminUI to provide a complete admin interface. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/admin/ Admin documentation} + * + * @example + * // Basic usage with dataProvider and Resources + * import { Admin } from "@/components/admin"; + * import { Resource } from 'ra-core'; + * import simpleRestProvider from 'ra-data-simple-rest'; + * + * const App = () => ( + * + * + * + * ); + * + * @example + * // With authentication and i18n + * + * + * + */ +export const Admin = (props: CoreAdminProps) => { + const { + accessDenied = AccessDenied, + authCallbackPage = AuthCallback, + authenticationError, + authProvider, + basename, + catchAll = NotFound, + children, + dashboard, + dataProvider, + disableTelemetry, + error, + i18nProvider = defaultI18nProvider, + layout = Layout, + loading, + loginPage = LoginPage, + queryClient, + ready = Ready, + requireAuth, + store = defaultStore, + title = "Shadcn Admin", + } = props; + return ( + + + {children} + + + ); +}; diff --git a/apps/web/src/components/admin/app-sidebar.tsx b/apps/web/src/components/admin/app-sidebar.tsx new file mode 100644 index 0000000..4f3ad11 --- /dev/null +++ b/apps/web/src/components/admin/app-sidebar.tsx @@ -0,0 +1,166 @@ +import { createElement } from "react"; +import { + useCanAccess, + useCreatePath, + useGetResourceLabel, + useHasDashboard, + useResourceDefinitions, + useTranslate, +} from "ra-core"; +import { Link, useMatch } from "react-router"; +import { + Sidebar, + SidebarContent, + SidebarFooter, + SidebarGroup, + SidebarGroupContent, + SidebarHeader, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@/components/ui/sidebar"; +import { Skeleton } from "@/components/ui/skeleton"; +import { House, List, Shell } from "lucide-react"; + +/** + * Navigation sidebar displaying menu items, allowing users to navigate between different sections of the application. + * + * The sidebar can collapse to an icon-only view and renders as a collapsible drawer on mobile devices. + * It automatically includes links to the dashboard (if defined) and all list views defined in Resource components. + * + * Included in the default Layout component + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/appsidebar AppSidebar documentation} + * @see {@link https://ui.shadcn.com/docs/components/sidebar shadcn/ui Sidebar component} + * @see layout.tsx + */ +export function AppSidebar() { + const hasDashboard = useHasDashboard(); + const resources = useResourceDefinitions(); + const { openMobile, setOpenMobile } = useSidebar(); + const handleClick = () => { + if (openMobile) { + setOpenMobile(false); + } + }; + return ( + + + + + + + + Acme Inc. + + + + + + + + + + {hasDashboard ? ( + + ) : null} + {Object.keys(resources) + .filter((name) => resources[name].hasList) + .map((name) => ( + + ))} + + + + + + + ); +} + +/** + * Menu item for the dashboard link in the sidebar. + * + * This component renders a sidebar menu item that links to the dashboard page. + * It displays as active when the user is on the dashboard route. + * + * @example + * + */ +export const DashboardMenuItem = ({ onClick }: { onClick?: () => void }) => { + const translate = useTranslate(); + const label = translate("ra.page.dashboard", { + _: "Dashboard", + }); + const match = useMatch({ path: "/", end: true }); + return ( + + + + + {label} + + + + ); +}; + +/** + * Menu item for a resource link in the sidebar. + * + * This component renders a sidebar menu item that links to a resource's list view. + * It checks permissions using canAccess and displays as active when the user is viewing that resource. + * The component icon and label are derived from the resource definition. + * + * @example + * + */ +export const ResourceMenuItem = ({ + name, + onClick, +}: { + name: string; + onClick?: () => void; +}) => { + const { canAccess, isPending } = useCanAccess({ + resource: name, + action: "list", + }); + const resources = useResourceDefinitions(); + const getResourceLabel = useGetResourceLabel(); + const createPath = useCreatePath(); + const to = createPath({ + resource: name, + type: "list", + }); + const match = useMatch({ path: to, end: false }); + + if (isPending) { + return ; + } + + if (!resources || !resources[name] || !canAccess) return null; + + return ( + + + + {resources[name].icon ? ( + createElement(resources[name].icon) + ) : ( + + )} + {getResourceLabel(name, 2)} + + + + ); +}; diff --git a/apps/web/src/components/admin/array-field.tsx b/apps/web/src/components/admin/array-field.tsx new file mode 100644 index 0000000..5da8972 --- /dev/null +++ b/apps/web/src/components/admin/array-field.tsx @@ -0,0 +1,59 @@ +import type { ReactNode } from "react"; +import type { RaRecord, UseListOptions, UseFieldValueOptions } from "ra-core"; +import { ListContextProvider, useList, useFieldValue } from "ra-core"; + +/** + * Reads an array field value, puts it in a ListContext and renders its children. + * + * This field enables the use of list rendering components like SingleFieldList or + * DataTable to display array data. + * To be used with RecordField or DataTable.Col components, or anywhere a RecordContext is available. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/arrayfield/ ArrayField documentation} + * + * @example + * import { + * Show, + * ArrayField, + * RecordField, + * SingleFieldList, + * BadgeField, + * } from '@/components/admin'; + * + * const PostShow = () => ( + * + *
+ * + * + * + * + * + * + * + * + * + *
+ *
+ * ); + */ +export const ArrayField = ( + props: ArrayFieldProps, +) => { + const { children, resource, perPage, sort, filter } = props; + const data = useFieldValue(props) || emptyArray; + const listContext = useList({ data, resource, perPage, sort, filter }); + + return ( + {children} + ); +}; +export type ArrayFieldProps< + RecordType extends RaRecord = RaRecord, + ErrorType = Error, +> = UseListOptions & + UseFieldValueOptions & { + children?: ReactNode; + }; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const emptyArray: any[] = []; diff --git a/apps/web/src/components/admin/array-input.tsx b/apps/web/src/components/admin/array-input.tsx new file mode 100644 index 0000000..be53553 --- /dev/null +++ b/apps/web/src/components/admin/array-input.tsx @@ -0,0 +1,115 @@ +import * as React from "react"; +import type { InputProps } from "ra-core"; +import { + FieldTitle, + isRequired, + useSourceContext, + sanitizeInputRestProps, + ArrayInputBase, +} from "ra-core"; + +import { Label } from "@/components/ui/label"; +import { cn } from "@/lib/utils"; +import { Skeleton } from "../ui/skeleton"; +import { InputHelperText } from "@/components/admin/input-helper-text"; +import { FormError, FormField } from "@/components/admin/form"; + +/** + * Creates a list of sub-forms for editing arrays of data embedded inside a record. + * + * Use `` when you need to edit array fields like order items, tags, or any + * repeatable embedded data. Requires a form iterator child (typically ``) + * to render and manage individual array items. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/arrayinput/ ArrayInput documentation} + * + * @example + * import { + * Edit, + * SimpleForm, + * TextInput, + * NumberInput, + * ArrayInput, + * SimpleFormIterator, + * } from '@/components/admin'; + * + * const OrderEdit = () => ( + * + * + * + * + * + * + * + * + * + * + * + * + * + * ); + */ +export const ArrayInput = (props: ArrayInputProps) => { + const { + className, + defaultValue = [], + label, + isPending, + children, + helperText, + resource: resourceFromProps, + source: arraySource, + validate, + ...rest + } = props; + + const parentSourceContext = useSourceContext(); + const finalSource = parentSourceContext.getSource(arraySource); + + const labelId = React.useId(); + + if (isPending) { + return ; + } + + return ( + + + + {children} + + + + + + ); +}; + +export interface ArrayInputProps extends Omit< + InputProps, + "disabled" | "readOnly" +> { + className?: string; + children: React.ReactNode; + isFetching?: boolean; + isLoading?: boolean; + isPending?: boolean; +} diff --git a/apps/web/src/components/admin/authentication.tsx b/apps/web/src/components/admin/authentication.tsx new file mode 100644 index 0000000..da94d48 --- /dev/null +++ b/apps/web/src/components/admin/authentication.tsx @@ -0,0 +1,86 @@ +import { Link } from "react-router"; +import { Translate, useHandleAuthCallback, useTranslate } from "ra-core"; +import { CircleAlert, LockIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { Loading } from "@/components/admin/loading"; + +/** + * A standalone page to be used as a redirection target for external authentication services (e.g. OAuth) + * + * It displays a loading indicator while processing the authentication response, + * then redirects to the admin app or shows an error message if authentication fails. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/security/ Security documentation} + * + * @example + * import { Admin } from "@/components/admin"; + * import MyAuthCallbackPage from './MyAuthCallbackPage'; + * const App = () => ( + * + * ... + * + * ); + */ +export const AuthCallback = () => { + const { error } = useHandleAuthCallback(); + if (error) { + return ( + + ); + } + return ; +}; + +export interface AuthErrorProps { + className?: string; + title?: string; + message?: string; +} + +/** + * Authentication error page displayed when authentication fails. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/security/ Security documentation} + * + * @example + * import { Admin } from "@/components/admin"; + * import MyAuthErrorPage from './MyAuthErrorPage'; + * const App = () => ( + * + * ... + * + * ); + */ +export const AuthError = (props: AuthErrorProps) => { + const { + className, + title = "ra.page.error", + message = "ra.message.auth_error", + ...rest + } = props; + + const translate = useTranslate(); + return ( +
+

+ + +

+

{translate(message, { _: message })}

+ +
+ ); +}; diff --git a/apps/web/src/components/admin/autocomplete-array-input.tsx b/apps/web/src/components/admin/autocomplete-array-input.tsx new file mode 100644 index 0000000..fcee81d --- /dev/null +++ b/apps/web/src/components/admin/autocomplete-array-input.tsx @@ -0,0 +1,324 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import * as React from "react"; +import { X } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { + Command, + CommandGroup, + CommandItem, + CommandList, +} from "@/components/ui/command"; +import { + FormControl, + FormError, + FormField, + FormLabel, +} from "@/components/admin/form"; +import { Command as CommandPrimitive } from "cmdk"; +import type { + ChoicesProps, + InputProps, + SupportCreateSuggestionOptions, +} from "ra-core"; +import { + useChoices, + useChoicesContext, + useGetRecordRepresentation, + useInput, + useTranslate, + FieldTitle, + useEvent, + useSupportCreateSuggestion, +} from "ra-core"; +import { InputHelperText } from "./input-helper-text"; +import { useCallback } from "react"; + +/** + * Form control that lets users choose multiple values from a list using a dropdown with autocompletion. + * + * This input allows editing array values with a searchable dropdown interface and displays selected items as removable badges. + * Works seamlessly inside ReferenceArrayInput for creating and editing many-to-many relationships. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/autocompletearrayinput/ AutocompleteArrayInput documentation} + * + * @example + * import { + * Create, + * SimpleForm, + * AutocompleteArrayInput, + * ReferenceArrayInput, + * } from '@/components/admin'; + * + * const PostCreate = () => ( + * + * + * + * + * + * + * + * + * ); + */ +export const AutocompleteArrayInput = ( + props: Omit & + Omit & + Partial> & + ChoicesProps & { + className?: string; + disableValue?: string; + filterToQuery?: (searchText: string) => any; + translateChoice?: boolean; + placeholder?: string; + inputText?: + | React.ReactNode + | ((option: any | undefined) => React.ReactNode); + }, +) => { + const { + filterToQuery = DefaultFilterToQuery, + inputText, + create, + createValue, + createLabel, + createHintValue, + createItemLabel, + onCreate, + optionText, + } = props; + const { + allChoices = [], + source, + resource, + isFromReference, + setFilters, + } = useChoicesContext(props); + const { id, field, isRequired } = useInput({ ...props, source }); + const translate = useTranslate(); + const { placeholder = translate("ra.action.search", { _: "Search..." }) } = + props; + + const getRecordRepresentation = useGetRecordRepresentation(resource); + const { getChoiceText, getChoiceValue } = useChoices({ + optionText: + props.optionText ?? (isFromReference ? getRecordRepresentation : "name"), + optionValue: props.optionValue ?? "id", + disableValue: props.disableValue, + translateChoice: props.translateChoice ?? !isFromReference, + createValue, + createHintValue, + }); + + const inputRef = React.useRef(null); + const listRef = React.useRef(null); + const [open, setOpen] = React.useState(false); + + const handleUnselect = useEvent((choice: any) => { + field.onChange( + field.value.filter((v: any) => v !== getChoiceValue(choice)), + ); + }); + + const handleKeyDown = useEvent((e: React.KeyboardEvent) => { + const input = inputRef.current; + if (input) { + if (e.key === "Delete" || e.key === "Backspace") { + if (input.value === "") { + field.onChange(field.value.slice(0, -1)); + } + } + // This is not a default behavior of the field + if (e.key === "Escape") { + input.blur(); + } + } + }); + + const availableChoices = allChoices.filter( + (choice) => !field.value.includes(getChoiceValue(choice)), + ); + const selectedChoices = allChoices.filter((choice) => + field.value.includes(getChoiceValue(choice)), + ); + const [filterValue, setFilterValue] = React.useState(""); + + const getInputText = useCallback( + (selectedChoice: any) => { + if (typeof inputText === "function") { + return inputText(selectedChoice); + } + if (inputText !== undefined) { + return inputText; + } + return getChoiceText(selectedChoice); + }, + [inputText, getChoiceText], + ); + + const handleChange = useEvent((choice: any) => { + setFilterValue(""); + if (isFromReference) { + setFilters(filterToQuery("")); + } + const value = getChoiceValue(choice); + if (field.value.includes(value)) { + return; + } + field.onChange([...field.value, value]); + }); + + const { + getCreateItem, + handleChange: handleChangeWithCreateSupport, + createElement, + getOptionDisabled, + } = useSupportCreateSuggestion({ + create, + createLabel, + createValue, + createHintValue, + createItemLabel, + onCreate, + handleChange, + optionText, + filter: filterValue, + }); + + const createItem = + (create || onCreate) && (filterValue !== "" || createLabel) + ? getCreateItem(filterValue) + : null; + const finalChoices = createItem + ? [...availableChoices, createItem] + : availableChoices; + + return ( + <> + + {props.label !== false && ( + + + + )} + + +
+
+ {selectedChoices.map((choice) => ( + + {getInputText(choice)} + + + ))} + {/* Avoid having the "Search" Icon by not using CommandInput */} + { + setFilterValue(filter); + requestAnimationFrame(() => { + listRef.current?.scrollTo(0, 0); + }); + // We don't want the ChoicesContext to filter the choices if the input + // is not from a reference as it would also filter out the selected values + if (isFromReference) { + setFilters(filterToQuery(filter), undefined, true); + } + }} + onBlur={() => setOpen(false)} + onFocus={() => setOpen(true)} + placeholder={placeholder} + className="ml-2 flex-1 bg-transparent outline-none placeholder:text-muted-foreground" + /> +
+
+
+ + {open && finalChoices.length > 0 ? ( +
+ + {finalChoices.map((choice) => { + const isCreateItem = + !!createItem && choice?.id === createItem.id; + const choiceText = getChoiceText(choice); + return ( + { + e.preventDefault(); + e.stopPropagation(); + }} + onSelect={() => + handleChangeWithCreateSupport(choice) + } + className="cursor-pointer" + > + {choiceText} + + ); + })} + +
+ ) : null} +
+
+
+
+ + +
+ {createElement} + + ); +}; + +const DefaultFilterToQuery = (searchText: string) => ({ q: searchText }); diff --git a/apps/web/src/components/admin/autocomplete-input.tsx b/apps/web/src/components/admin/autocomplete-input.tsx new file mode 100644 index 0000000..0a7652c --- /dev/null +++ b/apps/web/src/components/admin/autocomplete-input.tsx @@ -0,0 +1,331 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import * as React from "react"; +import { useCallback } from "react"; +import { Check, ChevronsUpDown, X } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from "@/components/ui/command"; +import { + FormControl, + FormError, + FormField, + FormLabel, +} from "@/components/admin/form"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import type { + ChoicesProps, + InputProps, + SupportCreateSuggestionOptions, +} from "ra-core"; +import { + useChoices, + useChoicesContext, + useGetRecordRepresentation, + useInput, + useTranslate, + FieldTitle, + useEvent, + useSupportCreateSuggestion, +} from "ra-core"; +import { InputHelperText } from "./input-helper-text"; +import { PopoverProps } from "@radix-ui/react-popover"; + +/** + * Form control that lets users choose a value from a list using a dropdown with autocompletion. + * + * This input allows editing scalar values with a searchable dropdown interface. It supports creating + * new choices on the fly and works seamlessly inside ReferenceInput for editing foreign key relationships. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/autocompleteinput/ AutocompleteInput documentation} + * + * @example + * import { + * Create, + * SimpleForm, + * AutocompleteInput, + * ReferenceInput, + * } from '@/components/admin'; + * + * const PostCreate = () => ( + * + * + * + * + * + * + * + * + * ); + */ +export const AutocompleteInput = ( + props: Omit & + Omit & + Partial> & + ChoicesProps & { + className?: string; + clearable?: boolean; + disableValue?: string; + filterToQuery?: (searchText: string) => any; + translateChoice?: boolean; + placeholder?: string; + inputText?: + | React.ReactNode + | ((option: any | undefined) => React.ReactNode); + } & Pick, +) => { + const { + clearable = false, + filterToQuery = DefaultFilterToQuery, + inputText, + create, + createValue, + createLabel, + createHintValue, + createItemLabel, + onCreate, + optionText, + modal, + } = props; + const { + allChoices = [], + source, + resource, + isFromReference, + setFilters, + } = useChoicesContext(props); + const { id, field, isRequired } = useInput({ ...props, source }); + const uniqueId = React.useId(); + const translate = useTranslate(); + const { placeholder = translate("ra.action.search", { _: "Search..." }) } = + props; + const hasLabel = props.label !== false; + const accessibleName = + !hasLabel && props.placeholder ? placeholder : undefined; + const isClearable = clearable && !isRequired && !!field.value; + + const getRecordRepresentation = useGetRecordRepresentation(resource); + const { getChoiceText, getChoiceValue } = useChoices({ + optionText: + props.optionText ?? (isFromReference ? getRecordRepresentation : "name"), + optionValue: props.optionValue ?? "id", + disableValue: props.disableValue, + translateChoice: props.translateChoice ?? !isFromReference, + }); + + const [filterValue, setFilterValue] = React.useState(""); + const listRef = React.useRef(null); + + const [open, setOpen] = React.useState(false); + const selectedChoice = allChoices.find( + (choice) => getChoiceValue(choice) === field.value, + ); + + const getInputText = useCallback( + (selectedChoice: any) => { + if (typeof inputText === "function") { + return inputText(selectedChoice); + } + if (inputText !== undefined) { + return inputText; + } + return getChoiceText(selectedChoice); + }, + [inputText, getChoiceText], + ); + + const handleOpenChange = useEvent((isOpen: boolean) => { + setOpen(isOpen); + // Reset the filter when the popover is closed + if (!isOpen) { + setFilters(filterToQuery("")); + } + }); + + const handleReset = useEvent(() => { + field.onChange(""); + setFilterValue(""); + if (isFromReference) { + setFilters(filterToQuery("")); + } + setOpen(false); + }); + + const handleChange = useCallback( + (choice: any) => { + if (field.value === getChoiceValue(choice) && !isRequired) { + handleReset(); + return; + } + field.onChange(getChoiceValue(choice)); + setOpen(false); + }, + [field, getChoiceValue, isRequired, handleReset, setOpen], + ); + + const { + getCreateItem, + handleChange: handleChangeWithCreateSupport, + createElement, + getOptionDisabled, + } = useSupportCreateSuggestion({ + create, + createLabel, + createValue, + createHintValue, + createItemLabel, + onCreate, + handleChange, + optionText, + filter: filterValue, + }); + + const createItem = + (create || onCreate) && (filterValue !== "" || createLabel) + ? getCreateItem(filterValue) + : null; + let finalChoices = allChoices; + if (createItem) { + finalChoices = [...finalChoices, createItem]; + } + + return ( + <> + + {props.label !== false && ( + + + + )} + + +
+ + + + {isClearable && ( + + )} +
+ + {/* We handle the filtering ourselves */} + + { + setFilterValue(filter); + requestAnimationFrame(() => { + listRef.current?.scrollTo(0, 0); + }); + // We don't want the ChoicesContext to filter the choices if the input + // is not from a reference as it would also filter out the selected values + if (isFromReference) { + setFilters(filterToQuery(filter)); + } + }} + /> + + No matching item found. + + {finalChoices.map((choice) => { + const isCreateItem = + !!createItem && choice?.id === createItem.id; + const disabled = getOptionDisabled(choice); + + const choiceText = getChoiceText( + isCreateItem ? createItem : choice, + ); + + return ( + handleChangeWithCreateSupport(choice)} + disabled={disabled} + > + + {choiceText} + + ); + })} + + + + +
+
+ + +
+ {createElement} + + ); +}; + +const DefaultFilterToQuery = (searchText: string) => ({ q: searchText }); diff --git a/apps/web/src/components/admin/badge-field.tsx b/apps/web/src/components/admin/badge-field.tsx new file mode 100644 index 0000000..f1ca3cf --- /dev/null +++ b/apps/web/src/components/admin/badge-field.tsx @@ -0,0 +1,64 @@ +import * as React from "react"; +import type { RaRecord } from "ra-core"; +import { useFieldValue, useTranslate } from "ra-core"; +import { Badge } from "@/components/ui/badge"; +import type { FieldProps } from "@/lib/field.type"; + +type BadgeProps = React.ComponentProps; + +/** + * Displays a text value inside a styled badge component. + * + * This field wraps values in a Badge UI component with customizable variants (default, outline, secondary, destructive). + * Use it to highlight status values, tags, or categorical information. + * To be used with RecordField or DataTable.Col components, or anywhere a RecordContext is available. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/badgefield/ BadgeField documentation} + * @see {@link https://ui.shadcn.com/docs/components/badge Badge documentation} + * + * @example + * import { + * List, + * DataTable, + * BadgeField, + * } from '@/components/admin'; + * + * const OrderList = () => ( + * + * + * + * + * + * + * + * + * ); + */ +export const BadgeField = ({ + defaultValue, + source, + record, + empty, + variant = "outline", + ...rest +}: BadgeFieldProps) => { + const value = useFieldValue({ defaultValue, source, record }); + const translate = useTranslate(); + + if (value == null) { + return empty && typeof empty === "string" + ? translate(empty, { _: empty }) + : empty; + } + + return ( + + {typeof value !== "string" ? value.toString() : value} + + ); +}; + +export interface BadgeFieldProps + extends FieldProps, BadgeProps { + variant?: "default" | "outline" | "secondary" | "destructive"; +} diff --git a/apps/web/src/components/admin/boolean-field.tsx b/apps/web/src/components/admin/boolean-field.tsx new file mode 100644 index 0000000..15cb1f5 --- /dev/null +++ b/apps/web/src/components/admin/boolean-field.tsx @@ -0,0 +1,110 @@ +import { Check, type LucideIcon, X } from "lucide-react"; +import { RaRecord, useFieldValue, useTranslate } from "ra-core"; + +import type { FieldProps } from "@/lib/field.type"; +import { cn } from "@/lib/utils"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; + +/** + * Displays a boolean value as a colored check or close icon. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/booleanfield/ BooleanField documentation} + * + * @example + * import { Show, SimpleShowLayout, BooleanField } from '@/components/admin'; + * + * const PostShow = () => ( + * + * + * + * + * + * + * ); + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const BooleanField = ({ + source, + record, + defaultValue, + className, + TrueIcon = Check, + FalseIcon = X, + valueLabelFalse, + valueLabelTrue, + looseValue = false, + empty = null, +}: BooleanFieldProps) => { + const value = useFieldValue({ source, record, defaultValue }); + const isTruthyValue = value === true || (looseValue && value); + const baseClassName = "size-5 text-foreground"; + + if (looseValue || typeof value === "boolean") { + return ( + + + + {isTruthyValue ? ( + TrueIcon ? ( + + ) : ( +
+ ) + ) : FalseIcon ? ( + + ) : ( +
+ )} + + + + + + + ); + } + + return <>{empty}; +}; + +function RenderLabel({ + value, + valueLabelTrue, + valueLabelFalse, +}: Pick & { + value: boolean; +}) { + const translate = useTranslate(); + + let label = value ? valueLabelTrue : valueLabelFalse; + if (!label) { + label = value ? "ra.boolean.true" : "ra.boolean.false"; + } + if (typeof label === "string") { + label = translate(label, { _: label }); + } + + return

{label}

; +} + +export interface BooleanFieldProps< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends RaRecord = any, +> extends FieldProps { + className?: string; + defaultValue?: unknown; + TrueIcon?: LucideIcon | null; + FalseIcon?: LucideIcon | null; + valueLabelTrue?: string; + valueLabelFalse?: string; + looseValue?: boolean; +} diff --git a/apps/web/src/components/admin/boolean-input.tsx b/apps/web/src/components/admin/boolean-input.tsx new file mode 100644 index 0000000..76e1647 --- /dev/null +++ b/apps/web/src/components/admin/boolean-input.tsx @@ -0,0 +1,118 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import React, { useCallback } from "react"; +import { Switch } from "@/components/ui/switch"; +import { FormError, FormField, FormLabel } from "@/components/admin/form"; +import { useInput, FieldTitle } from "ra-core"; +import { InputHelperText } from "./input-helper-text"; + +/** + * Toggle switch for boolean (true/false) values. + * + * Use `` for binary settings like "is published", "is active", or feature flags. + * Leverages shadcn's Switch component for a native-looking toggle. Note: this input doesn't + * support `null` values—use `` for nullable booleans. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/booleaninput/ BooleanInput documentation} + * @see {@link https://ui.shadcn.com/docs/components/switch Switch documentation} + * + * @example + * import { + * Edit, + * SimpleForm, + * BooleanInput, + * TextInput, + * } from '@/components/admin'; + * + * const PostEdit = () => ( + * + * + * + * + * + * + * + * ); + */ +export const BooleanInput = (props: BooleanInputProps) => { + const { + className, + defaultValue = false, + format, + label, + helperText, + onBlur, + onChange, + onFocus, + readOnly, + disabled, + parse, + resource, + source, + validate, + ...rest + } = props; + const { id, field, isRequired } = useInput({ + defaultValue, + format, + parse, + resource, + source, + onBlur, + onChange, + type: "checkbox", + validate, + disabled, + readOnly, + ...rest, + }); + + const handleChange = useCallback( + (checked: boolean) => { + field.onChange(checked); + // Ensure field is considered as touched + field.onBlur(); + }, + [field], + ); + + return ( + +
+ + + + +
+ + +
+ ); +}; + +export interface BooleanInputProps { + className?: string; + defaultValue?: boolean; + format?: (value: any) => any; + helperText?: React.ReactNode; + label?: React.ReactNode; + onBlur?: (event: React.FocusEvent) => void; + onChange?: (value: any) => void; + onFocus?: (event: React.FocusEvent) => void; + readOnly?: boolean; + disabled?: boolean; + parse?: (value: any) => any; + resource?: string; + source: string; + validate?: any; +} diff --git a/apps/web/src/components/admin/breadcrumb.tsx b/apps/web/src/components/admin/breadcrumb.tsx new file mode 100644 index 0000000..be4e5e3 --- /dev/null +++ b/apps/web/src/components/admin/breadcrumb.tsx @@ -0,0 +1,135 @@ +import * as React from "react"; +import { createPortal } from "react-dom"; +import { Separator } from "@/components/ui/separator"; +import { + Breadcrumb as BaseBreadcrumb, + BreadcrumbEllipsis, + BreadcrumbItem, + BreadcrumbPage, + BreadcrumbList, + BreadcrumbSeparator, +} from "@/components/ui/breadcrumb"; +import { Button } from "@/components/ui/button"; +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from "@/components/ui/drawer"; +import { useIsMobile } from "@/hooks/use-mobile"; +import { Translate } from "ra-core"; + +/** + * A breadcrumb navigation component with mobile drawer support. + * + * Renders breadcrumb navigation in the app header via portal. On mobile, shows a drawer with + * ellipsis for long breadcrumb trails. Use Breadcrumb.Item and Breadcrumb.PageItem as children. + * + * CRUD pages already include a Breadcrumb by default; set `disableBreadcrumb` to hide the + * breadcrumb and/or provide your own. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/breadcrumb/ Breadcrumb documentation} + * @see {@link https://ui.shadcn.com/docs/components/breadcrumb Breadcrumb UI documentation} + * + * @example + * import { Edit, Breadcrumb, SimpleForm } from "@/components/admin"; + * import { RecordRepresentation } from 'ra-core'; + * import { Link } from "react-router"; + * + * const PostEdit = () => ( + * + * + * Home + * Articles + * + * Edit Article "" + * + * + * + * ... + * + * + * ); + */ +export const Breadcrumb = ({ children, ref }: BreadcrumbProps) => { + const breadcrumbPortal = document.getElementById("breadcrumb"); + const isMobile = useIsMobile(); + const [open, setOpen] = React.useState(false); + if (!breadcrumbPortal) return null; + return createPortal( + <> + + + + {isMobile && React.Children.count(children) > 2 ? ( + + + + + + + + + + + Navigate to + + + + + Select a page to navigate to. + + + +
    + {React.Children.toArray(children) + .slice(0, -1) + .map((item) => item)} +
+ + + + + +
+
+
+ + {React.Children.toArray(children).slice(-1)} +
+ ) : ( + React.Children.map( + children, + (child, index) => + child && ( + + {child} + {index < React.Children.count(children) - 1 ? ( + + ) : null} + + ), + ) + )} +
+
+ , + breadcrumbPortal, + ); +}; +Breadcrumb.Item = BreadcrumbItem; +Breadcrumb.PageItem = BreadcrumbPage; + +export { BreadcrumbItem, BreadcrumbPage }; + +export type BreadcrumbProps = React.ComponentProps<"nav">; diff --git a/apps/web/src/components/admin/bulk-actions-toolbar.tsx b/apps/web/src/components/admin/bulk-actions-toolbar.tsx new file mode 100644 index 0000000..b48bb70 --- /dev/null +++ b/apps/web/src/components/admin/bulk-actions-toolbar.tsx @@ -0,0 +1,85 @@ +import type { ReactNode } from "react"; +import { useListContext, Translate } from "ra-core"; +import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { BulkDeleteButton } from "@/components/admin/bulk-delete-button"; +import { SelectAllButton } from "@/components/admin/select-all-button"; +import { X } from "lucide-react"; +import { BulkExportButton } from "./bulk-export-button"; + +/** + * Default children for BulkActionsToolbar. Renders SelectAllButton, BulkExportButton, and BulkDeleteButton. + * + * @internal + */ +export function BulkActionsToolbarChildren() { + return ( + <> + + + + + ); +} + +/** + * A sticky toolbar that appears when rows are selected in a DataTable. + * + * Shows the number of selected rows and provides bulk action buttons. Automatically hidden + * when no rows are selected. Positioned at the bottom center of the screen. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/bulkactionstoolbar/ BulkActionsToolbar documentation} + * + * @example + * import { BulkActionsToolbar, BulkDeleteButton } from '@/components/admin'; + * + * const CustomBulkToolbar = () => ( + * + * + * + * ); + * + * const PostList = () => ( + * + * }> + * ... + * + * + * ); + */ +export const BulkActionsToolbar = ({ + children = , +}: { + children?: ReactNode; +}) => { + const { selectedIds, onUnselectItems } = useListContext(); + if (!selectedIds?.length) { + return null; + } + const handleUnselectAll = (e: React.MouseEvent) => { + e.stopPropagation(); + onUnselectItems(); + }; + return ( + +
+ + + + {selectedIds.length} rows selected + + +
+ {children} +
+ ); +}; diff --git a/apps/web/src/components/admin/bulk-delete-button.tsx b/apps/web/src/components/admin/bulk-delete-button.tsx new file mode 100644 index 0000000..ca438f5 --- /dev/null +++ b/apps/web/src/components/admin/bulk-delete-button.tsx @@ -0,0 +1,87 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { Button } from "@/components/ui/button"; +import { Trash } from "lucide-react"; +import type { RaRecord, UseBulkDeleteControllerParams } from "ra-core"; +import { + useBulkDeleteController, + useGetResourceLabel, + useResourceContext, + useResourceTranslation, +} from "ra-core"; +import { cn } from "@/lib/utils"; +import type { ReactNode } from "react"; + +/** + * A button that deletes multiple selected records at once. + * + * Allows to delete selected records in a DataTable. Use within + * the bulkActionsButtons prop of DataTable or inside BulkActionsToolbar. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/bulkdeletebutton/ BulkDeleteButton documentation} + * + * @example + * import { BulkDeleteButton, BulkExportButton, DataTable, List } from '@/components/admin'; + * + * export const PostList = () => ( + * + * + * + * + * + * } + * > + * ... + * + * + * ); + */ +export const BulkDeleteButton = < + RecordType extends RaRecord = any, + MutationOptionsError = unknown, +>({ + icon = defaultIcon, + label: labelProp, + className, + ...props +}: BulkDeleteButtonProps) => { + const { handleDelete, isPending } = useBulkDeleteController(props); + const resource = useResourceContext(props); + const getResourceLabel = useGetResourceLabel(); + const label = useResourceTranslation({ + resourceI18nKey: resource + ? `resources.${resource}.action.delete` + : undefined, + baseI18nKey: "ra.action.delete", + options: { + name: resource ? getResourceLabel(resource, 1) : undefined, + }, + userText: labelProp, + }); + + return ( + + ); +}; + +export type BulkDeleteButtonProps< + RecordType extends RaRecord = any, + MutationOptionsError = unknown, +> = { + label?: string; + icon?: ReactNode; +} & React.ComponentPropsWithoutRef<"button"> & + UseBulkDeleteControllerParams; + +const defaultIcon = ; diff --git a/apps/web/src/components/admin/bulk-export-button.tsx b/apps/web/src/components/admin/bulk-export-button.tsx new file mode 100644 index 0000000..a42604b --- /dev/null +++ b/apps/web/src/components/admin/bulk-export-button.tsx @@ -0,0 +1,94 @@ +import { Download } from "lucide-react"; +import type { RaRecord, UseBulkExportOptions } from "ra-core"; +import { + useBulkExport, + useGetResourceLabel, + useResourceContext, + useResourceTranslation, +} from "ra-core"; + +import { Button } from "../ui/button"; + +/** + * Export the selected rows + * + * To be used inside the prop. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/bulkexportbutton/ BulkExportButton documentation} + * + * @example + * import { BulkDeleteButton, BulkExportButton, DataTable, List } from '@/components/admin'; + * + * export const PostList = () => ( + * + * + * + * + * + * } + * > + * ... + * + * + * ); + */ +export const BulkExportButton = ({ + icon = defaultIcon, + label: labelProp, + onClick, + ...props +}: BulkExportButtonProps) => { + const bulkExport = useBulkExport(props); + const resource = useResourceContext(props); + const getResourceLabel = useGetResourceLabel(); + const label = useResourceTranslation({ + resourceI18nKey: resource + ? `resources.${resource}.action.export` + : undefined, + baseI18nKey: "ra.action.export", + options: { + name: resource ? getResourceLabel(resource, 1) : undefined, + }, + userText: labelProp, + }); + + const handleClick = (event: React.MouseEvent) => { + bulkExport(); + onClick?.(event); + }; + + return ( + + ); +}; + +const defaultIcon = ; + +export type BulkExportButtonProps = + UseBulkExportOptions & { + icon?: React.ReactNode; + label?: string; + } & React.ComponentProps; + +const sanitizeRestProps = ({ + resource: _resource, + exporter: _exporter, + onClick: _onClick, + label: _label, + icon: _icon, + meta: _meta, + ...rest +}: BulkExportButtonProps) => rest; diff --git a/apps/web/src/components/admin/cancel-button.tsx b/apps/web/src/components/admin/cancel-button.tsx new file mode 100644 index 0000000..22ea21e --- /dev/null +++ b/apps/web/src/components/admin/cancel-button.tsx @@ -0,0 +1,46 @@ +import { CircleX } from "lucide-react"; +import { Translate } from "ra-core"; +import { useNavigate } from "react-router"; + +import { Button } from "../ui/button"; + +/** + * A button that navigates back to the previous page. + * + * Commonly used in form toolbars alongside SaveButton. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/cancelbutton/ CancelButton documentation} + * + * @example + * import { CancelButton, SaveButton, SimpleForm } from '@/components/admin'; + * + * const FormToolbar = () => ( + *
+ * + * + *
+ * ); + * + * const PostEdit = () => ( + * + * }> + * ... + * + * + * ); + */ +export function CancelButton(props: React.ComponentProps<"button">) { + const navigate = useNavigate(); + return ( + + ); +} diff --git a/apps/web/src/components/admin/columns-button.tsx b/apps/web/src/components/admin/columns-button.tsx new file mode 100644 index 0000000..197554d --- /dev/null +++ b/apps/web/src/components/admin/columns-button.tsx @@ -0,0 +1,345 @@ +import { + useState, + useEffect, + Children, + type ComponentProps, + type ReactNode, +} from "react"; +import { createPortal } from "react-dom"; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import * as diacritic from "diacritic"; +import { + useDataTableStoreContext, + useStore, + useTranslate, + useResourceContext, + useDataTableColumnRankContext, + useDataTableColumnFilterContext, + useTranslateLabel, + DataTableColumnRankContext, + DataTableColumnFilterContext, + type RaRecord, + type Identifier, + type SortPayload, + type HintedString, + type ExtractRecordPaths, +} from "ra-core"; +import { Columns, Search } from "lucide-react"; +import * as PopoverPrimitive from "@radix-ui/react-popover"; +import { useIsMobile } from "@/hooks/use-mobile"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { FieldToggle } from "@/components/admin/field-toggle"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { Popover, PopoverTrigger } from "@/components/ui/popover"; +import { cn } from "@/lib/utils"; + +/** + * Renders a button that lets users show / hide columns in a DataTable + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/columnsbutton/ ColumnsButton documentation} + * + * @example + * import { List, DataTable, EditButton, CreateButton, ExportButton, ColumnsButton } from '@/components/admin'; + * + * const PostsList = () => ( + * + * + * + * + * } + * > + * + * + * + * + * + * + * + * ); + */ +export const ColumnsButton = (props: ColumnsButtonProps) => { + const { className, storeKey: _, ...rest } = props; + const resource = useResourceContext(props); + const storeKey = props.storeKey || `${resource}.datatable`; + + const [open, setOpen] = useState(false); + const isMobile = useIsMobile(); + const translate = useTranslate(); + + const title = translate("ra.action.select_columns", { _: "Columns" }); + + return ( + + + + {isMobile ? ( + + + + + {title} + + ) : ( + + )} + + +
+ +
+ +
+ + + + ); +}; + +export interface ColumnsButtonProps extends ComponentProps { + resource?: string; + storeKey?: string; +} + +/** + * Render DataTable.Col elements in the ColumnsButton selector using a React Portal. + * + * @see ColumnsButton + */ +export const ColumnsSelector = ({ children }: ColumnsSelectorProps) => { + const translate = useTranslate(); + const { storeKey, defaultHiddenColumns } = useDataTableStoreContext(); + const [columnRanks, setColumnRanks] = useStore( + `${storeKey}_columnRanks`, + ); + const [_hiddenColumns, setHiddenColumns] = useStore( + storeKey, + defaultHiddenColumns, + ); + const elementId = `${storeKey}-columnsSelector`; + + const [container, setContainer] = useState(() => + typeof document !== "undefined" ? document.getElementById(elementId) : null, + ); + + // on first mount, we don't have the container yet, so we wait for it + useEffect(() => { + if ( + container && + typeof document !== "undefined" && + document.body.contains(container) + ) + return; + // look for the container in the DOM every 100ms + const interval = setInterval(() => { + const target = document.getElementById(elementId); + if (target) setContainer(target); + }, 100); + // stop looking after 500ms + const timeout = setTimeout(() => clearInterval(interval), 500); + return () => { + clearInterval(interval); + clearTimeout(timeout); + }; + }, [elementId, container]); + + const [columnFilter, setColumnFilter] = useState(""); + + if (!container) return null; + + const childrenArray = Children.toArray(children); + const paddedColumnRanks = padRanks(columnRanks ?? [], childrenArray.length); + const shouldDisplaySearchInput = childrenArray.length > 5; + + return createPortal( +
+ {shouldDisplaySearchInput && ( +
+ ) => { + setColumnFilter(e.target.value); + }} + placeholder={translate("ra.action.search_columns", { + _: "Search columns", + })} + className="pr-8" + /> + + {columnFilter && ( + + )} +
+ )} +
    + {paddedColumnRanks.map((position, index) => ( + + + {childrenArray[position]} + + + ))} +
+
+ +
+
, + container, + ); +}; + +interface ColumnsSelectorProps { + children?: React.ReactNode; +} + +export const ColumnsSelectorItem = < + RecordType extends RaRecord = RaRecord, +>({ + source, + label, +}: ColumnsSelectorItemProps) => { + const resource = useResourceContext(); + const { storeKey, defaultHiddenColumns } = useDataTableStoreContext(); + const [hiddenColumns, setHiddenColumns] = useStore( + storeKey, + defaultHiddenColumns, + ); + const columnRank = useDataTableColumnRankContext(); + const [columnRanks, setColumnRanks] = useStore( + `${storeKey}_columnRanks`, + ); + const columnFilter = useDataTableColumnFilterContext(); + const translateLabel = useTranslateLabel(); + if (!source && !label) return null; + const fieldLabel = translateLabel({ + label: typeof label === "string" ? label : undefined, + resource, + source, + }) as string; + const isColumnHidden = hiddenColumns.includes(source!); + const isColumnFiltered = fieldLabelMatchesFilter(fieldLabel, columnFilter); + + const handleMove = ( + index1: number | string, + index2: number | string | null, + ) => { + const colRanks = !columnRanks + ? padRanks([], Math.max(Number(index1), Number(index2 || 0)) + 1) + : Math.max(Number(index1), Number(index2 || 0)) > columnRanks.length - 1 + ? padRanks( + columnRanks, + Math.max(Number(index1), Number(index2 || 0)) + 1, + ) + : columnRanks; + const index1Pos = colRanks.findIndex((index) => index == Number(index1)); + const index2Pos = colRanks.findIndex((index) => index == Number(index2)); + if (index1Pos === -1 || index2Pos === -1) { + return; + } + let newColumnRanks; + if (index1Pos > index2Pos) { + newColumnRanks = [ + ...colRanks.slice(0, index2Pos), + colRanks[index1Pos], + ...colRanks.slice(index2Pos, index1Pos), + ...colRanks.slice(index1Pos + 1), + ]; + } else { + newColumnRanks = [ + ...colRanks.slice(0, index1Pos), + ...colRanks.slice(index1Pos + 1, index2Pos + 1), + colRanks[index1Pos], + ...colRanks.slice(index2Pos + 1), + ]; + } + setColumnRanks(newColumnRanks); + }; + + return isColumnFiltered ? ( + + isColumnHidden + ? setHiddenColumns( + hiddenColumns.filter((column) => column !== source!), + ) + : setHiddenColumns([...hiddenColumns, source!]) + } + onMove={handleMove} + /> + ) : null; +}; + +// this is the same interface as DataTableColumnProps +// but we copied it here to avoid circular dependencies with data-table +export interface ColumnsSelectorItemProps< + RecordType extends RaRecord = RaRecord, +> { + className?: string; + cellClassName?: string; + headerClassName?: string; + conditionalClassName?: (record: RecordType) => string | false | undefined; + children?: ReactNode; + render?: (record: RecordType) => React.ReactNode; + field?: React.ElementType; + source?: NoInfer>>; + label?: React.ReactNode; + disableSort?: boolean; + sortByOrder?: SortPayload["order"]; +} +// Function to help with column ranking +const padRanks = (ranks: number[], length: number) => + ranks.concat( + Array.from({ length: length - ranks.length }, (_, i) => ranks.length + i), + ); + +const fieldLabelMatchesFilter = (fieldLabel: string, columnFilter?: string) => + columnFilter + ? diacritic + .clean(fieldLabel) + .toLowerCase() + .includes(diacritic.clean(columnFilter).toLowerCase()) + : true; diff --git a/apps/web/src/components/admin/confirm.tsx b/apps/web/src/components/admin/confirm.tsx new file mode 100644 index 0000000..6cc08b7 --- /dev/null +++ b/apps/web/src/components/admin/confirm.tsx @@ -0,0 +1,166 @@ +import { AlertCircle, CheckCircle } from "lucide-react"; +import { useTranslate } from "ra-core"; +import * as React from "react"; +import { type ComponentType, type MouseEventHandler, useCallback } from "react"; + +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; + +/** + * Generic confirmation dialog component for destructive actions. + * + * Displays a dialog with customizable title, content, and action buttons. + * Used internally for delete operations and other confirmations. + * Supports custom icons, button labels, and loading states. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/confirm Confirm documentation} + * + * @example + * import { useState } from "react"; + * import { useDelete, useRecordContext, useResourceContext, useRedirect } from "ra-core"; + * import { Button } from "@/components/ui/button"; + * import { Confirm } from "@/components/admin/confirm"; + * + * const DeleteButton = () => { + * const resource = useResourceContext(); + * const record = useRecordContext(); + * const [isOpen, setIsOpen] = useState(false); + * const [deleteOne, { isPending }] = useDelete(); + * const redirect = useRedirect(); + * + * const handleDelete = () => { + * deleteOne( + * resource, + * { id: record?.id, previousData: record }, + * { + * onSuccess: () => { + * setIsOpen(false); + * redirect("list", resource); + * }, + * }, + * ); + * }; + * + * return ( + * <> + * + * setIsOpen(false)} + * loading={isPending} + * /> + * + * ); + * }; + */ +export const Confirm = (props: ConfirmProps) => { + const { + className, + isOpen = false, + loading, + title, + content, + cancel = "ra.action.cancel", + confirm = "ra.action.confirm", + confirmColor = "primary", + ConfirmIcon = CheckCircle, + CancelIcon = AlertCircle, + onClose, + onConfirm, + translateOptions = {}, + titleTranslateOptions = translateOptions, + contentTranslateOptions = translateOptions, + ...rest + } = props; + + const translate = useTranslate(); + + const handleConfirm = useCallback( + (e: React.MouseEvent) => { + e.stopPropagation(); + onConfirm(e); + }, + [onConfirm], + ); + + const handleClick = useCallback((e: React.MouseEvent) => { + e.stopPropagation(); + }, []); + + return ( + onClose()}> + + + + {typeof title === "string" + ? translate(title, { _: title, ...titleTranslateOptions }) + : title} + + {typeof content === "string" ? ( + + {translate(content, { + _: content, + ...contentTranslateOptions, + })} + + ) : ( + content + )} + + + + + + + + ); +}; + +export interface ConfirmProps { + cancel?: string; + className?: string; + confirm?: string; + confirmColor?: "primary" | "warning"; + ConfirmIcon?: ComponentType; + CancelIcon?: ComponentType; + content?: React.ReactNode; + isOpen?: boolean; + loading?: boolean; + onClose: () => void; + onConfirm: MouseEventHandler; + title: React.ReactNode; + /** + * @deprecated use `titleTranslateOptions` and `contentTranslateOptions` instead + */ + translateOptions?: object; + titleTranslateOptions?: object; + contentTranslateOptions?: object; +} diff --git a/apps/web/src/components/admin/count.tsx b/apps/web/src/components/admin/count.tsx new file mode 100644 index 0000000..84bb991 --- /dev/null +++ b/apps/web/src/components/admin/count.tsx @@ -0,0 +1,94 @@ +import type { SortPayload } from "ra-core"; +import { + useResourceContext, + useGetList, + useTimeout, + useCreatePath, +} from "ra-core"; +import { CircleX, LoaderCircle } from "lucide-react"; + +import { Link } from "react-router"; + +/** + * Fetches and displays the item count for a resource. + * + * Uses dataProvider.getList() with minimal pagination to fetch the total count. + * Displays a loading spinner while fetching and an error icon on failure. + * By default, uses the current resource from ResourceContext. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/count/ Count documentation} + * + * @example + * import { Count } from '@/components/admin'; + * // Display the number of records in the current resource + * + * + * @example + * // Display the number of posts + * + * + * @example + * // Display the number of published posts with a link + * + */ +export const Count = (props: CountProps) => { + const { + filter, + sort, + link, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + resource: resourceFromProps, + timeout = 1000, + ...rest + } = props; + const resource = useResourceContext(props); + if (!resource) { + throw new Error( + "The Count component must be used inside a ResourceContext or must be passed a resource prop.", + ); + } + const oneSecondHasPassed = useTimeout(timeout); + const createPath = useCreatePath(); + + const { total, isPending, error } = useGetList(resource, { + filter, + sort, + pagination: { perPage: 1, page: 1 }, + }); + + const body = isPending ? ( + oneSecondHasPassed ? ( + + ) : ( + "" + ) + ) : error ? ( + + ) : ( + total + ); + + return link ? ( + e.stopPropagation()} + {...rest} + > + {body} + + ) : ( + {body} + ); +}; + +export interface CountProps { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + filter?: any; + sort?: SortPayload; + link?: boolean; + resource?: string; + timeout?: number; +} diff --git a/apps/web/src/components/admin/create-button.tsx b/apps/web/src/components/admin/create-button.tsx new file mode 100644 index 0000000..27a13e3 --- /dev/null +++ b/apps/web/src/components/admin/create-button.tsx @@ -0,0 +1,71 @@ +import React from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { Plus } from "lucide-react"; +import { + useCreatePath, + useGetResourceLabel, + useResourceContext, + useResourceTranslation, +} from "ra-core"; +import { Link } from "react-router"; + +export type CreateButtonProps = { + label?: string; + resource?: string; +}; + +/** + * A button that navigates to the create page for a resource. + * + * Automatically uses the current resource unless overridden. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/createbutton/ CreateButton documentation} + * + * @example + * import { CreateButton, List, ExportButton } from '@/components/admin'; + * + * const PostList = () => ( + * + * + * + * } + * > + * ... + * + * ); + */ +export const CreateButton = (props: CreateButtonProps) => { + const { label: labelProp } = props; + const resource = useResourceContext(props); + const createPath = useCreatePath(); + const getResourceLabel = useGetResourceLabel(); + const link = createPath({ + resource, + type: "create", + }); + const label = useResourceTranslation({ + resourceI18nKey: resource + ? `resources.${resource}.action.create` + : undefined, + baseI18nKey: "ra.action.create", + options: { + name: resource ? getResourceLabel(resource, 1) : undefined, + }, + userText: labelProp, + }); + return ( + + + {label} + + ); +}; + +// useful to prevent click bubbling in a datagrid with rowClick +const stopPropagation = (e: React.MouseEvent) => e.stopPropagation(); diff --git a/apps/web/src/components/admin/create.tsx b/apps/web/src/components/admin/create.tsx new file mode 100644 index 0000000..61289c1 --- /dev/null +++ b/apps/web/src/components/admin/create.tsx @@ -0,0 +1,132 @@ +import { + Breadcrumb, + BreadcrumbItem, + BreadcrumbPage, +} from "@/components/admin/breadcrumb"; +import type { CreateBaseProps } from "ra-core"; +import { + CreateBase, + Translate, + useCreateContext, + useCreatePath, + useGetResourceLabel, + useHasDashboard, + useResourceContext, +} from "ra-core"; +import type { ReactNode } from "react"; +import { Link } from "react-router"; +import { cn } from "@/lib/utils"; + +export type CreateProps = CreateViewProps & CreateBaseProps; + +/** + * A complete create page with breadcrumb, title, and actions. + * + * Combines data fetching, form context, and UI layout for creating new records. Renders breadcrumb + * navigation, page title, and wraps your form components. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/create/ Create documentation} + * + * @example + * import { Create, SimpleForm, TextInput } from '@/components/admin'; + * + * export const PostCreate = () => ( + * + * + * + * + * + * + * ); + */ +export const Create = ({ + actions, + children, + className, + disableBreadcrumb, + title, + ...rest +}: CreateProps) => ( + + + {children} + + +); + +export type CreateViewProps = { + actions?: ReactNode; + disableBreadcrumb?: boolean; + children: ReactNode; + className?: string; + title?: ReactNode | string | false; +}; + +/** + * The view component for Create pages with layout and UI. + * + * @internal + */ +export const CreateView = ({ + actions, + disableBreadcrumb, + title, + children, + className, +}: CreateViewProps) => { + const context = useCreateContext(); + + const resource = useResourceContext(); + if (!resource) { + throw new Error( + "The CreateView component must be used within a ResourceContextProvider", + ); + } + const getResourceLabel = useGetResourceLabel(); + const listLabel = getResourceLabel(resource, 2); + const createPath = useCreatePath(); + const listLink = createPath({ + resource, + type: "list", + }); + const hasDashboard = useHasDashboard(); + + return ( + <> + {!disableBreadcrumb && ( + + {hasDashboard && ( + + + Home + + + )} + + {listLabel} + + + Create + + + )} +
+

+ {title !== undefined ? title : context.defaultTitle} +

+ {actions} +
+
{children}
+ + ); +}; diff --git a/apps/web/src/components/admin/data-table.tsx b/apps/web/src/components/admin/data-table.tsx new file mode 100644 index 0000000..452eb17 --- /dev/null +++ b/apps/web/src/components/admin/data-table.tsx @@ -0,0 +1,522 @@ +import type { ReactNode } from "react"; +import { Children, createElement, isValidElement, useCallback } from "react"; +import type { + DataTableBaseProps, + ExtractRecordPaths, + HintedString, + Identifier, + RaRecord, + SortPayload, +} from "ra-core"; +import { + DataTableBase, + DataTableRenderContext, + FieldTitle, + RecordContextProvider, + useDataTableCallbacksContext, + useDataTableConfigContext, + useDataTableDataContext, + useDataTableRenderContext, + useDataTableSelectedIdsContext, + useDataTableSortContext, + useDataTableStoreContext, + useGetPathForRecordCallback, + useRecordContext, + useResourceContext, + useStore, + useTranslate, + useTranslateLabel, +} from "ra-core"; +import { useNavigate } from "react-router"; +import { ArrowDownAZ, ArrowUpZA } from "lucide-react"; +import get from "lodash/get"; +import { cn } from "@/lib/utils"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { + ColumnsSelector, + ColumnsSelectorItem, +} from "@/components/admin/columns-button"; +import { NumberField } from "@/components/admin/number-field"; +import { + BulkActionsToolbar, + BulkActionsToolbarChildren, +} from "@/components/admin/bulk-actions-toolbar"; + +const defaultBulkActionButtons = ; + +/** + * A powerful data table with sorting, selection, and column customization. + * + * Displays records in a table with built-in support for column sorting, bulk selection, row clicks, + * and column visibility controls. Use DataTable.Col to define columns. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/datatable/ DataTable documentation} + * + * @example + * import { List, DataTable, ReferenceField, EditButton } from '@/components/admin'; + * + * export const PostList = () => ( + * + * + * + * + * + * + * + * + * + * + * + * + * ); + */ +export function DataTable( + props: DataTableProps, +) { + const { + children, + className, + rowClassName, + bulkActionButtons = defaultBulkActionButtons, + bulkActionsToolbar, + ...rest + } = props; + const hasBulkActions = !!bulkActionsToolbar || bulkActionButtons !== false; + const resourceFromContext = useResourceContext(props); + const storeKey = props.storeKey || `${resourceFromContext}.datatable`; + const [columnRanks] = useStore(`${storeKey}_columnRanks`); + const columns = columnRanks + ? reorderChildren(children, columnRanks) + : children; + + return ( + + hasBulkActions={hasBulkActions} + loading={null} + empty={} + {...rest} + > +
+ + + {columns} + + rowClassName={rowClassName}> + {columns} + +
+
+ {bulkActionsToolbar ?? + (bulkActionButtons !== false && ( + + {isValidElement(bulkActionButtons) + ? bulkActionButtons + : defaultBulkActionButtons} + + ))} + + {children} + + + ); +} + +DataTable.Col = DataTableColumn; +DataTable.NumberCol = DataTableNumberColumn; + +const DataTableHead = ({ children }: { children: ReactNode }) => { + const data = useDataTableDataContext(); + const { hasBulkActions = false } = useDataTableConfigContext(); + const { onSelect } = useDataTableCallbacksContext(); + const selectedIds = useDataTableSelectedIdsContext(); + const handleToggleSelectAll = (checked: boolean) => { + if (!onSelect || !data || !selectedIds) return; + onSelect( + checked + ? selectedIds.concat( + data + .filter((record) => !selectedIds.includes(record.id)) + .map((record) => record.id), + ) + : // We should only unselect the ids present in the current page + selectedIds.filter((id) => !data.some((record) => record.id === id)), + ); + }; + const selectableIds = Array.isArray(data) + ? data.map((record) => record.id) + : []; + return ( + + + {hasBulkActions ? ( + + 0 && + selectableIds.length > 0 && + selectableIds.every((id) => selectedIds.includes(id)) + } + className="mb-2" + /> + + ) : null} + {children} + + + ); +}; + +const DataTableBody = ({ + children, + rowClassName, +}: { + children: ReactNode; + rowClassName?: (record: RecordType) => string | undefined; +}) => { + const data = useDataTableDataContext(); + return ( + + {data?.map((record, rowIndex) => ( + + + {children} + + + ))} + + ); +}; + +const DataTableRow = ({ + children, + className, +}: { + children: ReactNode; + className?: string; +}) => { + const { rowClick, handleToggleItem } = useDataTableCallbacksContext(); + const selectedIds = useDataTableSelectedIdsContext(); + const { hasBulkActions = false } = useDataTableConfigContext(); + + const record = useRecordContext(); + if (!record) { + throw new Error("DataTableRow can only be used within a RecordContext"); + } + + const resource = useResourceContext(); + if (!resource) { + throw new Error("DataTableRow can only be used within a ResourceContext"); + } + + const navigate = useNavigate(); + const getPathForRecord = useGetPathForRecordCallback(); + + const handleToggle = useCallback( + (event: React.MouseEvent) => { + event.stopPropagation(); + if (!handleToggleItem) return; + handleToggleItem(record.id, event); + }, + [handleToggleItem, record.id], + ); + + const handleClick = useCallback(async () => { + const temporaryLink = + typeof rowClick === "function" + ? rowClick(record.id, resource, record) + : rowClick; + + const link = isPromise(temporaryLink) ? await temporaryLink : temporaryLink; + + const path = await getPathForRecord({ + record, + resource, + link, + }); + if (path === false || path == null) { + return; + } + navigate(path, { + state: { _scrollToTop: true }, + }); + }, [record, resource, rowClick, navigate, getPathForRecord]); + + return ( + + {hasBulkActions ? ( + + + + ) : null} + {children} + + ); +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const isPromise = (value: any): value is Promise => + value && typeof value.then === "function"; + +const DataTableEmpty = () => { + return ( + + No results found. + + ); +}; + +export interface DataTableProps< + RecordType extends RaRecord = RaRecord, +> extends Partial> { + children: ReactNode; + className?: string; + rowClassName?: (record: RecordType) => string | undefined; + bulkActionButtons?: ReactNode; + bulkActionsToolbar?: ReactNode; +} + +export function DataTableColumn< + RecordType extends RaRecord = RaRecord, +>(props: DataTableColumnProps) { + const renderContext = useDataTableRenderContext(); + switch (renderContext) { + case "columnsSelector": + return {...props} />; + case "header": + return ; + case "data": + return ; + } +} + +/** + * Reorder children based on columnRanks + * + * Note that columnRanks may be shorter than the number of children + */ +const reorderChildren = (children: ReactNode, columnRanks: number[]) => + Children.toArray(children).reduce((acc: ReactNode[], child, index) => { + const rank = columnRanks.indexOf(index); + if (rank === -1) { + // if the column is not in columnRanks, keep it at the same index + acc[index] = child; + } else { + // if the column is in columnRanks, move it to the rank index + acc[rank] = child; + } + return acc; + }, []); + +function DataTableHeadCell< + RecordType extends RaRecord = RaRecord, +>(props: DataTableColumnProps) { + const { + disableSort, + source, + label, + sortByOrder, + className, + headerClassName, + } = props; + + const sort = useDataTableSortContext(); + const { handleSort } = useDataTableCallbacksContext(); + const resource = useResourceContext(); + const translate = useTranslate(); + const translateLabel = useTranslateLabel(); + const { storeKey, defaultHiddenColumns } = useDataTableStoreContext(); + const [hiddenColumns] = useStore(storeKey, defaultHiddenColumns); + const isColumnHidden = hiddenColumns.includes(source!); + if (isColumnHidden) return null; + + const nextSortOrder = + sort && sort.field === source + ? oppositeOrder[sort.order] + : (sortByOrder ?? "ASC"); + const fieldLabel = translateLabel({ + label: typeof label === "string" ? label : undefined, + resource, + source, + }); + const sortLabel = translate("ra.sort.sort_by", { + field: fieldLabel, + field_lower_first: + typeof fieldLabel === "string" + ? fieldLabel.charAt(0).toLowerCase() + fieldLabel.slice(1) + : undefined, + order: translate(`ra.sort.${nextSortOrder}`), + _: translate("ra.action.sort"), + }); + + return ( + + {handleSort && sort && !disableSort && source ? ( + + + + + + +

{sortLabel}

+
+
+
+ ) : ( + + )} +
+ ); +} + +const oppositeOrder: Record = { + ASC: "DESC", + DESC: "ASC", +}; + +function DataTableCell< + RecordType extends RaRecord = RaRecord, +>(props: DataTableColumnProps) { + const { + children, + render, + field, + source, + className, + cellClassName, + conditionalClassName, + } = props; + + const { storeKey, defaultHiddenColumns } = useDataTableStoreContext(); + const [hiddenColumns] = useStore(storeKey, defaultHiddenColumns); + const record = useRecordContext(); + const isColumnHidden = hiddenColumns.includes(source!); + if (isColumnHidden) return null; + if (!render && !field && !children && !source) { + throw new Error( + "DataTableColumn: Missing at least one of the following props: render, field, children, or source", + ); + } + + return ( + + {children ?? + (render + ? record && render(record) + : field + ? createElement(field, { source }) + : get(record, source!))} + + ); +} + +export interface DataTableColumnProps< + RecordType extends RaRecord = RaRecord, +> { + className?: string; + cellClassName?: string; + headerClassName?: string; + conditionalClassName?: (record: RecordType) => string | false | undefined; + children?: ReactNode; + render?: (record: RecordType) => React.ReactNode; + field?: React.ElementType; + source?: NoInfer>>; + label?: React.ReactNode; + disableSort?: boolean; + sortByOrder?: SortPayload["order"]; +} + +export function DataTableNumberColumn< + RecordType extends RaRecord = RaRecord, +>(props: DataTableNumberColumnProps) { + const { + source, + options, + locales, + className, + headerClassName, + cellClassName, + ...rest + } = props; + return ( + + + + ); +} + +export interface DataTableNumberColumnProps< + RecordType extends RaRecord = RaRecord, +> extends DataTableColumnProps { + source: NoInfer>>; + locales?: string | string[]; + options?: Intl.NumberFormatOptions; +} diff --git a/apps/web/src/components/admin/date-field.tsx b/apps/web/src/components/admin/date-field.tsx new file mode 100644 index 0000000..4a4f78f --- /dev/null +++ b/apps/web/src/components/admin/date-field.tsx @@ -0,0 +1,135 @@ +import type { HTMLAttributes } from "react"; +import { genericMemo, useFieldValue, useTranslate } from "ra-core"; + +import type { FieldProps } from "@/lib/field.type"; + +const DateFieldImpl = < + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +>( + inProps: DateFieldProps, +) => { + const { + empty, + locales, + options, + showTime = false, + showDate = true, + transform = defaultTransform, + source, + record, + defaultValue, + ...rest + } = inProps; + const translate = useTranslate(); + + if (!showTime && !showDate) { + throw new Error( + " cannot have showTime and showDate false at the same time", + ); + } + + const value = useFieldValue({ source, record, defaultValue }); + if (value == null || value === "") { + if (!empty) { + return null; + } + + return ( + + {typeof empty === "string" ? translate(empty, { _: empty }) : empty} + + ); + } + + const date = transform(value); + + let dateString = ""; + if (date) { + if (showTime && showDate) { + dateString = toLocaleStringSupportsLocales + ? date.toLocaleString(locales, options) + : date.toLocaleString(); + } else if (showDate) { + // If input is a date string (e.g. '2022-02-15') without time and time zone, + // force timezone to UTC to fix issue with people in negative time zones + // who may see a different date when calling toLocaleDateString(). + const dateOptions = + options ?? + (typeof value === "string" && value.length <= 10 + ? { timeZone: "UTC" } + : undefined); + dateString = toLocaleStringSupportsLocales + ? date.toLocaleDateString(locales, dateOptions) + : date.toLocaleDateString(); + } else if (showTime) { + dateString = toLocaleStringSupportsLocales + ? date.toLocaleTimeString(locales, options) + : date.toLocaleTimeString(); + } + } + + return {dateString}; +}; +DateFieldImpl.displayName = "DateFieldImpl"; + +/** + * Displays a date value with locale-specific formatting. + * + * This field automatically formats dates according to the user's locale using Intl.DateTimeFormat. + * It supports showing date only, time only, or both, with custom locales and formatting options. + * To be used with RecordField or DataTable.Col components, or anywhere a RecordContext is available. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/datefield/ DateField documentation} + * + * @example + * import { + * List, + * DataTable, + * DateField, + * } from '@/components/admin'; + * + * const PostList = () => ( + * + * + * + * + * + * + * + * + * + * + * + * ); + */ +export const DateField = genericMemo(DateFieldImpl); + +export interface DateFieldProps< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +> + extends FieldProps, HTMLAttributes { + locales?: Intl.LocalesArgument; + options?: Intl.DateTimeFormatOptions; + showTime?: boolean; + showDate?: boolean; + transform?: (value: unknown) => Date; +} + +const defaultTransform = (value: unknown) => + value instanceof Date + ? value + : typeof value === "string" || typeof value === "number" + ? new Date(value) + : undefined; + +const toLocaleStringSupportsLocales = (() => { + // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString + try { + new Date().toLocaleString("i"); + } catch (error) { + return error instanceof RangeError; + } + return false; +})(); diff --git a/apps/web/src/components/admin/date-input.tsx b/apps/web/src/components/admin/date-input.tsx new file mode 100644 index 0000000..280b45d --- /dev/null +++ b/apps/web/src/components/admin/date-input.tsx @@ -0,0 +1,317 @@ +import * as React from "react"; +import type { InputProps } from "ra-core"; +import { useInput, FieldTitle, useEvent, useResourceContext } from "ra-core"; +import { + FormControl, + FormError, + FormField, + FormLabel, +} from "@/components/admin/form"; +import { Input } from "@/components/ui/input"; +import { InputHelperText } from "@/components/admin/input-helper-text"; +import { cn } from "@/lib/utils"; + +/** + * Date picker input for editing date values in "YYYY-MM-DD" format. + * + * Use `` for publication dates, deadlines, birthdays, or any date field. Renders + * a native browser date picker (appearance varies by browser). Automatically handles date parsing + * from ISO strings, Date objects, or timestamps. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/dateinput/ DateInput documentation} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date MDN documentation for input type="date"} + * + * @example + * import { + * Edit, + * SimpleForm, + * DateInput, + * TextInput, + * } from '@/components/admin'; + * + * const PostEdit = () => ( + * + * + * + * + * + * + * + * ); + * + * @example + * // If the initial value string contains more than a date (e.g. an hour, a timezone), + * // these details are ignored. + * + * // The input will display '2021-09-11' regardless of the browser timezone. + * + * @example + * // If the initial value is a Date object, DateInput converts it to a string + * // and ignores the timezone. + * + * // The input will display '2021-09-11' regardless of the browser timezone. + * + * @example + * // If you want to manipulate the value from the field to adjust its timezone, use the format prop + * new Date(value).toISOString().split("T")[0]} /> + * // The input will display the UTC day regardless of the browser timezone. + * + * @example + * // If you want the returned value to be a Date, you must pass a custom parse method + * // to convert the form value (which is always a date string) back to a Date object. + * new Date(val)} /> + */ +export const DateInput = (props: DateInputProps) => { + const { + className, + inputClassName, + defaultValue, + format = defaultFormat, + label, + source, + helperText, + onChange, + onFocus, + validate, + disabled, + readOnly, + ...rest + } = props; + + const resource = useResourceContext(props); + + const { + field, + fieldState: _fieldState, + id, + isRequired, + } = useInput({ + defaultValue, + source, + validate, + disabled, + readOnly, + format, + ...rest, + }); + const localInputRef = React.useRef(null); + // DateInput is not a really controlled input to ensure users can start entering a date, go to another input and come back to complete it. + // This ref stores the value that is passed to the input defaultValue prop to solve this issue. + const initialDefaultValueRef = React.useRef(field.value); + // As the defaultValue prop won't trigger a remount of the HTML input, we will force it by changing the key. + const [inputKey, setInputKey] = React.useState(1); + // This ref let us track that the last change of the form state value was made by the input itself + const wasLastChangedByInput = React.useRef(false); + + // This effect ensures we stays in sync with the react-hook-form state when the value changes from outside the input + // for instance by using react-hook-form reset or setValue methods. + React.useEffect(() => { + // Ignore react-hook-form state changes if it came from the input itself + if (wasLastChangedByInput.current) { + // Resets the flag to ensure futures changes are handled + wasLastChangedByInput.current = false; + return; + } + + const hasNewValueFromForm = + localInputRef.current?.value !== field.value && + !(localInputRef.current?.value === "" && field.value == null); + + if (hasNewValueFromForm) { + // The value has changed from outside the input, we update the input value + initialDefaultValueRef.current = field.value; + // Trigger a remount of the HTML input + setInputKey((r) => r + 1); + // Resets the flag to ensure futures changes are handled + wasLastChangedByInput.current = false; + } + }, [setInputKey, field.value]); + + const { onBlur: onBlurFromField } = field; + const hasFocus = React.useRef(false); + + // Update the input text when the user types in the input. + // Also, update the react-hook-form value if the input value is a valid date string. + const handleChange = useEvent( + (event: React.ChangeEvent) => { + if (onChange) { + onChange(event); + } + if ( + typeof event.target === "undefined" || + typeof event.target.value === "undefined" + ) { + return; + } + const target = event.target; + const newValue = target.value; + const isNewValueValid = + newValue === "" || + (target.valueAsDate != null && + !isNaN(new Date(target.valueAsDate).getTime())); + + // Some browsers will return null for an invalid date + // so we only change react-hook-form value if it's not null. + // The input reset is handled in the onBlur event handler + if (newValue !== "" && newValue != null && isNewValueValid) { + field.onChange(newValue); + // Track the fact that the next react-hook-form state change was triggered by the input itself + wasLastChangedByInput.current = true; + } + }, + ); + + const handleFocus = useEvent((event: React.FocusEvent) => { + if (onFocus) { + onFocus(event); + } + hasFocus.current = true; + }); + + const handleBlur = useEvent(() => { + hasFocus.current = false; + + if (!localInputRef.current) { + return; + } + + const newValue = localInputRef.current.value; + // To ensure users can clear the input, we check its value on blur + // and submit it to react-hook-form + const isNewValueValid = + newValue === "" || + (localInputRef.current.valueAsDate != null && + !isNaN(new Date(localInputRef.current.valueAsDate).getTime())); + + if (isNewValueValid && field.value !== newValue) { + field.onChange(newValue ?? ""); + } + + if (onBlurFromField) { + onBlurFromField(); + } + }); + + const { ref, name } = field; + const inputRef = React.useCallback( + (node: HTMLInputElement | null) => { + if (typeof ref === "function") { + ref(node); + } else if (ref && node) { + (ref as React.MutableRefObject).current = node; + } + localInputRef.current = node; + }, + [ref], + ); + + return ( + + {label !== false && ( + + + + )} + + + + + + + ); +}; + +export type DateInputProps = InputProps & { + inputClassName?: string; +} & Omit, "label" | "defaultValue">; + +/** + * Convert Date object to String, using the local timezone + * + * @param {Date} value value to convert + * @returns {String} A standardized date (yyyy-MM-dd), to be passed to an + */ +const convertDateToString = (value: Date) => { + if (!(value instanceof Date) || isNaN(value.getDate())) return ""; + const localDate = new Date(value.getTime()); + const pad = "00"; + const yyyy = localDate.getFullYear().toString(); + const MM = (localDate.getMonth() + 1).toString(); + const dd = localDate.getDate().toString(); + return `${yyyy}-${(pad + MM).slice(-2)}-${(pad + dd).slice(-2)}`; +}; + +const dateRegex = /^\d{4}-\d{2}-\d{2}$/; + +/** + * Convert a form state value to a date string for the `` value. + * + * Form state values can be anything from: + * - a string in the "YYYY-MM-DD" format + * - A valid date string + * - an ISO date string + * - a Date object + * - a Linux timestamp + * - an empty string + * + * When it's not a bare date string (YYYY-MM-DD), the value is converted to + * this format using the JS Date object. + * THIS MAY CHANGE THE DATE VALUE depending on the browser locale. + * For example, the string "09/11/2021" may be converted to "2021-09-10" + * in Honolulu. This is expected behavior. + * If this is not what you want, you should provide your own parse method. + * + * The output is always a string in the "YYYY-MM-DD" format. + * + * @example + * defaultFormat('2021-09-11'); // '2021-09-11' + * defaultFormat('09/11/2021'); // '2021-09-11' (may change depending on the browser locale) + * defaultFormat('2021-09-11T20:46:20.000Z'); // '2021-09-11' (may change depending on the browser locale) + * defaultFormat(new Date('2021-09-11T20:46:20.000Z')); // '2021-09-11' (may change depending on the browser locale) + * defaultFormat(1631385980000); // '2021-09-11' (may change depending on the browser locale) + * defaultFormat(''); // null + */ +const defaultFormat = (value: string | Date | number) => { + // null, undefined and empty string values should not go through dateFormatter + // otherwise, it returns undefined and will make the input an uncontrolled one. + if (value == null || value === "") { + return null; + } + + // Date objects should be converted to strings + if (value instanceof Date) { + return convertDateToString(value); + } + + // Valid date strings (YYYY-MM-DD) should be considered as is + if (typeof value === "string") { + if (dateRegex.test(value)) { + return value; + } + } + + // other values (e.g., localized date strings, timestamps) need to be converted to Dates first + return convertDateToString(new Date(value)); +}; diff --git a/apps/web/src/components/admin/date-time-input.tsx b/apps/web/src/components/admin/date-time-input.tsx new file mode 100644 index 0000000..10a2c45 --- /dev/null +++ b/apps/web/src/components/admin/date-time-input.tsx @@ -0,0 +1,331 @@ +import * as React from "react"; +import clsx from "clsx"; +import type { InputProps } from "ra-core"; +import { useInput, FieldTitle } from "ra-core"; +import { + FormControl, + FormError, + FormField, + FormLabel, +} from "@/components/admin/form"; +import { Input } from "@/components/ui/input"; +import { InputHelperText } from "@/components/admin/input-helper-text"; + +/** + * Date and time picker input for editing datetime values with timezone support. + * + * Use `` for timestamps like "created at", "updated at", or scheduled events. + * Renders a native browser datetime-local picker. Expects and returns ISO 8601 formatted strings + * (e.g. '2025-11-17T10:10:32.390Z'), automatically converting other formats like Date objects or timestamps. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/datetimeinput/ DateTimeInput documentation} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local MDN documentation for input type="datetime-local"} + * + * @example + * import { + * Edit, + * SimpleForm, + * DateTimeInput, + * TextInput, + * } from '@/components/admin'; + * + * const EventEdit = () => ( + * + * + * + * + * + * + * + * ); + */ +export const DateTimeInput = ({ + className, + defaultValue, + format = formatDateTime, + parse = convertDateStringToISO, + label, + helperText, + onBlur, + onChange, + onFocus, + source, + resource, + validate, + disabled, + readOnly, + ...rest +}: DateTimeInputProps) => { + const { field, id, isRequired } = useInput({ + defaultValue, + onBlur, + resource, + source, + validate, + disabled, + readOnly, + format, + parse, + ...rest, + }); + const localInputRef = React.useRef(undefined); + // DateInput is not a really controlled input to ensure users can start entering a date, go to another input and come back to complete it. + // This ref stores the value that is passed to the input defaultValue prop to solve this issue. + const initialDefaultValueRef = React.useRef(field.value); + // As the defaultValue prop won't trigger a remount of the HTML input, we will force it by changing the key. + const [inputKey, setInputKey] = React.useState(1); + // This ref let us track that the last change of the form state value was made by the input itself + const wasLastChangedByInput = React.useRef(false); + + // This effect ensures we stays in sync with the react-hook-form state when the value changes from outside the input + // for instance by using react-hook-form reset or setValue methods. + React.useEffect(() => { + // Ignore react-hook-form state changes if it came from the input itself + if (wasLastChangedByInput.current) { + // Resets the flag to ensure futures changes are handled + wasLastChangedByInput.current = false; + return; + } + + const hasNewValueFromForm = + localInputRef.current?.value !== field.value && + !(localInputRef.current?.value === "" && field.value == null); + + if (hasNewValueFromForm) { + // The value has changed from outside the input, we update the input value + initialDefaultValueRef.current = field.value; + // Trigger a remount of the HTML input + setInputKey((r) => r + 1); + // Resets the flag to ensure futures changes are handled + wasLastChangedByInput.current = false; + } + }, [setInputKey, field.value]); + + const { onBlur: onBlurFromField } = field; + const hasFocus = React.useRef(false); + + // update the input text when the user types in the input + const handleChange = (event: React.ChangeEvent) => { + if (onChange) { + onChange(event); + } + if ( + typeof event.target === "undefined" || + typeof event.target.value === "undefined" + ) { + return; + } + const target = event.target; + const newValue = target.value; + const isNewValueValid = + newValue === "" || !isNaN(new Date(target.value).getTime()); + + // Some browsers will return null for an invalid date + // so we only change react-hook-form value if it's not null. + // The input reset is handled in the onBlur event handler + if (newValue !== "" && newValue != null && isNewValueValid) { + field.onChange(newValue); + // Track the fact that the next react-hook-form state change was triggered by the input itself + wasLastChangedByInput.current = true; + } + }; + + const handleFocus = (event: React.FocusEvent) => { + if (onFocus) { + onFocus(event); + } + hasFocus.current = true; + }; + + const handleBlur = () => { + hasFocus.current = false; + + if (!localInputRef.current) { + return; + } + + const newValue = localInputRef.current.value; + // To ensure users can clear the input, we check its value on blur + // and submit it to react-hook-form + const isNewValueValid = + newValue === "" || + !isNaN(new Date(localInputRef.current.value).getTime()); + + if (isNewValueValid && field.value !== newValue) { + field.onChange(newValue ?? ""); + } + + if (onBlurFromField) { + onBlurFromField(); + } + }; + + const { ref, name } = field; + const inputRef = useForkRef(ref, localInputRef); + + return ( + + {label !== false && ( + + + + )} + + + + + + + ); +}; + +export type DateTimeInputProps = Omit & { + defaultValue?: string | number | Date; +} & Omit, "defaultValue" | "type">; + +const leftPad = + (nb = 2) => + (value: number) => + ("0".repeat(nb) + value).slice(-nb); +const leftPad4 = leftPad(4); +const leftPad2 = leftPad(2); + +/** + * @param {Date} value value to convert + * @returns {String} A standardized datetime (yyyy-MM-ddThh:mm), to be passed to an + */ +const convertDateToString = (value: Date) => { + if (!(value instanceof Date) || isNaN(value.getDate())) return ""; + const yyyy = leftPad4(value.getFullYear()); + const MM = leftPad2(value.getMonth() + 1); + const dd = leftPad2(value.getDate()); + const hh = leftPad2(value.getHours()); + const mm = leftPad2(value.getMinutes()); + return `${yyyy}-${MM}-${dd}T${hh}:${mm}`; +}; + +// yyyy-MM-ddThh:mm +const dateTimeRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/; + +/** + * Converts a date from the dataProvider, with timezone, to a date string + * without timezone for use in an . + * + * @param {Date | String} value date string or object + */ +const formatDateTime = (value: string | Date) => { + // null, undefined and empty string values should not go through convertDateToString + // otherwise, it returns undefined and will make the input an uncontrolled one. + if (value == null || value === "") { + return ""; + } + + if (value instanceof Date) { + return convertDateToString(value); + } + // valid dates should not be converted + if (dateTimeRegex.test(value)) { + return value; + } + + return convertDateToString(new Date(value)); +}; + +// converts a date string entered usinf a datetime-local input +// into an ISO date using the browser timezone +const convertDateStringToISO = (date: string) => { + const localDate = new Date(date); + return localDate.toISOString(); +}; + +/** + * Imported from material-ui + * Merges refs into a single memoized callback ref or `null`. + * + * ```tsx + * const rootRef = React.useRef(null); + * const refFork = useForkRef(rootRef, props.ref); + * + * return ( + * + * ); + * ``` + * + * @param {Array | undefined>} refs The ref array. + * @returns {React.RefCallback | null} The new ref callback. + */ +function useForkRef( + ...refs: Array | undefined> +): React.RefCallback | null { + const cleanupRef = React.useRef<() => void>(undefined); + + const refEffect = React.useCallback((instance: Instance) => { + const cleanups = refs.map((ref) => { + if (ref == null) { + return null; + } + + if (typeof ref === "function") { + const refCallback = ref; + const refCleanup: void | (() => void) = refCallback(instance); + return typeof refCleanup === "function" + ? refCleanup + : () => { + refCallback(null); + }; + } + + ref.current = instance; + return () => { + ref.current = null; + }; + }); + + return () => { + cleanups.forEach((refCleanup) => refCleanup?.()); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, refs); + + return React.useMemo(() => { + if (refs.every((ref) => ref == null)) { + return null; + } + + return (value) => { + if (cleanupRef.current) { + cleanupRef.current(); + cleanupRef.current = undefined; + } + + if (value != null) { + cleanupRef.current = refEffect(value); + } + }; + // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- intentionally ignoring that the dependency array must be an array literal + // eslint-disable-next-line react-hooks/exhaustive-deps + }, refs); +} diff --git a/apps/web/src/components/admin/delete-button.tsx b/apps/web/src/components/admin/delete-button.tsx new file mode 100644 index 0000000..0f0b52a --- /dev/null +++ b/apps/web/src/components/admin/delete-button.tsx @@ -0,0 +1,113 @@ +import * as React from "react"; +import { Trash } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { humanize, singularize } from "inflection"; +import type { UseDeleteOptions, RedirectionSideEffect } from "ra-core"; +import { + useDeleteWithUndoController, + useGetRecordRepresentation, + useResourceTranslation, + useRecordContext, + useResourceContext, + useTranslate, +} from "ra-core"; + +export type DeleteButtonProps = { + label?: string; + size?: "default" | "sm" | "lg" | "icon"; + onClick?: React.ReactEventHandler; + mutationOptions?: UseDeleteOptions; + redirect?: RedirectionSideEffect; + resource?: string; + successMessage?: string; + className?: string; + variant?: + | "default" + | "destructive" + | "outline" + | "secondary" + | "ghost" + | "link"; +}; + +/** + * A button that deletes a record with undo capability. + * + * Renders a destructive button that deletes the current record and shows an undo notification. + * Automatically redirects after deletion and works with the RecordContext. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/deletebutton/ DeleteButton documentation} + * + * @example + * import { DeleteButton, Edit } from '@/components/admin'; + * + * const PostEdit = () => ( + * }> + * ... + * + * ); + */ +export const DeleteButton = (props: DeleteButtonProps) => { + const { + label: labelProp, + onClick, + size, + mutationOptions, + redirect = "list", + successMessage, + variant = "outline", + className = "cursor-pointer hover:bg-destructive/10! text-destructive! border-destructive! focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40", + } = props; + const record = useRecordContext(props); + const resource = useResourceContext(props); + + const { isPending, handleDelete } = useDeleteWithUndoController({ + record, + resource, + redirect, + onClick, + mutationOptions, + successMessage, + }); + const translate = useTranslate(); + const getRecordRepresentation = useGetRecordRepresentation(resource); + let recordRepresentation = getRecordRepresentation(record); + const resourceName = translate(`resources.${resource}.forcedCaseName`, { + smart_count: 1, + _: humanize( + translate(`resources.${resource}.name`, { + smart_count: 1, + _: resource ? singularize(resource) : undefined, + }), + true, + ), + }); + // We don't support React elements for this + if (React.isValidElement(recordRepresentation)) { + recordRepresentation = `#${record?.id}`; + } + const label = useResourceTranslation({ + resourceI18nKey: `resources.${resource}.action.delete`, + baseI18nKey: "ra.action.delete", + options: { + name: resourceName, + recordRepresentation, + }, + userText: labelProp, + }); + + return ( + + ); +}; diff --git a/apps/web/src/components/admin/edit-button.tsx b/apps/web/src/components/admin/edit-button.tsx new file mode 100644 index 0000000..f621af0 --- /dev/null +++ b/apps/web/src/components/admin/edit-button.tsx @@ -0,0 +1,82 @@ +import React from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { Pencil } from "lucide-react"; +import type { RaRecord } from "ra-core"; +import { + useCreatePath, + useGetRecordRepresentation, + useGetResourceLabel, + useRecordContext, + useResourceContext, + useResourceTranslation, +} from "ra-core"; +import { Link } from "react-router"; + +export type EditButtonProps = { + record?: RaRecord; + resource?: string; + label?: string; +}; + +/** + * A button that navigates to the edit page for a record. + * + * Works within RecordContext to automatically get the record ID. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/editbutton/ EditButton documentation} + * + * @example + * import { DataTable, EditButton } from '@/components/admin'; + * + * const PostList = () => ( + * + * + * + * + * + * + * + * + * ); + */ +export const EditButton = (props: EditButtonProps) => { + const { label: labelProp } = props; + const resource = useResourceContext(props); + const record = useRecordContext(props); + const createPath = useCreatePath(); + const getResourceLabel = useGetResourceLabel(); + const getRecordRepresentation = useGetRecordRepresentation(resource); + const recordRepresentationValue = getRecordRepresentation(record); + const recordRepresentation = + typeof recordRepresentationValue === "string" + ? recordRepresentationValue + : recordRepresentationValue?.toString(); + const link = createPath({ + resource, + type: "edit", + id: record?.id, + }); + const label = useResourceTranslation({ + resourceI18nKey: resource ? `resources.${resource}.action.edit` : undefined, + baseI18nKey: "ra.action.edit", + options: { + name: resource ? getResourceLabel(resource, 1) : undefined, + recordRepresentation, + }, + userText: labelProp, + }); + return ( + + + {label} + + ); +}; + +// useful to prevent click bubbling in a datagrid with rowClick +const stopPropagation = (e: React.MouseEvent) => e.stopPropagation(); diff --git a/apps/web/src/components/admin/edit-guesser.tsx b/apps/web/src/components/admin/edit-guesser.tsx new file mode 100644 index 0000000..703ed5a --- /dev/null +++ b/apps/web/src/components/admin/edit-guesser.tsx @@ -0,0 +1,162 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import type { ReactNode } from "react"; +import { useEffect, useState } from "react"; +import type { InferredTypeMap } from "ra-core"; +import { + EditBase, + InferredElement, + useResourceContext, + useEditContext, + getElementsFromRecords, +} from "ra-core"; +import { capitalize, singularize } from "inflection"; +import { EditView } from "@/components/admin/edit"; +import { SimpleForm } from "@/components/admin/simple-form"; +import { TextInput } from "@/components/admin/text-input"; +import { BooleanInput } from "@/components/admin/boolean-input"; +import { ReferenceInput } from "@/components/admin/reference-input"; +import { AutocompleteInput } from "@/components/admin/autocomplete-input"; +import { ReferenceArrayInput } from "@/components/admin/reference-array-input"; + +/** + * An edit page that automatically generates a form from your data. + * + * Inspects the record to infer field types and automatically creates appropriate inputs. + * Useful for rapid prototyping. Logs generated code to console. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/edit/#scaffolding-an-edit-page EditGuesser documentation} + * + * @example + * import { Admin, EditGuesser } from '@/components/admin'; + * import { Resource } from 'ra-core'; + * import dataProvider from './dataProvider'; + * + * const App = () => ( + * + * ... + * + * + * ); + */ +export const EditGuesser = (props: EditGuesserProps) => { + return ( + + + + ); +}; + +const EditViewGuesser = (props: EditGuesserProps) => { + const resource = useResourceContext(); + + if (!resource) { + throw new Error(`Cannot use outside of a ResourceContext`); + } + + const { record } = useEditContext(); + const [child, setChild] = useState(null); + const { enableLog = process.env.NODE_ENV === "development", ...rest } = props; + + useEffect(() => { + setChild(null); + }, [resource]); + + useEffect(() => { + if (record && !child) { + const inferredElements = getElementsFromRecords([record], editFieldTypes); + const inferredChild = new InferredElement( + editFieldTypes.form, + null, + inferredElements, + ); + setChild(inferredChild.getElement()); + + if (!enableLog) return; + + const representation = inferredChild.getRepresentation(); + + const components = ["Edit"] + .concat( + Array.from( + new Set( + Array.from(representation.matchAll(/<([^/\s>]+)/g)) + .map((match) => match[1]) + .filter((component) => component !== "span"), + ), + ), + ) + .sort(); + + // eslint-disable-next-line no-console + console.log( + `Guessed Edit: + +${components + .map( + (component) => + `import { ${component} } from "@/components/admin/${kebabCase( + component, + )}";`, + ) + .join("\n")} + +export const ${capitalize(singularize(resource))}Edit = () => ( + +${representation} + +);`, + ); + } + }, [record, child, resource, enableLog]); + + return {child}; +}; + +interface EditGuesserProps { + enableLog?: boolean; +} + +const editFieldTypes: InferredTypeMap = { + form: { + component: (props: any) => , + representation: ( + _props: any, + children: { getRepresentation: () => string }[], + ) => ` +${children + .map((child) => ` ${child.getRepresentation()}`) + .join("\n")} + `, + }, + reference: { + component: (props: any) => ( + + + + ), + representation: (props: any) => + ` + + `, + }, + referenceArray: { + component: (props: any) => , + representation: (props: any) => + ``, + }, + boolean: { + component: (props: any) => , + representation: (props: any) => ``, + }, + string: { + component: (props: any) => , + representation: (props: any) => ``, + }, +}; + +const kebabCase = (name: string) => { + return name + .replace(/([a-z])([A-Z])/g, "$1-$2") + .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2") + .toLowerCase(); +}; diff --git a/apps/web/src/components/admin/edit.tsx b/apps/web/src/components/admin/edit.tsx new file mode 100644 index 0000000..3c23138 --- /dev/null +++ b/apps/web/src/components/admin/edit.tsx @@ -0,0 +1,152 @@ +import type { EditBaseProps } from "ra-core"; +import { + EditBase, + Translate, + useCreatePath, + useEditContext, + useGetRecordRepresentation, + useGetResourceLabel, + useHasDashboard, + useResourceContext, + useResourceDefinition, +} from "ra-core"; +import type { ReactNode } from "react"; +import { Link } from "react-router"; +import { + Breadcrumb, + BreadcrumbItem, + BreadcrumbPage, +} from "@/components/admin/breadcrumb"; +import { cn } from "@/lib/utils"; +import { ShowButton } from "@/components/admin/show-button"; +import { DeleteButton } from "./delete-button"; + +export interface EditProps extends EditViewProps, EditBaseProps {} + +/** + * A complete edit page with breadcrumb, title, and default actions. + * + * Combines data fetching, form context, and UI layout for editing records. Renders breadcrumb, + * page title, Show and Delete buttons, and wraps your form components. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/edit/ Edit documentation} + * + * @example + * import { Edit, SimpleForm, BooleanInput, TextInput } from "@/components/admin"; + * import { required } from 'ra-core'; + * + * export const CustomerEdit = () => ( + * + * + * + * + * + * + * + * + * + * ); + */ +export const Edit = ({ + actions, + children, + className, + disableBreadcrumb, + title, + ...rest +}: EditProps) => ( + + + {children} + + +); + +export interface EditViewProps { + disableBreadcrumb?: boolean; + title?: ReactNode | string | false; + actions?: ReactNode; + children?: ReactNode; + className?: string; +} + +/** + * The view component for Edit pages with layout and UI. + * + * @internal + */ +export const EditView = ({ + disableBreadcrumb, + title, + actions, + className, + children, +}: EditViewProps) => { + const context = useEditContext(); + + const resource = useResourceContext(); + if (!resource) { + throw new Error( + "The EditView component must be used within a ResourceContextProvider", + ); + } + const getResourceLabel = useGetResourceLabel(); + const listLabel = getResourceLabel(resource, 2); + const createPath = useCreatePath(); + const listLink = createPath({ + resource, + type: "list", + }); + + const getRecordRepresentation = useGetRecordRepresentation(resource); + const recordRepresentation = getRecordRepresentation(context.record); + + const { hasShow } = useResourceDefinition({ resource }); + const hasDashboard = useHasDashboard(); + + if (context.isLoading || !context.record) { + return null; + } + + return ( + <> + {!disableBreadcrumb && ( + + {hasDashboard && ( + + + Home + + + )} + + {listLabel} + + {recordRepresentation} + + )} +
+

+ {title !== undefined ? title : context.defaultTitle} +

+ {actions ?? ( +
+ {hasShow ? : null} + +
+ )} +
+
{children}
+ + ); +}; diff --git a/apps/web/src/components/admin/email-field.tsx b/apps/web/src/components/admin/email-field.tsx new file mode 100644 index 0000000..14e4017 --- /dev/null +++ b/apps/web/src/components/admin/email-field.tsx @@ -0,0 +1,73 @@ +import { genericMemo, useFieldValue, useTranslate } from "ra-core"; +import type { AnchorHTMLAttributes } from "react"; +import React from "react"; + +import { cn } from "@/lib/utils"; +import type { FieldProps } from "@/lib/field.type"; + +const EmailFieldImpl = < + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +>( + inProps: EmailFieldProps, +) => { + const { className, empty, defaultValue, source, record, ...rest } = inProps; + const value = useFieldValue({ defaultValue, source, record }); + const translate = useTranslate(); + + if (value == null) { + if (!empty) { + return null; + } + + return ( + + {typeof empty === "string" ? translate(empty, { _: empty }) : empty} + + ); + } + + return ( + + {value} + + ); +}; +EmailFieldImpl.displayName = "EmailFieldImpl"; + +/** + * Displays an email address as a clickable mailto link. + * + * Click events are prevented from bubbling up, making it safe to use in DataTable rows with rowClick. + * To be used with RecordField or DataTable.Col components, or anywhere a RecordContext is available. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/emailfield/ EmailField documentation} + * + * @example + * import { List, DataTable, EmailField } from '@/components/admin'; + * + * const UserList = () => ( + * + * + * + * + * + * + * ); + */ +export const EmailField = genericMemo(EmailFieldImpl); + +export interface EmailFieldProps< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +> + extends FieldProps, AnchorHTMLAttributes {} + +// useful to prevent click bubbling in a DataTable with rowClick +const stopPropagation = (e: React.MouseEvent) => + e.stopPropagation(); diff --git a/apps/web/src/components/admin/error.tsx b/apps/web/src/components/admin/error.tsx new file mode 100644 index 0000000..df7832b --- /dev/null +++ b/apps/web/src/components/admin/error.tsx @@ -0,0 +1,120 @@ +import type { FallbackProps } from "react-error-boundary"; +import { useResetErrorBoundaryOnLocationChange, Translate } from "ra-core"; +import { CircleAlert, History } from "lucide-react"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion"; +import { Button } from "@/components/ui/button"; +import type { HtmlHTMLAttributes, ErrorInfo } from "react"; + +/** + * App-wide error component for displaying error boundaries. + * + * Displays the error message and a back button. + * In development mode, also shows the component stack trace in an expandable accordion. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/error Error documentation} + */ +export const Error = (props: InternalErrorProps & {}) => { + const { error, errorInfo, resetErrorBoundary, ...rest } = props; + + useResetErrorBoundaryOnLocationChange(resetErrorBoundary); + + const errorMessage: string = + typeof error === "object" && + error !== null && + "message" in error && + typeof error.message === "string" + ? (error.message ?? "") + : typeof error === "string" + ? error + : String(error ?? "Unknown error"); + + return ( +
+

+ + +

+
+ +
+ {process.env.NODE_ENV !== "production" && ( + <> + + + + {errorMessage} + + +
{errorInfo?.componentStack}
+
+
+
+ +

+ Need help with this error? Try the following: +

+
+ +
+ + )} +
+ +
+
+ ); +}; + +interface InternalErrorProps + extends Omit, "title">, FallbackProps { + className?: string; + errorInfo?: ErrorInfo; +} + +export interface ErrorProps extends Pick { + errorInfo?: ErrorInfo; +} + +function goBack() { + window.history.go(-1); +} diff --git a/apps/web/src/components/admin/export-button.tsx b/apps/web/src/components/admin/export-button.tsx new file mode 100644 index 0000000..c280126 --- /dev/null +++ b/apps/web/src/components/admin/export-button.tsx @@ -0,0 +1,132 @@ +import * as React from "react"; +import { useCallback } from "react"; +import { Download } from "lucide-react"; +import type { Exporter } from "ra-core"; +import { + fetchRelatedRecords, + useDataProvider, + useGetResourceLabel, + useNotify, + useListContext, + useResourceTranslation, +} from "ra-core"; +import { Button } from "@/components/ui/button"; + +/** + * A button that exports list data to a file. + * + * Respects current filters and sort order, with configurable maximum results. + * Use a custom exporter to customize the result and fetch related records. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/exportbutton/ ExportButton documentation} + * + * @example + * import { CreateButton, ExportButton, TopToolbar } from '@/components/admin'; + * + * const PostListActions = () => ( + * <> + * + * + * + * + * ); + * + * export const PostList = () => ( + * }> + * ... + * + * ); + */ +export const ExportButton = (props: ExportButtonProps) => { + const { + maxResults = 1000, + onClick, + label: labelProp, + icon = defaultIcon, + exporter: customExporter, + meta, + className = "cursor-pointer", + } = props; + const { + getData, + total, + resource, + exporter: exporterFromContext, + } = useListContext(); + const getResourceLabel = useGetResourceLabel(); + const label = useResourceTranslation({ + resourceI18nKey: `resources.${resource}.action.export`, + baseI18nKey: "ra.action.export", + options: { + name: getResourceLabel(resource, 1), + }, + userText: labelProp, + }); + const exporter = customExporter || exporterFromContext; + const dataProvider = useDataProvider(); + const notify = useNotify(); + const handleClick = useCallback( + (event: React.MouseEvent) => { + if (!getData) { + throw new Error( + "ListContext.getData must be defined to use ExportButton.", + ); + } + + getData({ maxResults, meta }) + .then( + (data) => + exporter && + exporter( + data, + fetchRelatedRecords(dataProvider), + dataProvider, + resource, + ), + ) + .catch((error) => { + console.error(error); + notify("HTTP Error", { type: "error" }); + }); + if (typeof onClick === "function") { + onClick(event); + } + }, + [ + dataProvider, + exporter, + getData, + notify, + onClick, + resource, + maxResults, + meta, + ], + ); + + return ( + + ); +}; + +const defaultIcon = ; + +export interface ExportButtonProps { + className?: string; + exporter?: Exporter; + icon?: React.ReactNode; + label?: string; + maxResults?: number; + onClick?: (e: React.MouseEvent) => void; + resource?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + meta?: any; +} diff --git a/apps/web/src/components/admin/field-toggle.tsx b/apps/web/src/components/admin/field-toggle.tsx new file mode 100644 index 0000000..38b61e6 --- /dev/null +++ b/apps/web/src/components/admin/field-toggle.tsx @@ -0,0 +1,164 @@ +import * as React from "react"; +import { FieldTitle, useResourceContext } from "ra-core"; +import { GripVertical } from "lucide-react"; +import { Switch } from "@/components/ui/switch"; +import { cn } from "@/lib/utils"; + +/** + * A toggleable field item with drag-and-drop reordering, used by ColumnsSelector + * + * @internal + */ +export const FieldToggle = (props: FieldToggleProps) => { + const { selected, label, onToggle, onMove, source, index } = props; + const resource = useResourceContext(); + const dropIndex = React.useRef(null); + const x = React.useRef(null); + const y = React.useRef(null); + + const handleDocumentDragOver = React.useCallback((event: DragEvent) => { + x.current = event.clientX; + y.current = event.clientY; + }, []); + + const handleDragStart = () => { + document.addEventListener( + "dragover", + handleDocumentDragOver as EventListener, + ); + }; + + const handleDrag = (event: React.DragEvent) => { + // imperative DOM manipulations using the native Drag API + const selectedItem = event.target as HTMLElement; + selectedItem.dataset.dragActive = "true"; + const list = selectedItem.closest("ul"); + if (x.current == null || y.current == null) { + return; + } + const elementAtDragCoordinates = document.elementFromPoint( + x.current, + y.current, + ); + let dropItem = + elementAtDragCoordinates === null + ? selectedItem + : elementAtDragCoordinates.closest("li"); + + if (!dropItem) { + return; + } + if (dropItem.classList.contains("dragIcon")) { + const parent = dropItem.parentNode; + if (parent instanceof HTMLElement) { + dropItem = parent; + } + } + if (dropItem === selectedItem) { + return; + } + const dropItemParent = dropItem.parentNode; + if ( + list && + dropItemParent instanceof HTMLElement && + list === dropItemParent.closest("ul") + ) { + const dataIndex = dropItem.dataset.index; + if (dataIndex) { + dropIndex.current = parseInt(dataIndex, 10); + } + if (dropItem === selectedItem.nextSibling) { + dropItem = dropItem.nextSibling as HTMLElement; + } + list.insertBefore(selectedItem, dropItem); + } + }; + + const handleDragEnd = (event: React.DragEvent) => { + const selectedItem = event.target as HTMLElement; + const list = selectedItem.closest("ul"); + + const elementFromPoint = + x.current != null && y.current != null + ? document.elementFromPoint(x.current, y.current) + : null; + + let dropItem = + x.current == null || y.current == null || elementFromPoint === null + ? selectedItem + : elementFromPoint.closest("li"); + + if (y.current !== null && list && !dropItem) { + const closestUL = selectedItem.closest("ul"); + if (closestUL && y.current > closestUL.getBoundingClientRect().bottom) { + dropItem = list.lastChild as HTMLElement; + } else { + dropItem = list.firstChild as HTMLElement; + } + } + + if (dropItem && list && dropItem.closest("ul") === list) { + if (onMove) onMove(selectedItem.dataset.index!, dropIndex.current!); + } else { + event.preventDefault(); + event.stopPropagation(); + } + selectedItem.dataset.dragActive = "false"; + document.removeEventListener( + "dragover", + handleDocumentDragOver as EventListener, + ); + }; + + const handleDragOver = (event: React.DragEvent) => { + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + }; + + return ( +
  • + + {onMove && ( + + )} +
  • + ); +}; + +export interface FieldToggleProps { + selected: boolean; + label: React.ReactNode; + onToggle?: (event: boolean) => void; + onMove?: ( + dragIndex: string | number, + dropIndex: string | number | null, + ) => void; + source: string; + index: number | string; +} diff --git a/apps/web/src/components/admin/file-field.tsx b/apps/web/src/components/admin/file-field.tsx new file mode 100644 index 0000000..c50c9f8 --- /dev/null +++ b/apps/web/src/components/admin/file-field.tsx @@ -0,0 +1,123 @@ +import type { HTMLAttributes } from "react"; +import get from "lodash/get"; +import type { ExtractRecordPaths, HintedString } from "ra-core"; +import { useFieldValue, useTranslate } from "ra-core"; +import { cn } from "@/lib/utils"; +import type { FieldProps } from "@/lib/field.type"; + +/** + * Displays a downloadable file link with customizable title and target. + * + * This field renders file URLs as clickable links that can open in new tabs or trigger downloads. + * It supports arrays of files and prevents click bubbling in DataTable rows. + * To be used with RecordField or DataTable.Col components, or anywhere a RecordContext is available. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/filefield/ FileField documentation} + * + * @example + * import { FileField } from '@/components/admin/file-field'; + * + * + * + * // renders the record { id: 123, url: 'doc.pdf', title: 'Presentation' } as + *
    + * Presentation + *
    + */ +export const FileField = < + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +>( + props: FileFieldProps, +) => { + const { + className, + empty, + title, + src, + target, + download, + defaultValue, + source, + record, + ...rest + } = props; + const sourceValue = useFieldValue({ defaultValue, source, record }); + const titleValue = + useFieldValue({ + ...props, + // @ts-expect-error We ignore here because title might be a custom label or undefined instead of a field name + source: title, + })?.toString() ?? title; + const translate = useTranslate(); + + if ( + sourceValue == null || + (Array.isArray(sourceValue) && sourceValue.length === 0) + ) { + if (!empty) { + return null; + } + + return ( +
    + {typeof empty === "string" ? translate(empty, { _: empty }) : empty} +
    + ); + } + + if (Array.isArray(sourceValue)) { + return ( +
      + {sourceValue.map((file, index) => { + const fileTitleValue = title ? get(file, title, title) : title; + const srcValue = src ? get(file, src, title) : title; + + return ( +
    • + e.stopPropagation()} + > + {fileTitleValue} + +
    • + ); + })} +
    + ); + } + + return ( + + ); +}; + +export interface FileFieldProps< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RecordType extends Record = Record, +> + extends FieldProps, HTMLAttributes { + /** + * The source of the link to the file, for an array of files. + */ + src?: string; + title?: HintedString>; + target?: HTMLAnchorElement["target"]; + download?: HTMLAnchorElement["download"]; +} diff --git a/apps/web/src/components/admin/file-input.tsx b/apps/web/src/components/admin/file-input.tsx new file mode 100644 index 0000000..e6fb312 --- /dev/null +++ b/apps/web/src/components/admin/file-input.tsx @@ -0,0 +1,362 @@ +import * as React from "react"; +import type { + ComponentType, + ReactElement, + ReactNode, + HTMLAttributes, +} from "react"; +import { Children, isValidElement, useEffect } from "react"; +import type { InputProps } from "ra-core"; +import { + FieldTitle, + RecordContextProvider, + shallowEqual, + useInput, + useTranslate, +} from "ra-core"; +import type { + DropzoneOptions, + FileRejection, + DropEvent, + DropzoneInputProps, +} from "react-dropzone"; +import { useDropzone } from "react-dropzone"; +import { XCircle } from "lucide-react"; + +import { cn } from "@/lib/utils"; +import { FormError, FormField, FormLabel } from "@/components/admin/form"; +import { InputHelperText } from "@/components/admin/input-helper-text"; +import { Button } from "@/components/ui/button"; + +/** + * File upload input with drag-and-drop support and preview capabilities. + * + * Use `` for document uploads, images, PDFs, CSV files, or any file attachment field. + * Powered by react-dropzone with support for multiple files, file type restrictions (accept), and + * size constraints. Pass a child component (typically ``) to render file previews. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/fileinput/ FileInput documentation} + * @see {@link https://react-dropzone.js.org/ React Dropzone documentation} + * + * @example + * import { + * Edit, + * SimpleForm, + * TextInput, + * FileInput, + * FileField, + * } from '@/components/admin'; + * + * const DocumentEdit = () => ( + * + * + * + * + * + * + * + * + * ); + */ +export const FileInput = (props: FileInputProps) => { + const { + alwaysOn, + defaultValue, + format, + label, + helperText, + name: nameProp, + onBlur: onBlurProp, + onChange: onChangeProp, + parse, + resource, + source, + validate, + readOnly, + disabled, + + accept, + maxSize, + minSize, + multiple = false, + options = {}, + + children, + className, + inputProps: inputPropsOptions, + + onRemove: onRemoveProp, + validateFileRemoval, + + placeholder, + labelMultiple = "ra.input.file.upload_several", + labelSingle = "ra.input.file.upload_single", + removeIcon, + ...rest + } = props; + const { onDrop: onDropProp } = options; + const translate = useTranslate(); + + // turn a browser dropped file structure into expected structure + const transformFile = (file: unknown) => { + if (!(file instanceof File)) { + return file; + } + + const preview = URL.createObjectURL(file); + const transformedFile: TransformedFile = { + rawFile: file, + src: preview, + title: file.name, + }; + + return transformedFile; + }; + + const transformFiles = (files: unknown[]) => { + if (!files) { + return multiple ? [] : null; + } + + if (Array.isArray(files)) { + return files.map(transformFile); + } + + return transformFile(files); + }; + + const { + id, + field: { onChange, onBlur, value, name }, + isRequired, + } = useInput({ + alwaysOn, + defaultValue, + format: format || transformFiles, + label, + helperText, + name: nameProp, + onBlur: onBlurProp, + onChange: onChangeProp, + parse: parse || transformFiles, + resource, + source, + validate, + readOnly, + disabled, + }); + const files = value ? (Array.isArray(value) ? value : [value]) : []; + + const onDrop = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newFiles: any[], + rejectedFiles: FileRejection[], + event: DropEvent, + ) => { + const updatedFiles = multiple ? [...files, ...newFiles] : [...newFiles]; + + if (multiple) { + onChange(updatedFiles); + onBlur(); + } else { + onChange(updatedFiles[0]); + onBlur(); + } + + if (onDropProp) { + onDropProp(newFiles, rejectedFiles, event); + } + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const onRemove = (file: any) => async () => { + if (validateFileRemoval) { + try { + await validateFileRemoval(file); + } catch { + return; + } + } + + if (multiple) { + const filteredFiles = files.filter( + (stateFile) => !shallowEqual(stateFile, file), + ); + onChange(filteredFiles); + onBlur(); + } else { + onChange(null); + onBlur(); + } + + if (onRemoveProp) { + onRemoveProp(file); + } + }; + + const childrenElement = + children && isValidElement(Children.only(children)) + ? (Children.only(children) as ReactElement) + : undefined; + + const { getRootProps, getInputProps } = useDropzone({ + accept, + maxSize, + minSize, + multiple, + disabled: disabled || readOnly, + ...options, + onDrop, + }); + + return ( + + + + + +
    + + + {placeholder ? ( + placeholder + ) : multiple ? ( +

    {translate(labelMultiple)}

    + ) : ( +

    {translate(labelSingle)}

    + )} +
    + + + + + {children && ( +
    + { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + files.map((file: any, index: number) => ( + + + {childrenElement} + + + )) + } +
    + )} +
    + ); +}; + +export type FileInputProps = Omit & { + accept?: DropzoneOptions["accept"]; + className?: string; + children?: ReactNode; + labelMultiple?: string; + labelSingle?: string; + maxSize?: DropzoneOptions["maxSize"]; + minSize?: DropzoneOptions["minSize"]; + multiple?: DropzoneOptions["multiple"]; + options?: DropzoneOptions; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onRemove?: (file: any) => void; + placeholder?: ReactNode; + removeIcon?: ComponentType<{ className?: string }>; + inputProps?: DropzoneInputProps & React.ComponentProps<"input">; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validateFileRemoval?(file: any): boolean | Promise; +}; + +export interface TransformedFile { + rawFile: File; + src: string; + title: string; +} + +/** + * Preview container for uploaded files in ``, with a remove button. + * + * @internal + */ +export const FileInputPreview = (props: FileInputPreviewProps) => { + const { + className, + children, + + file, + onRemove, + removeIcon: RemoveIcon = XCircle, + + ...rest + } = props; + + const translate = useTranslate(); + + useEffect(() => { + return () => { + const preview = file.rawFile ? file.rawFile.preview : file.preview; + + if (preview) { + window.URL.revokeObjectURL(preview); + } + }; + }, [file]); + + return ( +
    + + {children} +
    + ); +}; + +export interface FileInputPreviewProps extends HTMLAttributes { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file: any; + onRemove: () => void; + removeIcon?: React.ComponentType<{ className?: string }>; +} diff --git a/apps/web/src/components/admin/filter-form.tsx b/apps/web/src/components/admin/filter-form.tsx new file mode 100644 index 0000000..0b04d95 --- /dev/null +++ b/apps/web/src/components/admin/filter-form.tsx @@ -0,0 +1,513 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import * as React from "react"; +import type { HtmlHTMLAttributes, ReactNode } from "react"; +import { useCallback, useEffect, useState, isValidElement } from "react"; +import get from "lodash/get"; +import isEqual from "lodash/isEqual"; +import queryString from "query-string"; +import { + extractValidSavedQueries, + FieldTitle, + FilterLiveForm, + type SavedQuery, + useFilterContext, + useListContext, + useResourceContext, + useSavedQueries, + useTranslate, +} from "ra-core"; +import { useNavigate } from "react-router"; +import { + Bookmark, + BookmarkMinus, + BookmarkPlus, + Check, + Filter, + MinusCircle, + X, +} from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + AddSavedQueryDialog, + RemoveSavedQueryDialog, +} from "@/components/admin/saved-queries"; + +/** + * A form for filter inputs with live updates. Included by default in List. + * + * To be used in conjunction with FilterButton. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/list/#filter-button--form-combo FilterForm documentation} + */ +export const FilterForm = (inProps: FilterFormProps) => { + const { filters: filtersProps, ...rest } = inProps; + const filters = useFilterContext() || filtersProps; + + return ( + + + + ); +}; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface FilterFormProps extends FilterFormBaseProps {} + +/** + * @deprecated Use FilterFormBase from `ra-core` once available. + */ +export const FilterFormBase = (props: FilterFormBaseProps) => { + const { filters } = props; + const resource = useResourceContext(props); + const { displayedFilters = {}, filterValues, hideFilter } = useListContext(); + + useEffect(() => { + if (!filters) return; + filters + .filter((filterElement) => isValidElement(filterElement)) + .forEach((filter) => { + if ( + (filter.props as any).alwaysOn && + (filter.props as any).defaultValue + ) { + throw new Error( + "Cannot use alwaysOn and defaultValue on a filter input. Please set the filterDefaultValues props on the element instead.", + ); + } + }); + }, [filters]); + + const getShownFilters = () => { + if (!filters) return []; + const values = filterValues; + return filters + .filter((filterElement) => isValidElement(filterElement)) + .filter((filterElement) => { + const filterValue = get(values, (filterElement.props as any).source); + return ( + (filterElement.props as any).alwaysOn || + displayedFilters[(filterElement.props as any).source] || + !isEmptyValue(filterValue) + ); + }); + }; + + const handleHide = useCallback( + (event: React.MouseEvent) => + hideFilter(event.currentTarget.dataset.key!), + [hideFilter], + ); + + return ( + <> + {getShownFilters().map((filterElement) => ( + + ))} + + ); +}; + +const sanitizeRestProps = ({ + hasCreate: _hasCreate, + resource: _resource, + ...props +}: Partial & { hasCreate?: boolean }) => props; + +export type FilterFormBaseProps = Omit< + HtmlHTMLAttributes, + "children" +> & { + className?: string; + resource?: string; + filters?: ReactNode[]; +}; + +const StyledForm = (props: React.FormHTMLAttributes) => { + return ( +
    + ); +}; + +const isEmptyValue = (filterValue: any): boolean => { + if (filterValue === "" || filterValue == null) return true; + + // If one of the value leaf is not empty + // the value is considered not empty + if (typeof filterValue === "object") { + return Object.keys(filterValue).every((key) => + isEmptyValue(filterValue[key]), + ); + } + + return false; +}; + +export const FilterFormInput = (inProps: FilterFormInputProps) => { + const { filterElement, handleHide, className } = inProps; + const resource = useResourceContext(inProps); + const translate = useTranslate(); + const { alwaysOn: _, ...filterElementProps } = filterElement.props; + const filterElementType = + typeof filterElement === "string" ? filterElement : filterElement.type; + + return ( +
    + {React.createElement(filterElementType, { + ...filterElementProps, + resource, + record: emptyRecord, + size: filterElement.props.size ?? "small", + helperText: false, + // ignore defaultValue in Field because it was already set in Form (via mergedInitialValuesWithDefaultValues) + defaultValue: undefined, + })} + {!filterElement.props.alwaysOn && ( + + )} +
    + ); +}; + +export interface FilterFormInputProps { + filterElement: React.ReactElement; + handleHide: (event: React.MouseEvent) => void; + className?: string; + resource?: string; +} + +const emptyRecord = {}; + +/** + * A button that opens a dropdown to add, remove, and manage filters. + * + * Displays available filters, saved queries, and options to save or clear current filters. + * Works with the FilterForm to provide a complete filtering UI. + * + * @see {@link https://marmelab.com/shadcn-admin-kit/docs/list/#filter-button--form-combo FilterForm documentation} + */ +export const FilterButton = (props: FilterButtonProps) => { + const { + filters: filtersProp, + className, + disableSaveQuery, + size, + variant = "outline", + ...rest + } = props; + const filters = useFilterContext() || filtersProp; + const resource = useResourceContext(props); + const translate = useTranslate(); + if (!resource && !disableSaveQuery) { + throw new Error( + " must be called inside a ResourceContextProvider, or must provide a resource prop", + ); + } + const [savedQueries] = useSavedQueries(resource || ""); + const navigate = useNavigate(); + const { + displayedFilters = {}, + filterValues, + perPage, + setFilters, + showFilter, + hideFilter, + sort, + } = useListContext(); + const hasFilterValues = !isEqual(filterValues, {}); + const validSavedQueries = extractValidSavedQueries(savedQueries); + const hasSavedCurrentQuery = validSavedQueries.some((savedQuery) => + isEqual(savedQuery.value, { + filter: filterValues, + sort, + perPage, + displayedFilters, + }), + ); + const [open, setOpen] = useState(false); + + if (filters === undefined) { + throw new Error( + "The component requires the prop to be set", + ); + } + + const allTogglableFilters = filters.filter( + (filterElement) => + isValidElement(filterElement) && !(filterElement.props as any).alwaysOn, + ); + + const handleShow = useCallback( + ({ source, defaultValue }: { source: string; defaultValue: any }) => { + showFilter(source, defaultValue === "" ? undefined : defaultValue); + // We have to fallback to imperative code because the new FilterFormInput + // has no way of knowing it has just been displayed (and thus that it should focus its input) + setTimeout(() => { + const inputElement = document.querySelector( + `input[name='${source}']`, + ) as HTMLInputElement; + if (inputElement) { + inputElement.focus(); + } + }, 50); + setOpen(false); + }, + [showFilter, setOpen], + ); + + const handleRemove = useCallback( + ({ source }: { source: string }) => { + hideFilter(source); + setOpen(false); + }, + [hideFilter, setOpen], + ); + + // add query dialog state + const [addSavedQueryDialogOpen, setAddSavedQueryDialogOpen] = useState(false); + const hideAddSavedQueryDialog = (): void => { + setAddSavedQueryDialogOpen(false); + }; + const showAddSavedQueryDialog = (): void => { + setOpen(false); + setAddSavedQueryDialogOpen(true); + }; + + // remove query dialog state + const [removeSavedQueryDialogOpen, setRemoveSavedQueryDialogOpen] = + useState(false); + const hideRemoveSavedQueryDialog = (): void => { + setRemoveSavedQueryDialogOpen(false); + }; + const showRemoveSavedQueryDialog = (): void => { + setOpen(false); + setRemoveSavedQueryDialogOpen(true); + }; + + if ( + allTogglableFilters.length === 0 && + validSavedQueries.length === 0 && + !hasFilterValues + ) { + return null; + } + return ( +
    + + + + + + {allTogglableFilters + .filter((filterElement) => isValidElement(filterElement)) + .map((filterElement, index: number) => ( + + ))} + {(hasFilterValues || validSavedQueries.length > 0) && ( + + )} + {validSavedQueries.map((savedQuery: SavedQuery, index: number) => + isEqual(savedQuery.value, { + filter: filterValues, + sort, + perPage, + displayedFilters, + }) ? ( + + + {translate("ra.saved_queries.remove_label_with_name", { + _: 'Remove query "%{name}"', + name: savedQuery.label, + })} + + ) : ( + { + navigate({ + search: queryString.stringify({ + filter: JSON.stringify(savedQuery.value.filter), + sort: savedQuery.value.sort?.field, + order: savedQuery.value.sort?.order, + page: 1, + perPage: savedQuery.value.perPage, + displayedFilters: JSON.stringify( + savedQuery.value.displayedFilters, + ), + }), + }); + setOpen(false); + }} + key={index} + > + + {savedQuery.label} + + ), + )} + {hasFilterValues && !hasSavedCurrentQuery && !disableSaveQuery && ( + + + {translate("ra.saved_queries.new_label", { + _: "Save current query...", + })} + + )} + {hasFilterValues && ( + { + setFilters({}, {}); + setOpen(false); + }} + > + + {translate("ra.action.remove_all_filters", { + _: "Remove all filters", + })} + + )} + + + {!disableSaveQuery && ( + <> + + + + )} +
    + ); +}; + +export interface FilterButtonProps extends HtmlHTMLAttributes { + className?: string; + disableSaveQuery?: boolean; + filters?: ReactNode[]; + resource?: string; + variant?: + | "default" + | "destructive" + | "outline" + | "secondary" + | "ghost" + | "link"; + size?: "default" | "sm" | "lg" | "icon"; +} + +export const FilterButtonMenuItem = React.forwardRef< + HTMLDivElement, + FilterButtonMenuItemProps +>((props, ref) => { + const { filter, onShow, onHide, displayed } = props; + const resource = useResourceContext(props); + const handleShow = useCallback(() => { + onShow({ + source: filter.props.source, + defaultValue: filter.props.defaultValue, + }); + }, [filter.props.defaultValue, filter.props.source, onShow]); + const handleHide = useCallback(() => { + onHide({ + source: filter.props.source, + }); + }, [filter.props.source, onHide]); + + return ( +
    +
    + {displayed && } +
    +
    + +
    +
    + ); +}); + +export interface FilterButtonMenuItemProps { + filter: React.ReactElement; + displayed: boolean; + + onShow: (params: { source: string; defaultValue: any }) => void; + onHide: (params: { source: string }) => void; + resource?: string; + autoFocus?: boolean; +} diff --git a/apps/web/src/components/admin/form.tsx b/apps/web/src/components/admin/form.tsx new file mode 100644 index 0000000..d87e2cf --- /dev/null +++ b/apps/web/src/components/admin/form.tsx @@ -0,0 +1,290 @@ +import * as React from "react"; +import type { MouseEventHandler } from "react"; +import { createContext, useCallback, useContext, useMemo } from "react"; +import type { + CreateParams, + RaRecord, + TransformData, + UpdateParams, +} from "ra-core"; +import { + setSubmissionErrors, + useSaveContext, + useTranslate, + ValidationError, + warning, +} from "ra-core"; +import { Loader2, Save } from "lucide-react"; +import * as LabelPrimitive from "@radix-ui/react-label"; +import { Slot } from "@radix-ui/react-slot"; +import { FormProvider, useFormContext, useFormState } from "react-hook-form"; +import type { UseMutationOptions } from "@tanstack/react-query"; +import { cn } from "@/lib/utils"; +import { Label } from "@/components/ui/label"; +import { Button } from "@/components/ui/button"; + +const Form = FormProvider; + +type FormItemContextValue = { + id: string; + name: string; +}; + +const FormItemContext = createContext( + {} as FormItemContextValue, +); + +const useFormField = () => { + const { getFieldState, formState } = useFormContext(); + const { id, name } = useContext(FormItemContext); + + const fieldState = getFieldState(name, formState); + + return useMemo( + () => ({ + formItemId: id, + formDescriptionId: `${id}-description`, + formMessageId: `${id}-message`, + ...fieldState, + }), + [id, fieldState], + ); +}; + +function FormField({ className, id, name, ...props }: FormItemProps) { + const contextValue: FormItemContextValue = useMemo( + () => ({ + id, + name, + }), + [id, name], + ); + + return ( + +
    + + ); +} + +type FormItemProps = Omit, "id"> & { + id: string; + name: string; +}; + +function FormLabel({ + className, + ...props +}: React.ComponentProps) { + const { error, formItemId } = useFormField(); + + return ( +