@parall/cli 1.74.0 → 1.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/apps-add.d.ts +6 -0
- package/dist/commands/apps-add.d.ts.map +1 -0
- package/dist/commands/apps-add.js +93 -0
- package/dist/commands/apps-blocks.d.ts +96 -0
- package/dist/commands/apps-blocks.d.ts.map +1 -0
- package/dist/commands/apps-blocks.js +196 -0
- package/dist/commands/apps-scaffold-actions.d.ts +4 -9
- package/dist/commands/apps-scaffold-actions.d.ts.map +1 -1
- package/dist/commands/apps-scaffold-actions.js +4 -163
- package/dist/commands/apps-scaffold.d.ts +5 -4
- package/dist/commands/apps-scaffold.d.ts.map +1 -1
- package/dist/commands/apps-scaffold.js +24 -144
- package/dist/commands/apps-template.d.ts +15 -0
- package/dist/commands/apps-template.d.ts.map +1 -0
- package/dist/commands/apps-template.js +105 -0
- package/dist/commands/apps-templates.gen.d.ts +5 -0
- package/dist/commands/apps-templates.gen.d.ts.map +1 -0
- package/dist/commands/apps-templates.gen.js +540 -0
- package/dist/commands/apps.d.ts +5 -4
- package/dist/commands/apps.d.ts.map +1 -1
- package/dist/commands/apps.js +7 -4
- package/dist/lib/output.d.ts +11 -0
- package/dist/lib/output.d.ts.map +1 -1
- package/dist/lib/output.js +40 -4
- package/package.json +25 -5
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
export const TEMPLATE_BASE = {
|
|
2
|
+
"AGENTS.md": "# {{APP_NAME}} — Mini App 约定\n\n这是一个 Parall Mini App:纯静态的页面 bundle,Parall 在 app 自己的 origin 上出货,嵌在 Parall 里运行(Web / Desktop 是 iframe,iOS / Android 是原生网页控件)。\n\n## 技术栈\n\n- Vite 6 + React 19 + TypeScript + Tailwind CSS v4 + shadcn/ui(new-york,Radix)。需要 Node 20 以上。\n- `pnpm install && pnpm build`(npm 也行)产出 `dist/`;`build` 先跑 `tsc` 类型检查,类型错了不出产物。\n- 依赖都钉死了确切版本(只有 `--actions` 项目里本地跑 action 用的 miniflare 是 `^` 范围,跟着 CLI 的本地运行器走);加依赖也写确切版本。不要从 CDN 引任何东西(见下一节)。\n\n## 产物约束(发布时平台验收,不合规就 BUNDLE_REJECTED)\n\n- 脚本、样式、字体、图片全部打进 `dist/`:HTML 与 CSS 里不能有指向 `http(s)://` 或 `//` 的 script、link、`@import`、`url()`。\n- 资源用相对路径(`vite.config.ts` 已设 `base: './'`);以 `/` 开头的根路径会被拒。\n- 解包后最多 20 MiB、200 个文件,只能是普通文件。\n- 页面没有网络(CSP `connect-src 'none'`):fetch、XHR、WebSocket 都不通,数据只经 action(`parall app init --actions`)。图片只能来自 bundle、`data:` / `blob:` 或 Parall 的附件域。\n- 字体只能来自 bundle(`font-src 'self'`):模板打包了 Geist(拉丁字母),中文用系统字体;`vite.config.ts` 不让字体被内联成 `data:`,别去掉。\n- `public/manifest.json` 随构建进入 `dist/` 根部;`entry` 固定 `index.html`。\n\n## 目录\n\n- `src/pages.tsx`:页面列表,多于一页时顶部显示标签,第一页默认打开。链接 `prll://app_…#<页面 id>/<余下部分>` 打开对应页面,余下部分作为 `route` 传给页面(例:`#items/<id>` 选中一条)。\n- `src/pages/<page>/`:一个页面一个目录——`index.ts`(id、标题、图标)、组件、`messages.ts`(中英文文案)。\n- `src/components/ui/`:shadcn/ui 组件原文(button、card、table、dialog、alert-dialog、sheet、input、textarea、label、select、checkbox、switch、tabs、toggle-group、badge、skeleton、avatar、dropdown-menu、popover、tooltip、scroll-area、separator、sonner、spinner、empty)。要改样式直接改它们;有网络时可以 `npx shadcn@latest add <组件>` 加别的(`components.json` 已配好)。\n- `src/components/`:`app-shell`(外框与页面标签)、`page`(`PageContainer` / `PageHeader`)、`states`(加载、空、出错)、`responsive-dialog`(宽屏是对话框,手机是底部抽屉)、`confirm-dialog`、`user-avatar`。\n- `src/hooks/`:`use-host`(握手、`useViewer()`、route)、`use-media-query`(`useIsMobile()`)。\n- `src/lib/`:`i18n`(`defineMessages`,按浏览器语言选中文或英文;要固定语言改 `FORCED_LOCALE`)、`format`(日期、相对时间)、`errors`(把错误码变成给人看的话)、`keys`(`onEnter`)、`utils`(`cn`)。\n- `src/index.css`:颜色、圆角、字体 token。改 `--primary` 等变量换配色;浅色 / 深色跟随系统设置(`prefers-color-scheme`),Parall 不下发主题。\n\n## 界面约定\n\n- 用 Tailwind utility 和 `src/components/ui` 的组件;颜色只用 token(`bg-background`、`text-muted-foreground`、`border`…),深浅色才都对。\n- 375px 宽也要好用。Parall 还会把 app 开在对话旁边的窄面板里,所以窄屏不只是手机。布局用 CSS 断点(`md:` 768px、`lg:` 1024px),行为不同时才用 `useIsMobile()`。\n- 每块数据都处理三种状态:`LoadingState`、`EmptyState`、`ErrorState`(`src/components/states.tsx`)。\n- Parall 的 Web 与 Desktop 宿主不让页面提交表单(iframe 没有 allow-forms):`<form>` 不会触发 submit、`onSubmit` 永远不跑。保存按钮用 `onClick`,单行输入框按回车保存用 `onKeyDown={onEnter(save)}`(`src/lib/keys.ts`,输入法确认候选词的回车不算)。\n- 手机宿主不弹 `alert` / `confirm` / `prompt`:确认用 `ConfirmDialog`。外链与新窗口在手机上不打开。\n- 交互元素用原生 `button` / `input`;只有图标的按钮要有 `aria-label`。\n\n## 本地看\n\n- `pnpm build` 后 `parall app dev --dist dist`:本地宿主页加页面。不带 `--app` 时只应答握手,页面调 action 会得到 `NOT_GRANTED`。\n- `parall app dev` 在前台一直运行到被结束,不会自己退出:在 agent 里放到后台跑,`parall app dev --dist dist > dev.log 2>&1 &`,从 `dev.log` 里取它打印的地址,用完结束它。\n- 直接打开 `dist/index.html` 或 `pnpm dev` 不在宿主里,页面只会显示「请在 Parall 里打开」。\n\n## 发布\n\n- `parall app create --name \"…\"` → `parall app publish dist --app <app_…> --source .` → 把 `prll://app_…` 发给要用的人。\n- 你不是这个 app 的作者时:请作者或组织 owner / admin 执行 `parall app authors add <app_…> <你的 usr_…>`。\n- `src/parall.ts` 是 @parall/miniapp-sdk 的 vendored 副本(npm 发布前),不要改。\n- 借用的代码(shadcn/ui、shadcn-admin、Kibo UI)与字体的许可证见 `THIRD_PARTY_NOTICES.md`,保留这个文件。\n",
|
|
3
|
+
"THIRD_PARTY_NOTICES.md": "# Third-party notices\n\nThis app was scaffolded by `parall app init`. Parts of its source are\nadapted from the projects below, under their licenses. Keep this file with\nthe source.\n\n## shadcn/ui\n\n`src/components/ui/*` are shadcn/ui components (new-york style), lightly\nadapted. https://github.com/shadcn-ui/ui\n\n```\nMIT License\n\nCopyright (c) 2023 shadcn\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n## shadcn-admin\n\n`src/components/confirm-dialog.tsx` and parts of `src/index.css` (the base\nlayer) are adapted from shadcn-admin. https://github.com/satnaing/shadcn-admin\n\n```\nMIT License\n\nCopyright (c) 2024 Sat Naing\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n## Kibo UI\n\nBlocks added with `parall app add` (`src/blocks/*`) adapt patterns from\nKibo UI's kanban and calendar components. https://www.kibo-ui.com\n\n```\nCopyright (c) 2023 — Present shadcnblocks\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n## Geist\n\nThe Geist typeface, bundled from `@fontsource-variable/geist`, is licensed\nunder the SIL Open Font License 1.1 (see that package's LICENSE).\nhttps://github.com/vercel/geist-font\n",
|
|
4
|
+
"_gitignore": "node_modules\ndist\n*.log\n",
|
|
5
|
+
"components.json": "{\n \"$schema\": \"https://ui.shadcn.com/schema.json\",\n \"style\": \"new-york\",\n \"rsc\": false,\n \"tsx\": true,\n \"tailwind\": {\n \"config\": \"\",\n \"css\": \"src/index.css\",\n \"baseColor\": \"neutral\",\n \"cssVariables\": true,\n \"prefix\": \"\"\n },\n \"aliases\": {\n \"components\": \"@/components\",\n \"utils\": \"@/lib/utils\",\n \"ui\": \"@/components/ui\",\n \"lib\": \"@/lib\",\n \"hooks\": \"@/hooks\"\n },\n \"iconLibrary\": \"lucide\"\n}\n",
|
|
6
|
+
"index.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, viewport-fit=cover\" />\n <meta name=\"color-scheme\" content=\"light dark\" />\n <title>{{APP_NAME}}</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"./src/main.tsx\"></script>\n </body>\n</html>\n",
|
|
7
|
+
"package.json": "{\n \"name\": \"mini-app\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"typecheck\": \"tsc -p tsconfig.json\",\n \"build\": \"tsc -p tsconfig.json && vite build\"\n },\n \"dependencies\": {\n \"@fontsource-variable/geist\": \"5.3.0\",\n \"class-variance-authority\": \"0.7.1\",\n \"clsx\": \"2.1.1\",\n \"lucide-react\": \"0.576.0\",\n \"radix-ui\": \"1.8.0\",\n \"react\": \"19.2.5\",\n \"react-dom\": \"19.2.5\",\n \"sonner\": \"2.0.8\",\n \"tailwind-merge\": \"3.5.0\"\n },\n \"devDependencies\": {\n \"@tailwindcss/vite\": \"4.2.2\",\n \"@types/react\": \"19.2.14\",\n \"@types/react-dom\": \"19.2.3\",\n \"@vitejs/plugin-react\": \"4.7.0\",\n \"tailwindcss\": \"4.2.2\",\n \"tw-animate-css\": \"1.4.0\",\n \"typescript\": \"5.9.3\",\n \"vite\": \"6.4.1\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"pnpm\": {\n \"onlyBuiltDependencies\": [\n \"esbuild\"\n ]\n }\n}\n",
|
|
8
|
+
"public/manifest.json": "{\n \"entry\": \"index.html\",\n \"sdk_version\": \"0.1.0\",\n \"capabilities\": []\n}\n",
|
|
9
|
+
"src/App.tsx": "import { AppShell } from '@/components/app-shell';\nimport { HostConnecting, HostMissing } from '@/components/states';\nimport { useHostState } from '@/hooks/use-host';\nimport { pages } from '@/pages';\n\nexport function App() {\n const host = useHostState();\n if (host.status === 'connecting') return <HostConnecting />;\n if (host.status === 'missing') return <HostMissing />;\n return <AppShell pages={pages} />;\n}\n",
|
|
10
|
+
"src/components/app-shell.tsx": "import type { LucideIcon } from 'lucide-react';\nimport { type ComponentType, useEffect, useMemo, useState } from 'react';\nimport { Toaster } from '@/components/ui/sonner';\nimport { TooltipProvider } from '@/components/ui/tooltip';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useHost } from '@/hooks/use-host';\nimport { cn } from '@/lib/utils';\n\nexport interface PageProps {\n /** The rest of the route after \"<page id>/\" — '' when there is none. A\n * link prll://app_…#items/42 opens the items page with route \"42\". */\n route: string;\n}\n\nexport interface AppPage {\n /** Names the page in links: prll://app_…#<id>. */\n id: string;\n title: string;\n icon: LucideIcon;\n component: ComponentType<PageProps>;\n}\n\n/** Splits a host route (\"calendar/2026-10-12\") into a page and the rest. */\nfunction resolveRoute(pages: AppPage[], route: string): { id: string; rest: string } {\n const clean = route.replace(/^[#/]+/, '');\n const slash = clean.indexOf('/');\n const id = slash === -1 ? clean : clean.slice(0, slash);\n const page = pages.find((p) => p.id === id);\n if (!page) return { id: pages[0]?.id ?? '', rest: '' };\n return { id: page.id, rest: slash === -1 ? '' : clean.slice(slash + 1) };\n}\n\n/**\n * The frame every page renders in: a top bar with one tab per page (none\n * for a single page), the active page, and the toaster. Layout follows the\n * frame's width — the full Parall panel, the narrow panel beside a chat, or\n * a phone.\n */\nexport function AppShell({ pages }: { pages: AppPage[] }) {\n const host = useHost();\n const [active, setActive] = useState(() => resolveRoute(pages, host.route));\n\n // The host moves the route when someone opens a link to another place in\n // the app while it is open.\n useEffect(() => {\n setActive(resolveRoute(pages, host.route));\n }, [pages, host.route]);\n\n const page = useMemo(() => pages.find((p) => p.id === active.id) ?? pages[0], [pages, active]);\n if (!page) return null;\n const Page = page.component;\n\n return (\n <TooltipProvider>\n <div className=\"flex min-h-svh flex-col\">\n {pages.length > 1 ? (\n <header className=\"sticky top-0 z-30 border-b bg-background/90 backdrop-blur-md\">\n <div className=\"mx-auto flex h-12 w-full max-w-screen-2xl items-center gap-3 px-2 md:px-4\">\n <nav\n aria-label=\"Pages\"\n className=\"no-scrollbar flex min-w-0 flex-1 items-center gap-1 overflow-x-auto\"\n >\n {pages.map((p) => {\n const Icon = p.icon;\n const current = p.id === page.id;\n return (\n <button\n key={p.id}\n type=\"button\"\n aria-current={current ? 'page' : undefined}\n onClick={() => setActive({ id: p.id, rest: '' })}\n className={cn(\n 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2.5 font-medium text-muted-foreground text-sm transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50',\n current && 'bg-accent text-foreground',\n )}\n >\n <Icon className=\"size-4\" />\n {p.title}\n </button>\n );\n })}\n </nav>\n <UserAvatar\n id={host.viewer.id}\n name={host.viewer.display_name}\n className=\"hidden sm:flex\"\n title={host.viewer.display_name}\n />\n </div>\n </header>\n ) : null}\n <main className=\"flex min-w-0 flex-1 flex-col\">\n <Page key={page.id} route={active.rest} />\n </main>\n <Toaster position=\"top-center\" />\n </div>\n </TooltipProvider>\n );\n}\n",
|
|
11
|
+
"src/components/confirm-dialog.tsx": "import type { ReactNode } from 'react';\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '@/components/ui/alert-dialog';\nimport { Button } from '@/components/ui/button';\nimport { t } from '@/lib/messages';\n\n/**\n * Asks before doing something that cannot be undone. Use it instead of\n * window.confirm(), which Parall's phone apps do not show.\n * (Adapted from shadcn-admin's ConfirmDialog, MIT.)\n */\nexport function ConfirmDialog({\n open,\n onOpenChange,\n title,\n description,\n confirmText,\n destructive,\n pending,\n onConfirm,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: ReactNode;\n description?: ReactNode;\n confirmText?: ReactNode;\n destructive?: boolean;\n pending?: boolean;\n onConfirm: () => void;\n}) {\n return (\n <AlertDialog open={open} onOpenChange={onOpenChange}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>{title}</AlertDialogTitle>\n {description ? <AlertDialogDescription>{description}</AlertDialogDescription> : null}\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={pending}>{t('cancel')}</AlertDialogCancel>\n <Button\n variant={destructive ? 'destructive' : 'default'}\n disabled={pending}\n onClick={onConfirm}\n >\n {confirmText ?? t('confirm')}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n );\n}\n",
|
|
12
|
+
"src/components/page.tsx": "import type { ReactNode } from 'react';\nimport { cn } from '@/lib/utils';\n\n/** A page's frame: centered, padded, narrower on phones. `width=\"full\"`\n * suits boards and calendars that use every pixel. */\nexport function PageContainer({\n children,\n width = 'default',\n className,\n}: {\n children: ReactNode;\n width?: 'default' | 'wide' | 'full';\n className?: string;\n}) {\n return (\n <div\n className={cn(\n 'mx-auto flex w-full min-w-0 flex-1 flex-col px-4 py-5 md:px-6 md:py-6',\n width === 'default' && 'max-w-5xl',\n width === 'wide' && 'max-w-screen-2xl',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\n/** Title, a line of description and the page's main actions. Actions wrap\n * under the title on narrow screens. */\nexport function PageHeader({\n title,\n description,\n actions,\n className,\n}: {\n title: ReactNode;\n description?: ReactNode;\n actions?: ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn('mb-4 flex flex-wrap items-end justify-between gap-x-4 gap-y-3', className)}>\n <div className=\"min-w-0\">\n <h1 className=\"font-semibold text-xl tracking-tight md:text-2xl\">{title}</h1>\n {description ? <p className=\"mt-1 text-muted-foreground text-sm\">{description}</p> : null}\n </div>\n {actions ? <div className=\"flex shrink-0 flex-wrap items-center gap-2\">{actions}</div> : null}\n </div>\n );\n}\n",
|
|
13
|
+
"src/components/responsive-dialog.tsx": "import type { ReactNode } from 'react';\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@/components/ui/dialog';\nimport {\n Sheet,\n SheetContent,\n SheetDescription,\n SheetFooter,\n SheetHeader,\n SheetTitle,\n} from '@/components/ui/sheet';\nimport { useIsMobile } from '@/hooks/use-media-query';\nimport { cn } from '@/lib/utils';\n\n/**\n * A dialog on wide screens and a sheet from the bottom on phones, with one\n * API. Put the fields in children and the buttons in footer; save with the\n * button's onClick, not a <form> submit (see onEnter in lib/keys.ts).\n */\nexport function ResponsiveDialog({\n open,\n onOpenChange,\n title,\n description,\n children,\n footer,\n className,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: ReactNode;\n description?: ReactNode;\n children: ReactNode;\n footer?: ReactNode;\n className?: string;\n}) {\n const mobile = useIsMobile();\n if (mobile) {\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent\n side=\"bottom\"\n className={cn(\n 'max-h-[92svh] gap-0 rounded-t-2xl pb-[env(safe-area-inset-bottom)]',\n className,\n )}\n >\n <SheetHeader className=\"pr-12\">\n <SheetTitle>{title}</SheetTitle>\n {description ? (\n <SheetDescription>{description}</SheetDescription>\n ) : (\n <SheetDescription className=\"sr-only\">{title}</SheetDescription>\n )}\n </SheetHeader>\n <div className=\"min-h-0 flex-1 overflow-y-auto px-4 pb-2\">{children}</div>\n {footer ? (\n <SheetFooter className=\"flex-col-reverse border-t\">{footer}</SheetFooter>\n ) : null}\n </SheetContent>\n </Sheet>\n );\n }\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className={cn('max-h-[90svh] overflow-y-auto sm:max-w-lg', className)}>\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n {description ? (\n <DialogDescription>{description}</DialogDescription>\n ) : (\n <DialogDescription className=\"sr-only\">{title}</DialogDescription>\n )}\n </DialogHeader>\n {children}\n {footer ? <DialogFooter>{footer}</DialogFooter> : null}\n </DialogContent>\n </Dialog>\n );\n}\n",
|
|
14
|
+
"src/components/states.tsx": "import { AlertTriangle, type LucideIcon, PlugZap, RotateCw } from 'lucide-react';\nimport type { ReactNode } from 'react';\nimport { Button } from '@/components/ui/button';\nimport {\n Empty,\n EmptyContent,\n EmptyDescription,\n EmptyHeader,\n EmptyMedia,\n EmptyTitle,\n} from '@/components/ui/empty';\nimport { Skeleton } from '@/components/ui/skeleton';\nimport { Spinner } from '@/components/ui/spinner';\nimport { describeError } from '@/lib/errors';\nimport { t } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\n\n/** Placeholder rows shaped like the content that is loading. */\nexport function LoadingState({\n variant = 'list',\n rows = 5,\n className,\n}: {\n variant?: 'list' | 'cards' | 'board';\n rows?: number;\n className?: string;\n}) {\n if (variant === 'board') {\n return (\n <div className={cn('flex gap-3 overflow-hidden', className)} aria-busy=\"true\">\n <span className=\"sr-only\">{t('loading')}</span>\n {[0, 1, 2].map((column) => (\n <div\n key={column}\n className=\"flex w-72 shrink-0 flex-col gap-2 rounded-xl bg-muted/50 p-2\"\n >\n <Skeleton className=\"h-5 w-24\" />\n {Array.from({ length: 3 - (column % 2) }, (_, i) => (\n <Skeleton key={i} className=\"h-20 w-full rounded-lg\" />\n ))}\n </div>\n ))}\n </div>\n );\n }\n if (variant === 'cards') {\n return (\n <div className={cn('grid gap-3 sm:grid-cols-2 lg:grid-cols-3', className)} aria-busy=\"true\">\n <span className=\"sr-only\">{t('loading')}</span>\n {Array.from({ length: rows }, (_, i) => (\n <Skeleton key={i} className=\"h-28 rounded-xl\" />\n ))}\n </div>\n );\n }\n return (\n <div className={cn('flex flex-col gap-2', className)} aria-busy=\"true\">\n <span className=\"sr-only\">{t('loading')}</span>\n {Array.from({ length: rows }, (_, i) => (\n <div key={i} className=\"flex items-center gap-3 rounded-lg border p-3\">\n <Skeleton className=\"size-8 rounded-full\" />\n <div className=\"flex flex-1 flex-col gap-2\">\n <Skeleton className=\"h-4 w-2/5\" />\n <Skeleton className=\"h-3 w-3/5\" />\n </div>\n </div>\n ))}\n </div>\n );\n}\n\n/** Nothing to show yet, with the action that fills it. */\nexport function EmptyState({\n icon: Icon,\n title,\n description,\n action,\n className,\n}: {\n icon?: LucideIcon;\n title: ReactNode;\n description?: ReactNode;\n action?: ReactNode;\n className?: string;\n}) {\n return (\n <Empty className={cn('border', className)}>\n <EmptyHeader>\n {Icon ? (\n <EmptyMedia variant=\"icon\">\n <Icon />\n </EmptyMedia>\n ) : null}\n <EmptyTitle>{title}</EmptyTitle>\n {description ? <EmptyDescription>{description}</EmptyDescription> : null}\n </EmptyHeader>\n {action ? <EmptyContent>{action}</EmptyContent> : null}\n </Empty>\n );\n}\n\n/** A failed call: what went wrong in words, the code and invocation to quote,\n * and a retry. */\nexport function ErrorState({\n error,\n onRetry,\n className,\n}: {\n error: unknown;\n onRetry?: () => void;\n className?: string;\n}) {\n const described = describeError(error);\n return (\n <Empty className={cn('border border-destructive/30', className)} role=\"alert\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\" className=\"bg-destructive/10 text-destructive\">\n <AlertTriangle />\n </EmptyMedia>\n <EmptyTitle>{t('errorTitle')}</EmptyTitle>\n <EmptyDescription>\n {described.message}\n {described.hint ? <span className=\"mt-1 block\">{described.hint}</span> : null}\n </EmptyDescription>\n {described.code || described.invocationId ? (\n <p className=\"font-mono text-muted-foreground text-xs\">\n {[described.code, described.invocationId].filter(Boolean).join(' · ')}\n </p>\n ) : null}\n </EmptyHeader>\n {onRetry ? (\n <EmptyContent>\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry}>\n <RotateCw />\n {t('retry')}\n </Button>\n </EmptyContent>\n ) : null}\n </Empty>\n );\n}\n\n/** Shown while the host handshake runs, and when there is no host at all. */\nexport function HostConnecting() {\n return (\n <div className=\"flex min-h-svh items-center justify-center gap-2 text-muted-foreground text-sm\">\n <Spinner />\n {t('connecting')}\n </div>\n );\n}\n\nexport function HostMissing() {\n return (\n <div className=\"flex min-h-svh items-center justify-center p-6\">\n <EmptyState icon={PlugZap} title={t('hostMissingTitle')} description={t('hostMissingBody')} />\n </div>\n );\n}\n",
|
|
15
|
+
"src/components/ui/alert-dialog.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { AlertDialog as AlertDialogPrimitive } from 'radix-ui';\n\nimport { Button } from '@/components/ui/button';\n\nfunction AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {\n return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />;\n}\n\nfunction AlertDialogTrigger({\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {\n return <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />;\n}\n\nfunction AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {\n return <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />;\n}\n\nfunction AlertDialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {\n return (\n <AlertDialogPrimitive.Overlay\n data-slot=\"alert-dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogContent({\n className,\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {\n size?: 'default' | 'sm';\n}) {\n return (\n <AlertDialogPortal>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Content\n data-slot=\"alert-dialog-content\"\n data-size={size}\n className={cn(\n 'group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg',\n className,\n )}\n {...props}\n />\n </AlertDialogPortal>\n );\n}\n\nfunction AlertDialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"alert-dialog-header\"\n className={cn(\n 'grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogFooter({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"alert-dialog-footer\"\n className={cn(\n 'flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot=\"alert-dialog-title\"\n className={cn(\n 'text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot=\"alert-dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction AlertDialogMedia({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"alert-dialog-media\"\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogAction({\n className,\n variant = 'default',\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &\n Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {\n return (\n <Button variant={variant} size={size} asChild>\n <AlertDialogPrimitive.Action\n data-slot=\"alert-dialog-action\"\n className={cn(className)}\n {...props}\n />\n </Button>\n );\n}\n\nfunction AlertDialogCancel({\n className,\n variant = 'outline',\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &\n Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {\n return (\n <Button variant={variant} size={size} asChild>\n <AlertDialogPrimitive.Cancel\n data-slot=\"alert-dialog-cancel\"\n className={cn(className)}\n {...props}\n />\n </Button>\n );\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n};\n",
|
|
16
|
+
"src/components/ui/avatar.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Avatar as AvatarPrimitive } from 'radix-ui';\n\nfunction Avatar({\n className,\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AvatarPrimitive.Root> & {\n size?: 'default' | 'sm' | 'lg';\n}) {\n return (\n <AvatarPrimitive.Root\n data-slot=\"avatar\"\n data-size={size}\n className={cn(\n 'group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {\n return (\n <AvatarPrimitive.Image\n data-slot=\"avatar-image\"\n className={cn('aspect-square size-full', className)}\n {...props}\n />\n );\n}\n\nfunction AvatarFallback({\n className,\n ...props\n}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {\n return (\n <AvatarPrimitive.Fallback\n data-slot=\"avatar-fallback\"\n className={cn(\n 'flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AvatarBadge({ className, ...props }: React.ComponentProps<'span'>) {\n return (\n <span\n data-slot=\"avatar-badge\"\n className={cn(\n 'absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none',\n 'group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden',\n 'group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2',\n 'group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AvatarGroup({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"avatar-group\"\n className={cn(\n 'group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AvatarGroupCount({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"avatar-group-count\"\n className={cn(\n 'relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Avatar, AvatarImage, AvatarFallback, AvatarBadge, AvatarGroup, AvatarGroupCount };\n",
|
|
17
|
+
"src/components/ui/badge.tsx": "import * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\nimport { Slot } from 'radix-ui';\n\nconst badgeVariants = cva(\n 'inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3',\n {\n variants: {\n variant: {\n default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90',\n secondary: 'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',\n destructive:\n 'bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90',\n outline:\n 'border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',\n ghost: '[a&]:hover:bg-accent [a&]:hover:text-accent-foreground',\n link: 'text-primary underline-offset-4 [a&]:hover:underline',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n },\n);\n\nfunction Badge({\n className,\n variant = 'default',\n asChild = false,\n ...props\n}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {\n const Comp = asChild ? Slot.Root : 'span';\n\n return (\n <Comp\n data-slot=\"badge\"\n data-variant={variant}\n className={cn(badgeVariants({ variant }), className)}\n {...props}\n />\n );\n}\n\nexport { Badge, badgeVariants };\n",
|
|
18
|
+
"src/components/ui/button.tsx": "import * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\nimport { Slot } from 'radix-ui';\n\nconst buttonVariants = cva(\n \"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: 'bg-primary text-primary-foreground hover:bg-primary/90',\n destructive:\n 'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40',\n outline:\n 'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',\n secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',\n ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',\n link: 'text-primary underline-offset-4 hover:underline',\n },\n size: {\n default: 'h-9 px-4 py-2 has-[>svg]:px-3',\n xs: \"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',\n lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',\n icon: 'size-9',\n 'icon-xs': \"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3\",\n 'icon-sm': 'size-8',\n 'icon-lg': 'size-10',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n },\n);\n\nfunction Button({\n className,\n variant = 'default',\n size = 'default',\n asChild = false,\n ...props\n}: React.ComponentProps<'button'> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : 'button';\n\n return (\n <Comp\n data-slot=\"button\"\n data-variant={variant}\n data-size={size}\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n",
|
|
19
|
+
"src/components/ui/card.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\n\nfunction Card({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n 'flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n '@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn('leading-none font-semibold', className)}\n {...props}\n />\n );\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}\n {...props}\n />\n );\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<'div'>) {\n return <div data-slot=\"card-content\" className={cn('px-6', className)} {...props} />;\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn('flex items-center px-6 [.border-t]:pt-6', className)}\n {...props}\n />\n );\n}\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };\n",
|
|
20
|
+
"src/components/ui/checkbox.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { CheckIcon } from 'lucide-react';\nimport { Checkbox as CheckboxPrimitive } from 'radix-ui';\n\nfunction Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\n return (\n <CheckboxPrimitive.Root\n data-slot=\"checkbox\"\n className={cn(\n 'peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary',\n className,\n )}\n {...props}\n >\n <CheckboxPrimitive.Indicator\n data-slot=\"checkbox-indicator\"\n className=\"grid place-content-center text-current transition-none\"\n >\n <CheckIcon className=\"size-3.5\" />\n </CheckboxPrimitive.Indicator>\n </CheckboxPrimitive.Root>\n );\n}\n\nexport { Checkbox };\n",
|
|
21
|
+
"src/components/ui/dialog.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { XIcon } from 'lucide-react';\nimport { Dialog as DialogPrimitive } from 'radix-ui';\n\nimport { Button } from '@/components/ui/button';\n\nfunction Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />;\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />;\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />;\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />;\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n showCloseButton?: boolean;\n}) {\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n data-slot=\"dialog-content\"\n className={cn(\n 'fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',\n className,\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n className=\"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Content>\n </DialogPortal>\n );\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn('flex flex-col gap-2 text-center sm:text-left', className)}\n {...props}\n />\n );\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean;\n}) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close asChild>\n <Button variant=\"outline\">Close</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n );\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n );\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n};\n",
|
|
22
|
+
"src/components/ui/dropdown-menu.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';\nimport { DropdownMenu as DropdownMenuPrimitive } from 'radix-ui';\n\nfunction DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {\n return <DropdownMenuPrimitive.Root data-slot=\"dropdown-menu\" {...props} />;\n}\n\nfunction DropdownMenuPortal({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {\n return <DropdownMenuPrimitive.Portal data-slot=\"dropdown-menu-portal\" {...props} />;\n}\n\nfunction DropdownMenuTrigger({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {\n return <DropdownMenuPrimitive.Trigger data-slot=\"dropdown-menu-trigger\" {...props} />;\n}\n\nfunction DropdownMenuContent({\n className,\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {\n return (\n <DropdownMenuPrimitive.Portal>\n <DropdownMenuPrimitive.Content\n data-slot=\"dropdown-menu-content\"\n sideOffset={sideOffset}\n className={cn(\n 'z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',\n className,\n )}\n {...props}\n />\n </DropdownMenuPrimitive.Portal>\n );\n}\n\nfunction DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {\n return <DropdownMenuPrimitive.Group data-slot=\"dropdown-menu-group\" {...props} />;\n}\n\nfunction DropdownMenuItem({\n className,\n inset,\n variant = 'default',\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {\n inset?: boolean;\n variant?: 'default' | 'destructive';\n}) {\n return (\n <DropdownMenuPrimitive.Item\n data-slot=\"dropdown-menu-item\"\n data-inset={inset}\n data-variant={variant}\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuCheckboxItem({\n className,\n children,\n checked,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {\n return (\n <DropdownMenuPrimitive.CheckboxItem\n data-slot=\"dropdown-menu-checkbox-item\"\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className,\n )}\n checked={checked}\n {...props}\n >\n <span className=\"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.CheckboxItem>\n );\n}\n\nfunction DropdownMenuRadioGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {\n return <DropdownMenuPrimitive.RadioGroup data-slot=\"dropdown-menu-radio-group\" {...props} />;\n}\n\nfunction DropdownMenuRadioItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {\n return (\n <DropdownMenuPrimitive.RadioItem\n data-slot=\"dropdown-menu-radio-item\"\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className,\n )}\n {...props}\n >\n <span className=\"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CircleIcon className=\"size-2 fill-current\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.RadioItem>\n );\n}\n\nfunction DropdownMenuLabel({\n className,\n inset,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.Label\n data-slot=\"dropdown-menu-label\"\n data-inset={inset}\n className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {\n return (\n <DropdownMenuPrimitive.Separator\n data-slot=\"dropdown-menu-separator\"\n className={cn('-mx-1 my-1 h-px bg-border', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {\n return (\n <span\n data-slot=\"dropdown-menu-shortcut\"\n className={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {\n return <DropdownMenuPrimitive.Sub data-slot=\"dropdown-menu-sub\" {...props} />;\n}\n\nfunction DropdownMenuSubTrigger({\n className,\n inset,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.SubTrigger\n data-slot=\"dropdown-menu-sub-trigger\"\n data-inset={inset}\n className={cn(\n \"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className,\n )}\n {...props}\n >\n {children}\n <ChevronRightIcon className=\"ml-auto size-4\" />\n </DropdownMenuPrimitive.SubTrigger>\n );\n}\n\nfunction DropdownMenuSubContent({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {\n return (\n <DropdownMenuPrimitive.SubContent\n data-slot=\"dropdown-menu-sub-content\"\n className={cn(\n 'z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport {\n DropdownMenu,\n DropdownMenuPortal,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuCheckboxItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n};\n",
|
|
23
|
+
"src/components/ui/empty.tsx": "import { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\n\nfunction Empty({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"empty\"\n className={cn(\n 'flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction EmptyHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"empty-header\"\n className={cn('flex max-w-sm flex-col items-center gap-2 text-center', className)}\n {...props}\n />\n );\n}\n\nconst emptyMediaVariants = cva(\n 'mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0',\n {\n variants: {\n variant: {\n default: 'bg-transparent',\n icon: \"flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-6\",\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n },\n);\n\nfunction EmptyMedia({\n className,\n variant = 'default',\n ...props\n}: React.ComponentProps<'div'> & VariantProps<typeof emptyMediaVariants>) {\n return (\n <div\n data-slot=\"empty-icon\"\n data-variant={variant}\n className={cn(emptyMediaVariants({ variant, className }))}\n {...props}\n />\n );\n}\n\nfunction EmptyTitle({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"empty-title\"\n className={cn('text-lg font-medium tracking-tight', className)}\n {...props}\n />\n );\n}\n\nfunction EmptyDescription({ className, ...props }: React.ComponentProps<'p'>) {\n return (\n <div\n data-slot=\"empty-description\"\n className={cn(\n 'text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction EmptyContent({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"empty-content\"\n className={cn(\n 'flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia };\n",
|
|
24
|
+
"src/components/ui/input.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\n\nfunction Input({ className, type, ...props }: React.ComponentProps<'input'>) {\n return (\n <input\n type={type}\n data-slot=\"input\"\n className={cn(\n 'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30',\n 'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',\n 'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Input };\n",
|
|
25
|
+
"src/components/ui/label.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Label as LabelPrimitive } from 'radix-ui';\n\nfunction Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {\n return (\n <LabelPrimitive.Root\n data-slot=\"label\"\n className={cn(\n 'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Label };\n",
|
|
26
|
+
"src/components/ui/popover.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Popover as PopoverPrimitive } from 'radix-ui';\n\nfunction Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {\n return <PopoverPrimitive.Root data-slot=\"popover\" {...props} />;\n}\n\nfunction PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {\n return <PopoverPrimitive.Trigger data-slot=\"popover-trigger\" {...props} />;\n}\n\nfunction PopoverContent({\n className,\n align = 'center',\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Content>) {\n return (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n data-slot=\"popover-content\"\n align={align}\n sideOffset={sideOffset}\n className={cn(\n 'z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',\n className,\n )}\n {...props}\n />\n </PopoverPrimitive.Portal>\n );\n}\n\nfunction PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {\n return <PopoverPrimitive.Anchor data-slot=\"popover-anchor\" {...props} />;\n}\n\nfunction PopoverHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"popover-header\"\n className={cn('flex flex-col gap-1 text-sm', className)}\n {...props}\n />\n );\n}\n\nfunction PopoverTitle({ className, ...props }: React.ComponentProps<'h2'>) {\n return <div data-slot=\"popover-title\" className={cn('font-medium', className)} {...props} />;\n}\n\nfunction PopoverDescription({ className, ...props }: React.ComponentProps<'p'>) {\n return (\n <p\n data-slot=\"popover-description\"\n className={cn('text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nexport {\n Popover,\n PopoverTrigger,\n PopoverContent,\n PopoverAnchor,\n PopoverHeader,\n PopoverTitle,\n PopoverDescription,\n};\n",
|
|
27
|
+
"src/components/ui/scroll-area.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { ScrollArea as ScrollAreaPrimitive } from 'radix-ui';\n\nfunction ScrollArea({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {\n return (\n <ScrollAreaPrimitive.Root\n data-slot=\"scroll-area\"\n className={cn('relative', className)}\n {...props}\n >\n <ScrollAreaPrimitive.Viewport\n data-slot=\"scroll-area-viewport\"\n className=\"size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1\"\n >\n {children}\n </ScrollAreaPrimitive.Viewport>\n <ScrollBar />\n <ScrollAreaPrimitive.Corner />\n </ScrollAreaPrimitive.Root>\n );\n}\n\nfunction ScrollBar({\n className,\n orientation = 'vertical',\n ...props\n}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {\n return (\n <ScrollAreaPrimitive.ScrollAreaScrollbar\n data-slot=\"scroll-area-scrollbar\"\n orientation={orientation}\n className={cn(\n 'flex touch-none p-px transition-colors select-none',\n orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',\n orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',\n className,\n )}\n {...props}\n >\n <ScrollAreaPrimitive.ScrollAreaThumb\n data-slot=\"scroll-area-thumb\"\n className=\"relative flex-1 rounded-full bg-border\"\n />\n </ScrollAreaPrimitive.ScrollAreaScrollbar>\n );\n}\n\nexport { ScrollArea, ScrollBar };\n",
|
|
28
|
+
"src/components/ui/select.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';\nimport { Select as SelectPrimitive } from 'radix-ui';\n\nfunction Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root data-slot=\"select\" {...props} />;\n}\n\nfunction SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot=\"select-group\" {...props} />;\n}\n\nfunction SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot=\"select-value\" {...props} />;\n}\n\nfunction SelectTrigger({\n className,\n size = 'default',\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: 'sm' | 'default';\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot=\"select-trigger\"\n data-size={size}\n className={cn(\n \"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className,\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDownIcon className=\"size-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n );\n}\n\nfunction SelectContent({\n className,\n children,\n position = 'item-aligned',\n align = 'center',\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Content>) {\n return (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n data-slot=\"select-content\"\n className={cn(\n 'relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',\n position === 'popper' &&\n 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',\n className,\n )}\n position={position}\n align={align}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n 'p-1',\n position === 'popper' &&\n 'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n );\n}\n\nfunction SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {\n return (\n <SelectPrimitive.Label\n data-slot=\"select-label\"\n className={cn('px-2 py-1.5 text-xs text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction SelectItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot=\"select-item\"\n className={cn(\n \"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className,\n )}\n {...props}\n >\n <span\n data-slot=\"select-item-indicator\"\n className=\"absolute right-2 flex size-3.5 items-center justify-center\"\n >\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n );\n}\n\nfunction SelectSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot=\"select-separator\"\n className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}\n {...props}\n />\n );\n}\n\nfunction SelectScrollUpButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {\n return (\n <SelectPrimitive.ScrollUpButton\n data-slot=\"select-scroll-up-button\"\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronUpIcon className=\"size-4\" />\n </SelectPrimitive.ScrollUpButton>\n );\n}\n\nfunction SelectScrollDownButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {\n return (\n <SelectPrimitive.ScrollDownButton\n data-slot=\"select-scroll-down-button\"\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronDownIcon className=\"size-4\" />\n </SelectPrimitive.ScrollDownButton>\n );\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n};\n",
|
|
29
|
+
"src/components/ui/separator.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Separator as SeparatorPrimitive } from 'radix-ui';\n\nfunction Separator({\n className,\n orientation = 'horizontal',\n decorative = true,\n ...props\n}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {\n return (\n <SeparatorPrimitive.Root\n data-slot=\"separator\"\n decorative={decorative}\n orientation={orientation}\n className={cn(\n 'shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Separator };\n",
|
|
30
|
+
"src/components/ui/sheet.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { XIcon } from 'lucide-react';\nimport { Dialog as SheetPrimitive } from 'radix-ui';\n\nfunction Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {\n return <SheetPrimitive.Root data-slot=\"sheet\" {...props} />;\n}\n\nfunction SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {\n return <SheetPrimitive.Trigger data-slot=\"sheet-trigger\" {...props} />;\n}\n\nfunction SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {\n return <SheetPrimitive.Close data-slot=\"sheet-close\" {...props} />;\n}\n\nfunction SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {\n return <SheetPrimitive.Portal data-slot=\"sheet-portal\" {...props} />;\n}\n\nfunction SheetOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {\n return (\n <SheetPrimitive.Overlay\n data-slot=\"sheet-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction SheetContent({\n className,\n children,\n side = 'right',\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Content> & {\n side?: 'top' | 'right' | 'bottom' | 'left';\n showCloseButton?: boolean;\n}) {\n return (\n <SheetPortal>\n <SheetOverlay />\n <SheetPrimitive.Content\n data-slot=\"sheet-content\"\n className={cn(\n 'fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500',\n side === 'right' &&\n 'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',\n side === 'left' &&\n 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',\n side === 'top' &&\n 'inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',\n side === 'bottom' &&\n 'inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',\n className,\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <SheetPrimitive.Close className=\"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary\">\n <XIcon className=\"size-4\" />\n <span className=\"sr-only\">Close</span>\n </SheetPrimitive.Close>\n )}\n </SheetPrimitive.Content>\n </SheetPortal>\n );\n}\n\nfunction SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"sheet-header\"\n className={cn('flex flex-col gap-1.5 p-4', className)}\n {...props}\n />\n );\n}\n\nfunction SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"sheet-footer\"\n className={cn('mt-auto flex flex-col gap-2 p-4', className)}\n {...props}\n />\n );\n}\n\nfunction SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {\n return (\n <SheetPrimitive.Title\n data-slot=\"sheet-title\"\n className={cn('font-semibold text-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction SheetDescription({\n className,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Description>) {\n return (\n <SheetPrimitive.Description\n data-slot=\"sheet-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nexport {\n Sheet,\n SheetTrigger,\n SheetClose,\n SheetContent,\n SheetHeader,\n SheetFooter,\n SheetTitle,\n SheetDescription,\n};\n",
|
|
31
|
+
"src/components/ui/skeleton.tsx": "import { cn } from '@/lib/utils';\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"skeleton\"\n className={cn('animate-pulse rounded-md bg-accent', className)}\n {...props}\n />\n );\n}\n\nexport { Skeleton };\n",
|
|
32
|
+
"src/components/ui/sonner.tsx": "import {\n CircleCheckIcon,\n InfoIcon,\n Loader2Icon,\n OctagonXIcon,\n TriangleAlertIcon,\n} from 'lucide-react';\nimport type * as React from 'react';\nimport { Toaster as Sonner, type ToasterProps } from 'sonner';\n\n// shadcn/ui's Toaster without next-themes: the page follows the system\n// theme (prefers-color-scheme), and so does the toaster.\nfunction Toaster(props: ToasterProps) {\n return (\n <Sonner\n theme=\"system\"\n className=\"toaster group\"\n icons={{\n success: <CircleCheckIcon className=\"size-4\" />,\n info: <InfoIcon className=\"size-4\" />,\n warning: <TriangleAlertIcon className=\"size-4\" />,\n error: <OctagonXIcon className=\"size-4\" />,\n loading: <Loader2Icon className=\"size-4 animate-spin\" />,\n }}\n style={\n {\n '--normal-bg': 'var(--popover)',\n '--normal-text': 'var(--popover-foreground)',\n '--normal-border': 'var(--border)',\n '--border-radius': 'var(--radius)',\n } as React.CSSProperties\n }\n {...props}\n />\n );\n}\n\nexport { Toaster };\n",
|
|
33
|
+
"src/components/ui/spinner.tsx": "import { Loader2Icon } from 'lucide-react';\nimport type * as React from 'react';\nimport { cn } from '@/lib/utils';\n\nfunction Spinner({ className, ...props }: React.ComponentProps<'svg'>) {\n return (\n <Loader2Icon\n role=\"status\"\n aria-label=\"Loading\"\n className={cn('size-4 animate-spin', className)}\n {...props}\n />\n );\n}\n\nexport { Spinner };\n",
|
|
34
|
+
"src/components/ui/switch.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Switch as SwitchPrimitive } from 'radix-ui';\n\nfunction Switch({\n className,\n size = 'default',\n ...props\n}: React.ComponentProps<typeof SwitchPrimitive.Root> & {\n size?: 'sm' | 'default';\n}) {\n return (\n <SwitchPrimitive.Root\n data-slot=\"switch\"\n data-size={size}\n className={cn(\n 'peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80',\n className,\n )}\n {...props}\n >\n <SwitchPrimitive.Thumb\n data-slot=\"switch-thumb\"\n className={cn(\n 'pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground',\n )}\n />\n </SwitchPrimitive.Root>\n );\n}\n\nexport { Switch };\n",
|
|
35
|
+
"src/components/ui/table.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\n\nfunction Table({ className, ...props }: React.ComponentProps<'table'>) {\n return (\n <div data-slot=\"table-container\" className=\"relative w-full overflow-x-auto\">\n <table\n data-slot=\"table\"\n className={cn('w-full caption-bottom text-sm', className)}\n {...props}\n />\n </div>\n );\n}\n\nfunction TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {\n return <thead data-slot=\"table-header\" className={cn('[&_tr]:border-b', className)} {...props} />;\n}\n\nfunction TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {\n return (\n <tbody\n data-slot=\"table-body\"\n className={cn('[&_tr:last-child]:border-0', className)}\n {...props}\n />\n );\n}\n\nfunction TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {\n return (\n <tfoot\n data-slot=\"table-footer\"\n className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}\n {...props}\n />\n );\n}\n\nfunction TableRow({ className, ...props }: React.ComponentProps<'tr'>) {\n return (\n <tr\n data-slot=\"table-row\"\n className={cn(\n 'border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction TableHead({ className, ...props }: React.ComponentProps<'th'>) {\n return (\n <th\n data-slot=\"table-head\"\n className={cn(\n 'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction TableCell({ className, ...props }: React.ComponentProps<'td'>) {\n return (\n <td\n data-slot=\"table-cell\"\n className={cn(\n 'p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {\n return (\n <caption\n data-slot=\"table-caption\"\n className={cn('mt-4 text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nexport { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };\n",
|
|
36
|
+
"src/components/ui/tabs.tsx": "import * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\nimport { Tabs as TabsPrimitive } from 'radix-ui';\n\nfunction Tabs({\n className,\n orientation = 'horizontal',\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root\n data-slot=\"tabs\"\n data-orientation={orientation}\n orientation={orientation}\n className={cn('group/tabs flex gap-2 data-[orientation=horizontal]:flex-col', className)}\n {...props}\n />\n );\n}\n\nconst tabsListVariants = cva(\n 'group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none',\n {\n variants: {\n variant: {\n default: 'bg-muted',\n line: 'gap-1 bg-transparent',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n },\n);\n\nfunction TabsList({\n className,\n variant = 'default',\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {\n return (\n <TabsPrimitive.List\n data-slot=\"tabs-list\"\n data-variant={variant}\n className={cn(tabsListVariants({ variant }), className)}\n {...props}\n />\n );\n}\n\nfunction TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {\n return (\n <TabsPrimitive.Trigger\n data-slot=\"tabs-trigger\"\n className={cn(\n \"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent',\n 'data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground',\n 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return (\n <TabsPrimitive.Content\n data-slot=\"tabs-content\"\n className={cn('flex-1 outline-none', className)}\n {...props}\n />\n );\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };\n",
|
|
37
|
+
"src/components/ui/textarea.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\n\nfunction Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n 'flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Textarea };\n",
|
|
38
|
+
"src/components/ui/toggle-group.tsx": "import * as React from 'react';\nimport { type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\nimport { ToggleGroup as ToggleGroupPrimitive } from 'radix-ui';\n\nimport { toggleVariants } from '@/components/ui/toggle';\n\nconst ToggleGroupContext = React.createContext<\n VariantProps<typeof toggleVariants> & {\n spacing?: number;\n }\n>({\n size: 'default',\n variant: 'default',\n spacing: 0,\n});\n\nfunction ToggleGroup({\n className,\n variant,\n size,\n spacing = 0,\n children,\n ...props\n}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &\n VariantProps<typeof toggleVariants> & {\n spacing?: number;\n }) {\n return (\n <ToggleGroupPrimitive.Root\n data-slot=\"toggle-group\"\n data-variant={variant}\n data-size={size}\n data-spacing={spacing}\n style={{ '--gap': spacing } as React.CSSProperties}\n className={cn(\n 'group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs',\n className,\n )}\n {...props}\n >\n <ToggleGroupContext.Provider value={{ variant, size, spacing }}>\n {children}\n </ToggleGroupContext.Provider>\n </ToggleGroupPrimitive.Root>\n );\n}\n\nfunction ToggleGroupItem({\n className,\n children,\n variant,\n size,\n ...props\n}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>) {\n const context = React.useContext(ToggleGroupContext);\n\n return (\n <ToggleGroupPrimitive.Item\n data-slot=\"toggle-group-item\"\n data-variant={context.variant || variant}\n data-size={context.size || size}\n data-spacing={context.spacing}\n className={cn(\n toggleVariants({\n variant: context.variant || variant,\n size: context.size || size,\n }),\n 'w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10',\n 'data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l',\n className,\n )}\n {...props}\n >\n {children}\n </ToggleGroupPrimitive.Item>\n );\n}\n\nexport { ToggleGroup, ToggleGroupItem };\n",
|
|
39
|
+
"src/components/ui/toggle.tsx": "import * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport { cn } from '@/lib/utils';\nimport { Toggle as TogglePrimitive } from 'radix-ui';\n\nconst toggleVariants = cva(\n \"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: 'bg-transparent',\n outline:\n 'border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground',\n },\n size: {\n default: 'h-9 min-w-9 px-2',\n sm: 'h-8 min-w-8 px-1.5',\n lg: 'h-10 min-w-10 px-2.5',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n },\n);\n\nfunction Toggle({\n className,\n variant,\n size,\n ...props\n}: React.ComponentProps<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>) {\n return (\n <TogglePrimitive.Root\n data-slot=\"toggle\"\n className={cn(toggleVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Toggle, toggleVariants };\n",
|
|
40
|
+
"src/components/ui/tooltip.tsx": "import * as React from 'react';\nimport { cn } from '@/lib/utils';\nimport { Tooltip as TooltipPrimitive } from 'radix-ui';\n\nfunction TooltipProvider({\n delayDuration = 0,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {\n return (\n <TooltipPrimitive.Provider\n data-slot=\"tooltip-provider\"\n delayDuration={delayDuration}\n {...props}\n />\n );\n}\n\nfunction Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {\n return <TooltipPrimitive.Root data-slot=\"tooltip\" {...props} />;\n}\n\nfunction TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {\n return <TooltipPrimitive.Trigger data-slot=\"tooltip-trigger\" {...props} />;\n}\n\nfunction TooltipContent({\n className,\n sideOffset = 0,\n children,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Content>) {\n return (\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n data-slot=\"tooltip-content\"\n sideOffset={sideOffset}\n className={cn(\n 'z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',\n className,\n )}\n {...props}\n >\n {children}\n <TooltipPrimitive.Arrow className=\"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground\" />\n </TooltipPrimitive.Content>\n </TooltipPrimitive.Portal>\n );\n}\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n",
|
|
41
|
+
"src/components/user-avatar.tsx": "import { Avatar, AvatarFallback } from '@/components/ui/avatar';\nimport { cn } from '@/lib/utils';\n\n// Soft background + readable text, in both themes.\nconst COLORS = [\n 'bg-sky-500/15 text-sky-700 dark:text-sky-300',\n 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300',\n 'bg-amber-500/20 text-amber-800 dark:text-amber-300',\n 'bg-rose-500/15 text-rose-700 dark:text-rose-300',\n 'bg-violet-500/15 text-violet-700 dark:text-violet-300',\n 'bg-teal-500/15 text-teal-700 dark:text-teal-300',\n 'bg-orange-500/15 text-orange-700 dark:text-orange-300',\n 'bg-indigo-500/15 text-indigo-700 dark:text-indigo-300',\n];\n\nfunction hash(text: string): number {\n let h = 0;\n for (let i = 0; i < text.length; i++) h = (h * 31 + text.charCodeAt(i)) | 0;\n return Math.abs(h);\n}\n\n/** \"Ada Lovelace\" → \"AL\"; \"张三\" → \"张\". */\nexport function initials(name: string): string {\n const trimmed = name.trim();\n if (!trimmed) return '?';\n if (/[㐀-鿿]/.test(trimmed[0] ?? '')) return trimmed[0] ?? '?';\n const words = trimmed.split(/\\s+/).filter(Boolean);\n const letters = words.length > 1 ? `${words[0]?.[0]}${words[1]?.[0]}` : trimmed.slice(0, 2);\n return letters.toUpperCase();\n}\n\n/** A person by initials, colored by their id so they look the same everywhere. */\nexport function UserAvatar({\n id,\n name,\n size = 'default',\n className,\n title,\n}: {\n id: string;\n name: string;\n size?: 'sm' | 'default' | 'lg';\n className?: string;\n title?: string;\n}) {\n return (\n <Avatar size={size} className={className} title={title}>\n <AvatarFallback\n className={cn('font-medium', COLORS[hash(id || name) % COLORS.length])}\n aria-label={name}\n >\n {initials(name)}\n </AvatarFallback>\n </Avatar>\n );\n}\n",
|
|
42
|
+
"src/hooks/use-action.ts": "import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { hostReady } from '@/hooks/use-host';\nimport { type BridgeError, parall } from '@/parall';\n\n/**\n * Typed hooks over parall.action:\n *\n * const items = useAction<Item[]>('items_list'); // read, kept fresh\n * const save = useMutation<Item, ItemInput>('items_save'); // write\n * await save.run({ title: 'New' });\n *\n * Reads with the same name and params share one call and one result. They\n * call again when params change, on reload(), and when the app's Database\n * gets new writes (parall.onDataChanged) — from this page, another person\n * or an agent. Every call counts toward the viewer's 100 requests a minute\n * on this Database, so load a list once and filter it in the page.\n */\n\n/** An action's params: a plain object (interfaces welcome). */\nexport type ActionParams = object;\n\nexport interface ActionState<T> {\n data: T | undefined;\n error: BridgeError | null;\n /** True until the first answer arrives. */\n loading: boolean;\n /** True while calling again with data already shown. */\n refreshing: boolean;\n reload: () => void;\n /** Changes the shown data locally — for optimistic updates. The next call\n * replaces it with what the action returns. */\n setData: (update: T | ((current: T | undefined) => T)) => void;\n}\n\ninterface Snapshot {\n data: unknown;\n error: BridgeError | null;\n loaded: boolean;\n fetching: boolean;\n}\n\ninterface Query {\n name: string;\n params: ActionParams;\n snapshot: Snapshot;\n listeners: Set<() => void>;\n /** Mounted useAction calls with enabled: true. Only these call it again\n * on data changes: a disabled read may still lack its params. */\n active: number;\n inFlight: boolean;\n again: boolean;\n dropTimer: ReturnType<typeof setTimeout> | null;\n}\n\nconst queries = new Map<string, Query>();\n// A query nobody shows is kept this long, so going back to a page is instant.\nconst KEEP_UNUSED_MS = 60_000;\n// Data changes arriving close together cause one call per query.\nconst CHANGE_DEBOUNCE_MS = 100;\n\nfunction keyOf(name: string, params: ActionParams | undefined): string {\n return `${name}\\u0000${JSON.stringify(params ?? {})}`;\n}\n\nfunction update(query: Query, patch: Partial<Snapshot>): void {\n query.snapshot = { ...query.snapshot, ...patch };\n for (const listener of query.listeners) listener();\n}\n\nfunction fetchQuery(query: Query): void {\n if (query.inFlight) {\n // Something changed while a call was out: call once more after it.\n query.again = true;\n return;\n }\n query.inFlight = true;\n update(query, { fetching: true });\n hostReady()\n .then(() => parall.action(query.name, query.params as Record<string, unknown>))\n .then(\n (data) => update(query, { data, error: null, loaded: true, fetching: false }),\n (error: BridgeError) => update(query, { error, loaded: true, fetching: false }),\n )\n .finally(() => {\n query.inFlight = false;\n if (query.again) {\n query.again = false;\n fetchQuery(query);\n }\n });\n}\n\nlet changeTimer: ReturnType<typeof setTimeout> | null = null;\nlet watching = false;\n\nfunction watchDataChanges(): void {\n if (watching) return;\n watching = true;\n parall.onDataChanged(() => {\n if (changeTimer) clearTimeout(changeTimer);\n changeTimer = setTimeout(refreshActions, CHANGE_DEBOUNCE_MS);\n });\n}\n\n/** Calls every enabled read that is on screen again. */\nexport function refreshActions(): void {\n for (const query of queries.values()) {\n if (query.active > 0) fetchQuery(query);\n }\n}\n\nfunction scheduleDrop(key: string, query: Query): void {\n query.dropTimer = setTimeout(() => {\n if (query.listeners.size === 0) queries.delete(key);\n }, KEEP_UNUSED_MS);\n}\n\nfunction acquire(name: string, params: ActionParams | undefined): Query {\n const key = keyOf(name, params);\n let query = queries.get(key);\n if (!query) {\n query = {\n name,\n params: params ?? {},\n snapshot: { data: undefined, error: null, loaded: false, fetching: false },\n listeners: new Set(),\n active: 0,\n inFlight: false,\n again: false,\n dropTimer: null,\n };\n queries.set(key, query);\n // Dropped unless a component subscribes (a render can be thrown away).\n scheduleDrop(key, query);\n }\n return query;\n}\n\n/**\n * Calls a read action and keeps the answer current. Pass `enabled: false`\n * to wait (for example until a required param is known): it then makes no\n * call at all — not on data changes, not on reload().\n */\nexport function useAction<T, P extends ActionParams = ActionParams>(\n name: string,\n params?: P,\n options: { enabled?: boolean } = {},\n): ActionState<T> {\n const enabled = options.enabled ?? true;\n const key = keyOf(name, params);\n // Params are compared by value: a new object with the same content is\n // the same query.\n const query = acquire(name, params);\n\n const subscribe = useCallback(\n (listener: () => void) => {\n if (query.dropTimer) {\n clearTimeout(query.dropTimer);\n query.dropTimer = null;\n }\n query.listeners.add(listener);\n return () => {\n query.listeners.delete(listener);\n if (query.listeners.size === 0) scheduleDrop(key, query);\n };\n },\n [query, key],\n );\n const snapshot = useSyncExternalStore(subscribe, () => query.snapshot);\n\n useEffect(() => {\n if (!enabled) return;\n watchDataChanges();\n query.active += 1;\n // A cached answer is shown at once and refreshed in the background.\n fetchQuery(query);\n return () => {\n query.active -= 1;\n };\n }, [query, enabled]);\n\n const reload = useCallback(() => {\n if (enabled) fetchQuery(query);\n }, [query, enabled]);\n const setData = useCallback(\n (next: T | ((current: T | undefined) => T)) => {\n const data =\n typeof next === 'function'\n ? (next as (current: T | undefined) => T)(query.snapshot.data as T | undefined)\n : next;\n update(query, { data });\n },\n [query],\n );\n\n return {\n data: snapshot.data as T | undefined,\n error: snapshot.error,\n loading: enabled && !snapshot.loaded,\n refreshing: snapshot.loaded && snapshot.fetching,\n reload,\n setData,\n };\n}\n\nexport interface MutationState<T, P extends ActionParams> {\n /** Calls the action; resolves with its result or rejects with the error\n * (also kept in `error`). */\n run: (params?: P) => Promise<T>;\n pending: boolean;\n error: BridgeError | null;\n reset: () => void;\n}\n\n/**\n * Calls a write action. Reads refresh by themselves when the write lands\n * (data.changed); update the shown data from the result with setData when\n * the page should change before that.\n *\n * A write that failed with HOST_TIMEOUT, HOST_UNAVAILABLE or ACTION_TIMEOUT\n * may still have happened: read again before offering a retry.\n */\nexport function useMutation<T, P extends ActionParams = ActionParams>(\n name: string,\n): MutationState<T, P> {\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<BridgeError | null>(null);\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const run = useCallback(\n async (params?: P) => {\n setPending(true);\n setError(null);\n try {\n await hostReady();\n return await parall.action<T>(name, params as Record<string, unknown> | undefined);\n } catch (err) {\n if (mounted.current) setError(err as BridgeError);\n throw err;\n } finally {\n if (mounted.current) setPending(false);\n }\n },\n [name],\n );\n const reset = useCallback(() => setError(null), []);\n return { run, pending, error, reset };\n}\n",
|
|
43
|
+
"src/hooks/use-host.tsx": "import { createContext, type ReactNode, useContext, useEffect, useState } from 'react';\nimport { parall, type ReadyResult, type ViewerSummary } from '@/parall';\n\nlet readyPromise: Promise<ReadyResult> | null = null;\n\n/**\n * The host handshake, once per page: resolves with the viewer, the app and\n * the route the page was opened at. Rejects when the page is not running in\n * a Parall host (opened directly in a browser, say).\n */\nexport function hostReady(): Promise<ReadyResult> {\n readyPromise ??= parall.ready().then((result) => {\n // Outside a host the bridge talks to itself and answers nothing useful.\n if (!result || typeof result !== 'object' || typeof result.viewer?.id !== 'string') {\n throw Object.assign(new Error('not running inside a Parall host'), { code: 'NO_HOST' });\n }\n return result;\n });\n return readyPromise;\n}\n\ntype HostState =\n | { status: 'connecting' }\n | { status: 'ready'; host: ReadyResult }\n | { status: 'missing'; error: Error };\n\nconst HostContext = createContext<HostState>({ status: 'connecting' });\n\n/** Runs the handshake and keeps viewer and route current as the host\n * reports changes (viewer.changed, route.changed). */\nexport function HostProvider({ children }: { children: ReactNode }) {\n const [state, setState] = useState<HostState>({ status: 'connecting' });\n\n useEffect(() => {\n let alive = true;\n hostReady().then(\n (host) => alive && setState({ status: 'ready', host }),\n (error: Error) => alive && setState({ status: 'missing', error }),\n );\n const off = parall.onEvent((event) => {\n setState((current) => {\n if (current.status !== 'ready') return current;\n if (event.event === 'viewer.changed') {\n return { status: 'ready', host: { ...current.host, viewer: event.data.viewer } };\n }\n if (event.event === 'route.changed') {\n return { status: 'ready', host: { ...current.host, route: event.data.route } };\n }\n return current;\n });\n });\n return () => {\n alive = false;\n off();\n };\n }, []);\n\n return <HostContext.Provider value={state}>{children}</HostContext.Provider>;\n}\n\nexport function useHostState(): HostState {\n return useContext(HostContext);\n}\n\n/** The handshake result; only call it under a ready host (App gates on it). */\nexport function useHost(): ReadyResult {\n const state = useContext(HostContext);\n if (state.status !== 'ready') throw new Error('useHost() called before the host was ready');\n return state.host;\n}\n\n/** Who is looking at the page: id, display_name, is_agent and org role. */\nexport function useViewer(): ViewerSummary {\n return useHost().viewer;\n}\n\n/** Whether the viewer is an org owner or admin. Pages may use it to hide\n * buttons; the actions must still check (ctx.viewer.role). */\nexport function useIsOrgAdmin(): boolean {\n const role = useViewer().role;\n return role === 'owner' || role === 'admin';\n}\n",
|
|
44
|
+
"src/hooks/use-media-query.ts": "import { useCallback, useSyncExternalStore } from 'react';\n\n/** Whether a CSS media query matches, updated as the window resizes. */\nexport function useMediaQuery(query: string): boolean {\n const subscribe = useCallback(\n (onChange: () => void) => {\n const list = window.matchMedia(query);\n list.addEventListener('change', onChange);\n return () => list.removeEventListener('change', onChange);\n },\n [query],\n );\n return useSyncExternalStore(\n subscribe,\n () => window.matchMedia(query).matches,\n () => false,\n );\n}\n\n/** Below Tailwind's md breakpoint (768px): phones and the narrow panel\n * Parall opens an app in beside a chat. Prefer CSS (md:…) for layout and use\n * this only where the behavior differs, like a dialog that becomes a sheet. */\nexport function useIsMobile(): boolean {\n return !useMediaQuery('(min-width: 768px)');\n}\n",
|
|
45
|
+
"src/index.css": "/* Tailwind v4 + shadcn/ui theme. Everything is bundled: the font comes\n from @fontsource-variable/geist (woff2 files land in dist/assets), Chinese\n text falls back to the system's CJK font. Light/dark follows the viewer's\n system setting (prefers-color-scheme); Parall does not pass a theme. */\n@import 'tailwindcss';\n@import 'tw-animate-css';\n@import '@fontsource-variable/geist';\n\n:root {\n color-scheme: light dark;\n --radius: 0.625rem;\n --background: oklch(1 0 0);\n --foreground: oklch(0.145 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.145 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.145 0 0);\n --primary: oklch(0.205 0 0);\n --primary-foreground: oklch(0.985 0 0);\n --secondary: oklch(0.97 0 0);\n --secondary-foreground: oklch(0.205 0 0);\n --muted: oklch(0.97 0 0);\n --muted-foreground: oklch(0.556 0 0);\n --accent: oklch(0.97 0 0);\n --accent-foreground: oklch(0.205 0 0);\n --destructive: oklch(0.577 0.245 27.325);\n --success: oklch(0.6 0.13 155);\n --warning: oklch(0.7 0.15 70);\n --border: oklch(0.922 0 0);\n --input: oklch(0.922 0 0);\n --ring: oklch(0.708 0 0);\n --chart-1: oklch(0.646 0.222 41.116);\n --chart-2: oklch(0.6 0.118 184.704);\n --chart-3: oklch(0.398 0.07 227.392);\n --chart-4: oklch(0.828 0.189 84.429);\n --chart-5: oklch(0.769 0.188 70.08);\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n --background: oklch(0.145 0 0);\n --foreground: oklch(0.985 0 0);\n --card: oklch(0.205 0 0);\n --card-foreground: oklch(0.985 0 0);\n --popover: oklch(0.205 0 0);\n --popover-foreground: oklch(0.985 0 0);\n --primary: oklch(0.922 0 0);\n --primary-foreground: oklch(0.205 0 0);\n --secondary: oklch(0.269 0 0);\n --secondary-foreground: oklch(0.985 0 0);\n --muted: oklch(0.269 0 0);\n --muted-foreground: oklch(0.708 0 0);\n --accent: oklch(0.269 0 0);\n --accent-foreground: oklch(0.985 0 0);\n --destructive: oklch(0.704 0.191 22.216);\n --success: oklch(0.72 0.15 155);\n --warning: oklch(0.8 0.15 75);\n --border: oklch(1 0 0 / 10%);\n --input: oklch(1 0 0 / 15%);\n --ring: oklch(0.556 0 0);\n --chart-1: oklch(0.488 0.243 264.376);\n --chart-2: oklch(0.696 0.17 162.48);\n --chart-3: oklch(0.769 0.188 70.08);\n --chart-4: oklch(0.627 0.265 303.9);\n --chart-5: oklch(0.645 0.246 16.439);\n }\n}\n\n@theme inline {\n --font-sans:\n 'Geist Variable', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC',\n 'Noto Sans SC', system-ui, -apple-system, 'Segoe UI', sans-serif;\n --font-mono: ui-monospace, 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace;\n --radius-sm: calc(var(--radius) - 4px);\n --radius-md: calc(var(--radius) - 2px);\n --radius-lg: var(--radius);\n --radius-xl: calc(var(--radius) + 4px);\n --color-background: var(--background);\n --color-foreground: var(--foreground);\n --color-card: var(--card);\n --color-card-foreground: var(--card-foreground);\n --color-popover: var(--popover);\n --color-popover-foreground: var(--popover-foreground);\n --color-primary: var(--primary);\n --color-primary-foreground: var(--primary-foreground);\n --color-secondary: var(--secondary);\n --color-secondary-foreground: var(--secondary-foreground);\n --color-muted: var(--muted);\n --color-muted-foreground: var(--muted-foreground);\n --color-accent: var(--accent);\n --color-accent-foreground: var(--accent-foreground);\n --color-destructive: var(--destructive);\n --color-success: var(--success);\n --color-warning: var(--warning);\n --color-border: var(--border);\n --color-input: var(--input);\n --color-ring: var(--ring);\n --color-chart-1: var(--chart-1);\n --color-chart-2: var(--chart-2);\n --color-chart-3: var(--chart-3);\n --color-chart-4: var(--chart-4);\n --color-chart-5: var(--chart-5);\n}\n\n@layer base {\n * {\n @apply border-border outline-ring/50;\n }\n html {\n -webkit-text-size-adjust: 100%;\n -webkit-tap-highlight-color: transparent;\n }\n body {\n @apply min-h-svh bg-background font-sans text-foreground antialiased;\n }\n button:not(:disabled),\n [role='button']:not(:disabled) {\n cursor: pointer;\n }\n /* Phones zoom into inputs under 16px; keep them at 16px on small screens. */\n @media (max-width: 767px) {\n input,\n select,\n textarea {\n font-size: 16px !important;\n }\n }\n}\n\n@utility no-scrollbar {\n scrollbar-width: none;\n &::-webkit-scrollbar {\n display: none;\n }\n}\n",
|
|
46
|
+
"src/lib/errors.ts": "import { t } from '@/lib/messages';\nimport type { BridgeError } from '@/parall';\n\nexport interface DescribedError {\n /** What to tell the viewer. */\n message: string;\n /** A second line with what to do, when there is one. */\n hint?: string;\n /** The server's error code (ACTION_FAILED, RATE_LIMITED…), if any. */\n code?: string;\n /** The invocation (aci_…) to quote when reporting the problem. */\n invocationId?: string;\n}\n\n/**\n * Turns what parall.action rejected with into text for the viewer. An\n * ActionError thrown by an action arrives as ACTION_FAILED with the\n * action's own message; other failures get a message by their code.\n */\nexport function describeError(err: unknown): DescribedError {\n const e = err as Partial<BridgeError> | null;\n const code = typeof e?.code === 'string' ? e.code : undefined;\n const details = e?.details ?? {};\n const invocation = details.invocation_id;\n const invocationId = typeof invocation === 'string' ? invocation : undefined;\n const raw = typeof e?.message === 'string' && e.message !== '' ? e.message : t('errorTitle');\n switch (code) {\n case 'ACTION_FAILED':\n return { message: raw, code, invocationId };\n case 'HOST_TIMEOUT':\n case 'HOST_UNAVAILABLE':\n case 'ACTION_RUNTIME_UNAVAILABLE':\n return { message: t('errorOffline'), code, invocationId };\n case 'RATE_LIMITED':\n return { message: t('errorRateLimited'), code, invocationId };\n case 'ACTION_TIMEOUT':\n return { message: t('errorTimeout'), code, invocationId };\n case 'APP_VERSION_CHANGED':\n return { message: t('errorVersionChanged'), code, invocationId };\n case 'NOT_GRANTED':\n return {\n message: t('errorNotGranted'),\n hint: t('errorNotGrantedHint'),\n code,\n invocationId,\n };\n default:\n return { message: raw, code, invocationId };\n }\n}\n",
|
|
47
|
+
"src/lib/format.ts": "import { formatLocale } from '@/lib/i18n';\n\nconst dateTime = new Intl.DateTimeFormat(formatLocale, {\n dateStyle: 'medium',\n timeStyle: 'short',\n});\nconst dateOnly = new Intl.DateTimeFormat(formatLocale, { dateStyle: 'medium' });\nconst relative = new Intl.RelativeTimeFormat(formatLocale, { numeric: 'auto' });\n\n/** Accepts what actions return for timestamptz and date columns (ISO\n * strings) and Date objects; anything unreadable formats as ''. */\nfunction toDate(value: string | number | Date | null | undefined): Date | null {\n if (value === null || value === undefined || value === '') return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nexport function formatDateTime(value: string | number | Date | null | undefined): string {\n const date = toDate(value);\n return date ? dateTime.format(date) : '';\n}\n\nexport function formatDate(value: string | number | Date | null | undefined): string {\n const date = toDate(value);\n return date ? dateOnly.format(date) : '';\n}\n\nconst UNITS: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 365 * 24 * 3600],\n ['month', 30 * 24 * 3600],\n ['week', 7 * 24 * 3600],\n ['day', 24 * 3600],\n ['hour', 3600],\n ['minute', 60],\n];\n\n/** \"3 hours ago\" / \"3 小时前\"; under a minute reads as \"now\". */\nexport function formatRelative(value: string | number | Date | null | undefined): string {\n const date = toDate(value);\n if (!date) return '';\n const seconds = Math.round((date.getTime() - Date.now()) / 1000);\n for (const [unit, size] of UNITS) {\n if (Math.abs(seconds) >= size) return relative.format(Math.round(seconds / size), unit);\n }\n return relative.format(0, 'second');\n}\n",
|
|
48
|
+
"src/lib/i18n.ts": "/**\n * The language of the text this app shows. Parall does not pass one, so the\n * viewer's browser language decides: Chinese for zh-*, English otherwise.\n * Pin a language by setting FORCED_LOCALE.\n */\nexport type Locale = 'zh' | 'en';\n\nconst FORCED_LOCALE: Locale | null = null;\n\n/** The viewer's browser language (en-GB, fr-FR, zh-TW…), if known. Use it for\n * conventions that are not words, such as the first day of the week. */\nexport const browserLocale: string | undefined =\n typeof navigator === 'undefined'\n ? undefined\n : (navigator.languages?.[0] ?? navigator.language ?? undefined);\n\nexport const locale: Locale = FORCED_LOCALE ?? (/^zh\\b/i.test(browserLocale ?? '') ? 'zh' : 'en');\n\n/** The BCP 47 tag dates and times are written with, always in the texts'\n * language so an English sentence never holds French month names: zh-CN for\n * Chinese (the texts are Simplified Chinese); for English the browser's own\n * English tag (en-GB keeps day/month order), else en-US. */\nexport const formatLocale: string =\n locale === 'zh'\n ? 'zh-CN'\n : browserLocale && /^en\\b/i.test(browserLocale)\n ? browserLocale\n : 'en-US';\n\ntype Vars = Record<string, string | number>;\n\n/**\n * Declares a module's texts in both languages and returns its t(). The zh\n * table must have every key of the en one:\n *\n * const t = defineMessages({\n * en: { title: 'Tasks', count: '{n} open' },\n * zh: { title: '任务', count: '{n} 个未完成' },\n * });\n * t('count', { n: 3 });\n */\nexport function defineMessages<T extends Record<string, string>>(messages: {\n en: T;\n zh: { [K in keyof T]: string };\n}): (key: keyof T, vars?: Vars) => string {\n const table: Record<keyof T, string> = messages[locale];\n return (key, vars) => {\n const text = table[key] ?? messages.en[key] ?? String(key);\n if (!vars) return text;\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in vars ? String(vars[name]) : match,\n );\n };\n}\n",
|
|
49
|
+
"src/lib/keys.ts": "import type { KeyboardEvent } from 'react';\n\n/**\n * Runs fn when Enter is pressed in a field — the way to \"submit\" here.\n * Parall's Web and Desktop host run the page in a frame without\n * allow-forms, so a <form> never submits and its onSubmit never fires:\n * give the save button type=\"button\" and onClick, and put onEnter(save) on\n * single-line inputs. Enter that confirms an input method's composition\n * (Chinese, Japanese…) is left alone — Safari and WebKit views send that\n * Enter after the composition has ended, flagged only by keyCode 229.\n */\nexport function onEnter(fn: () => void) {\n return (event: KeyboardEvent) => {\n if (event.key !== 'Enter' || event.shiftKey) return;\n if (event.nativeEvent.isComposing || event.keyCode === 229) return;\n event.preventDefault();\n fn();\n };\n}\n",
|
|
50
|
+
"src/lib/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\n/** The template's own texts: states, dialogs and the shell. */\nexport const t = defineMessages({\n en: {\n loading: 'Loading…',\n retry: 'Try again',\n cancel: 'Cancel',\n save: 'Save',\n saving: 'Saving…',\n delete: 'Delete',\n deleting: 'Deleting…',\n edit: 'Edit',\n close: 'Close',\n back: 'Back',\n search: 'Search',\n confirm: 'Confirm',\n you: 'You',\n errorTitle: 'Something went wrong',\n errorOffline: 'Parall did not answer. Check the connection and try again.',\n errorRateLimited: 'Too many requests right now. Wait a moment and try again.',\n errorTimeout:\n 'This took too long. Try again; if you were saving, check first whether it was saved.',\n errorVersionChanged: 'This app was just updated. Reload it to continue.',\n errorNotGranted: 'This page runs without its actions here.',\n errorNotGrantedHint: 'Start it with parall app dev --dist dist --app <app_…> to call them.',\n errorReference: 'Reference: {id}',\n hostMissingTitle: 'Open this app in Parall',\n hostMissingBody:\n 'This page talks to Parall through its host. Open it from Parall, or try it locally with parall app dev --dist dist.',\n connecting: 'Connecting to Parall…',\n },\n zh: {\n loading: '加载中…',\n retry: '重试',\n cancel: '取消',\n save: '保存',\n saving: '保存中…',\n delete: '删除',\n deleting: '删除中…',\n edit: '编辑',\n close: '关闭',\n back: '返回',\n search: '搜索',\n confirm: '确定',\n you: '我',\n errorTitle: '出错了',\n errorOffline: '没有收到 Parall 的回应,请检查网络后重试。',\n errorRateLimited: '请求太频繁,请稍等片刻再试。',\n errorTimeout: '处理超时。请重试;如果刚才在保存,先确认是否已经保存。',\n errorVersionChanged: '这个应用刚刚更新了,重新加载后继续。',\n errorNotGranted: '这里运行的页面没有连上它的 action。',\n errorNotGrantedHint: '用 parall app dev --dist dist --app <app_…> 启动后即可调用。',\n errorReference: '编号:{id}',\n hostMissingTitle: '请在 Parall 里打开这个应用',\n hostMissingBody:\n '这个页面通过 Parall 宿主读写数据。请从 Parall 打开它,或用 parall app dev --dist dist 在本地试用。',\n connecting: '正在连接 Parall…',\n },\n});\n",
|
|
51
|
+
"src/lib/utils.ts": "import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\n/** Merges Tailwind classes, later ones winning (shadcn/ui's cn). */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n",
|
|
52
|
+
"src/main.tsx": "import { StrictMode } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport { App } from '@/App';\nimport { HostProvider } from '@/hooks/use-host';\nimport { locale } from '@/lib/i18n';\nimport './index.css';\n\ndocument.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en';\n\ncreateRoot(document.getElementById('root') as HTMLElement).render(\n <StrictMode>\n <HostProvider>\n <App />\n </HostProvider>\n </StrictMode>,\n);\n",
|
|
53
|
+
"src/pages/home/HomePage.tsx": "import { Blocks, Database, PencilRuler } from 'lucide-react';\nimport type { PageProps } from '@/components/app-shell';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { Card, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';\nimport { useHost } from '@/hooks/use-host';\nimport { t } from './messages';\n\nconst CARDS = [\n { icon: PencilRuler, title: t('pageTitle'), body: t('pageBody') },\n { icon: Database, title: t('dataTitle'), body: t('dataBody') },\n { icon: Blocks, title: t('blocksTitle'), body: t('blocksBody') },\n];\n\nexport function HomePage(_props: PageProps) {\n const { viewer, app } = useHost();\n return (\n <PageContainer>\n <PageHeader\n title={t('greeting', { name: viewer.display_name })}\n description={t('intro', { app: app.name, version: app.version_seq })}\n />\n <div className=\"grid gap-3 sm:grid-cols-2 lg:grid-cols-3\">\n {CARDS.map(({ icon: Icon, title, body }) => (\n <Card key={title} className=\"gap-3 py-5\">\n <CardHeader className=\"px-5\">\n <div className=\"mb-1 flex size-9 items-center justify-center rounded-lg bg-muted\">\n <Icon className=\"size-4.5\" />\n </div>\n <CardTitle>{title}</CardTitle>\n <CardDescription>{body}</CardDescription>\n </CardHeader>\n </Card>\n ))}\n </div>\n </PageContainer>\n );\n}\n",
|
|
54
|
+
"src/pages/home/index.ts": "import { House } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { HomePage } from './HomePage';\nimport { t } from './messages';\n\nexport const homePage: AppPage = {\n id: 'home',\n title: t('title'),\n icon: House,\n component: HomePage,\n};\n",
|
|
55
|
+
"src/pages/home/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Home',\n greeting: 'Hello, {name}',\n intro: 'This is {app}, version {version}.',\n pageTitle: 'Make it yours',\n pageBody: 'Replace this page with what the app is for: src/pages/home/HomePage.tsx.',\n dataTitle: 'Keep data',\n dataBody:\n 'Pages read and write through actions. Scaffold with parall app init <dir> --actions to start from a list wired to the app’s Database.',\n blocksTitle: 'Start from a block',\n blocksBody:\n 'parall app add --list shows ready-made pages, such as a calendar and a board, for an app scaffolded with --actions.',\n },\n zh: {\n title: '首页',\n greeting: '你好,{name}',\n intro: '这是 {app},版本 {version}。',\n pageTitle: '换成你的内容',\n pageBody: '把这一页换成应用真正要做的事:src/pages/home/HomePage.tsx。',\n dataTitle: '保存数据',\n dataBody:\n '页面通过 action 读写数据。用 parall app init <dir> --actions 生成,起步就是一个接好 Database 的列表。',\n blocksTitle: '从现成模块开始',\n blocksBody:\n 'parall app add --list 列出现成的页面,例如日历和看板(需要 --actions 生成的项目)。',\n },\n});\n",
|
|
56
|
+
"src/pages.tsx": "import type { AppPage } from '@/components/app-shell';\nimport { homePage } from '@/pages/home';\n// parall:page-imports — `parall app add` puts block imports above this line.\n\n/** The app's pages, in tab order; the first one opens by default. */\nexport const pages: AppPage[] = [\n homePage,\n // parall:pages — `parall app add` puts block pages above this line.\n];\n",
|
|
57
|
+
"tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"bundler\",\n \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"noEmit\": true,\n \"skipLibCheck\": true,\n \"isolatedModules\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"paths\": {\n \"@/*\": [\"./src/*\"],\n \"@shared/*\": [\"./shared/*\"]\n },\n \"types\": []\n },\n \"include\": [\"src\", \"shared\"]\n}\n",
|
|
58
|
+
"vite.config.ts": "import { fileURLToPath, URL } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\n\n// Parall serves the build from the app's own origin under a strict CSP:\n// scripts, styles and fonts only from the bundle ('self'), images also from\n// data: and blob:, and no network at all. So:\n// - base './': assets load by relative path (the app lives under /v/<seq>/);\n// - fonts are never inlined as data: URLs (font-src allows 'self' only);\n// - nothing may point at a CDN — install packages instead.\nexport default defineConfig({\n base: './',\n plugins: [react(), tailwindcss()],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n '@shared': fileURLToPath(new URL('./shared', import.meta.url)),\n },\n },\n build: {\n outDir: 'dist',\n assetsInlineLimit: (file) => (/\\.(woff2?|ttf|otf)$/i.test(file) ? false : undefined),\n chunkSizeWarningLimit: 2048,\n },\n});\n"
|
|
59
|
+
};
|
|
60
|
+
export const TEMPLATE_WITH_ACTIONS = {
|
|
61
|
+
"AGENTS.md": "## 数据:action 与 Database\n\n- 页面的数据只经 action:`parall.action(name, params)` 以看页面的人的身份调本 app 的服务端 action,`parall.onDataChanged(fn)` 在 Database 有新写入时通知页面。桥上没有 SQL、files、clip 方法。\n- 页面里用 `src/hooks/use-action.ts`:`useAction<T>(name, params)` 读,同名同参数共用一次调用,参数变化、`reload()` 或 Database 有新写入(不论是谁写的)时重读;`useMutation<T, P>(name)` 写,写完读会自己刷新,要立刻变就用读的 `setData` 先改界面。\n- `actions/*.ts` 实现,`actions/index.ts` 的 `defineActions` 汇总,`public/manifest.json` 的 `actions.functions` 声明:`kind` 是 read(只能查询)或 write(可以写);`params` 是 JSON Schema 子集——object、array、string、number、integer、boolean,不支持 null 与联合类型,未声明的字段会被拒,`format` 只有 date 与 date-time。两边要一一对应:`parall app check dist` 核对,`publish` 也会先跑。action 名只能用字母、数字、下划线,一个版本最多 64 个。\n- 例子:`actions/items.ts`(`items_list` 读,`items_save`、`items_delete` 写)+ `src/pages/items/`(列表、详情、表单)+ `shared/items.ts`(两边共用的类型)+ `db/schema.sql`。照着它加自己的数据;用不上就删掉这几处,并从 manifest 去掉声明。\n\n## Database(PostgreSQL)\n\n- Database 是 PostgreSQL,不是 SQLite:`uuid`、`timestamptz`、`jsonb`、`ILIKE`、`ON CONFLICT`、`gen_random_uuid()` 都能用;没有 `rowid`,也没有 `AUTOINCREMENT`。自增整数主键写 `id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY`;模板与现成模块的表用的是 `id uuid PRIMARY KEY DEFAULT gen_random_uuid()`,两种都行。\n- 参数占位符是 `$1`、`$2`…,按编号取值:同一个占位符用两次只算一个,`$1` 出现两次也只传一个值。\n- 看现有的表:`parall app db schema --app <app_…>`(表、列、主键、枚举),或在 SQL 里查 `information_schema`。\n- 建表:`parall app db exec --app <app_…> --file db/schema.sql`(全是 IF NOT EXISTS,可以重复执行)。\n- 改表只能往上加(`ALTER TABLE … ADD COLUMN IF NOT EXISTS …`):agent 不能删表、清空表或删列(`DB_DDL_APPROVAL_REQUIRED`)。先加列再发布用到它的代码。\n- 结果每行是以列名为键的对象,两列同名会被拒(用 `AS` 起别名)。`date` 列回来是 `2026-10-12T00:00:00Z` 这样的时间戳字符串,只要日期就在 SQL 里 `to_char(d, 'YYYY-MM-DD')`。\n- 谁能看、谁能改写在 SQL 里,依据 `ctx.viewer`(`{id, display_name, is_agent, role}`,平台担保、改不了);不要用 params 里的用户 ID 做权限判断。能打开 app 的人都能调全部 action,action 就是唯一的门。`db/schema.sql` 末尾有「创建者或管理员可改」与「访问名单」两种写法;`actions/people.ts` 的 `rememberViewer` 在保存(新建、修改、移动)时记下调用者,`people_list` 列出这样用过 app 的人,可以拿来选负责人或分享对象。\n\n## 限额(超了就报错)\n\n- 一次 action 默认:10 秒、1 秒 CPU、50 次数据库调用(每次 `ctx.db.query` / `exec` / `batch` 算一次,能合并就合并)。\n- `ctx.db.batch` 最多 50 条语句、合计 256 KiB,是一个事务;单条 SQL 文本最多 256 KiB——`parall app db exec --file` 的整个文件也是一次请求,大的种子数据拆成几个文件分别执行。\n- action 里一次查询最多返回 1 MiB,超出的行被截掉(结果标 `truncated`);params 最多 1 MiB。\n- 每人每个 Database 每分钟 100 次请求,action 调用与 `parall app db` 共用:列表一次读出来在页面里筛选,不要每敲一个字调一次。\n\n## 写 action\n\n- 给调用者看的错误抛 `ActionError`;其他异常只有作者与 owner / admin 看得到完整消息与堆栈。写类调用的参数记进全组织可查的调用记录:不要经参数传凭据。\n- 没有网络、没有文件系统;模块级变量在调用者之间共享,不能存调用者的状态。\n- 要调 Clip:在 manifest 里给写类 action 加 `\"clip\": true`,代码里 `await ctx.clip.exec('<clip>', '<command>', args, { connection: '<alias>', timeoutMs: 60_000 })`。它以调用 action 的人的身份执行,那个人没有这个 connection 的权限就被拒(`ClipError`,`code` 如 `CONNECTION_NOT_ALLOWED`);接住它,换成给人看的 `ActionError`。`OUTCOME_UNKNOWN` 表示命令可能已经执行,不要自动重试。调 Clip 的 action 有 100 秒、最多 10 次 Clip 调用;单次命令默认只等 30 秒,命令慢就传 `timeoutMs`,并给之后的数据库写入留出时间(平台会把它截到 action 剩余时间减 8 秒)。\n- 页面拿到的失败带 `err.code`:`ACTION_FAILED`(消息是 `ActionError` 的原文)、`INVALID_ACTION_PARAMS`、`ACTION_TIMEOUT`(写类可能已生效)、`RATE_LIMITED`、`APP_VERSION_CHANGED`(app 已更新,宿主会提示看的人重新加载);`HOST_TIMEOUT` / `HOST_UNAVAILABLE` 是没拿到答复,写类先重读再决定是否重试。`describeError()`(`src/lib/errors.ts`)把这些变成给人看的话。\n- `actions/parall-actions.ts` 是 SDK 的 vendored 副本,不要改。\n\n## 调试\n\n- 核对一个 action:改完 `pnpm build`,然后 `parall app action run <app_…> items_list --local`(换成要试的 action 名):在本机 workerd 里跑本地构建,跑完就返回,不用先发布,也不用起 `app dev`。它连的是 app 的真实 Database,**写会真的生效**;`console.log` 打到 stderr,出错时堆栈按本地 source map 映射回 `actions/*.ts`。\n- 页面连本地 action:`parall app dev --dist dist --app <app_…>`,打开 CLI 打印的地址(带令牌)。页面调的 action 在本机运行,同样**写会真的生效**;右侧列出每次调用、结果与 `console` 输出。它同样在前台一直运行到被结束:在 agent 里放后台跑(`parall app dev --dist dist --app <app_…> > dev.log 2>&1 &`)、用完结束;改完重新 `pnpm build` 即可,不用重启。\n- 要在线上运行时里试:`parall app publish dist --app <app_…> --preview` 后 `parall app action run <app_…> items_list --v <seq>`。调用记录 `parall app action log <app_…>`,执行过的 SQL `parall app db log --app <app_…>`(加 `--invocation <aci_… 或 acd_…>` 只看一次调用)。\n\n## 现成模块(@parall blocks)\n\n- `parall app add --list` 列出模块(如 calendar 日历、kanban 看板);`parall app add calendar` 把它的页面(`src/blocks/<block>/`)、action(`actions/<block>.ts`)、类型(`shared/<block>.ts`)、SQL(`db/<block>.sql`)与 manifest 声明加进本项目,并接到 `src/pages.tsx` 与 `actions/index.ts` 的 `parall:` 标记处。它只改本地文件。\n- 加完照打印的步骤做:`parall app db exec --app <app_…> --file db/<block>.sql` 建表 → `pnpm install && pnpm build` → `parall app check dist` → 发布。\n- 加进来的代码就归这个 app:随意改。文件已存在且内容不同时 `add` 拒绝并什么都不写(`--force` 覆盖);`--dry-run` 只看会改什么。\n",
|
|
62
|
+
"_overlay.json": "{\n \"remove\": [\"src/pages/home\"]\n}\n",
|
|
63
|
+
"actions/cloudflare-workers.d.ts": "// The Workers runtime module the action wrapper imports; the runtime\n// provides it. Declared only as far as parall-actions.ts uses it.\ndeclare module 'cloudflare:workers' {\n export abstract class WorkerEntrypoint<Env = unknown> {\n protected readonly ctx: unknown;\n protected readonly env: Env;\n constructor(ctx: unknown, env: Env);\n }\n}\n",
|
|
64
|
+
"actions/index.ts": "import { itemActions } from './items';\nimport { defineActions } from './parall-actions';\nimport { peopleActions } from './people';\n// parall:action-imports — `parall app add` puts block imports above this line.\n\n// Every action is declared in public/manifest.json under actions.functions\n// (kind read | write, params as a JSON Schema) and implemented here;\n// `parall app check dist` compares the two, and publish runs it too. The\n// loader looks the module up by the export name ActionRunner.\nexport const ActionRunner = defineActions({\n ...peopleActions,\n ...itemActions,\n // parall:actions — `parall app add` puts block actions above this line.\n});\n",
|
|
65
|
+
"actions/items.ts": "import type { Item, ItemInput, ItemStatus } from '@shared/items';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// The example list behind src/pages/items: everyone in the organization\n// reads every item; the creator or an org owner/admin changes or deletes it.\n// The rule lives in SQL, keyed on ctx.viewer (see db/schema.sql for an\n// access-list variant).\n\nconst COLUMNS = `id, title, notes, status, created_by, created_by_name, created_at, updated_at`;\n// Whether the caller ($1 = ctx.viewer.id, $2 = ctx.viewer.role) may change a row.\nconst CAN_EDIT = `(created_by = $1 OR $2 IN ('owner', 'admin'))`;\nconst STATUSES: ItemStatus[] = ['open', 'done'];\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction checkId(id: unknown): string {\n if (typeof id !== 'string' || !UUID.test(id)) throw new ActionError('This item does not exist.');\n return id;\n}\n\nexport const itemActions = {\n /** read: every item, most recently changed first. */\n async items_list(ctx: ActionContext): Promise<Item[]> {\n const { rows } = await ctx.db.query(\n `SELECT ${COLUMNS}, ${CAN_EDIT} AS can_edit\n FROM items\n ORDER BY updated_at DESC\n LIMIT 1000`,\n [ctx.viewer.id, ctx.viewer.role],\n );\n return rows as unknown as Item[];\n },\n\n /** write: creates an item (no id) or updates one the caller may change. */\n async items_save(ctx: ActionContext, input: ItemInput): Promise<Item> {\n const title = input.title.trim();\n if (!title) throw new ActionError('A title is required.');\n const notes = (input.notes ?? '').trim();\n const status = input.status ?? 'open';\n if (!STATUSES.includes(status)) throw new ActionError(`Unknown status ${status}.`);\n\n if (input.id === undefined) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO items (title, notes, status, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING ${COLUMNS}, true AS can_edit`,\n params: [title, notes, status, ctx.viewer.id, ctx.viewer.display_name],\n },\n ]);\n return results[1]?.rows[0] as unknown as Item;\n }\n\n const id = checkId(input.id);\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE items\n SET title = $3, notes = $4, status = $5, updated_at = now()\n WHERE id = $6 AND ${CAN_EDIT}\n RETURNING ${COLUMNS}, true AS can_edit`,\n params: [ctx.viewer.id, ctx.viewer.role, title, notes, status, id],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('Only its creator or an org admin can change this item.');\n return row as unknown as Item;\n },\n\n /** write: deletes an item the caller may change. */\n async items_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = checkId(params.id);\n const { rows_affected } = await ctx.db.exec(`DELETE FROM items WHERE id = $3 AND ${CAN_EDIT}`, [\n ctx.viewer.id,\n ctx.viewer.role,\n id,\n ]);\n if (rows_affected === 0) {\n throw new ActionError('Only its creator or an org admin can delete this item.');\n }\n return { id };\n },\n};\n",
|
|
66
|
+
"actions/people.ts": "import type { Person } from '@shared/people';\nimport type { ActionBatchStatement, ActionContext, ActionViewer } from './parall-actions';\n\n/** Org owners and admins may change anything; members their own rows. */\nexport function isOrgAdmin(viewer: ActionViewer): boolean {\n return viewer.role === 'owner' || viewer.role === 'admin';\n}\n\n/**\n * Remembers the caller in app_people, so pages can offer the people who use\n * the app (as assignees, for an access list…). Put it in the same\n * ctx.db.batch as the write: one round trip, one transaction.\n */\nexport function rememberViewer(ctx: ActionContext): ActionBatchStatement {\n return {\n sql: `INSERT INTO app_people (user_id, display_name, is_agent, last_seen_at)\n VALUES ($1, $2, $3, now())\n ON CONFLICT (user_id) DO UPDATE\n SET display_name = EXCLUDED.display_name,\n is_agent = EXCLUDED.is_agent,\n last_seen_at = now()`,\n params: [ctx.viewer.id, ctx.viewer.display_name, ctx.viewer.is_agent],\n };\n}\n\nexport const peopleActions = {\n /** read: the people who used the app, most recent first. */\n async people_list(ctx: ActionContext): Promise<Person[]> {\n const { rows } = await ctx.db.query(\n `SELECT user_id AS id, display_name, is_agent\n FROM app_people\n ORDER BY last_seen_at DESC\n LIMIT 500`,\n );\n return rows as unknown as Person[];\n },\n};\n",
|
|
67
|
+
"actions/tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ES2022\",\n \"moduleResolution\": \"bundler\",\n \"lib\": [\"ES2022\"],\n \"strict\": true,\n \"noEmit\": true,\n \"skipLibCheck\": true,\n \"isolatedModules\": true,\n \"paths\": {\n \"@shared/*\": [\"../shared/*\"]\n },\n \"types\": []\n },\n \"include\": [\".\", \"../shared\"]\n}\n",
|
|
68
|
+
"db/schema.sql": "-- The app's tables. The Database is PostgreSQL (not SQLite): uuid,\n-- timestamptz, jsonb, ILIKE, ON CONFLICT and gen_random_uuid() all work.\n--\n-- Apply (safe to run again — everything is IF NOT EXISTS):\n-- parall app db exec --app <app_…> --file db/schema.sql\n--\n-- To change a table later, add to it (ALTER TABLE … ADD COLUMN IF NOT\n-- EXISTS …): an agent cannot DROP or TRUNCATE a table or drop a column.\n-- Add a column before publishing code that uses it; stop using one before\n-- a person removes it.\n\n-- People who used the app. Write actions remember the caller here\n-- (actions/people.ts rememberViewer), so pages can offer them as assignees\n-- or for an access list. ctx.viewer is the only trustworthy identity.\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- The example list (src/pages/items, actions/items.ts).\nCREATE TABLE IF NOT EXISTS items (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n notes text NOT NULL DEFAULT '',\n status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'done')),\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS items_updated_at_idx ON items (updated_at DESC);\n\n-- Who may see or change a row is decided in SQL, from ctx.viewer — every\n-- member of the organization can call every action, so the action is the\n-- only gate. Pass the viewer from the action; never take a user id from\n-- params for this.\n--\n-- 1. Everyone reads; the creator or an org owner/admin changes\n-- (what actions/items.ts does, $1 = ctx.viewer.id, $2 = ctx.viewer.role):\n--\n-- UPDATE items SET … WHERE id = $3 AND (created_by = $1 OR $2 IN ('owner', 'admin'))\n--\n-- 2. Private rows shared through an access list:\n--\n-- CREATE TABLE IF NOT EXISTS item_access (\n-- item_id uuid NOT NULL REFERENCES items (id) ON DELETE CASCADE,\n-- user_id text NOT NULL,\n-- can_edit boolean NOT NULL DEFAULT false,\n-- PRIMARY KEY (item_id, user_id)\n-- );\n--\n-- -- what the caller may read\n-- SELECT i.* FROM items i\n-- WHERE i.created_by = $1\n-- OR $2 IN ('owner', 'admin')\n-- OR EXISTS (SELECT 1 FROM item_access a WHERE a.item_id = i.id AND a.user_id = $1);\n--\n-- -- what the caller may change: the same, with a.can_edit\n-- … OR EXISTS (SELECT 1 FROM item_access a\n-- WHERE a.item_id = i.id AND a.user_id = $1 AND a.can_edit)\n--\n-- Pick who to share with from app_people (the people_list action).\n",
|
|
69
|
+
"package.json": "{\n \"scripts\": {\n \"typecheck\": \"tsc -p tsconfig.json && tsc -p actions/tsconfig.json\",\n \"build\": \"tsc -p tsconfig.json && tsc -p actions/tsconfig.json && vite build && vite build --config vite.actions.config.ts\"\n },\n \"devDependencies\": {\n \"miniflare\": \"^4.20260415.0\"\n },\n \"pnpm\": {\n \"onlyBuiltDependencies\": [\n \"esbuild\",\n \"workerd\"\n ]\n }\n}\n",
|
|
70
|
+
"public/manifest.json": "{\n \"actions\": {\n \"entry\": \"_actions/index.js\",\n \"functions\": {\n \"people_list\": { \"kind\": \"read\" },\n \"items_list\": { \"kind\": \"read\" },\n \"items_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"notes\": { \"type\": \"string\", \"maxLength\": 10000 },\n \"status\": { \"type\": \"string\", \"enum\": [\"open\", \"done\"] }\n },\n \"required\": [\"title\"]\n }\n },\n \"items_delete\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n }\n }\n }\n}\n",
|
|
71
|
+
"shared/items.ts": "// Types shared by the actions (actions/items.ts) and the page\n// (src/pages/items): the action returns rows of this shape.\n\nexport type ItemStatus = 'open' | 'done';\n\nexport interface Item {\n id: string;\n title: string;\n notes: string;\n status: ItemStatus;\n created_by: string;\n created_by_name: string;\n /** ISO timestamps. */\n created_at: string;\n updated_at: string;\n /** Whether the caller may change or delete it (creator or org owner/admin). */\n can_edit: boolean;\n}\n\n/** items_save params: no id creates an item, an id updates it. */\nexport interface ItemInput {\n id?: string;\n title: string;\n notes?: string;\n status?: ItemStatus;\n}\n",
|
|
72
|
+
"shared/people.ts": "/** Someone who used the app (actions remember every caller who writes). */\nexport interface Person {\n id: string;\n display_name: string;\n is_agent: boolean;\n}\n",
|
|
73
|
+
"src/hooks/use-people.ts": "import type { Person } from '@shared/people';\nimport { useMemo } from 'react';\nimport { useAction } from '@/hooks/use-action';\nimport { useViewer } from '@/hooks/use-host';\n\n/** The people who used the app (people_list), the viewer first. */\nexport function usePeople(): { people: Person[]; loading: boolean } {\n const viewer = useViewer();\n const { data, loading } = useAction<Person[]>('people_list');\n const people = useMemo(() => {\n const me: Person = {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n };\n return [me, ...(data ?? []).filter((p) => p.id !== viewer.id)];\n }, [data, viewer]);\n return { people, loading };\n}\n",
|
|
74
|
+
"src/pages/items/ItemDetail.tsx": "import type { Item, ItemStatus } from '@shared/items';\nimport { ArrowLeft, Check, Lock, Pencil, RotateCcw, Trash2 } from 'lucide-react';\nimport { useState } from 'react';\nimport { toast } from 'sonner';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\nimport { Badge } from '@/components/ui/badge';\nimport { Button } from '@/components/ui/button';\nimport { Card, CardContent, CardHeader } from '@/components/ui/card';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { formatDateTime, formatRelative } from '@/lib/format';\nimport { t as common } from '@/lib/messages';\nimport { t } from './messages';\n\nexport function ItemDetail({\n item,\n onBack,\n onEdit,\n onDeleted,\n onStatus,\n}: {\n item: Item;\n /** Shown on narrow screens, where the detail replaces the list. */\n onBack?: () => void;\n onEdit: () => void;\n onDeleted: (id: string) => void;\n onStatus: (status: ItemStatus) => void;\n}) {\n const remove = useMutation<{ id: string }, { id: string }>('items_delete');\n const [confirming, setConfirming] = useState(false);\n const done = item.status === 'done';\n\n async function confirmDelete() {\n try {\n await remove.run({ id: item.id });\n setConfirming(false);\n onDeleted(item.id);\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n return (\n <div className=\"flex flex-col gap-3\">\n {onBack ? (\n <Button variant=\"ghost\" size=\"sm\" className=\"-ml-2 self-start\" onClick={onBack}>\n <ArrowLeft />\n {common('back')}\n </Button>\n ) : null}\n <Card className=\"gap-4\">\n <CardHeader className=\"gap-3\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <Badge variant={done ? 'secondary' : 'outline'}>{done ? t('done') : t('open')}</Badge>\n {!item.can_edit ? (\n <Badge variant=\"outline\" className=\"text-muted-foreground\">\n <Lock />\n {t('readOnly')}\n </Badge>\n ) : null}\n </div>\n <h2 className=\"break-words font-semibold text-xl leading-snug\">{item.title}</h2>\n <div className=\"flex items-center gap-2 text-muted-foreground text-sm\">\n <UserAvatar id={item.created_by} name={item.created_by_name} size=\"sm\" />\n <span className=\"min-w-0 truncate\">\n {item.created_by_name} · {formatDateTime(item.created_at)}\n </span>\n </div>\n </CardHeader>\n <CardContent className=\"flex flex-col gap-4\">\n <p className=\"whitespace-pre-wrap break-words text-sm leading-relaxed\">\n {item.notes || <span className=\"text-muted-foreground\">{t('noNotes')}</span>}\n </p>\n <p className=\"text-muted-foreground text-xs\">\n {t('updated', { when: formatRelative(item.updated_at) })}\n </p>\n {item.can_edit ? (\n <div className=\"flex flex-wrap gap-2 border-t pt-4\">\n <Button variant=\"outline\" size=\"sm\" onClick={() => onStatus(done ? 'open' : 'done')}>\n {done ? <RotateCcw /> : <Check />}\n {done ? t('markOpen') : t('markDone')}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={onEdit}>\n <Pencil />\n {common('edit')}\n </Button>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-destructive hover:text-destructive\"\n onClick={() => setConfirming(true)}\n >\n <Trash2 />\n {common('delete')}\n </Button>\n </div>\n ) : null}\n </CardContent>\n </Card>\n <ConfirmDialog\n open={confirming}\n onOpenChange={setConfirming}\n title={t('deleteTitle', { title: item.title })}\n description={t('deleteBody')}\n confirmText={remove.pending ? common('deleting') : common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </div>\n );\n}\n",
|
|
75
|
+
"src/pages/items/ItemFormDialog.tsx": "import type { Item, ItemInput, ItemStatus } from '@shared/items';\nimport { useEffect, useId, useState } from 'react';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { Textarea } from '@/components/ui/textarea';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { t } from './messages';\n\n/** Creates an item (item = null) or edits one, through items_save. */\nexport function ItemFormDialog({\n item,\n open,\n onOpenChange,\n onSaved,\n}: {\n item: Item | null;\n open: boolean;\n onOpenChange: (open: boolean) => void;\n onSaved: (item: Item) => void;\n}) {\n const formId = useId();\n const save = useMutation<Item, ItemInput>('items_save');\n const resetSave = save.reset;\n const [title, setTitle] = useState('');\n const [notes, setNotes] = useState('');\n const [status, setStatus] = useState<ItemStatus>('open');\n\n // Start from the item each time the dialog opens.\n useEffect(() => {\n if (!open) return;\n setTitle(item?.title ?? '');\n setNotes(item?.notes ?? '');\n setStatus(item?.status ?? 'open');\n resetSave();\n }, [open, item, resetSave]);\n\n async function submit() {\n if (!title.trim() || save.pending) return;\n try {\n const saved = await save.run({\n ...(item ? { id: item.id } : {}),\n title: title.trim(),\n notes,\n status,\n });\n onSaved(saved);\n onOpenChange(false);\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={onOpenChange}\n title={item ? t('editItem') : t('newItem')}\n footer={\n <>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)} disabled={save.pending}>\n {common('cancel')}\n </Button>\n <Button onClick={submit} disabled={save.pending || !title.trim()}>\n {save.pending ? common('saving') : common('save')}\n </Button>\n </>\n }\n >\n <div className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-title`}>{t('fieldTitle')}</Label>\n <Input\n id={`${formId}-title`}\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder={t('titlePlaceholder')}\n maxLength={200}\n required\n autoFocus\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-notes`}>{t('fieldNotes')}</Label>\n <Textarea\n id={`${formId}-notes`}\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n placeholder={t('notesPlaceholder')}\n rows={4}\n maxLength={10000}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-status`}>{t('fieldStatus')}</Label>\n <Select value={status} onValueChange={(value) => setStatus(value as ItemStatus)}>\n <SelectTrigger id={`${formId}-status`} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"open\">{t('open')}</SelectItem>\n <SelectItem value=\"done\">{t('done')}</SelectItem>\n </SelectContent>\n </Select>\n </div>\n {save.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(save.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n );\n}\n",
|
|
76
|
+
"src/pages/items/ItemList.tsx": "import type { Item, ItemStatus } from '@shared/items';\nimport { CheckCircle2, Circle, SearchX } from 'lucide-react';\nimport { EmptyState } from '@/components/states';\nimport { Input } from '@/components/ui/input';\nimport { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { formatRelative } from '@/lib/format';\nimport { cn } from '@/lib/utils';\nimport { t } from './messages';\n\nexport type ItemFilter = 'all' | ItemStatus;\n\nexport function ItemList({\n items,\n total,\n query,\n onQuery,\n filter,\n onFilter,\n selectedId,\n onSelect,\n onStatus,\n}: {\n items: Item[];\n total: Item[];\n query: string;\n onQuery: (query: string) => void;\n filter: ItemFilter;\n onFilter: (filter: ItemFilter) => void;\n selectedId: string | null;\n onSelect: (id: string) => void;\n onStatus: (item: Item, status: ItemStatus) => void;\n}) {\n const counts = {\n all: total.length,\n open: total.filter((i) => i.status === 'open').length,\n done: total.filter((i) => i.status === 'done').length,\n };\n return (\n <div className=\"flex min-w-0 flex-col gap-3\">\n <div className=\"flex flex-col gap-2 sm:flex-row sm:items-center\">\n <Input\n type=\"search\"\n value={query}\n onChange={(e) => onQuery(e.target.value)}\n placeholder={t('searchPlaceholder')}\n aria-label={t('searchPlaceholder')}\n className=\"sm:flex-1\"\n />\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n value={filter}\n onValueChange={(value) => value && onFilter(value as ItemFilter)}\n className=\"w-full sm:w-auto\"\n >\n {(['all', 'open', 'done'] as const).map((key) => (\n <ToggleGroupItem key={key} value={key} className=\"flex-1 gap-1.5 sm:flex-none\">\n {t(key)}\n <span className=\"text-muted-foreground text-xs tabular-nums\">{counts[key]}</span>\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n </div>\n\n {items.length === 0 ? (\n <EmptyState icon={SearchX} title={t('noMatchTitle')} description={t('noMatchBody')} />\n ) : (\n <ul className=\"flex flex-col divide-y overflow-hidden rounded-xl border bg-card\">\n {items.map((item) => {\n const done = item.status === 'done';\n const selected = item.id === selectedId;\n return (\n <li key={item.id} className={cn('flex items-start gap-1', selected && 'bg-accent')}>\n <button\n type=\"button\"\n disabled={!item.can_edit}\n onClick={() => onStatus(item, done ? 'open' : 'done')}\n aria-label={done ? t('markOpen') : t('markDone')}\n className=\"mt-0.5 shrink-0 rounded-md p-3 text-muted-foreground transition-colors hover:text-foreground disabled:cursor-default disabled:opacity-60\"\n >\n {done ? (\n <CheckCircle2 className=\"size-5 text-success\" />\n ) : (\n <Circle className=\"size-5\" />\n )}\n </button>\n <button\n type=\"button\"\n onClick={() => onSelect(item.id)}\n aria-current={selected ? 'true' : undefined}\n className=\"flex min-w-0 flex-1 flex-col items-start gap-0.5 py-3 pr-4 text-left\"\n >\n <span\n className={cn(\n 'w-full truncate font-medium text-sm',\n done && 'text-muted-foreground line-through',\n )}\n >\n {item.title}\n </span>\n <span className=\"w-full truncate text-muted-foreground text-xs\">\n {t('createdBy', {\n name: item.created_by_name,\n when: formatRelative(item.updated_at),\n })}\n </span>\n </button>\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n}\n",
|
|
77
|
+
"src/pages/items/ItemsPage.tsx": "import type { Item, ItemInput, ItemStatus } from '@shared/items';\nimport { ListTodo, Plus } from 'lucide-react';\nimport { type ReactNode, useEffect, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useMediaQuery } from '@/hooks/use-media-query';\nimport { describeError } from '@/lib/errors';\nimport { ItemDetail } from './ItemDetail';\nimport { ItemFormDialog } from './ItemFormDialog';\nimport { type ItemFilter, ItemList } from './ItemList';\nimport { t } from './messages';\n\nconst NO_ITEMS: Item[] = [];\n\n/**\n * A list with a detail view, wired to one read action (items_list) and\n * writes (items_save, items_delete). Wide screens show both side by side;\n * narrow ones show the list, then the item with a back button. A link\n * prll://app_…#items/<id> opens with that item selected.\n */\nexport function ItemsPage({ route }: PageProps) {\n const items = useAction<Item[]>('items_list');\n const save = useMutation<Item, ItemInput>('items_save');\n const split = useMediaQuery('(min-width: 1024px)');\n\n const [selectedId, setSelectedId] = useState<string | null>(route || null);\n const [query, setQuery] = useState('');\n const [filter, setFilter] = useState<ItemFilter>('all');\n const [editing, setEditing] = useState<Item | 'new' | null>(null);\n\n useEffect(() => {\n if (route) setSelectedId(route);\n }, [route]);\n\n const all = items.data ?? NO_ITEMS;\n const visible = useMemo(() => {\n const needle = query.trim().toLowerCase();\n return all.filter(\n (item) =>\n (filter === 'all' || item.status === filter) &&\n (!needle ||\n item.title.toLowerCase().includes(needle) ||\n item.notes.toLowerCase().includes(needle)),\n );\n }, [all, query, filter]);\n const selected = all.find((item) => item.id === selectedId) ?? null;\n\n // A quick status flip shows at once; the data.changed refresh confirms it.\n async function setStatus(item: Item, status: ItemStatus) {\n items.setData((current = []) => current.map((i) => (i.id === item.id ? { ...i, status } : i)));\n try {\n await save.run({ id: item.id, title: item.title, notes: item.notes, status });\n } catch (err) {\n items.reload();\n toast.error(describeError(err).message);\n }\n }\n\n function onSaved(item: Item) {\n items.setData((current = []) => [item, ...current.filter((i) => i.id !== item.id)]);\n setSelectedId(item.id);\n toast.success(t('saved'));\n }\n\n function onDeleted(id: string) {\n items.setData((current = []) => current.filter((i) => i.id !== id));\n setSelectedId(null);\n toast.success(t('deleted'));\n }\n\n const header = (\n <PageHeader\n title={t('title')}\n description={t('description')}\n actions={\n <Button onClick={() => setEditing('new')}>\n <Plus />\n {t('newItem')}\n </Button>\n }\n />\n );\n\n let body: ReactNode;\n if (items.loading) {\n body = <LoadingState />;\n } else if (items.error && !items.data) {\n body = <ErrorState error={items.error} onRetry={items.reload} />;\n } else if (all.length === 0) {\n body = (\n <EmptyState\n icon={ListTodo}\n title={t('emptyTitle')}\n description={t('emptyBody')}\n action={\n <Button onClick={() => setEditing('new')}>\n <Plus />\n {t('newItem')}\n </Button>\n }\n />\n );\n } else if (!split && selected) {\n body = (\n <ItemDetail\n item={selected}\n onBack={() => setSelectedId(null)}\n onEdit={() => setEditing(selected)}\n onDeleted={onDeleted}\n onStatus={(status) => setStatus(selected, status)}\n />\n );\n } else {\n const list = (\n <ItemList\n items={visible}\n total={all}\n query={query}\n onQuery={setQuery}\n filter={filter}\n onFilter={setFilter}\n selectedId={split ? selectedId : null}\n onSelect={setSelectedId}\n onStatus={setStatus}\n />\n );\n body = split ? (\n <div className=\"grid min-h-0 flex-1 grid-cols-[minmax(0,26rem)_minmax(0,1fr)] gap-6\">\n {list}\n <div className=\"min-w-0\">\n {selected ? (\n <ItemDetail\n item={selected}\n onEdit={() => setEditing(selected)}\n onDeleted={onDeleted}\n onStatus={(status) => setStatus(selected, status)}\n />\n ) : (\n <div className=\"flex h-48 items-center justify-center rounded-xl border border-dashed text-muted-foreground text-sm\">\n {t('selectHint')}\n </div>\n )}\n </div>\n </div>\n ) : (\n list\n );\n }\n\n return (\n <PageContainer width=\"wide\">\n {header}\n {body}\n <ItemFormDialog\n item={editing === 'new' ? null : editing}\n open={editing !== null}\n onOpenChange={(open) => !open && setEditing(null)}\n onSaved={onSaved}\n />\n </PageContainer>\n );\n}\n",
|
|
78
|
+
"src/pages/items/index.ts": "import { ListTodo } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { ItemsPage } from './ItemsPage';\nimport { t } from './messages';\n\nexport const itemsPage: AppPage = {\n id: 'items',\n title: t('title'),\n icon: ListTodo,\n component: ItemsPage,\n};\n",
|
|
79
|
+
"src/pages/items/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Items',\n description:\n 'A list the whole organization shares. Its creator or an org admin can change an item.',\n newItem: 'New item',\n editItem: 'Edit item',\n searchPlaceholder: 'Search items',\n all: 'All',\n open: 'Open',\n done: 'Done',\n markDone: 'Mark as done',\n markOpen: 'Mark as open',\n emptyTitle: 'No items yet',\n emptyBody: 'Add the first one; everyone in the organization will see it.',\n noMatchTitle: 'Nothing matches',\n noMatchBody: 'Try another search or filter.',\n selectHint: 'Select an item to see it here.',\n createdBy: '{name} · {when}',\n updated: 'Updated {when}',\n noNotes: 'No notes.',\n fieldTitle: 'Title',\n fieldNotes: 'Notes',\n fieldStatus: 'Status',\n titlePlaceholder: 'What needs doing?',\n notesPlaceholder: 'Details, links, next steps…',\n saved: 'Saved',\n deleted: 'Deleted',\n deleteTitle: 'Delete “{title}”?',\n deleteBody: 'It is removed for everyone. This cannot be undone.',\n readOnly: 'Only its creator or an org admin can change this item.',\n },\n zh: {\n title: '事项',\n description: '全组织共享的清单。创建者或组织管理员可以修改。',\n newItem: '新建事项',\n editItem: '编辑事项',\n searchPlaceholder: '搜索事项',\n all: '全部',\n open: '进行中',\n done: '已完成',\n markDone: '标为已完成',\n markOpen: '标为进行中',\n emptyTitle: '还没有事项',\n emptyBody: '添加第一条,组织里的每个人都能看到。',\n noMatchTitle: '没有匹配的事项',\n noMatchBody: '换个关键词或筛选条件试试。',\n selectHint: '选择一条事项,在这里查看详情。',\n createdBy: '{name} · {when}',\n updated: '更新于 {when}',\n noNotes: '没有备注。',\n fieldTitle: '标题',\n fieldNotes: '备注',\n fieldStatus: '状态',\n titlePlaceholder: '要做什么?',\n notesPlaceholder: '细节、链接、下一步…',\n saved: '已保存',\n deleted: '已删除',\n deleteTitle: '删除“{title}”?',\n deleteBody: '所有人都将看不到它,无法撤销。',\n readOnly: '只有创建者或组织管理员可以修改这条事项。',\n },\n});\n",
|
|
80
|
+
"src/pages.tsx": "import type { AppPage } from '@/components/app-shell';\nimport { itemsPage } from '@/pages/items';\n// parall:page-imports — `parall app add` puts block imports above this line.\n\n/** The app's pages, in tab order; the first one opens by default. */\nexport const pages: AppPage[] = [\n itemsPage,\n // parall:pages — `parall app add` puts block pages above this line.\n];\n",
|
|
81
|
+
"vite.actions.config.ts": "import { fileURLToPath, URL } from 'node:url';\nimport { defineConfig } from 'vite';\n\n// The action module: one ES module file in dist/_actions/, built after the\n// page (which empties dist/). Not minified and with a source map, so\n// `parall app action run` can map a stack back to actions/*.ts. The only\n// import left is cloudflare:workers, which the Workers runtime provides.\nexport default defineConfig({\n publicDir: false,\n resolve: {\n alias: { '@shared': fileURLToPath(new URL('./shared', import.meta.url)) },\n },\n build: {\n outDir: 'dist/_actions',\n emptyOutDir: false,\n minify: false,\n sourcemap: true,\n target: 'es2022',\n lib: { entry: 'actions/index.ts', formats: ['es'], fileName: () => 'index.js' },\n rollupOptions: { external: ['cloudflare:workers'] },\n },\n});\n"
|
|
82
|
+
};
|
|
83
|
+
export const TEMPLATE_BLOCKS = [
|
|
84
|
+
{
|
|
85
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
86
|
+
"name": "calendar",
|
|
87
|
+
"type": "registry:block",
|
|
88
|
+
"title": "Calendar",
|
|
89
|
+
"description": "A shared calendar: month and week views and an agenda list; create, edit and delete events through actions. Phones get a compact month with the day's agenda and a one-day week grid.",
|
|
90
|
+
"author": "Parall",
|
|
91
|
+
"dependencies": [
|
|
92
|
+
"date-fns@4.4.0"
|
|
93
|
+
],
|
|
94
|
+
"registryDependencies": [],
|
|
95
|
+
"files": [
|
|
96
|
+
{
|
|
97
|
+
"path": "src/blocks/calendar/index.ts",
|
|
98
|
+
"type": "registry:page",
|
|
99
|
+
"target": "src/blocks/calendar/index.ts",
|
|
100
|
+
"content": "import { CalendarDays } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { CalendarPage } from './CalendarPage';\nimport { t } from './messages';\n\n/** The calendar block's page; `parall app add calendar` lists it in src/pages.tsx. */\nexport const calendarPage: AppPage = {\n id: 'calendar',\n title: t('title'),\n icon: CalendarDays,\n component: CalendarPage,\n};\n"
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
"path": "src/blocks/calendar/CalendarPage.tsx",
|
|
104
|
+
"type": "registry:component",
|
|
105
|
+
"target": "src/blocks/calendar/CalendarPage.tsx",
|
|
106
|
+
"content": "import type { CalendarEventRow } from '@shared/calendar';\nimport {\n addHours,\n addMonths,\n addWeeks,\n isSameMonth,\n isWithinInterval,\n setHours,\n startOfDay,\n startOfMonth,\n} from 'date-fns';\nimport { ChevronLeft, ChevronRight, Plus } from 'lucide-react';\nimport { useEffect, useMemo, useState } from 'react';\nimport type { PageProps } from '@/components/app-shell';\nimport { PageContainer } from '@/components/page';\nimport { ErrorState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { Spinner } from '@/components/ui/spinner';\nimport { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { useAction } from '@/hooks/use-action';\nimport { useIsMobile } from '@/hooks/use-media-query';\nimport { AgendaView } from './AgendaView';\nimport {\n type CalendarEvent,\n type CalendarView,\n eachDay,\n parseDay,\n rangeParams,\n toEvent,\n viewTitle,\n visibleDays,\n} from './dates';\nimport { EventDialog, type EventDraft } from './EventDialog';\nimport { MonthView } from './MonthView';\nimport { t } from './messages';\nimport { WeekView } from './WeekView';\n\n/**\n * The calendar block: month and week views and an agenda, over\n * calendar_list (read) and calendar_save / calendar_delete (write). A link\n * prll://app_…#calendar/2026-10-12 opens at that day.\n */\nexport function CalendarPage({ route }: PageProps) {\n const compact = useIsMobile();\n const [view, setView] = useState<CalendarView>('month');\n const [cursor, setCursor] = useState(() =>\n /^\\d{4}-\\d{2}-\\d{2}$/.test(route) ? parseDay(route) : startOfDay(new Date()),\n );\n const [selected, setSelected] = useState(cursor);\n const [draft, setDraft] = useState<EventDraft | null>(null);\n\n // A link to a day (#calendar/2026-10-12) while the calendar is open goes there.\n useEffect(() => {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(route)) return;\n const day = parseDay(route);\n setCursor(day);\n setSelected(day);\n }, [route]);\n\n const { start, end } = useMemo(() => visibleDays(view, cursor), [view, cursor]);\n const days = useMemo(() => eachDay(start, end), [start, end]);\n const query = useAction<CalendarEventRow[]>('calendar_list', rangeParams(start, end));\n const events = useMemo(() => (query.data ?? []).map(toEvent), [query.data]);\n\n function move(step: 1 | -1) {\n const next = view === 'week' ? addWeeks(cursor, step) : addMonths(cursor, step);\n setCursor(next);\n // Keep a selected day inside what is shown: today if it is there.\n const today = startOfDay(new Date());\n if (view === 'week') setSelected(addWeeks(selected, step));\n else setSelected(isSameMonth(today, next) ? today : startOfMonth(next));\n }\n\n function goToday() {\n const today = startOfDay(new Date());\n setCursor(today);\n setSelected(today);\n }\n\n /** A new one-hour event from `start`. */\n function createAt(start: Date) {\n setDraft({ mode: 'create', start, end: addHours(start, 1), allDay: false });\n }\n\n /** A new event on a day, at 9:00 local time (also on a DST change day). */\n function createOn(day: Date) {\n createAt(setHours(startOfDay(day), 9));\n }\n\n function onSaved(row: CalendarEventRow) {\n query.setData((rows = []) => [...rows.filter((r) => r.id !== row.id), row]);\n }\n\n function onDeleted(id: string) {\n query.setData((rows = []) => rows.filter((r) => r.id !== id));\n }\n\n const open = (event: CalendarEvent) => setDraft({ mode: 'edit', event });\n const newAt = isWithinInterval(selected, { start, end }) ? selected : cursor;\n\n return (\n <PageContainer width=\"wide\" className=\"gap-4\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h1 className=\"min-w-0 flex-1 truncate font-semibold text-xl tracking-tight md:flex-none md:text-2xl\">\n {viewTitle(view, cursor)}\n </h1>\n {query.loading || query.refreshing ? <Spinner className=\"text-muted-foreground\" /> : null}\n <div className=\"flex items-center gap-1 md:ml-2\">\n <Button variant=\"outline\" size=\"sm\" onClick={goToday}>\n {t('today')}\n </Button>\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={t('previous')}\n onClick={() => move(-1)}\n >\n <ChevronLeft />\n </Button>\n <Button variant=\"ghost\" size=\"icon-sm\" aria-label={t('next')} onClick={() => move(1)}>\n <ChevronRight />\n </Button>\n </div>\n <div className=\"flex w-full items-center gap-2 md:ml-auto md:w-auto\">\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n size=\"sm\"\n value={view}\n onValueChange={(value) => {\n if (!value) return;\n // The new view opens around the selected day.\n setView(value as CalendarView);\n setCursor(selected);\n }}\n className=\"flex-1 md:flex-none\"\n >\n {(['month', 'week', 'agenda'] as const).map((key) => (\n <ToggleGroupItem key={key} value={key} className=\"flex-1 md:flex-none\">\n {t(key)}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n <Button size=\"sm\" onClick={() => createOn(newAt)}>\n <Plus />\n <span className=\"sr-only sm:not-sr-only\">{t('newEvent')}</span>\n </Button>\n </div>\n </div>\n\n {query.error && !query.data ? (\n <ErrorState error={query.error} onRetry={query.reload} />\n ) : view === 'month' ? (\n <MonthView\n days={days}\n cursor={cursor}\n events={events}\n selected={selected}\n compact={compact}\n loading={query.loading}\n onSelectDay={setSelected}\n onCreate={createOn}\n onOpen={open}\n />\n ) : view === 'week' ? (\n <WeekView\n days={days}\n events={events}\n selected={selected}\n compact={compact}\n onSelectDay={setSelected}\n onCreate={createAt}\n onOpen={open}\n />\n ) : (\n <AgendaView days={days} events={events} loading={query.loading} onOpen={open} />\n )}\n\n <EventDialog\n draft={draft}\n onClose={() => setDraft(null)}\n onSaved={onSaved}\n onDeleted={onDeleted}\n />\n </PageContainer>\n );\n}\n"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
"path": "src/blocks/calendar/MonthView.tsx",
|
|
110
|
+
"type": "registry:component",
|
|
111
|
+
"target": "src/blocks/calendar/MonthView.tsx",
|
|
112
|
+
"content": "import { isSameDay, isSameMonth, isToday } from 'date-fns';\nimport { Plus } from 'lucide-react';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { cn } from '@/lib/utils';\nimport { AgendaList } from './AgendaView';\nimport {\n COLOR_CLASSES,\n type CalendarEvent,\n eventsOn,\n formatLongDay,\n formatTime,\n weekdayNames,\n} from './dates';\nimport { t } from './messages';\n\nconst MAX_CHIPS = 3;\n\n/** A month grid. Wide: events as chips in each day, \"+N more\" opens the\n * rest. Narrow (`compact`): dots under each day, and the selected day's\n * events listed below the grid. */\nexport function MonthView({\n days,\n cursor,\n events,\n selected,\n compact,\n loading = false,\n onSelectDay,\n onCreate,\n onOpen,\n}: {\n days: Date[];\n cursor: Date;\n events: CalendarEvent[];\n selected: Date;\n compact: boolean;\n /** No answer yet for these days. */\n loading?: boolean;\n onSelectDay: (day: Date) => void;\n onCreate: (day: Date) => void;\n onOpen: (event: CalendarEvent) => void;\n}) {\n const names = weekdayNames();\n if (compact) {\n return (\n <div className=\"flex flex-col gap-4\">\n <div className=\"rounded-xl border bg-card p-2\">\n <div className=\"grid grid-cols-7 pb-1 text-center text-muted-foreground text-xs\">\n {names.map((name) => (\n <div key={name} className=\"py-1\">\n {name}\n </div>\n ))}\n </div>\n <div className=\"grid grid-cols-7 gap-y-1\">\n {days.map((day) => {\n const dayEvents = eventsOn(events, day);\n const isSelected = isSameDay(day, selected);\n return (\n <button\n key={day.toISOString()}\n type=\"button\"\n aria-pressed={isSelected}\n aria-label={formatLongDay(day)}\n onClick={() => onSelectDay(day)}\n className=\"flex h-12 flex-col items-center justify-start gap-1 rounded-lg pt-1\"\n >\n <span\n className={cn(\n 'flex size-8 items-center justify-center rounded-full text-sm tabular-nums',\n !isSameMonth(day, cursor) && 'text-muted-foreground/50',\n isToday(day) &&\n !isSelected &&\n 'font-semibold text-primary ring-1 ring-primary/40',\n isSelected && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n <span className=\"flex h-1.5 gap-0.5\">\n {dayEvents.slice(0, 3).map((event) => (\n <span\n key={event.id}\n className={cn('size-1.5 rounded-full', COLOR_CLASSES[event.color].dot)}\n />\n ))}\n </span>\n </button>\n );\n })}\n </div>\n </div>\n <section className=\"flex flex-col gap-2\">\n <h2 className=\"font-medium text-sm\">{formatLongDay(selected)}</h2>\n <AgendaList\n events={eventsOn(events, selected)}\n onOpen={onOpen}\n empty={t('noEventsDay')}\n loading={loading}\n />\n </section>\n </div>\n );\n }\n\n return (\n <div className=\"overflow-hidden rounded-xl border bg-card\">\n <div className=\"grid grid-cols-7 border-b bg-muted/40\">\n {names.map((name) => (\n <div key={name} className=\"px-2 py-2 font-medium text-muted-foreground text-xs\">\n {name}\n </div>\n ))}\n </div>\n <div className=\"grid auto-rows-fr grid-cols-7\">\n {days.map((day, index) => {\n const dayEvents = eventsOn(events, day);\n const extra = dayEvents.length - MAX_CHIPS;\n const inMonth = isSameMonth(day, cursor);\n return (\n <div\n key={day.toISOString()}\n className={cn(\n 'group flex min-h-28 min-w-0 flex-col gap-1 border-b p-1.5',\n index % 7 !== 6 && 'border-r',\n index >= days.length - 7 && 'border-b-0',\n !inMonth && 'bg-muted/30',\n )}\n >\n <div className=\"flex items-center justify-between\">\n <span\n className={cn(\n 'flex size-6 items-center justify-center rounded-full text-xs tabular-nums',\n !inMonth && 'text-muted-foreground',\n isToday(day) && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n <button\n type=\"button\"\n aria-label={`${t('newEvent')} · ${formatLongDay(day)}`}\n onClick={() => onCreate(day)}\n className=\"flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100\"\n >\n <Plus className=\"size-3.5\" />\n </button>\n </div>\n {dayEvents.slice(0, MAX_CHIPS).map((event) => (\n <EventChip key={event.id} event={event} onOpen={onOpen} />\n ))}\n {extra > 0 ? (\n <Popover>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n className=\"self-start rounded px-1.5 text-muted-foreground text-xs hover:bg-accent hover:text-foreground\"\n >\n {t('more', { n: extra })}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"start\" className=\"flex w-64 flex-col gap-1 p-2\">\n <p className=\"px-1 pb-1 font-medium text-sm\">{formatLongDay(day)}</p>\n {dayEvents.map((event) => (\n <EventChip key={event.id} event={event} onOpen={onOpen} />\n ))}\n </PopoverContent>\n </Popover>\n ) : null}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nfunction EventChip({\n event,\n onOpen,\n}: {\n event: CalendarEvent;\n onOpen: (e: CalendarEvent) => void;\n}) {\n const colors = COLOR_CLASSES[event.color];\n return (\n <button\n type=\"button\"\n onClick={() => onOpen(event)}\n className={cn(\n 'flex w-full min-w-0 items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-xs transition-colors',\n colors.chip,\n )}\n >\n {event.all_day ? null : (\n <span className=\"shrink-0 tabular-nums opacity-70\">{formatTime(event.start)}</span>\n )}\n <span className=\"min-w-0 truncate font-medium\">{event.title}</span>\n </button>\n );\n}\n"
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
"path": "src/blocks/calendar/WeekView.tsx",
|
|
116
|
+
"type": "registry:component",
|
|
117
|
+
"target": "src/blocks/calendar/WeekView.tsx",
|
|
118
|
+
"content": "import { isSameDay, isToday } from 'date-fns';\nimport { useEffect, useRef, useState } from 'react';\nimport { cn } from '@/lib/utils';\nimport {\n COLOR_CLASSES,\n type CalendarEvent,\n eventsOn,\n formatHour,\n formatLongDay,\n formatTime,\n layoutDay,\n weekdayNames,\n} from './dates';\nimport { t } from './messages';\n\nconst HOUR_PX = 48;\nconst HOURS = Array.from({ length: 24 }, (_, h) => h);\nconst FIRST_VISIBLE_HOUR = 8;\n\n/** A time grid. Wide: the seven days side by side. Narrow (`compact`): a\n * strip to pick a day, and that day's grid. Clicking an empty hour starts\n * an event there. */\nexport function WeekView({\n days,\n events,\n selected,\n compact,\n onSelectDay,\n onCreate,\n onOpen,\n}: {\n days: Date[];\n events: CalendarEvent[];\n selected: Date;\n compact: boolean;\n onSelectDay: (day: Date) => void;\n onCreate: (start: Date) => void;\n onOpen: (event: CalendarEvent) => void;\n}) {\n const names = weekdayNames();\n const shown = compact ? days.filter((day) => isSameDay(day, selected)) : days;\n const columns = `3.25rem repeat(${shown.length}, minmax(0, 1fr))`;\n const allDay = shown.map((day) => eventsOn(events, day).filter((event) => event.all_day));\n const scroller = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (scroller.current) scroller.current.scrollTop = FIRST_VISIBLE_HOUR * HOUR_PX - 8;\n }, []);\n\n return (\n <div className=\"flex min-h-0 flex-col overflow-hidden rounded-xl border bg-card\">\n {compact ? (\n <div className=\"grid grid-cols-7 gap-1 border-b p-2\">\n {days.map((day, i) => {\n const isSelected = isSameDay(day, selected);\n return (\n <button\n key={day.toISOString()}\n type=\"button\"\n aria-pressed={isSelected}\n aria-label={formatLongDay(day)}\n onClick={() => onSelectDay(day)}\n className=\"flex flex-col items-center gap-1 rounded-lg py-1 text-xs\"\n >\n <span className=\"text-muted-foreground\">{names[i]}</span>\n <span\n className={cn(\n 'flex size-8 items-center justify-center rounded-full text-sm tabular-nums',\n isToday(day) &&\n !isSelected &&\n 'font-semibold text-primary ring-1 ring-primary/40',\n isSelected && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n <span className=\"flex h-1.5 gap-0.5\">\n {eventsOn(events, day)\n .slice(0, 3)\n .map((event) => (\n <span\n key={event.id}\n className={cn('size-1.5 rounded-full', COLOR_CLASSES[event.color].dot)}\n />\n ))}\n </span>\n </button>\n );\n })}\n </div>\n ) : (\n <div className=\"grid border-b\" style={{ gridTemplateColumns: columns }}>\n <div />\n {shown.map((day, i) => (\n <div\n key={day.toISOString()}\n className=\"flex flex-col items-center gap-0.5 border-l py-2\"\n >\n <span className=\"text-muted-foreground text-xs\">{names[i]}</span>\n <span\n className={cn(\n 'flex size-7 items-center justify-center rounded-full font-medium text-sm tabular-nums',\n isToday(day) && 'bg-primary text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n </div>\n ))}\n </div>\n )}\n\n {allDay.some((list) => list.length > 0) ? (\n <div className=\"grid border-b\" style={{ gridTemplateColumns: columns }}>\n <div className=\"px-1 py-1.5 text-right text-[11px] text-muted-foreground\">\n {t('allDay')}\n </div>\n {allDay.map((list, i) => (\n <div\n key={shown[i]?.toISOString()}\n className=\"flex min-w-0 flex-col gap-0.5 border-l p-0.5\"\n >\n {list.map((event) => (\n <button\n key={event.id}\n type=\"button\"\n onClick={() => onOpen(event)}\n className={cn(\n 'truncate rounded px-1.5 py-0.5 text-left font-medium text-xs',\n COLOR_CLASSES[event.color].chip,\n )}\n >\n {event.title}\n </button>\n ))}\n </div>\n ))}\n </div>\n ) : null}\n\n <div ref={scroller} className=\"relative max-h-[calc(100svh-15rem)] min-h-80 overflow-y-auto\">\n <div className=\"grid\" style={{ gridTemplateColumns: columns, height: 24 * HOUR_PX }}>\n <div className=\"relative\">\n {HOURS.slice(1).map((hour) => (\n <span\n key={hour}\n className=\"absolute right-2 -translate-y-1/2 text-[11px] text-muted-foreground tabular-nums\"\n style={{ top: hour * HOUR_PX }}\n >\n {formatHour(hour)}\n </span>\n ))}\n </div>\n {shown.map((day) => (\n <DayColumn\n key={day.toISOString()}\n day={day}\n events={events}\n onCreate={onCreate}\n onOpen={onOpen}\n />\n ))}\n </div>\n </div>\n </div>\n );\n}\n\nfunction DayColumn({\n day,\n events,\n onCreate,\n onOpen,\n}: {\n day: Date;\n events: CalendarEvent[];\n onCreate: (start: Date) => void;\n onOpen: (event: CalendarEvent) => void;\n}) {\n const items = layoutDay(events, day);\n return (\n <div className=\"relative border-l\">\n {HOURS.map((hour) => (\n <button\n key={hour}\n type=\"button\"\n tabIndex={-1}\n aria-label={`${t('newEvent')} · ${formatLongDay(day)} ${formatHour(hour)}`}\n onClick={() => {\n const start = new Date(day);\n start.setHours(hour, 0, 0, 0);\n onCreate(start);\n }}\n className=\"absolute inset-x-0 border-border/60 border-t transition-colors hover:bg-accent/40\"\n style={{ top: hour * HOUR_PX, height: HOUR_PX }}\n />\n ))}\n {items.map(({ event, top, height, column, columns }) => (\n <button\n key={event.id}\n type=\"button\"\n onClick={() => onOpen(event)}\n className={cn(\n 'absolute flex flex-col overflow-hidden rounded-md border-l-[3px] px-1.5 py-1 text-left text-xs shadow-xs',\n COLOR_CLASSES[event.color].block,\n )}\n style={{\n top: (top / 60) * HOUR_PX + 1,\n height: Math.max((height / 60) * HOUR_PX - 2, 18),\n left: `calc(${(column / columns) * 100}% + 2px)`,\n width: `calc(${100 / columns}% - 4px)`,\n }}\n >\n <span className=\"truncate font-medium\">{event.title}</span>\n {height >= 45 ? (\n <span className=\"truncate tabular-nums opacity-75\">\n {formatTime(event.start)} – {formatTime(event.end)}\n </span>\n ) : null}\n </button>\n ))}\n {isToday(day) ? <NowLine /> : null}\n </div>\n );\n}\n\n/** A line at the current time, moved every minute. */\nfunction NowLine() {\n const [now, setNow] = useState(() => new Date());\n useEffect(() => {\n const timer = setInterval(() => setNow(new Date()), 60_000);\n return () => clearInterval(timer);\n }, []);\n const top = ((now.getHours() * 60 + now.getMinutes()) / 60) * HOUR_PX;\n return (\n <div className=\"pointer-events-none absolute inset-x-0 z-10\" style={{ top }}>\n <div className=\"relative h-0.5 bg-rose-500\">\n <span className=\"absolute -top-[3px] -left-1 size-2 rounded-full bg-rose-500\" />\n </div>\n </div>\n );\n}\n"
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
"path": "src/blocks/calendar/AgendaView.tsx",
|
|
122
|
+
"type": "registry:component",
|
|
123
|
+
"target": "src/blocks/calendar/AgendaView.tsx",
|
|
124
|
+
"content": "import { isToday } from 'date-fns';\nimport { CalendarDays, MapPin } from 'lucide-react';\nimport { EmptyState, LoadingState } from '@/components/states';\nimport { cn } from '@/lib/utils';\nimport {\n COLOR_CLASSES,\n type CalendarEvent,\n eventsOn,\n formatLongDay,\n formatTimeRange,\n} from './dates';\nimport { t } from './messages';\n\n/** The month's events as a list, one group per day that has any. Until\n * the first answer for these days arrives (`loading`) it shows a skeleton,\n * not \"no events\". */\nexport function AgendaView({\n days,\n events,\n loading = false,\n onOpen,\n}: {\n days: Date[];\n events: CalendarEvent[];\n loading?: boolean;\n onOpen: (event: CalendarEvent) => void;\n}) {\n const groups = days\n .map((day) => ({ day, events: eventsOn(events, day) }))\n .filter((group) => group.events.length > 0);\n if (groups.length === 0 && loading) return <LoadingState rows={4} />;\n if (groups.length === 0) {\n return <EmptyState icon={CalendarDays} title={t('noEvents')} description={t('noEventsBody')} />;\n }\n return (\n <div className=\"flex flex-col gap-5\">\n {groups.map(({ day, events: dayEvents }) => (\n <section key={day.toISOString()} className=\"flex flex-col gap-2\">\n <h2 className={cn('font-medium text-sm', isToday(day) && 'text-primary')}>\n {formatLongDay(day)}\n {isToday(day) ? <span className=\"text-muted-foreground\"> · {t('today')}</span> : null}\n </h2>\n <AgendaList events={dayEvents} onOpen={onOpen} />\n </section>\n ))}\n </div>\n );\n}\n\n/** One day's events: time, color, title and place. */\nexport function AgendaList({\n events,\n onOpen,\n empty,\n loading = false,\n}: {\n events: CalendarEvent[];\n onOpen: (event: CalendarEvent) => void;\n empty?: string;\n /** No answer yet: a skeleton instead of `empty`. */\n loading?: boolean;\n}) {\n if (events.length === 0 && loading) return <LoadingState rows={2} />;\n if (events.length === 0) {\n return (\n <p className=\"rounded-xl border border-dashed px-4 py-6 text-center text-muted-foreground text-sm\">\n {empty ?? t('noEventsDay')}\n </p>\n );\n }\n return (\n <ul className=\"flex flex-col divide-y overflow-hidden rounded-xl border bg-card\">\n {events.map((event) => (\n <li key={event.id}>\n <button\n type=\"button\"\n onClick={() => onOpen(event)}\n className=\"flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/60\"\n >\n <span\n className={cn('mt-1 h-8 w-1 shrink-0 rounded-full', COLOR_CLASSES[event.color].dot)}\n />\n <span className=\"w-24 shrink-0 pt-0.5 text-muted-foreground text-xs tabular-nums sm:w-32\">\n {event.all_day ? t('allDay') : formatTimeRange(event)}\n </span>\n <span className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <span className=\"truncate font-medium text-sm\">{event.title}</span>\n {event.location ? (\n <span className=\"flex min-w-0 items-center gap-1 text-muted-foreground text-xs\">\n <MapPin className=\"size-3 shrink-0\" />\n <span className=\"truncate\">{event.location}</span>\n </span>\n ) : null}\n </span>\n </button>\n </li>\n ))}\n </ul>\n );\n}\n"
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"path": "src/blocks/calendar/EventDialog.tsx",
|
|
128
|
+
"type": "registry:component",
|
|
129
|
+
"target": "src/blocks/calendar/EventDialog.tsx",
|
|
130
|
+
"content": "import {\n type CalendarEventInput,\n type CalendarEventRow,\n EVENT_COLORS,\n type EventColor,\n} from '@shared/calendar';\nimport { addDays, addMinutes } from 'date-fns';\nimport { Check, Lock, Trash2 } from 'lucide-react';\nimport { useEffect, useId, useState } from 'react';\nimport { toast } from 'sonner';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport { Switch } from '@/components/ui/switch';\nimport { Textarea } from '@/components/ui/textarea';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { COLOR_CLASSES, type CalendarEvent, isoDay } from './dates';\nimport { t } from './messages';\n\nexport type EventDraft =\n | { mode: 'create'; start: Date; end: Date; allDay: boolean }\n | { mode: 'edit'; event: CalendarEvent };\n\nfunction hhmm(date: Date): string {\n return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;\n}\n\n/** Creates, edits and deletes an event through calendar_save and\n * calendar_delete; read-only for people who may not change it. */\nexport function EventDialog({\n draft,\n onClose,\n onSaved,\n onDeleted,\n}: {\n draft: EventDraft | null;\n onClose: () => void;\n onSaved: (row: CalendarEventRow) => void;\n onDeleted: (id: string) => void;\n}) {\n const formId = useId();\n const save = useMutation<CalendarEventRow, CalendarEventInput>('calendar_save');\n const resetSave = save.reset;\n const remove = useMutation<{ id: string }, { id: string }>('calendar_delete');\n const [confirming, setConfirming] = useState(false);\n const [title, setTitle] = useState('');\n const [allDay, setAllDay] = useState(false);\n const [startDate, setStartDate] = useState('');\n const [startTime, setStartTime] = useState('09:00');\n const [endDate, setEndDate] = useState('');\n const [endTime, setEndTime] = useState('10:00');\n const [location, setLocation] = useState('');\n const [color, setColor] = useState<EventColor>('blue');\n const [description, setDescription] = useState('');\n\n const event = draft?.mode === 'edit' ? draft.event : null;\n const readOnly = event !== null && !event.can_edit;\n\n useEffect(() => {\n if (!draft) return;\n const source = draft.mode === 'edit' ? draft.event : null;\n const start = draft.mode === 'edit' ? draft.event.start : draft.start;\n // An all-day event's end is the midnight after its last day.\n const end = draft.mode === 'edit' ? draft.event.end : draft.end;\n const isAllDay = draft.mode === 'edit' ? draft.event.all_day : draft.allDay;\n setTitle(source?.title ?? '');\n setAllDay(isAllDay);\n setStartDate(isoDay(start));\n setStartTime(hhmm(start));\n setEndDate(isoDay(isAllDay ? addDays(end, -1) : end));\n setEndTime(hhmm(end));\n setLocation(source?.location ?? '');\n setColor(source?.color ?? 'blue');\n setDescription(source?.description ?? '');\n resetSave();\n }, [draft, resetSave]);\n\n const start = allDay ? new Date(`${startDate}T00:00`) : new Date(`${startDate}T${startTime}`);\n const end = allDay ? new Date(`${endDate}T00:00`) : new Date(`${endDate}T${endTime}`);\n const invalid = !title.trim() || Number.isNaN(start.getTime()) || Number.isNaN(end.getTime());\n const backwards = !invalid && end < start;\n\n /** Moving the start keeps the duration. */\n function changeStart(date: string, time: string) {\n const before = new Date(`${startDate}T${allDay ? '00:00' : startTime}`);\n const after = new Date(`${date}T${allDay ? '00:00' : time}`);\n setStartDate(date);\n setStartTime(time);\n if (!Number.isNaN(before.getTime()) && !Number.isNaN(after.getTime())) {\n const moved = addMinutes(end, (after.getTime() - before.getTime()) / 60000);\n if (!Number.isNaN(moved.getTime())) {\n setEndDate(isoDay(moved));\n setEndTime(hhmm(moved));\n }\n }\n }\n\n async function submit() {\n if (invalid || backwards || readOnly || save.pending) return;\n const input: CalendarEventInput = {\n ...(event ? { id: event.id } : {}),\n title: title.trim(),\n description,\n location,\n color,\n all_day: allDay,\n ...(allDay\n ? { start_date: startDate, end_date: endDate }\n : { starts_at: start.toISOString(), ends_at: end.toISOString() }),\n };\n try {\n onSaved(await save.run(input));\n toast.success(t('saved'));\n onClose();\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n async function confirmDelete() {\n if (!event) return;\n try {\n await remove.run({ id: event.id });\n setConfirming(false);\n onDeleted(event.id);\n toast.success(t('deleted'));\n onClose();\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n return (\n <>\n <ResponsiveDialog\n open={draft !== null}\n onOpenChange={(open) => !open && onClose()}\n title={readOnly ? t('eventDetails') : event ? t('editEvent') : t('newEvent')}\n description={event ? t('createdBy', { name: event.created_by_name }) : undefined}\n footer={\n readOnly ? (\n <Button variant=\"outline\" onClick={onClose}>\n {common('close')}\n </Button>\n ) : (\n <>\n {event ? (\n <Button\n variant=\"ghost\"\n className=\"text-destructive hover:text-destructive sm:mr-auto\"\n onClick={() => setConfirming(true)}\n >\n <Trash2 />\n {common('delete')}\n </Button>\n ) : null}\n <Button variant=\"outline\" onClick={onClose} disabled={save.pending}>\n {common('cancel')}\n </Button>\n <Button onClick={submit} disabled={save.pending || invalid || backwards}>\n {save.pending ? common('saving') : common('save')}\n </Button>\n </>\n )\n }\n >\n <div className=\"flex flex-col gap-4\">\n {readOnly ? (\n <p className=\"flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-muted-foreground text-sm\">\n <Lock className=\"size-4 shrink-0\" />\n {t('readOnly')}\n </p>\n ) : null}\n <fieldset disabled={readOnly} className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-title`}>{t('fieldTitle')}</Label>\n <Input\n id={`${formId}-title`}\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder={t('titlePlaceholder')}\n maxLength={200}\n required\n autoFocus={!event}\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className=\"flex items-center gap-3\">\n <Switch id={`${formId}-allday`} checked={allDay} onCheckedChange={setAllDay} />\n <Label htmlFor={`${formId}-allday`}>{t('allDay')}</Label>\n </div>\n <div className=\"grid gap-3\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-start`}>{t('fieldStart')}</Label>\n <div className=\"flex gap-2\">\n <Input\n id={`${formId}-start`}\n type=\"date\"\n value={startDate}\n onChange={(e) => changeStart(e.target.value, startTime)}\n required\n />\n {allDay ? null : (\n <Input\n type=\"time\"\n aria-label={t('fieldStart')}\n value={startTime}\n onChange={(e) => changeStart(startDate, e.target.value)}\n className=\"w-32 shrink-0\"\n required\n />\n )}\n </div>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-end`}>{t('fieldEnd')}</Label>\n <div className=\"flex gap-2\">\n <Input\n id={`${formId}-end`}\n type=\"date\"\n value={endDate}\n onChange={(e) => setEndDate(e.target.value)}\n aria-invalid={backwards}\n required\n />\n {allDay ? null : (\n <Input\n type=\"time\"\n aria-label={t('fieldEnd')}\n value={endTime}\n onChange={(e) => setEndTime(e.target.value)}\n aria-invalid={backwards}\n className=\"w-32 shrink-0\"\n required\n />\n )}\n </div>\n </div>\n </div>\n {backwards ? (\n <p role=\"alert\" className=\"-mt-2 text-destructive text-sm\">\n {t('endBeforeStart')}\n </p>\n ) : null}\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-location`}>{t('fieldLocation')}</Label>\n <Input\n id={`${formId}-location`}\n value={location}\n onChange={(e) => setLocation(e.target.value)}\n placeholder={t('locationPlaceholder')}\n maxLength={200}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <span className=\"font-medium text-sm\">{t('fieldColor')}</span>\n <div className=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label={t('fieldColor')}>\n {EVENT_COLORS.map((key) => (\n <button\n key={key}\n type=\"button\"\n role=\"radio\"\n aria-checked={color === key}\n aria-label={t(`color_${key}`)}\n onClick={() => setColor(key)}\n className={cn(\n 'flex size-8 items-center justify-center rounded-full text-white ring-offset-2 ring-offset-background transition-shadow',\n COLOR_CLASSES[key].dot,\n color === key && 'ring-2 ring-ring',\n )}\n >\n {color === key ? <Check className=\"size-4\" /> : null}\n </button>\n ))}\n </div>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-description`}>{t('fieldDescription')}</Label>\n <Textarea\n id={`${formId}-description`}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n placeholder={t('descriptionPlaceholder')}\n rows={3}\n maxLength={5000}\n />\n </div>\n </fieldset>\n {save.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(save.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n <ConfirmDialog\n open={confirming}\n onOpenChange={setConfirming}\n title={t('deleteTitle', { title: event?.title ?? '' })}\n description={t('deleteBody')}\n confirmText={remove.pending ? common('deleting') : common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </>\n );\n}\n"
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
"path": "src/blocks/calendar/dates.ts",
|
|
134
|
+
"type": "registry:lib",
|
|
135
|
+
"target": "src/blocks/calendar/dates.ts",
|
|
136
|
+
"content": "import type { CalendarEventRow, CalendarRange, EventColor } from '@shared/calendar';\nimport {\n addDays,\n endOfMonth,\n endOfWeek,\n isBefore,\n startOfDay,\n startOfMonth,\n startOfWeek,\n} from 'date-fns';\nimport { browserLocale, formatLocale } from '@/lib/i18n';\n\n// Date math for the calendar block. Month-grid and weekday-name helpers\n// follow Kibo UI's calendar (MIT, see THIRD_PARTY_NOTICES.md).\n\nexport type CalendarView = 'month' | 'week' | 'agenda';\n\n/** An event in the viewer's local time: [start, end) — an all-day event\n * runs from the local midnight of its first day to that after its last. */\nexport interface CalendarEvent extends CalendarEventRow {\n start: Date;\n end: Date;\n}\n\n/** The first day of the week where the viewer is (by the browser's\n * language and region): 0 Sunday … 6 Saturday. */\nconst regionLocale = browserLocale ?? formatLocale;\nexport const weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6 = (() => {\n try {\n const loc = new Intl.Locale(regionLocale) as Intl.Locale & {\n getWeekInfo?: () => { firstDay: number };\n weekInfo?: { firstDay: number };\n };\n const first = loc.getWeekInfo?.().firstDay ?? loc.weekInfo?.firstDay;\n if (first) return (first % 7) as 0 | 1 | 2 | 3 | 4 | 5 | 6;\n } catch {\n // Older engines: decide by region below.\n }\n return /-(US|CA|JP|BR|MX|IL|PH)\\b/i.test(regionLocale) ? 0 : 1;\n})();\n\n/** YYYY-MM-DD of a local date. */\nexport function isoDay(date: Date): string {\n const y = date.getFullYear();\n const m = String(date.getMonth() + 1).padStart(2, '0');\n const d = String(date.getDate()).padStart(2, '0');\n return `${y}-${m}-${d}`;\n}\n\n/** The local midnight of a YYYY-MM-DD. */\nexport function parseDay(value: string): Date {\n const [y, m, d] = value.split('-').map(Number);\n return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1);\n}\n\nexport function toEvent(row: CalendarEventRow): CalendarEvent {\n if (row.all_day) {\n const start = parseDay(row.start_date ?? '');\n const end = addDays(parseDay(row.end_date ?? row.start_date ?? ''), 1);\n return { ...row, start, end };\n }\n return { ...row, start: new Date(row.starts_at ?? ''), end: new Date(row.ends_at ?? '') };\n}\n\n/** The days a view shows: whole weeks around the month, one week, or the\n * month for the agenda. */\nexport function visibleDays(view: CalendarView, cursor: Date): { start: Date; end: Date } {\n if (view === 'week') {\n const start = startOfWeek(cursor, { weekStartsOn });\n return { start, end: addDays(start, 7) };\n }\n // endOfMonth / endOfWeek are the last millisecond; the range ends at the\n // following midnight.\n if (view === 'agenda') {\n return { start: startOfMonth(cursor), end: startOfDay(addDays(endOfMonth(cursor), 1)) };\n }\n const start = startOfWeek(startOfMonth(cursor), { weekStartsOn });\n const end = startOfDay(addDays(endOfWeek(endOfMonth(cursor), { weekStartsOn }), 1));\n return { start, end };\n}\n\n/** calendar_list params for [start, end). */\nexport function rangeParams(start: Date, end: Date): CalendarRange {\n return {\n from: start.toISOString(),\n to: end.toISOString(),\n from_date: isoDay(start),\n to_date: isoDay(addDays(end, -1)),\n };\n}\n\nexport function eachDay(start: Date, end: Date): Date[] {\n const days: Date[] = [];\n for (let d = startOfDay(start); isBefore(d, end); d = addDays(d, 1)) days.push(d);\n return days;\n}\n\n/** Whether the event covers any part of the local day. */\nexport function onDay(event: CalendarEvent, day: Date): boolean {\n const next = addDays(day, 1);\n return event.start < next && (event.end > day || event.start.getTime() === day.getTime());\n}\n\nexport function eventsOn(events: CalendarEvent[], day: Date): CalendarEvent[] {\n return events\n .filter((event) => onDay(event, day))\n .sort((a, b) => Number(b.all_day) - Number(a.all_day) || a.start.getTime() - b.start.getTime());\n}\n\nconst weekdayFormat = new Intl.DateTimeFormat(formatLocale, { weekday: 'short' });\n/** Short weekday names in display order, starting at weekStartsOn. */\nexport function weekdayNames(): string[] {\n const base = startOfWeek(new Date(2024, 0, 10), { weekStartsOn });\n return Array.from({ length: 7 }, (_, i) => weekdayFormat.format(addDays(base, i)));\n}\n\nconst timeFormat = new Intl.DateTimeFormat(formatLocale, { hour: 'numeric', minute: '2-digit' });\nexport function formatTime(date: Date): string {\n return timeFormat.format(date);\n}\n\nexport function formatTimeRange(event: CalendarEvent): string {\n return `${formatTime(event.start)} – ${formatTime(event.end)}`;\n}\n\nconst hourFormat = new Intl.DateTimeFormat(formatLocale, { hour: 'numeric' });\nexport function formatHour(hour: number): string {\n return /^zh|^ja|^ko/i.test(formatLocale)\n ? `${String(hour).padStart(2, '0')}:00`\n : hourFormat.format(new Date(2024, 0, 1, hour));\n}\n\nconst monthFormat = new Intl.DateTimeFormat(formatLocale, { year: 'numeric', month: 'long' });\nconst dayFormat = new Intl.DateTimeFormat(formatLocale, { month: 'long', day: 'numeric' });\nconst dayOfMonthFormat = new Intl.DateTimeFormat(formatLocale, { day: 'numeric' });\nconst longDayFormat = new Intl.DateTimeFormat(formatLocale, {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n});\n\n/** The toolbar title: \"October 2026\", or the week's dates. */\nexport function viewTitle(view: CalendarView, cursor: Date): string {\n if (view !== 'week') return monthFormat.format(cursor);\n const { start, end } = visibleDays('week', cursor);\n const last = addDays(end, -1);\n // \"October 12 – 18\" / \"10月12日 – 18日\"; the month again when it changes.\n const tail =\n last.getMonth() === start.getMonth() ? dayOfMonthFormat.format(last) : dayFormat.format(last);\n return `${dayFormat.format(start)} – ${tail}`;\n}\n\nexport function formatLongDay(day: Date): string {\n return longDayFormat.format(day);\n}\n\n/** Lays out one day's timed events side by side where they overlap: each\n * gets a column and the number of columns of its overlapping group. */\nexport function layoutDay(\n events: CalendarEvent[],\n day: Date,\n): Array<{ event: CalendarEvent; top: number; height: number; column: number; columns: number }> {\n const dayStart = startOfDay(day).getTime();\n const dayEnd = addDays(startOfDay(day), 1).getTime();\n // Minutes on the local clock, like the hour lines and the now line: a day\n // that changes to or from daylight saving time is 23 or 25 hours long.\n // An event spans from its start's clock time to its end's; where the clock\n // goes back (the repeated hour) and the end's clock time is not after the\n // start's, it spans its real length instead. Both 1 o'clocks share one row.\n const minutes = (ms: number) => {\n if (ms >= dayEnd) return 24 * 60;\n const at = new Date(ms);\n return at.getHours() * 60 + at.getMinutes() + at.getSeconds() / 60;\n };\n const items = events\n .filter((e) => !e.all_day && onDay(e, day))\n .map((event) => {\n const start = Math.max(event.start.getTime(), dayStart);\n const end = Math.min(Math.max(event.end.getTime(), start + 15 * 60000), dayEnd);\n const top = minutes(start);\n const byClock = minutes(end) - top;\n const length = byClock > 0 ? byClock : (end - start) / 60000;\n // At least 15 minutes, never past midnight.\n const height = Math.min(Math.max(length, 15), 24 * 60 - top);\n return { event, top, height, column: 0, columns: 1 };\n })\n .sort((a, b) => a.top - b.top || b.height - a.height);\n\n let group: typeof items = [];\n let groupEnd = -1;\n const close = () => {\n const columns = Math.max(...group.map((item) => item.column)) + 1;\n for (const item of group) item.columns = columns;\n };\n for (const item of items) {\n if (group.length > 0 && item.top >= groupEnd) {\n close();\n group = [];\n }\n const taken = new Set(\n group.filter((other) => other.top + other.height > item.top).map((other) => other.column),\n );\n let column = 0;\n while (taken.has(column)) column++;\n item.column = column;\n group.push(item);\n groupEnd = Math.max(groupEnd, item.top + item.height);\n }\n if (group.length > 0) close();\n return items;\n}\n\n/** Tailwind classes per event color, readable in both themes. */\nexport const COLOR_CLASSES: Record<EventColor, { dot: string; chip: string; block: string }> = {\n blue: {\n dot: 'bg-sky-500',\n chip: 'bg-sky-500/12 text-sky-900 dark:text-sky-100 hover:bg-sky-500/20',\n block: 'border-sky-500 bg-sky-500/15 text-sky-950 dark:text-sky-50',\n },\n green: {\n dot: 'bg-emerald-500',\n chip: 'bg-emerald-500/12 text-emerald-900 dark:text-emerald-100 hover:bg-emerald-500/20',\n block: 'border-emerald-500 bg-emerald-500/15 text-emerald-950 dark:text-emerald-50',\n },\n amber: {\n dot: 'bg-amber-500',\n chip: 'bg-amber-500/15 text-amber-900 dark:text-amber-100 hover:bg-amber-500/25',\n block: 'border-amber-500 bg-amber-500/20 text-amber-950 dark:text-amber-50',\n },\n rose: {\n dot: 'bg-rose-500',\n chip: 'bg-rose-500/12 text-rose-900 dark:text-rose-100 hover:bg-rose-500/20',\n block: 'border-rose-500 bg-rose-500/15 text-rose-950 dark:text-rose-50',\n },\n violet: {\n dot: 'bg-violet-500',\n chip: 'bg-violet-500/12 text-violet-900 dark:text-violet-100 hover:bg-violet-500/20',\n block: 'border-violet-500 bg-violet-500/15 text-violet-950 dark:text-violet-50',\n },\n gray: {\n dot: 'bg-zinc-400',\n chip: 'bg-zinc-500/12 text-zinc-800 dark:text-zinc-100 hover:bg-zinc-500/20',\n block: 'border-zinc-400 bg-zinc-500/15 text-zinc-900 dark:text-zinc-50',\n },\n};\n"
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"path": "src/blocks/calendar/messages.ts",
|
|
140
|
+
"type": "registry:lib",
|
|
141
|
+
"target": "src/blocks/calendar/messages.ts",
|
|
142
|
+
"content": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Calendar',\n today: 'Today',\n previous: 'Previous',\n next: 'Next',\n month: 'Month',\n week: 'Week',\n agenda: 'Agenda',\n newEvent: 'New event',\n editEvent: 'Edit event',\n eventDetails: 'Event',\n allDay: 'All day',\n more: '+{n} more',\n noEvents: 'No events',\n noEventsBody: 'Nothing on the calendar for this month yet.',\n noEventsDay: 'Nothing on this day.',\n fieldTitle: 'Title',\n titlePlaceholder: 'What is happening?',\n fieldStart: 'Starts',\n fieldEnd: 'Ends',\n fieldLocation: 'Location',\n locationPlaceholder: 'Room, address or link',\n fieldColor: 'Color',\n fieldDescription: 'Notes',\n descriptionPlaceholder: 'Agenda, people, links…',\n createdBy: 'Added by {name}',\n readOnly: 'Only its creator or an org admin can change this event.',\n endBeforeStart: 'The event ends before it starts.',\n saved: 'Saved',\n deleted: 'Deleted',\n deleteTitle: 'Delete “{title}”?',\n deleteBody: 'It is removed from everyone’s calendar.',\n color_blue: 'Blue',\n color_green: 'Green',\n color_amber: 'Amber',\n color_rose: 'Rose',\n color_violet: 'Violet',\n color_gray: 'Gray',\n },\n zh: {\n title: '日历',\n today: '今天',\n previous: '上一页',\n next: '下一页',\n month: '月',\n week: '周',\n agenda: '日程',\n newEvent: '新建日程',\n editEvent: '编辑日程',\n eventDetails: '日程',\n allDay: '全天',\n more: '还有 {n} 项',\n noEvents: '没有日程',\n noEventsBody: '这个月还没有安排。',\n noEventsDay: '这一天没有安排。',\n fieldTitle: '标题',\n titlePlaceholder: '什么事?',\n fieldStart: '开始',\n fieldEnd: '结束',\n fieldLocation: '地点',\n locationPlaceholder: '会议室、地址或链接',\n fieldColor: '颜色',\n fieldDescription: '备注',\n descriptionPlaceholder: '议程、参与人、链接…',\n createdBy: '{name} 添加',\n readOnly: '只有创建者或组织管理员可以修改这条日程。',\n endBeforeStart: '结束时间早于开始时间。',\n saved: '已保存',\n deleted: '已删除',\n deleteTitle: '删除“{title}”?',\n deleteBody: '所有人的日历上都会去掉它。',\n color_blue: '蓝',\n color_green: '绿',\n color_amber: '黄',\n color_rose: '红',\n color_violet: '紫',\n color_gray: '灰',\n },\n});\n"
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
"path": "shared/calendar.ts",
|
|
146
|
+
"type": "registry:file",
|
|
147
|
+
"target": "shared/calendar.ts",
|
|
148
|
+
"content": "// Types shared by the calendar block's actions (actions/calendar.ts) and its\n// pages (src/blocks/calendar).\n\nexport const EVENT_COLORS = ['blue', 'green', 'amber', 'rose', 'violet', 'gray'] as const;\nexport type EventColor = (typeof EVENT_COLORS)[number];\n\n/** A row as calendar_list returns it. Timed events have starts_at/ends_at\n * (ISO instants); all-day events have start_date/end_date (YYYY-MM-DD,\n * end inclusive), the same calendar days wherever the viewer is. */\nexport interface CalendarEventRow {\n id: string;\n title: string;\n description: string;\n location: string;\n color: EventColor;\n all_day: boolean;\n starts_at: string | null;\n ends_at: string | null;\n start_date: string | null;\n end_date: string | null;\n created_by: string;\n created_by_name: string;\n updated_at: string;\n /** Whether the caller may change or delete it (creator or org owner/admin). */\n can_edit: boolean;\n}\n\n/** calendar_list params: the visible range, as instants for timed events\n * and as local dates for all-day ones. */\nexport interface CalendarRange {\n from: string;\n to: string;\n from_date: string;\n to_date: string;\n}\n\n/** calendar_save params: no id creates an event. Send starts_at/ends_at for\n * a timed event, start_date/end_date for an all-day one. */\nexport interface CalendarEventInput {\n id?: string;\n title: string;\n description?: string;\n location?: string;\n color?: EventColor;\n all_day: boolean;\n starts_at?: string;\n ends_at?: string;\n start_date?: string;\n end_date?: string;\n}\n"
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
"path": "actions/calendar.ts",
|
|
152
|
+
"type": "registry:file",
|
|
153
|
+
"target": "actions/calendar.ts",
|
|
154
|
+
"content": "import {\n type CalendarEventInput,\n type CalendarEventRow,\n type CalendarRange,\n EVENT_COLORS,\n} from '@shared/calendar';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// The calendar block (parall app add calendar): everyone reads every event;\n// its creator or an org owner/admin changes or deletes it.\n\nconst COLUMNS = `id, title, description, location, color, all_day, starts_at, ends_at,\n to_char(start_date, 'YYYY-MM-DD') AS start_date, to_char(end_date, 'YYYY-MM-DD') AS end_date,\n created_by, created_by_name, updated_at`;\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst CAN_EDIT = `(created_by = $1 OR $2 IN ('owner', 'admin'))`;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n// An event may last at most this long; a list covers at most this range.\nconst MAX_SPAN_DAYS = 400;\nconst DAY_MS = 24 * 3600 * 1000;\n\nfunction checkId(id: unknown): string {\n if (typeof id !== 'string' || !UUID.test(id)) throw new ActionError('This event does not exist.');\n return id;\n}\n\nfunction instant(value: string | undefined, field: string): Date {\n const date = value ? new Date(value) : null;\n if (!date || Number.isNaN(date.getTime())) throw new ActionError(`${field} is not a valid time.`);\n return date;\n}\n\nfunction day(value: string | undefined, field: string): string {\n if (!value || !/^\\d{4}-\\d{2}-\\d{2}$/.test(value))\n throw new ActionError(`${field} is not a date.`);\n return value;\n}\n\n/** The validated column values of an event. */\nfunction eventValues(input: CalendarEventInput) {\n const title = input.title.trim();\n if (!title) throw new ActionError('A title is required.');\n const color = input.color ?? 'blue';\n if (!EVENT_COLORS.includes(color)) throw new ActionError(`Unknown color ${color}.`);\n let starts: string | null = null;\n let ends: string | null = null;\n let startDate: string | null = null;\n let endDate: string | null = null;\n if (input.all_day) {\n startDate = day(input.start_date, 'start_date');\n endDate = day(input.end_date ?? input.start_date, 'end_date');\n const span = (Date.parse(endDate) - Date.parse(startDate)) / DAY_MS;\n if (span < 0) throw new ActionError('The event ends before it starts.');\n if (span > MAX_SPAN_DAYS) throw new ActionError('An event can last at most 400 days.');\n } else {\n const s = instant(input.starts_at, 'starts_at');\n const e = instant(input.ends_at ?? input.starts_at, 'ends_at');\n if (e < s) throw new ActionError('The event ends before it starts.');\n if (e.getTime() - s.getTime() > MAX_SPAN_DAYS * DAY_MS) {\n throw new ActionError('An event can last at most 400 days.');\n }\n starts = s.toISOString();\n ends = e.toISOString();\n }\n return {\n title,\n description: (input.description ?? '').trim(),\n location: (input.location ?? '').trim(),\n color,\n all_day: input.all_day,\n starts,\n ends,\n startDate,\n endDate,\n };\n}\n\nexport const calendarActions = {\n /** read: the events that overlap the visible range. */\n async calendar_list(ctx: ActionContext, range: CalendarRange): Promise<CalendarEventRow[]> {\n const from = instant(range.from, 'from');\n const to = instant(range.to, 'to');\n if (to.getTime() - from.getTime() > MAX_SPAN_DAYS * DAY_MS) {\n throw new ActionError('Ask for at most 400 days at a time.');\n }\n const { rows } = await ctx.db.query(\n `SELECT ${COLUMNS}, ${CAN_EDIT} AS can_edit\n FROM calendar_events\n WHERE (NOT all_day AND starts_at < $4 AND ends_at > $3)\n OR (all_day AND start_date <= $6::date AND end_date >= $5::date)\n ORDER BY all_day DESC, coalesce(starts_at, start_date::timestamptz), title\n LIMIT 2000`,\n [\n ctx.viewer.id,\n ctx.viewer.role,\n from.toISOString(),\n to.toISOString(),\n day(range.from_date, 'from_date'),\n day(range.to_date, 'to_date'),\n ],\n );\n return rows as unknown as CalendarEventRow[];\n },\n\n /** write: creates an event (no id) or changes one the caller may change. */\n async calendar_save(ctx: ActionContext, input: CalendarEventInput): Promise<CalendarEventRow> {\n const v = eventValues(input);\n const fields = [\n v.title,\n v.description,\n v.location,\n v.color,\n v.all_day,\n v.starts,\n v.ends,\n v.startDate,\n v.endDate,\n ];\n if (input.id === undefined) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO calendar_events\n (title, description, location, color, all_day, starts_at, ends_at,\n start_date, end_date, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING ${COLUMNS}, true AS can_edit`,\n params: [...fields, ctx.viewer.id, ctx.viewer.display_name],\n },\n ]);\n return results[1]?.rows[0] as unknown as CalendarEventRow;\n }\n const id = checkId(input.id);\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE calendar_events\n SET title = $3, description = $4, location = $5, color = $6, all_day = $7,\n starts_at = $8, ends_at = $9, start_date = $10, end_date = $11,\n updated_at = now()\n WHERE id = $12 AND ${CAN_EDIT}\n RETURNING ${COLUMNS}, true AS can_edit`,\n params: [ctx.viewer.id, ctx.viewer.role, ...fields, id],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('Only its creator or an org admin can change this event.');\n return row as unknown as CalendarEventRow;\n },\n\n /** write: deletes an event the caller may change. */\n async calendar_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = checkId(params.id);\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM calendar_events WHERE id = $3 AND ${CAN_EDIT}`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (rows_affected === 0) {\n throw new ActionError('Only its creator or an org admin can delete this event.');\n }\n return { id };\n },\n};\n"
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
"path": "db/calendar.sql",
|
|
158
|
+
"type": "registry:file",
|
|
159
|
+
"target": "db/calendar.sql",
|
|
160
|
+
"content": "-- The calendar block's tables (PostgreSQL). Apply, safe to run again:\n-- parall app db exec --app <app_…> --file db/calendar.sql\n\n-- People who used the app (shared with the base scaffold's db/schema.sql).\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- One row per event. A timed event has starts_at/ends_at; an all-day event\n-- has start_date/end_date (end inclusive), so it stays on the same calendar\n-- days for viewers in every time zone.\nCREATE TABLE IF NOT EXISTS calendar_events (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n description text NOT NULL DEFAULT '',\n location text NOT NULL DEFAULT '',\n color text NOT NULL DEFAULT 'blue'\n CHECK (color IN ('blue', 'green', 'amber', 'rose', 'violet', 'gray')),\n all_day boolean NOT NULL DEFAULT false,\n starts_at timestamptz,\n ends_at timestamptz,\n start_date date,\n end_date date,\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n CHECK (\n (NOT all_day AND starts_at IS NOT NULL AND ends_at IS NOT NULL AND ends_at >= starts_at)\n OR (all_day AND start_date IS NOT NULL AND end_date IS NOT NULL AND end_date >= start_date)\n )\n);\nCREATE INDEX IF NOT EXISTS calendar_events_timed_idx ON calendar_events (starts_at, ends_at);\nCREATE INDEX IF NOT EXISTS calendar_events_all_day_idx ON calendar_events (start_date, end_date);\n\n-- Everyone in the organization reads every event; its creator or an org\n-- owner/admin changes it (actions/calendar.ts). For private calendars, add\n-- an access list as in db/schema.sql.\n"
|
|
161
|
+
}
|
|
162
|
+
],
|
|
163
|
+
"docs": "Create the table with `parall app db exec --app <app_…> --file db/calendar.sql`, then `pnpm install && pnpm build`. Everyone in the organization sees every event; its creator or an org owner/admin changes it (actions/calendar.ts). Open a day with prll://app_…#calendar/YYYY-MM-DD.",
|
|
164
|
+
"meta": {
|
|
165
|
+
"parall": {
|
|
166
|
+
"page": {
|
|
167
|
+
"import": "import { calendarPage } from '@/blocks/calendar';",
|
|
168
|
+
"entry": "calendarPage"
|
|
169
|
+
},
|
|
170
|
+
"actions": {
|
|
171
|
+
"import": "import { calendarActions } from './calendar';",
|
|
172
|
+
"entry": "...calendarActions"
|
|
173
|
+
},
|
|
174
|
+
"sql": "db/calendar.sql",
|
|
175
|
+
"functions": {
|
|
176
|
+
"calendar_list": {
|
|
177
|
+
"kind": "read",
|
|
178
|
+
"params": {
|
|
179
|
+
"type": "object",
|
|
180
|
+
"properties": {
|
|
181
|
+
"from": {
|
|
182
|
+
"type": "string",
|
|
183
|
+
"format": "date-time"
|
|
184
|
+
},
|
|
185
|
+
"to": {
|
|
186
|
+
"type": "string",
|
|
187
|
+
"format": "date-time"
|
|
188
|
+
},
|
|
189
|
+
"from_date": {
|
|
190
|
+
"type": "string",
|
|
191
|
+
"format": "date"
|
|
192
|
+
},
|
|
193
|
+
"to_date": {
|
|
194
|
+
"type": "string",
|
|
195
|
+
"format": "date"
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
"required": [
|
|
199
|
+
"from",
|
|
200
|
+
"to",
|
|
201
|
+
"from_date",
|
|
202
|
+
"to_date"
|
|
203
|
+
]
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
"calendar_save": {
|
|
207
|
+
"kind": "write",
|
|
208
|
+
"params": {
|
|
209
|
+
"type": "object",
|
|
210
|
+
"properties": {
|
|
211
|
+
"id": {
|
|
212
|
+
"type": "string",
|
|
213
|
+
"maxLength": 64
|
|
214
|
+
},
|
|
215
|
+
"title": {
|
|
216
|
+
"type": "string",
|
|
217
|
+
"minLength": 1,
|
|
218
|
+
"maxLength": 200
|
|
219
|
+
},
|
|
220
|
+
"description": {
|
|
221
|
+
"type": "string",
|
|
222
|
+
"maxLength": 5000
|
|
223
|
+
},
|
|
224
|
+
"location": {
|
|
225
|
+
"type": "string",
|
|
226
|
+
"maxLength": 200
|
|
227
|
+
},
|
|
228
|
+
"color": {
|
|
229
|
+
"type": "string",
|
|
230
|
+
"enum": [
|
|
231
|
+
"blue",
|
|
232
|
+
"green",
|
|
233
|
+
"amber",
|
|
234
|
+
"rose",
|
|
235
|
+
"violet",
|
|
236
|
+
"gray"
|
|
237
|
+
]
|
|
238
|
+
},
|
|
239
|
+
"all_day": {
|
|
240
|
+
"type": "boolean"
|
|
241
|
+
},
|
|
242
|
+
"starts_at": {
|
|
243
|
+
"type": "string",
|
|
244
|
+
"format": "date-time"
|
|
245
|
+
},
|
|
246
|
+
"ends_at": {
|
|
247
|
+
"type": "string",
|
|
248
|
+
"format": "date-time"
|
|
249
|
+
},
|
|
250
|
+
"start_date": {
|
|
251
|
+
"type": "string",
|
|
252
|
+
"format": "date"
|
|
253
|
+
},
|
|
254
|
+
"end_date": {
|
|
255
|
+
"type": "string",
|
|
256
|
+
"format": "date"
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
"required": [
|
|
260
|
+
"title",
|
|
261
|
+
"all_day"
|
|
262
|
+
]
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
"calendar_delete": {
|
|
266
|
+
"kind": "write",
|
|
267
|
+
"params": {
|
|
268
|
+
"type": "object",
|
|
269
|
+
"properties": {
|
|
270
|
+
"id": {
|
|
271
|
+
"type": "string",
|
|
272
|
+
"maxLength": 64
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
"required": [
|
|
276
|
+
"id"
|
|
277
|
+
]
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
286
|
+
"name": "kanban",
|
|
287
|
+
"type": "registry:block",
|
|
288
|
+
"title": "Kanban / pipeline",
|
|
289
|
+
"description": "A board of stages and cards with an assignee and dates: drag cards between stages on wide screens or move them from the card menu (how phones do it), filter by text, assignee and due date, and rename, reorder or add stages. Fits hiring pipelines, content calendars and task boards.",
|
|
290
|
+
"author": "Parall",
|
|
291
|
+
"dependencies": [
|
|
292
|
+
"@dnd-kit/core@6.3.1",
|
|
293
|
+
"@dnd-kit/sortable@10.0.0",
|
|
294
|
+
"@dnd-kit/utilities@3.2.2",
|
|
295
|
+
"date-fns@4.4.0"
|
|
296
|
+
],
|
|
297
|
+
"registryDependencies": [],
|
|
298
|
+
"files": [
|
|
299
|
+
{
|
|
300
|
+
"path": "src/blocks/kanban/index.ts",
|
|
301
|
+
"type": "registry:page",
|
|
302
|
+
"target": "src/blocks/kanban/index.ts",
|
|
303
|
+
"content": "import { SquareKanban } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { KanbanPage } from './KanbanPage';\nimport { t } from './messages';\n\n/** The kanban block's page; `parall app add kanban` lists it in src/pages.tsx. */\nexport const kanbanPage: AppPage = {\n id: 'board',\n title: t('title'),\n icon: SquareKanban,\n component: KanbanPage,\n};\n"
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
"path": "src/blocks/kanban/KanbanPage.tsx",
|
|
307
|
+
"type": "registry:component",
|
|
308
|
+
"target": "src/blocks/kanban/KanbanPage.tsx",
|
|
309
|
+
"content": "import type { KanbanBoardData, KanbanCard, KanbanMoveInput, KanbanStage } from '@shared/kanban';\nimport { Columns3, Plus, Settings2, SlidersHorizontal } from 'lucide-react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useViewer } from '@/hooks/use-host';\nimport { useIsMobile } from '@/hooks/use-media-query';\nimport { usePeople } from '@/hooks/use-people';\nimport { describeError } from '@/lib/errors';\nimport { t as common } from '@/lib/messages';\nimport { type AssigneeFilter, type DueFilter, matchesFilters, toColumns } from './board';\nimport { CardDialog, type CardDraft } from './CardDialog';\nimport { KanbanBoard } from './KanbanBoard';\nimport { t } from './messages';\nimport { StagesDialog } from './StagesDialog';\n\nconst NO_STAGES: KanbanStage[] = [];\nconst NO_CARDS: KanbanCard[] = [];\n\n/**\n * The kanban block: stages as columns, cards with an assignee and dates.\n * Cards move by drag and drop (mouse or keyboard) on wide screens and\n * through their menu everywhere, via kanban_move_card; reads come from\n * kanban_board. A link prll://app_…#board/<card id> opens that card.\n */\nexport function KanbanPage({ route }: PageProps) {\n const board = useAction<KanbanBoardData>('kanban_board');\n const move = useMutation<KanbanCard, KanbanMoveInput>('kanban_move_card');\n const remove = useMutation<{ id: string }, { id: string }>('kanban_delete_card');\n const viewer = useViewer();\n const { people } = usePeople();\n const compact = useIsMobile();\n\n const [query, setQuery] = useState('');\n const [assignee, setAssignee] = useState<AssigneeFilter>('all');\n const [due, setDue] = useState<DueFilter>('all');\n const [draft, setDraft] = useState<CardDraft | null>(null);\n const [deleting, setDeleting] = useState<KanbanCard | null>(null);\n const [stagesOpen, setStagesOpen] = useState(false);\n const [filtersOpen, setFiltersOpen] = useState(false);\n // The route whose card was last opened: a link to another card while the\n // board is open opens that one too.\n const [openedRoute, setOpenedRoute] = useState<string | null>(null);\n\n const stages = board.data?.stages ?? NO_STAGES;\n const cards = board.data?.cards ?? NO_CARDS;\n const doneStageId = stages.at(-1)?.id;\n const byId = useMemo(() => Object.fromEntries(cards.map((card) => [card.id, card])), [cards]);\n const columns = useMemo(\n () =>\n toColumns(\n stages,\n cards.filter((card) =>\n matchesFilters(card, {\n query,\n assignee,\n due,\n viewerId: viewer.id,\n done: card.stage_id === doneStageId,\n }),\n ),\n ),\n [stages, cards, query, assignee, due, viewer.id, doneStageId],\n );\n const counts = useMemo(() => {\n const out: Record<string, number> = {};\n for (const card of cards) out[card.stage_id] = (out[card.stage_id] ?? 0) + 1;\n return out;\n }, [cards]);\n\n // Open the card a link points at, once it has loaded. Leaving the card's\n // route forgets it, so the same link opens the card again later.\n useEffect(() => {\n if (!route) {\n setOpenedRoute(null);\n return;\n }\n const card = byId[route];\n if (card && openedRoute !== route) {\n setOpenedRoute(route);\n setDraft({ mode: 'edit', card });\n }\n }, [route, byId, openedRoute]);\n\n function replaceCard(card: KanbanCard) {\n board.setData((data = { stages: [], cards: [] }) => ({\n ...data,\n cards: [...data.cards.filter((c) => c.id !== card.id), card],\n }));\n }\n\n async function moveCard(cardId: string, stageId: string, afterId?: string, beforeId?: string) {\n const card = byId[cardId];\n if (!card) return;\n // Show the card in its new place at once, between the same neighbours\n // the action will use.\n const position = (id?: string) => (id ? byId[id]?.position : undefined);\n const above = position(afterId);\n const below = position(beforeId);\n const last = Math.max(0, ...cards.filter((c) => c.stage_id === stageId).map((c) => c.position));\n const provisional =\n above !== undefined && below !== undefined\n ? (above + below) / 2\n : above !== undefined\n ? above + 1\n : below !== undefined\n ? below - 1\n : last + 1;\n replaceCard({ ...card, stage_id: stageId, position: provisional });\n try {\n replaceCard(\n await move.run({\n id: cardId,\n stage_id: stageId,\n ...(afterId ? { after_id: afterId } : {}),\n ...(beforeId ? { before_id: beforeId } : {}),\n }),\n );\n if (stageId !== card.stage_id) {\n toast.success(t('moved', { stage: stages.find((s) => s.id === stageId)?.name ?? '' }));\n }\n } catch (err) {\n toast.error(describeError(err).message);\n board.reload();\n }\n }\n\n async function confirmDelete() {\n if (!deleting) return;\n try {\n await remove.run({ id: deleting.id });\n board.setData((data = { stages: [], cards: [] }) => ({\n ...data,\n cards: data.cards.filter((c) => c.id !== deleting.id),\n }));\n toast.success(t('deleted'));\n setDeleting(null);\n setDraft(null);\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n const header = (\n <PageHeader\n title={t('title')}\n description={t('description')}\n actions={\n <>\n <Button variant=\"outline\" onClick={() => setStagesOpen(true)} disabled={!board.data}>\n <Settings2 />\n {t('stages')}\n </Button>\n <Button\n onClick={() => stages[0] && setDraft({ mode: 'create', stageId: stages[0].id })}\n disabled={stages.length === 0}\n >\n <Plus />\n {t('newCard')}\n </Button>\n </>\n }\n />\n );\n\n const activeFilters = (assignee !== 'all' ? 1 : 0) + (due !== 'all' ? 1 : 0);\n const selects = (\n <>\n <Select value={assignee} onValueChange={(value) => setAssignee(value as AssigneeFilter)}>\n <SelectTrigger aria-label={t('assignee')} className=\"w-full sm:w-40\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"all\">{`${t('assignee')}: ${t('anyone')}`}</SelectItem>\n <SelectItem value=\"me\">{`${t('assignee')}: ${t('me')}`}</SelectItem>\n <SelectItem value=\"unassigned\">{t('unassigned')}</SelectItem>\n {people\n .filter((person) => person.id !== viewer.id)\n .map((person) => (\n <SelectItem key={person.id} value={person.id}>\n {person.display_name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select value={due} onValueChange={(value) => setDue(value as DueFilter)}>\n <SelectTrigger aria-label={t('due')} className=\"w-full sm:w-40\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"all\">{`${t('due')}: ${t('anyTime')}`}</SelectItem>\n <SelectItem value=\"overdue\">{t('overdue')}</SelectItem>\n <SelectItem value=\"week\">{t('thisWeek')}</SelectItem>\n </SelectContent>\n </Select>\n </>\n );\n const search = (\n <Input\n type=\"search\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={t('searchPlaceholder')}\n aria-label={t('searchPlaceholder')}\n className=\"min-w-0 flex-1 sm:max-w-64\"\n />\n );\n // Phones keep the board high on the screen: the two filters move into a sheet.\n const filters = compact ? (\n <div className=\"mb-3 flex gap-2\">\n {search}\n <Button\n variant=\"outline\"\n size=\"icon\"\n aria-label={t('filters')}\n onClick={() => setFiltersOpen(true)}\n className=\"relative shrink-0\"\n >\n <SlidersHorizontal />\n {activeFilters > 0 ? (\n <span className=\"absolute -top-1.5 -right-1.5 flex size-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground tabular-nums\">\n {activeFilters}\n </span>\n ) : null}\n </Button>\n </div>\n ) : (\n <div className=\"mb-3 flex items-center gap-2\">\n {search}\n {selects}\n </div>\n );\n\n return (\n <PageContainer width=\"full\">\n {header}\n {board.loading ? (\n <LoadingState variant=\"board\" />\n ) : board.error && !board.data ? (\n <ErrorState error={board.error} onRetry={board.reload} />\n ) : stages.length === 0 ? (\n <EmptyState\n icon={Columns3}\n title={t('noStagesTitle')}\n description={t('noStagesBody')}\n action={\n <Button onClick={() => setStagesOpen(true)}>\n <Settings2 />\n {t('stages')}\n </Button>\n }\n />\n ) : (\n <>\n {filters}\n <KanbanBoard\n stages={stages}\n cards={byId}\n columns={columns}\n doneStageId={doneStageId}\n draggable={!compact}\n onMove={moveCard}\n onOpen={(card) => setDraft({ mode: 'edit', card })}\n onAdd={(stageId) => setDraft({ mode: 'create', stageId })}\n onDelete={setDeleting}\n />\n </>\n )}\n <CardDialog\n draft={draft}\n stages={stages}\n onClose={() => setDraft(null)}\n onSaved={replaceCard}\n onDelete={setDeleting}\n />\n <ResponsiveDialog\n open={filtersOpen}\n onOpenChange={setFiltersOpen}\n title={t('filters')}\n footer={\n <>\n <Button\n variant=\"outline\"\n onClick={() => {\n setAssignee('all');\n setDue('all');\n }}\n >\n {t('clearFilters')}\n </Button>\n <Button onClick={() => setFiltersOpen(false)}>{common('close')}</Button>\n </>\n }\n >\n <div className=\"flex flex-col gap-3\">{selects}</div>\n </ResponsiveDialog>\n <StagesDialog\n open={stagesOpen}\n onOpenChange={setStagesOpen}\n stages={stages}\n cardCounts={counts}\n />\n <ConfirmDialog\n open={deleting !== null}\n onOpenChange={(open) => !open && setDeleting(null)}\n title={t('deleteTitle', { title: deleting?.title ?? '' })}\n description={t('deleteBody')}\n confirmText={remove.pending ? common('deleting') : common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </PageContainer>\n );\n}\n"
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
"path": "src/blocks/kanban/KanbanBoard.tsx",
|
|
313
|
+
"type": "registry:component",
|
|
314
|
+
"target": "src/blocks/kanban/KanbanBoard.tsx",
|
|
315
|
+
"content": "import {\n type Announcements,\n closestCorners,\n DndContext,\n type DragEndEvent,\n type DragOverEvent,\n DragOverlay,\n type DragStartEvent,\n KeyboardSensor,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n arrayMove,\n SortableContext,\n sortableKeyboardCoordinates,\n useSortable,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport type { KanbanCard, KanbanStage } from '@shared/kanban';\nimport { Plus } from 'lucide-react';\nimport { useEffect, useRef, useState } from 'react';\nimport { Button } from '@/components/ui/button';\nimport { cn } from '@/lib/utils';\nimport { type Columns, columnOf, STAGE_DOT } from './board';\nimport { CardView } from './CardView';\nimport { t } from './messages';\n\n// The board's drag-and-drop: columns are droppable stages, cards sortable\n// within and across them. Its shape — a provider over columns of sortable\n// cards with an overlay and announcements — follows Kibo UI's kanban\n// (MIT, see THIRD_PARTY_NOTICES.md); it keeps its own column order while a\n// card is dragged and reports one move when it is dropped.\n\nexport interface KanbanBoardProps {\n stages: KanbanStage[];\n cards: Record<string, KanbanCard>;\n /** Card ids per stage, as filtered for display. */\n columns: Columns;\n /** The last stage: its cards count as done. */\n doneStageId: string | undefined;\n /** Drag cards with a mouse or the keyboard; off on phones, where cards\n * move through their menu. */\n draggable: boolean;\n onMove: (cardId: string, stageId: string, afterId?: string, beforeId?: string) => void;\n onOpen: (card: KanbanCard) => void;\n onAdd: (stageId: string) => void;\n onDelete: (card: KanbanCard) => void;\n}\n\nexport function KanbanBoard(props: KanbanBoardProps) {\n const { stages, cards, doneStageId, draggable, onMove } = props;\n const [columns, setColumns] = useState(props.columns);\n const [activeId, setActiveId] = useState<string | null>(null);\n const before = useRef<Columns>(props.columns);\n\n // Follow the data except mid-drag, when the local order is the truth.\n useEffect(() => {\n if (!activeId) setColumns(props.columns);\n }, [props.columns, activeId]);\n\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),\n useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),\n );\n\n const container = (id: string) => (id in columns ? id : columnOf(columns, id));\n const stageName = (id: string | undefined) => stages.find((s) => s.id === id)?.name ?? '';\n const title = (id: string | number) => cards[String(id)]?.title ?? '';\n\n function onDragStart({ active }: DragStartEvent) {\n before.current = columns;\n setActiveId(String(active.id));\n }\n\n function onDragOver({ active, over }: DragOverEvent) {\n if (!over) return;\n const from = container(String(active.id));\n const to = container(String(over.id));\n if (!from || !to || from === to) return;\n setColumns((current) => {\n const source = (current[from] ?? []).filter((id) => id !== active.id);\n const target = [...(current[to] ?? [])];\n const overIndex = target.indexOf(String(over.id));\n target.splice(overIndex === -1 ? target.length : overIndex, 0, String(active.id));\n return { ...current, [from]: source, [to]: target };\n });\n }\n\n function onDragEnd({ active, over }: DragEndEvent) {\n setActiveId(null);\n const id = String(active.id);\n const to = over ? container(String(over.id)) : undefined;\n if (!to) {\n setColumns(before.current);\n return;\n }\n let next = columns;\n const list = columns[to] ?? [];\n const oldIndex = list.indexOf(id);\n const newIndex = over && over.id !== to ? list.indexOf(String(over.id)) : list.length - 1;\n if (oldIndex !== -1 && newIndex !== -1 && oldIndex !== newIndex) {\n next = { ...columns, [to]: arrayMove(list, oldIndex, newIndex) };\n setColumns(next);\n }\n const placed = next[to] ?? [];\n const at = placed.indexOf(id);\n const from = columnOf(before.current, id);\n const unchanged = from === to && (before.current[to] ?? []).indexOf(id) === at;\n if (!unchanged && at !== -1) onMove(id, to, placed[at - 1], placed[at + 1]);\n }\n\n const announcements: Announcements = {\n onDragStart: ({ active }) => t('pickedUp', { title: title(active.id) }),\n onDragOver: ({ active, over }) =>\n over\n ? t('movedOver', { title: title(active.id), stage: stageName(container(String(over.id))) })\n : undefined,\n onDragEnd: ({ active, over }) =>\n over\n ? t('dropped', { title: title(active.id), stage: stageName(container(String(over.id))) })\n : undefined,\n onDragCancel: ({ active }) => t('cancelled', { title: title(active.id) }),\n };\n\n // Phones see one column at a time: a row of stage buttons jumps between\n // them and shows which one is in view.\n const scroller = useRef<HTMLDivElement>(null);\n const [inView, setInView] = useState(0);\n function onScroll() {\n const el = scroller.current;\n const first = el?.firstElementChild as HTMLElement | null;\n if (!el || !first) return;\n setInView(Math.round(el.scrollLeft / (first.offsetWidth + 12)));\n }\n function show(index: number) {\n const column = scroller.current?.children[index] as HTMLElement | undefined;\n column?.scrollIntoView({ behavior: 'smooth', inline: 'start', block: 'nearest' });\n }\n\n const active = activeId ? cards[activeId] : undefined;\n return (\n <DndContext\n sensors={draggable ? sensors : []}\n collisionDetection={closestCorners}\n accessibility={{ announcements }}\n onDragStart={onDragStart}\n onDragOver={onDragOver}\n onDragEnd={onDragEnd}\n onDragCancel={() => {\n setActiveId(null);\n setColumns(before.current);\n }}\n >\n {draggable ? null : (\n <nav\n aria-label={t('stages')}\n className=\"no-scrollbar -mx-4 mb-2 flex gap-1.5 overflow-x-auto px-4\"\n >\n {stages.map((stage, index) => (\n <button\n key={stage.id}\n type=\"button\"\n aria-current={index === inView ? 'true' : undefined}\n onClick={() => show(index)}\n className={cn(\n 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border px-3 font-medium text-muted-foreground text-xs transition-colors',\n index === inView && 'border-foreground/15 bg-accent text-foreground',\n )}\n >\n <span className={cn('size-1.5 rounded-full', STAGE_DOT[stage.color])} />\n {stage.name}\n <span className=\"tabular-nums opacity-70\">{(columns[stage.id] ?? []).length}</span>\n </button>\n ))}\n </nav>\n )}\n <div\n ref={scroller}\n onScroll={draggable ? undefined : onScroll}\n className=\"-mx-4 flex min-h-0 flex-1 snap-x snap-mandatory scroll-px-4 gap-3 overflow-x-auto px-4 pb-3 md:mx-0 md:snap-none md:px-0\"\n >\n {stages.map((stage) => (\n <Column\n key={stage.id}\n stage={stage}\n ids={columns[stage.id] ?? []}\n {...props}\n done={stage.id === doneStageId}\n />\n ))}\n </div>\n <DragOverlay>\n {active ? (\n <CardView\n card={active}\n stages={stages}\n done={active.stage_id === doneStageId}\n overlay\n onMove={() => {}}\n onOpen={() => {}}\n onDelete={() => {}}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n );\n}\n\nfunction Column({\n stage,\n ids,\n done,\n cards,\n stages,\n draggable,\n onMove,\n onOpen,\n onAdd,\n onDelete,\n}: KanbanBoardProps & { stage: KanbanStage; ids: string[]; done: boolean }) {\n const { setNodeRef, isOver } = useDroppable({ id: stage.id });\n return (\n <section\n ref={setNodeRef}\n aria-label={stage.name}\n className={cn(\n // Phones: one column at a time with the next peeking in. Wider: the\n // stages share the width, scrolling only when there are many.\n 'flex w-[85%] shrink-0 snap-start flex-col gap-2 rounded-xl bg-muted/60 p-2 ring-2 ring-transparent transition-colors sm:w-72 md:w-auto md:min-w-52 md:flex-1 md:basis-0',\n isOver && 'ring-ring/40',\n )}\n >\n <header className=\"flex items-center gap-2 px-1.5 pt-1\">\n <span className={cn('size-2 shrink-0 rounded-full', STAGE_DOT[stage.color])} />\n <h2 className=\"min-w-0 truncate font-medium text-sm\">{stage.name}</h2>\n <span className=\"text-muted-foreground text-xs tabular-nums\">{ids.length}</span>\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n className=\"ml-auto text-muted-foreground\"\n aria-label={t('addCard', { stage: stage.name })}\n onClick={() => onAdd(stage.id)}\n >\n <Plus />\n </Button>\n </header>\n <SortableContext items={ids} strategy={verticalListSortingStrategy}>\n <div className=\"flex min-h-16 flex-col gap-2\">\n {ids.map((id) => {\n const card = cards[id];\n if (!card) return null;\n return (\n <SortableCard\n key={id}\n card={card}\n stages={stages}\n done={done}\n draggable={draggable}\n onMove={(stageId) => onMove(card.id, stageId)}\n onOpen={onOpen}\n onDelete={onDelete}\n />\n );\n })}\n {ids.length === 0 ? (\n <p className=\"rounded-lg border border-dashed px-3 py-5 text-center text-muted-foreground text-xs\">\n {t('emptyStage')}\n </p>\n ) : null}\n </div>\n </SortableContext>\n </section>\n );\n}\n\nfunction SortableCard({\n card,\n stages,\n done,\n draggable,\n onMove,\n onOpen,\n onDelete,\n}: {\n card: KanbanCard;\n stages: KanbanStage[];\n done: boolean;\n draggable: boolean;\n onMove: (stageId: string) => void;\n onOpen: (card: KanbanCard) => void;\n onDelete: (card: KanbanCard) => void;\n}) {\n const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({\n id: card.id,\n disabled: !draggable,\n });\n return (\n <div\n ref={setNodeRef}\n style={{ transform: CSS.Transform.toString(transform), transition }}\n {...(draggable ? { ...attributes, ...listeners } : {})}\n className={cn('rounded-lg outline-none', isDragging && 'opacity-30')}\n >\n <CardView\n card={card}\n stages={stages}\n done={done}\n draggable={draggable}\n onMove={onMove}\n onOpen={onOpen}\n onDelete={onDelete}\n />\n </div>\n );\n}\n"
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
"path": "src/blocks/kanban/CardView.tsx",
|
|
319
|
+
"type": "registry:component",
|
|
320
|
+
"target": "src/blocks/kanban/CardView.tsx",
|
|
321
|
+
"content": "import type { KanbanCard, KanbanStage } from '@shared/kanban';\nimport { ArrowRight, CalendarClock, Ellipsis, Pencil, Trash2 } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { dueState, formatDateRange, formatShortDate, STAGE_DOT } from './board';\nimport { t } from './messages';\n\n/** One card: title, a line of description, dates and assignee, and a menu\n * to edit, move (how phones move cards) or delete it. */\nexport function CardView({\n card,\n stages,\n done,\n draggable,\n overlay,\n onMove,\n onOpen,\n onDelete,\n}: {\n card: KanbanCard;\n stages: KanbanStage[];\n done: boolean;\n draggable?: boolean;\n /** Drawn under the pointer while dragging. */\n overlay?: boolean;\n onMove: (stageId: string) => void;\n onOpen: (card: KanbanCard) => void;\n onDelete: (card: KanbanCard) => void;\n}) {\n const due = dueState(card, done);\n // A click opens the card. From the keyboard, Enter or Space picks the card\n // up to move it and the menu's Edit opens it.\n return (\n <div\n onClick={() => onOpen(card)}\n className={cn(\n 'group relative flex cursor-pointer flex-col gap-2 rounded-lg border bg-card p-3 text-left shadow-xs transition-colors hover:border-ring/50',\n draggable && 'cursor-grab active:cursor-grabbing',\n overlay && 'rotate-1 cursor-grabbing shadow-lg ring-2 ring-ring/30',\n )}\n >\n <div className=\"flex items-start gap-2\">\n <p\n className={cn(\n 'min-w-0 flex-1 font-medium text-sm leading-snug',\n done && 'text-muted-foreground',\n )}\n >\n {card.title}\n </p>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('cardActions', { title: card.title })}\n className=\"-mt-1 -mr-1 shrink-0 text-muted-foreground\"\n onClick={(e) => e.stopPropagation()}\n onPointerDown={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n >\n <Ellipsis />\n </Button>\n </DropdownMenuTrigger>\n {/* React events bubble out of the portal: keep them from the card. */}\n <DropdownMenuContent\n align=\"end\"\n className=\"w-48\"\n onClick={(e) => e.stopPropagation()}\n onPointerDown={(e) => e.stopPropagation()}\n >\n <DropdownMenuItem onSelect={() => onOpen(card)}>\n <Pencil />\n {common('edit')}\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuLabel className=\"text-muted-foreground text-xs\">\n {t('moveTo')}\n </DropdownMenuLabel>\n {stages\n .filter((stage) => stage.id !== card.stage_id)\n .map((stage) => (\n <DropdownMenuItem key={stage.id} onSelect={() => onMove(stage.id)}>\n <span className={cn('size-2 rounded-full', STAGE_DOT[stage.color])} />\n {stage.name}\n <ArrowRight className=\"ml-auto\" />\n </DropdownMenuItem>\n ))}\n {card.can_delete ? (\n <>\n <DropdownMenuSeparator />\n <DropdownMenuItem variant=\"destructive\" onSelect={() => onDelete(card)}>\n <Trash2 />\n {common('delete')}\n </DropdownMenuItem>\n </>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n {card.description ? (\n <p className=\"line-clamp-2 text-muted-foreground text-xs leading-relaxed\">\n {card.description}\n </p>\n ) : null}\n {card.due_date || card.start_date || card.assignee_name ? (\n <div className=\"flex items-center gap-2\">\n {card.due_date || card.start_date ? (\n <span\n className={cn(\n 'inline-flex min-w-0 items-center gap-1 whitespace-nowrap rounded-md px-1.5 py-0.5 text-muted-foreground text-xs tabular-nums',\n due === 'overdue' && 'bg-destructive/10 text-destructive',\n due === 'soon' && 'bg-amber-500/15 text-amber-700 dark:text-amber-300',\n )}\n >\n <CalendarClock className=\"size-3.5\" />\n {card.start_date && card.due_date\n ? formatDateRange(card.start_date, card.due_date)\n : formatShortDate((card.due_date ?? card.start_date) as string)}\n </span>\n ) : null}\n {card.assignee_name ? (\n <UserAvatar\n id={card.assignee_id ?? card.assignee_name}\n name={card.assignee_name}\n size=\"sm\"\n className=\"ml-auto\"\n title={card.assignee_name}\n />\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n"
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
"path": "src/blocks/kanban/CardDialog.tsx",
|
|
325
|
+
"type": "registry:component",
|
|
326
|
+
"target": "src/blocks/kanban/CardDialog.tsx",
|
|
327
|
+
"content": "import type { KanbanCard, KanbanCardInput, KanbanStage } from '@shared/kanban';\nimport { Trash2 } from 'lucide-react';\nimport { useEffect, useId, useState } from 'react';\nimport { toast } from 'sonner';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { Textarea } from '@/components/ui/textarea';\nimport { useMutation } from '@/hooks/use-action';\nimport { usePeople } from '@/hooks/use-people';\nimport { describeError } from '@/lib/errors';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { STAGE_DOT } from './board';\nimport { t } from './messages';\n\nconst NOBODY = '__nobody__';\n\nexport type CardDraft = { mode: 'create'; stageId: string } | { mode: 'edit'; card: KanbanCard };\n\n/** Creates or edits a card through kanban_save_card. */\nexport function CardDialog({\n draft,\n stages,\n onClose,\n onSaved,\n onDelete,\n}: {\n draft: CardDraft | null;\n stages: KanbanStage[];\n onClose: () => void;\n onSaved: (card: KanbanCard) => void;\n onDelete: (card: KanbanCard) => void;\n}) {\n const formId = useId();\n const save = useMutation<KanbanCard, KanbanCardInput>('kanban_save_card');\n const resetSave = save.reset;\n const { people } = usePeople();\n const card = draft?.mode === 'edit' ? draft.card : null;\n const [title, setTitle] = useState('');\n const [description, setDescription] = useState('');\n const [stageId, setStageId] = useState('');\n const [assigneeId, setAssigneeId] = useState(NOBODY);\n const [startDate, setStartDate] = useState('');\n const [dueDate, setDueDate] = useState('');\n\n useEffect(() => {\n if (!draft) return;\n const source = draft.mode === 'edit' ? draft.card : null;\n setTitle(source?.title ?? '');\n setDescription(source?.description ?? '');\n setStageId(source?.stage_id ?? (draft.mode === 'create' ? draft.stageId : ''));\n setAssigneeId(source?.assignee_id ?? NOBODY);\n setStartDate(source?.start_date ?? '');\n setDueDate(source?.due_date ?? '');\n resetSave();\n }, [draft, resetSave]);\n\n // The current assignee stays pickable even if they never used the app.\n const choices =\n card?.assignee_id && !people.some((p) => p.id === card.assignee_id)\n ? [\n ...people,\n { id: card.assignee_id, display_name: card.assignee_name ?? '', is_agent: false },\n ]\n : people;\n const backwards = Boolean(startDate && dueDate && dueDate < startDate);\n\n async function submit() {\n if (!title.trim() || !stageId || backwards || save.pending) return;\n const assignee = choices.find((p) => p.id === assigneeId);\n try {\n const saved = await save.run({\n ...(card ? { id: card.id } : {}),\n stage_id: stageId,\n title: title.trim(),\n description,\n assignee_id: assignee?.id ?? '',\n assignee_name: assignee?.display_name ?? '',\n start_date: startDate,\n due_date: dueDate,\n });\n onSaved(saved);\n toast.success(t('saved'));\n onClose();\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n return (\n <ResponsiveDialog\n open={draft !== null}\n onOpenChange={(open) => !open && onClose()}\n title={card ? t('editCard') : t('newCard')}\n footer={\n <>\n {card?.can_delete ? (\n <Button\n variant=\"ghost\"\n className=\"text-destructive hover:text-destructive sm:mr-auto\"\n onClick={() => onDelete(card)}\n >\n <Trash2 />\n {common('delete')}\n </Button>\n ) : null}\n <Button variant=\"outline\" onClick={onClose} disabled={save.pending}>\n {common('cancel')}\n </Button>\n <Button\n onClick={submit}\n disabled={save.pending || !title.trim() || !stageId || backwards}\n >\n {save.pending ? common('saving') : common('save')}\n </Button>\n </>\n }\n >\n <div className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-title`}>{t('fieldTitle')}</Label>\n <Input\n id={`${formId}-title`}\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder={t('titlePlaceholder')}\n maxLength={200}\n required\n autoFocus={!card}\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-description`}>{t('fieldDescription')}</Label>\n <Textarea\n id={`${formId}-description`}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n placeholder={t('descriptionPlaceholder')}\n rows={3}\n maxLength={5000}\n />\n </div>\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-stage`}>{t('fieldStage')}</Label>\n <Select value={stageId} onValueChange={setStageId}>\n <SelectTrigger id={`${formId}-stage`} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {stages.map((stage) => (\n <SelectItem key={stage.id} value={stage.id}>\n <span className={cn('size-2 rounded-full', STAGE_DOT[stage.color])} />\n {stage.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-assignee`}>{t('assignee')}</Label>\n <Select value={assigneeId} onValueChange={setAssigneeId}>\n <SelectTrigger id={`${formId}-assignee`} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NOBODY}>{t('unassigned')}</SelectItem>\n {choices.map((person) => (\n <SelectItem key={person.id} value={person.id}>\n {person.display_name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-start`}>{t('fieldStart')}</Label>\n <Input\n id={`${formId}-start`}\n type=\"date\"\n value={startDate}\n onChange={(e) => setStartDate(e.target.value)}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-due`}>{t('fieldDue')}</Label>\n <Input\n id={`${formId}-due`}\n type=\"date\"\n value={dueDate}\n onChange={(e) => setDueDate(e.target.value)}\n aria-invalid={backwards}\n />\n </div>\n </div>\n {backwards ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {t('dueBeforeStart')}\n </p>\n ) : null}\n {save.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(save.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n );\n}\n"
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
"path": "src/blocks/kanban/StagesDialog.tsx",
|
|
331
|
+
"type": "registry:component",
|
|
332
|
+
"target": "src/blocks/kanban/StagesDialog.tsx",
|
|
333
|
+
"content": "import type { KanbanStage, KanbanStageInput } from '@shared/kanban';\nimport { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react';\nimport { useState } from 'react';\nimport { toast } from 'sonner';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { STAGE_DOT } from './board';\nimport { t } from './messages';\n\n/** Renames, reorders, adds and deletes stages. Every change is saved at\n * once; the board refreshes when it lands. */\nexport function StagesDialog({\n open,\n onOpenChange,\n stages,\n cardCounts,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n stages: KanbanStage[];\n cardCounts: Record<string, number>;\n}) {\n const saveStage = useMutation<KanbanStage, KanbanStageInput>('kanban_save_stage');\n const reorder = useMutation<{ ok: true }, { ids: string[] }>('kanban_reorder_stages');\n const remove = useMutation<{ id: string }, { id: string }>('kanban_delete_stage');\n const [names, setNames] = useState<Record<string, string>>({});\n const [newName, setNewName] = useState('');\n const busy = saveStage.pending || reorder.pending || remove.pending;\n\n async function run(work: () => Promise<unknown>) {\n try {\n await work();\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n function rename(stage: KanbanStage) {\n const name = (names[stage.id] ?? stage.name).trim();\n if (!name || name === stage.name) return;\n void run(() => saveStage.run({ id: stage.id, name, color: stage.color }));\n }\n\n function move(index: number, step: -1 | 1) {\n const ids = stages.map((stage) => stage.id);\n const [moved] = ids.splice(index, 1);\n if (!moved) return;\n ids.splice(index + step, 0, moved);\n void run(() => reorder.run({ ids }));\n }\n\n function add() {\n const name = newName.trim();\n if (!name) return;\n void run(async () => {\n await saveStage.run({ name });\n setNewName('');\n });\n }\n\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={onOpenChange}\n title={t('stages')}\n description={t('stagesHint')}\n footer={\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n {common('close')}\n </Button>\n }\n >\n <div className=\"flex flex-col gap-2\">\n {stages.map((stage, index) => {\n const count = cardCounts[stage.id] ?? 0;\n return (\n <div key={stage.id} className=\"flex items-center gap-1.5\">\n <span className={cn('size-2.5 shrink-0 rounded-full', STAGE_DOT[stage.color])} />\n <Input\n aria-label={t('stageName')}\n value={names[stage.id] ?? stage.name}\n onChange={(e) =>\n setNames((current) => ({ ...current, [stage.id]: e.target.value }))\n }\n onBlur={() => rename(stage)}\n onKeyDown={onEnter(() => rename(stage))}\n maxLength={60}\n className=\"h-8\"\n />\n <span className=\"w-6 shrink-0 text-center text-muted-foreground text-xs tabular-nums\">\n {count}\n </span>\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={t('moveUp', { stage: stage.name })}\n disabled={busy || index === 0}\n onClick={() => move(index, -1)}\n >\n <ArrowUp />\n </Button>\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={t('moveDown', { stage: stage.name })}\n disabled={busy || index === stages.length - 1}\n onClick={() => move(index, 1)}\n >\n <ArrowDown />\n </Button>\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={\n count > 0 ? t('stageNotEmpty') : t('deleteStage', { stage: stage.name })\n }\n title={count > 0 ? t('stageNotEmpty') : undefined}\n disabled={busy || count > 0}\n onClick={() => void run(() => remove.run({ id: stage.id }))}\n className=\"text-muted-foreground hover:text-destructive\"\n >\n <Trash2 />\n </Button>\n </div>\n );\n })}\n <div className=\"mt-2 flex items-center gap-2 border-t pt-3\">\n <Input\n aria-label={t('newStagePlaceholder')}\n value={newName}\n onChange={(e) => setNewName(e.target.value)}\n placeholder={t('newStagePlaceholder')}\n maxLength={60}\n className=\"h-8\"\n onKeyDown={onEnter(add)}\n />\n <Button size=\"sm\" onClick={add} disabled={busy || !newName.trim()}>\n <Plus />\n {t('addStage')}\n </Button>\n </div>\n </div>\n </ResponsiveDialog>\n );\n}\n"
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
"path": "src/blocks/kanban/board.ts",
|
|
337
|
+
"type": "registry:lib",
|
|
338
|
+
"target": "src/blocks/kanban/board.ts",
|
|
339
|
+
"content": "import type { KanbanCard, KanbanStage, StageColor } from '@shared/kanban';\nimport { addDays, startOfDay } from 'date-fns';\nimport { formatLocale } from '@/lib/i18n';\n\n/** Card ids per stage, in board order. */\nexport type Columns = Record<string, string[]>;\n\nexport function toColumns(stages: KanbanStage[], cards: KanbanCard[]): Columns {\n const columns: Columns = Object.fromEntries(stages.map((stage) => [stage.id, []]));\n // Stable: cards at the same position keep the server's order.\n const sorted = [...cards].sort((a, b) => a.position - b.position);\n for (const card of sorted) columns[card.stage_id]?.push(card.id);\n return columns;\n}\n\nexport function columnOf(columns: Columns, cardId: string): string | undefined {\n return Object.keys(columns).find((stageId) => columns[stageId]?.includes(cardId));\n}\n\nexport type DueFilter = 'all' | 'overdue' | 'week';\nexport type AssigneeFilter = 'all' | 'me' | 'unassigned' | (string & {});\n\n/** The local midnight of a YYYY-MM-DD. */\nexport function parseDay(value: string): Date {\n const [y, m, d] = value.split('-').map(Number);\n return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1);\n}\n\n/** overdue: due before today; soon: due within two days. Cards in the last\n * stage (done) are neither. */\nexport function dueState(card: KanbanCard, done: boolean): 'overdue' | 'soon' | null {\n if (!card.due_date || done) return null;\n const due = parseDay(card.due_date);\n const today = startOfDay(new Date());\n if (due < today) return 'overdue';\n if (due <= addDays(today, 2)) return 'soon';\n return null;\n}\n\nexport function matchesFilters(\n card: KanbanCard,\n filters: {\n query: string;\n assignee: AssigneeFilter;\n due: DueFilter;\n viewerId: string;\n done: boolean;\n },\n): boolean {\n const needle = filters.query.trim().toLowerCase();\n if (\n needle &&\n !card.title.toLowerCase().includes(needle) &&\n !card.description.toLowerCase().includes(needle)\n ) {\n return false;\n }\n if (filters.assignee === 'me' && card.assignee_id !== filters.viewerId) return false;\n if (filters.assignee === 'unassigned' && card.assignee_id) return false;\n if (\n !['all', 'me', 'unassigned'].includes(filters.assignee) &&\n card.assignee_id !== filters.assignee\n ) {\n return false;\n }\n if (filters.due === 'overdue' && dueState(card, filters.done) !== 'overdue') return false;\n if (filters.due === 'week') {\n if (!card.due_date || filters.done) return false;\n const due = parseDay(card.due_date);\n const today = startOfDay(new Date());\n if (due < today || due > addDays(today, 7)) return false;\n }\n return true;\n}\n\nconst shortDate = new Intl.DateTimeFormat(formatLocale, { month: 'short', day: 'numeric' });\nconst dayOfMonth = new Intl.DateTimeFormat(formatLocale, { day: 'numeric' });\nexport function formatShortDate(value: string): string {\n return shortDate.format(parseDay(value));\n}\n\n/** \"Oct 11 – 12\" / \"10月11日 – 12日\"; the month again when it changes. */\nexport function formatDateRange(start: string, end: string): string {\n const a = parseDay(start);\n const b = parseDay(end);\n const sameMonth = a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();\n return `${shortDate.format(a)} – ${sameMonth ? dayOfMonth.format(b) : shortDate.format(b)}`;\n}\n\nexport const STAGE_DOT: Record<StageColor, string> = {\n gray: 'bg-zinc-400',\n blue: 'bg-sky-500',\n violet: 'bg-violet-500',\n amber: 'bg-amber-500',\n rose: 'bg-rose-500',\n green: 'bg-emerald-500',\n};\n"
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
"path": "src/blocks/kanban/messages.ts",
|
|
343
|
+
"type": "registry:lib",
|
|
344
|
+
"target": "src/blocks/kanban/messages.ts",
|
|
345
|
+
"content": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Board',\n description: 'Cards move through the stages as work gets done.',\n newCard: 'New card',\n editCard: 'Edit card',\n addCard: 'Add a card to {stage}',\n stages: 'Stages',\n searchPlaceholder: 'Search cards',\n assignee: 'Assignee',\n anyone: 'Anyone',\n me: 'Me',\n unassigned: 'Unassigned',\n due: 'Due',\n filters: 'Filters',\n clearFilters: 'Clear filters',\n anyTime: 'Any time',\n overdue: 'Overdue',\n thisWeek: 'Due in 7 days',\n moveTo: 'Move to',\n cardActions: 'Card actions for {title}',\n emptyStage: 'No cards',\n noStagesTitle: 'No stages yet',\n noStagesBody: 'Add the first stage to start the board.',\n fieldTitle: 'Title',\n titlePlaceholder: 'What needs to happen?',\n fieldDescription: 'Description',\n descriptionPlaceholder: 'Details, links, notes…',\n fieldStage: 'Stage',\n fieldStart: 'Start date',\n fieldDue: 'Due date',\n dueBeforeStart: 'The due date is before the start date.',\n saved: 'Saved',\n moved: 'Moved to {stage}',\n deleted: 'Deleted',\n deleteTitle: 'Delete “{title}”?',\n deleteBody: 'It is removed from the board for everyone.',\n stageName: 'Stage name',\n addStage: 'Add stage',\n newStagePlaceholder: 'New stage',\n moveUp: 'Move {stage} up',\n moveDown: 'Move {stage} down',\n deleteStage: 'Delete {stage}',\n stageNotEmpty: 'Move its cards out first',\n stagesHint: 'Rename, reorder or add stages. A stage can be deleted once it is empty.',\n pickedUp: 'Picked up {title}.',\n movedOver: '{title} is over {stage}.',\n dropped: '{title} dropped in {stage}.',\n cancelled: 'Moving {title} was cancelled.',\n },\n zh: {\n title: '看板',\n description: '卡片随着工作推进,在各阶段之间移动。',\n newCard: '新建卡片',\n editCard: '编辑卡片',\n addCard: '在「{stage}」新建卡片',\n stages: '阶段',\n searchPlaceholder: '搜索卡片',\n assignee: '负责人',\n anyone: '所有人',\n me: '我',\n unassigned: '未分配',\n due: '截止',\n filters: '筛选',\n clearFilters: '清除筛选',\n anyTime: '不限',\n overdue: '已逾期',\n thisWeek: '7 天内到期',\n moveTo: '移到',\n cardActions: '「{title}」的操作',\n emptyStage: '没有卡片',\n noStagesTitle: '还没有阶段',\n noStagesBody: '添加第一个阶段,看板就可以用了。',\n fieldTitle: '标题',\n titlePlaceholder: '要做什么?',\n fieldDescription: '描述',\n descriptionPlaceholder: '细节、链接、备注…',\n fieldStage: '阶段',\n fieldStart: '开始日期',\n fieldDue: '截止日期',\n dueBeforeStart: '截止日期早于开始日期。',\n saved: '已保存',\n moved: '已移到「{stage}」',\n deleted: '已删除',\n deleteTitle: '删除“{title}”?',\n deleteBody: '所有人的看板上都会去掉这张卡片。',\n stageName: '阶段名称',\n addStage: '添加阶段',\n newStagePlaceholder: '新阶段',\n moveUp: '把「{stage}」上移',\n moveDown: '把「{stage}」下移',\n deleteStage: '删除「{stage}」',\n stageNotEmpty: '先移走里面的卡片',\n stagesHint: '可以改名、调整顺序或添加阶段;阶段里没有卡片时才能删除。',\n pickedUp: '拿起了「{title}」。',\n movedOver: '「{title}」移到了「{stage}」上方。',\n dropped: '「{title}」放进了「{stage}」。',\n cancelled: '取消移动「{title}」。',\n },\n});\n"
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
"path": "shared/kanban.ts",
|
|
349
|
+
"type": "registry:file",
|
|
350
|
+
"target": "shared/kanban.ts",
|
|
351
|
+
"content": "// Types shared by the kanban block's actions (actions/kanban.ts) and its\n// page (src/blocks/kanban).\n\nexport const STAGE_COLORS = ['gray', 'blue', 'violet', 'amber', 'rose', 'green'] as const;\nexport type StageColor = (typeof STAGE_COLORS)[number];\n\nexport interface KanbanStage {\n id: string;\n name: string;\n color: StageColor;\n position: number;\n}\n\nexport interface KanbanCard {\n id: string;\n stage_id: string;\n title: string;\n description: string;\n position: number;\n assignee_id: string | null;\n assignee_name: string | null;\n /** YYYY-MM-DD, or null. */\n start_date: string | null;\n due_date: string | null;\n created_by: string;\n created_by_name: string;\n updated_at: string;\n /** Whether the caller may delete it: its creator or an org owner/admin. */\n can_delete: boolean;\n}\n\n/** kanban_board: the stages in order and every card. */\nexport interface KanbanBoardData {\n stages: KanbanStage[];\n cards: KanbanCard[];\n}\n\n/** kanban_save_card params: no id creates a card at the end of its stage.\n * An empty string clears assignee_id, start_date or due_date. */\nexport interface KanbanCardInput {\n id?: string;\n stage_id: string;\n title: string;\n description?: string;\n assignee_id?: string;\n assignee_name?: string;\n start_date?: string;\n due_date?: string;\n}\n\n/** kanban_move_card params: the card lands in stage_id between after_id\n * (the card above it) and before_id (the card below it); either may be\n * left out at the ends of the stage. */\nexport interface KanbanMoveInput {\n id: string;\n stage_id: string;\n after_id?: string;\n before_id?: string;\n}\n\nexport interface KanbanStageInput {\n id?: string;\n name: string;\n color?: StageColor;\n}\n"
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
"path": "actions/kanban.ts",
|
|
355
|
+
"type": "registry:file",
|
|
356
|
+
"target": "actions/kanban.ts",
|
|
357
|
+
"content": "import {\n type KanbanBoardData,\n type KanbanCard,\n type KanbanCardInput,\n type KanbanMoveInput,\n type KanbanStage,\n type KanbanStageInput,\n STAGE_COLORS,\n} from '@shared/kanban';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// The kanban block (parall app add kanban): everyone in the organization\n// sees the board, adds, edits and moves cards and manages stages; a card is\n// deleted by its creator or an org owner/admin (not its assignee: anyone may\n// reassign a card, so that would let anyone delete it), a stage only once it\n// is empty. Tighten these here — the actions are the only gate.\n\nconst CARD_COLUMNS = `id, stage_id, title, description, position, assignee_id, assignee_name,\n to_char(start_date, 'YYYY-MM-DD') AS start_date, to_char(due_date, 'YYYY-MM-DD') AS due_date,\n created_by, created_by_name, updated_at`;\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst CAN_DELETE = `(created_by = $1 OR $2 IN ('owner', 'admin'))`;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n// Below this gap between neighbours a stage's positions are renumbered.\nconst MIN_GAP = 1e-6;\n\nfunction uuid(id: unknown, what: string): string {\n if (typeof id !== 'string' || !UUID.test(id))\n throw new ActionError(`This ${what} does not exist.`);\n return id;\n}\n\n/** '' clears the value; anything else must be a date. */\nfunction optionalDate(value: string | undefined, field: string): string | null {\n if (!value) return null;\n if (!DATE.test(value)) throw new ActionError(`${field} is not a date.`);\n return value;\n}\n\nasync function readCard(ctx: ActionContext, id: string): Promise<KanbanCard> {\n const { rows } = await ctx.db.query(\n `SELECT ${CARD_COLUMNS}, ${CAN_DELETE} AS can_delete FROM kanban_cards WHERE id = $3`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (!rows[0]) throw new ActionError('This card does not exist.');\n return rows[0] as unknown as KanbanCard;\n}\n\nexport const kanbanActions = {\n /** read: the stages in order and every card. */\n async kanban_board(ctx: ActionContext): Promise<KanbanBoardData> {\n const stages = await ctx.db.query(\n `SELECT id, name, color, position FROM kanban_stages ORDER BY position, created_at`,\n );\n const cards = await ctx.db.query(\n `SELECT ${CARD_COLUMNS}, ${CAN_DELETE} AS can_delete\n FROM kanban_cards\n ORDER BY stage_id, position, created_at, id\n LIMIT 2000`,\n [ctx.viewer.id, ctx.viewer.role],\n );\n return {\n stages: stages.rows as unknown as KanbanStage[],\n cards: cards.rows as unknown as KanbanCard[],\n };\n },\n\n /** write: creates a card at the end of its stage (no id) or edits one. */\n async kanban_save_card(ctx: ActionContext, input: KanbanCardInput): Promise<KanbanCard> {\n const title = input.title.trim();\n if (!title) throw new ActionError('A title is required.');\n const stageId = uuid(input.stage_id, 'stage');\n const startDate = optionalDate(input.start_date, 'start_date');\n const dueDate = optionalDate(input.due_date, 'due_date');\n if (startDate && dueDate && dueDate < startDate) {\n throw new ActionError('The due date is before the start date.');\n }\n const assigneeId = input.assignee_id || null;\n const assigneeName = assigneeId ? (input.assignee_name ?? '').trim() || null : null;\n const values = [\n stageId,\n title,\n (input.description ?? '').trim(),\n assigneeId,\n assigneeName,\n startDate,\n dueDate,\n ];\n if (input.id === undefined) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO kanban_cards\n (stage_id, title, description, assignee_id, assignee_name, start_date, due_date,\n position, created_by, created_by_name)\n SELECT $3::uuid, $4::text, $5::text, $6::text, $7::text, $8::date, $9::date,\n coalesce((SELECT max(position) FROM kanban_cards WHERE stage_id = $3), 0) + 1,\n $1::text, $10::text\n RETURNING ${CARD_COLUMNS}, ${CAN_DELETE} AS can_delete`,\n params: [ctx.viewer.id, ctx.viewer.role, ...values, ctx.viewer.display_name],\n },\n ]);\n return results[1]?.rows[0] as unknown as KanbanCard;\n }\n const id = uuid(input.id, 'card');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE kanban_cards\n SET stage_id = $3, title = $4, description = $5, assignee_id = $6,\n assignee_name = $7, start_date = $8, due_date = $9, updated_at = now(),\n position = CASE WHEN stage_id = $3 THEN position\n ELSE coalesce((SELECT max(position) FROM kanban_cards WHERE stage_id = $3), 0) + 1 END\n WHERE id = $10\n RETURNING ${CARD_COLUMNS}, ${CAN_DELETE} AS can_delete`,\n params: [ctx.viewer.id, ctx.viewer.role, ...values, id],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('This card does not exist.');\n return row as unknown as KanbanCard;\n },\n\n /** write: moves a card into a stage, between two of its cards. */\n async kanban_move_card(ctx: ActionContext, input: KanbanMoveInput): Promise<KanbanCard> {\n const id = uuid(input.id, 'card');\n const stageId = uuid(input.stage_id, 'stage');\n const afterId = input.after_id ? uuid(input.after_id, 'card') : null;\n const beforeId = input.before_id ? uuid(input.before_id, 'card') : null;\n // One read for the stage and both neighbours, renumbering the stage\n // first when its positions have grown too close.\n const neighbours = async () => {\n const { rows } = await ctx.db.query(\n `SELECT (SELECT position FROM kanban_cards WHERE id = $2 AND stage_id = $1) AS after_pos,\n (SELECT position FROM kanban_cards WHERE id = $3 AND stage_id = $1) AS before_pos,\n (SELECT max(position) FROM kanban_cards WHERE stage_id = $1 AND id <> $4) AS last_pos,\n EXISTS (SELECT 1 FROM kanban_stages WHERE id = $1) AS stage_exists`,\n [stageId, afterId, beforeId, id],\n );\n return rows[0] as {\n after_pos: number | null;\n before_pos: number | null;\n last_pos: number | null;\n stage_exists: boolean;\n };\n };\n let n = await neighbours();\n if (!n.stage_exists) throw new ActionError('This stage does not exist.');\n if (n.after_pos !== null && n.before_pos !== null && n.before_pos - n.after_pos < MIN_GAP) {\n await ctx.db.exec(\n `UPDATE kanban_cards c SET position = r.n\n FROM (SELECT id, row_number() OVER (ORDER BY position, created_at) AS n\n FROM kanban_cards WHERE stage_id = $1) r\n WHERE c.id = r.id`,\n [stageId],\n );\n n = await neighbours();\n }\n const position =\n n.after_pos !== null && n.before_pos !== null\n ? (n.after_pos + n.before_pos) / 2\n : n.after_pos !== null\n ? n.after_pos + 1\n : n.before_pos !== null\n ? n.before_pos - 1\n : (n.last_pos ?? 0) + 1;\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE kanban_cards SET stage_id = $3, position = $4, updated_at = now()\n WHERE id = $5\n RETURNING ${CARD_COLUMNS}, ${CAN_DELETE} AS can_delete`,\n params: [ctx.viewer.id, ctx.viewer.role, stageId, position, id],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('This card does not exist.');\n return row as unknown as KanbanCard;\n },\n\n /** write: deletes a card (its creator or an org owner/admin). */\n async kanban_delete_card(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'card');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM kanban_cards WHERE id = $3 AND ${CAN_DELETE}`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (rows_affected === 0) {\n await readCard(ctx, id);\n throw new ActionError('Only its creator or an org admin can delete this card.');\n }\n return { id };\n },\n\n /** write: adds a stage at the end (no id) or renames / recolors one. */\n async kanban_save_stage(ctx: ActionContext, input: KanbanStageInput): Promise<KanbanStage> {\n const name = input.name.trim();\n if (!name) throw new ActionError('A stage needs a name.');\n const color = input.color ?? 'gray';\n if (!STAGE_COLORS.includes(color)) throw new ActionError(`Unknown color ${color}.`);\n const { rows } =\n input.id === undefined\n ? await ctx.db.exec(\n `INSERT INTO kanban_stages (name, color, position)\n SELECT $1::text, $2::text, coalesce((SELECT max(position) FROM kanban_stages), 0) + 1\n RETURNING id, name, color, position`,\n [name, color],\n )\n : await ctx.db.exec(\n `UPDATE kanban_stages SET name = $1, color = $2 WHERE id = $3\n RETURNING id, name, color, position`,\n [name, color, uuid(input.id, 'stage')],\n );\n if (!rows[0]) throw new ActionError('This stage does not exist.');\n return rows[0] as unknown as KanbanStage;\n },\n\n /** write: puts the stages in the given order. */\n async kanban_reorder_stages(\n ctx: ActionContext,\n params: { ids: string[] },\n ): Promise<{ ok: true }> {\n const ids = params.ids.map((id) => uuid(id, 'stage'));\n if (ids.length > 49) throw new ActionError('A board can reorder at most 49 stages at once.');\n await ctx.db.batch(\n ids.map((id, i) => ({\n sql: 'UPDATE kanban_stages SET position = $1 WHERE id = $2',\n params: [i + 1, id],\n })),\n );\n return { ok: true };\n },\n\n /** write: deletes an empty stage. */\n async kanban_delete_stage(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'stage');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM kanban_stages s\n WHERE s.id = $1 AND NOT EXISTS (SELECT 1 FROM kanban_cards c WHERE c.stage_id = s.id)`,\n [id],\n );\n if (rows_affected === 0)\n throw new ActionError('Move or delete its cards before deleting a stage.');\n return { id };\n },\n};\n"
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
"path": "db/kanban.sql",
|
|
361
|
+
"type": "registry:file",
|
|
362
|
+
"target": "db/kanban.sql",
|
|
363
|
+
"content": "-- The kanban block's tables (PostgreSQL). Apply, safe to run again:\n-- parall app db exec --app <app_…> --file db/kanban.sql\n-- Rename the default stages below to the team's own before applying (for a\n-- hiring pipeline: Applied, Screening, Interview, Offer, Hired…); people\n-- can add, rename and reorder stages on the board later.\n\n-- People who used the app (shared with the base scaffold's db/schema.sql);\n-- the board offers them as assignees.\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE TABLE IF NOT EXISTS kanban_stages (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n name text NOT NULL CHECK (length(name) BETWEEN 1 AND 60),\n color text NOT NULL DEFAULT 'gray'\n CHECK (color IN ('gray', 'blue', 'violet', 'amber', 'rose', 'green')),\n position double precision NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Cards are ordered by position inside their stage; a move puts a card\n-- between its new neighbours (actions/kanban.ts kanban_move_card).\nCREATE TABLE IF NOT EXISTS kanban_cards (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n stage_id uuid NOT NULL REFERENCES kanban_stages (id),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n description text NOT NULL DEFAULT '',\n position double precision NOT NULL,\n assignee_id text,\n assignee_name text,\n start_date date,\n due_date date,\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS kanban_cards_stage_idx ON kanban_cards (stage_id, position);\n\n-- The first stages, only when the board has none.\nINSERT INTO kanban_stages (name, color, position)\nSELECT name, color, position\n FROM (VALUES ('To do', 'gray', 1), ('In progress', 'blue', 2), ('Review', 'amber', 3), ('Done', 'green', 4))\n AS defaults (name, color, position)\n WHERE NOT EXISTS (SELECT 1 FROM kanban_stages);\n\n-- Everyone in the organization reads the board, adds, edits and moves\n-- cards and manages stages; a card is deleted by its creator or an org\n-- owner/admin, a stage only once it is empty (actions/kanban.ts).\n-- To restrict stage changes to admins, check isOrgAdmin(ctx.viewer) there.\n"
|
|
364
|
+
}
|
|
365
|
+
],
|
|
366
|
+
"docs": "Rename the default stages in db/kanban.sql to the team's own, then create the tables with `parall app db exec --app <app_…> --file db/kanban.sql` and `pnpm install && pnpm build`. Everyone in the organization edits and moves cards and manages stages; a card is deleted by its creator or an org owner/admin (actions/kanban.ts). Open a card with prll://app_…#board/<card id>.",
|
|
367
|
+
"meta": {
|
|
368
|
+
"parall": {
|
|
369
|
+
"page": {
|
|
370
|
+
"import": "import { kanbanPage } from '@/blocks/kanban';",
|
|
371
|
+
"entry": "kanbanPage"
|
|
372
|
+
},
|
|
373
|
+
"actions": {
|
|
374
|
+
"import": "import { kanbanActions } from './kanban';",
|
|
375
|
+
"entry": "...kanbanActions"
|
|
376
|
+
},
|
|
377
|
+
"sql": "db/kanban.sql",
|
|
378
|
+
"functions": {
|
|
379
|
+
"kanban_board": {
|
|
380
|
+
"kind": "read"
|
|
381
|
+
},
|
|
382
|
+
"kanban_save_card": {
|
|
383
|
+
"kind": "write",
|
|
384
|
+
"params": {
|
|
385
|
+
"type": "object",
|
|
386
|
+
"properties": {
|
|
387
|
+
"id": {
|
|
388
|
+
"type": "string",
|
|
389
|
+
"maxLength": 64
|
|
390
|
+
},
|
|
391
|
+
"stage_id": {
|
|
392
|
+
"type": "string",
|
|
393
|
+
"maxLength": 64
|
|
394
|
+
},
|
|
395
|
+
"title": {
|
|
396
|
+
"type": "string",
|
|
397
|
+
"minLength": 1,
|
|
398
|
+
"maxLength": 200
|
|
399
|
+
},
|
|
400
|
+
"description": {
|
|
401
|
+
"type": "string",
|
|
402
|
+
"maxLength": 5000
|
|
403
|
+
},
|
|
404
|
+
"assignee_id": {
|
|
405
|
+
"type": "string",
|
|
406
|
+
"maxLength": 64
|
|
407
|
+
},
|
|
408
|
+
"assignee_name": {
|
|
409
|
+
"type": "string",
|
|
410
|
+
"maxLength": 200
|
|
411
|
+
},
|
|
412
|
+
"start_date": {
|
|
413
|
+
"type": "string",
|
|
414
|
+
"maxLength": 10
|
|
415
|
+
},
|
|
416
|
+
"due_date": {
|
|
417
|
+
"type": "string",
|
|
418
|
+
"maxLength": 10
|
|
419
|
+
}
|
|
420
|
+
},
|
|
421
|
+
"required": [
|
|
422
|
+
"stage_id",
|
|
423
|
+
"title"
|
|
424
|
+
]
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
"kanban_move_card": {
|
|
428
|
+
"kind": "write",
|
|
429
|
+
"params": {
|
|
430
|
+
"type": "object",
|
|
431
|
+
"properties": {
|
|
432
|
+
"id": {
|
|
433
|
+
"type": "string",
|
|
434
|
+
"maxLength": 64
|
|
435
|
+
},
|
|
436
|
+
"stage_id": {
|
|
437
|
+
"type": "string",
|
|
438
|
+
"maxLength": 64
|
|
439
|
+
},
|
|
440
|
+
"after_id": {
|
|
441
|
+
"type": "string",
|
|
442
|
+
"maxLength": 64
|
|
443
|
+
},
|
|
444
|
+
"before_id": {
|
|
445
|
+
"type": "string",
|
|
446
|
+
"maxLength": 64
|
|
447
|
+
}
|
|
448
|
+
},
|
|
449
|
+
"required": [
|
|
450
|
+
"id",
|
|
451
|
+
"stage_id"
|
|
452
|
+
]
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
"kanban_delete_card": {
|
|
456
|
+
"kind": "write",
|
|
457
|
+
"params": {
|
|
458
|
+
"type": "object",
|
|
459
|
+
"properties": {
|
|
460
|
+
"id": {
|
|
461
|
+
"type": "string",
|
|
462
|
+
"maxLength": 64
|
|
463
|
+
}
|
|
464
|
+
},
|
|
465
|
+
"required": [
|
|
466
|
+
"id"
|
|
467
|
+
]
|
|
468
|
+
}
|
|
469
|
+
},
|
|
470
|
+
"kanban_save_stage": {
|
|
471
|
+
"kind": "write",
|
|
472
|
+
"params": {
|
|
473
|
+
"type": "object",
|
|
474
|
+
"properties": {
|
|
475
|
+
"id": {
|
|
476
|
+
"type": "string",
|
|
477
|
+
"maxLength": 64
|
|
478
|
+
},
|
|
479
|
+
"name": {
|
|
480
|
+
"type": "string",
|
|
481
|
+
"minLength": 1,
|
|
482
|
+
"maxLength": 60
|
|
483
|
+
},
|
|
484
|
+
"color": {
|
|
485
|
+
"type": "string",
|
|
486
|
+
"enum": [
|
|
487
|
+
"gray",
|
|
488
|
+
"blue",
|
|
489
|
+
"violet",
|
|
490
|
+
"amber",
|
|
491
|
+
"rose",
|
|
492
|
+
"green"
|
|
493
|
+
]
|
|
494
|
+
}
|
|
495
|
+
},
|
|
496
|
+
"required": [
|
|
497
|
+
"name"
|
|
498
|
+
]
|
|
499
|
+
}
|
|
500
|
+
},
|
|
501
|
+
"kanban_reorder_stages": {
|
|
502
|
+
"kind": "write",
|
|
503
|
+
"params": {
|
|
504
|
+
"type": "object",
|
|
505
|
+
"properties": {
|
|
506
|
+
"ids": {
|
|
507
|
+
"type": "array",
|
|
508
|
+
"items": {
|
|
509
|
+
"type": "string",
|
|
510
|
+
"maxLength": 64
|
|
511
|
+
},
|
|
512
|
+
"minItems": 1,
|
|
513
|
+
"maxItems": 49
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
"required": [
|
|
517
|
+
"ids"
|
|
518
|
+
]
|
|
519
|
+
}
|
|
520
|
+
},
|
|
521
|
+
"kanban_delete_stage": {
|
|
522
|
+
"kind": "write",
|
|
523
|
+
"params": {
|
|
524
|
+
"type": "object",
|
|
525
|
+
"properties": {
|
|
526
|
+
"id": {
|
|
527
|
+
"type": "string",
|
|
528
|
+
"maxLength": 64
|
|
529
|
+
}
|
|
530
|
+
},
|
|
531
|
+
"required": [
|
|
532
|
+
"id"
|
|
533
|
+
]
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
];
|