@parall/cli 1.78.0 → 1.79.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.
Files changed (33) hide show
  1. package/dist/commands/apps-access.d.ts +8 -0
  2. package/dist/commands/apps-access.d.ts.map +1 -0
  3. package/dist/commands/apps-access.js +141 -0
  4. package/dist/commands/apps-actions.d.ts +5 -3
  5. package/dist/commands/apps-actions.d.ts.map +1 -1
  6. package/dist/commands/apps-actions.js +5 -3
  7. package/dist/commands/apps-dev-page.d.ts +2 -0
  8. package/dist/commands/apps-dev-page.d.ts.map +1 -1
  9. package/dist/commands/apps-dev-page.js +3 -3
  10. package/dist/commands/apps-dev-server.d.ts +10 -1
  11. package/dist/commands/apps-dev-server.d.ts.map +1 -1
  12. package/dist/commands/apps-dev-server.js +26 -3
  13. package/dist/commands/apps-dev.d.ts +12 -1
  14. package/dist/commands/apps-dev.d.ts.map +1 -1
  15. package/dist/commands/apps-dev.js +25 -10
  16. package/dist/commands/apps-page-sdk.generated.d.ts +1 -1
  17. package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -1
  18. package/dist/commands/apps-page-sdk.generated.js +1 -1
  19. package/dist/commands/apps-templates.gen.js +18 -18
  20. package/dist/commands/apps.d.ts +3 -2
  21. package/dist/commands/apps.d.ts.map +1 -1
  22. package/dist/commands/apps.js +10 -3
  23. package/dist/commands/chat-connections.d.ts +11 -0
  24. package/dist/commands/chat-connections.d.ts.map +1 -0
  25. package/dist/commands/chat-connections.js +162 -0
  26. package/dist/commands/chats.d.ts.map +1 -1
  27. package/dist/commands/chats.js +6 -1
  28. package/dist/commands/search.d.ts.map +1 -1
  29. package/dist/commands/search.js +1 -1
  30. package/dist/lib/output.d.ts +11 -0
  31. package/dist/lib/output.d.ts.map +1 -1
  32. package/dist/lib/output.js +32 -5
  33. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
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",
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;`useCanEdit()` 在看的人只能查看这个 app 时为 false,用来藏起编辑按钮,写类 action 仍由平台拒绝)、`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
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
4
  "_gitignore": "node_modules\ndist\n*.log\n# Secrets for local runs; never commit them.\n.dev.vars*\n",
5
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",
@@ -40,14 +40,14 @@ export const TEMPLATE_BASE = {
40
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
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
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",
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, org role and\n * access ('read' or 'write' on this app). */\nexport function useViewer(): ViewerSummary {\n return useHost().viewer;\n}\n\n/** Whether the viewer may change this app's data: false for someone who can\n * only view it. Use it to hide buttons that would call a write action — the\n * platform refuses their write actions anyway, so it is never the gate. A\n * host that does not say counts as true (every app could be changed by\n * everyone before access levels). */\nexport function useCanEdit(): boolean {\n return useViewer().access !== 'read';\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
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
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",
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 case 'PERMISSION_DENIED':\n // The viewer can only view this app: Parall refused a write action.\n // Hide such buttons with useCanEdit(); this is what a page says when\n // one was not hidden.\n return { message: t('errorViewOnly'), code, invocationId };\n default:\n return { message: raw, code, invocationId };\n }\n}\n",
47
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
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
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",
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 errorViewOnly:\n 'You can only view this app, so your change was not saved. To change its data, ask one of its authors or an org owner/admin to let you edit it.',\n viewOnly: 'You can only view this app.',\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 errorViewOnly:\n '你只能查看这个应用,刚才的修改没有保存。要改数据,请它的作者或组织 owner / admin 把你设成「可改」。',\n viewOnly: '你只能查看这个应用。',\n errorReference: '编号:{id}',\n hostMissingTitle: '请在 Parall 里打开这个应用',\n hostMissingBody:\n '这个页面通过 Parall 宿主读写数据。请从 Parall 打开它,或用 parall app dev --dist dist 在本地试用。',\n connecting: '正在连接 Parall…',\n },\n});\n",
51
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
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
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",
@@ -58,7 +58,7 @@ export const TEMPLATE_BASE = {
58
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
59
  };
60
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 默认:100 秒、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",
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 会被平台拒绝,页面用 `useCanEdit()` 把会写的按钮藏起来;能改的人之间谁能改什么,仍写在 action 里。读类 action 能做的事,能打开 app 的人都能触发:有副作用的外呼放写类 action。`db/schema.sql` 末尾有「创建者或管理员可改」与「访问名单」两种写法;`actions/people.ts` 的 `rememberViewer` 在保存(新建、修改、移动)时记下调用者,`people_list` 列出这样用过 app 的人,可以拿来选负责人或分享对象。\n\n## 限额(超了就报错)\n\n- 一次 action 默认:100 秒、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 看得到完整消息与堆栈。写类调用的参数记进调用记录,能打开 app 的人都能查:不要经参数传凭据。\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 已更新,宿主会提示看的人重新加载)、`PERMISSION_DENIED`(看的人只能查看这个 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
62
  "_overlay.json": "{\n \"remove\": [\"src/pages/home\"]\n}\n",
63
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
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",
@@ -71,12 +71,12 @@ export const TEMPLATE_WITH_ACTIONS = {
71
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
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
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",
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 { useCanEdit } from '@/hooks/use-host';\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 // Someone who can only view the app changes nothing; among those who can,\n // the action's own rule (can_edit) decides per item.\n const canEdit = useCanEdit();\n const editable = canEdit && item.can_edit;\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 {canEdit && !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 {editable ? (\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
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",
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 { useCanEdit } from '@/hooks/use-host';\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 canEdit = useCanEdit();\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={!canEdit || !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 { useCanEdit } from '@/hooks/use-host';\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. Someone who can\n * only view the app sees no button that would write (useCanEdit).\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 const canEdit = useCanEdit();\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 newItem = canEdit ? (\n <Button onClick={() => setEditing('new')}>\n <Plus />\n {t('newItem')}\n </Button>\n ) : undefined;\n const header = <PageHeader title={t('title')} description={t('description')} actions={newItem} />;\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={canEdit ? t('emptyBody') : t('emptyBodyViewOnly')}\n action={newItem}\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
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",
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 emptyBodyViewOnly: 'Nothing has been added yet.',\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 emptyBodyViewOnly: '还没有人添加。',\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
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
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
82
  };
@@ -103,19 +103,19 @@ export const TEMPLATE_BLOCKS = [
103
103
  "path": "src/blocks/calendar/CalendarPage.tsx",
104
104
  "type": "registry:component",
105
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"
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 { useCanEdit } from '@/hooks/use-host';\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. Someone who can only\n * view the app gets no way to create an event and opens events read-only.\n */\nexport function CalendarPage({ route }: PageProps) {\n const compact = useIsMobile();\n const canEdit = useCanEdit();\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 {canEdit ? (\n <Button size=\"sm\" onClick={() => createOn(newAt)}>\n <Plus />\n <span className=\"sr-only sm:not-sr-only\">{t('newEvent')}</span>\n </Button>\n ) : null}\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={canEdit ? createOn : undefined}\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={canEdit ? createAt : undefined}\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
107
  },
108
108
  {
109
109
  "path": "src/blocks/calendar/MonthView.tsx",
110
110
  "type": "registry:component",
111
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"
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 /** Starts an event on a day; left out for someone who can only view. */\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 {onCreate ? (\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 ) : null}\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
113
  },
114
114
  {
115
115
  "path": "src/blocks/calendar/WeekView.tsx",
116
116
  "type": "registry:component",
117
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"
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 /** Starts an event at an hour; left out for someone who can only view. */\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 onCreate ? (\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 <div\n key={hour}\n className=\"absolute inset-x-0 border-border/60 border-t\"\n style={{ top: hour * HOUR_PX, height: HOUR_PX }}\n />\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
119
  },
120
120
  {
121
121
  "path": "src/blocks/calendar/AgendaView.tsx",
@@ -127,7 +127,7 @@ export const TEMPLATE_BLOCKS = [
127
127
  "path": "src/blocks/calendar/EventDialog.tsx",
128
128
  "type": "registry:component",
129
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"
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 { useCanEdit } from '@/hooks/use-host';\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 — anyone who\n * can only view the app, and those the action's own rule (can_edit) keeps\n * out. */\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 canEdit = useCanEdit();\n const event = draft?.mode === 'edit' ? draft.event : null;\n const readOnly = !canEdit || (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 {canEdit ? t('readOnly') : common('viewOnly')}\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
131
  },
132
132
  {
133
133
  "path": "src/blocks/calendar/dates.ts",
@@ -306,25 +306,25 @@ export const TEMPLATE_BLOCKS = [
306
306
  "path": "src/blocks/kanban/KanbanPage.tsx",
307
307
  "type": "registry:component",
308
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"
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 { useCanEdit, 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 * Someone who can only view the app sees the board and opens cards, with no\n * control that would write (useCanEdit).\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 canEdit = useCanEdit();\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 canEdit ? (\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 ) : undefined\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={canEdit ? t('noStagesBody') : t('noStagesBodyViewOnly')}\n action={\n canEdit ? (\n <Button onClick={() => setStagesOpen(true)}>\n <Settings2 />\n {t('stages')}\n </Button>\n ) : undefined\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
310
  },
311
311
  {
312
312
  "path": "src/blocks/kanban/KanbanBoard.tsx",
313
313
  "type": "registry:component",
314
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"
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 { useCanEdit } from '@/hooks/use-host';\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. Nobody drags who can only view the app. */\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 canEdit = useCanEdit();\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 && canEdit ? 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 const canEdit = useCanEdit();\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 {canEdit ? (\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 ) : null}\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 canEdit = useCanEdit();\n const drag = draggable && canEdit;\n const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({\n id: card.id,\n disabled: !drag,\n });\n return (\n <div\n ref={setNodeRef}\n style={{ transform: CSS.Transform.toString(transform), transition }}\n {...(drag ? { ...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={drag}\n onMove={onMove}\n onOpen={onOpen}\n onDelete={onDelete}\n />\n </div>\n );\n}\n"
316
316
  },
317
317
  {
318
318
  "path": "src/blocks/kanban/CardView.tsx",
319
319
  "type": "registry:component",
320
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"
321
+ "content": "import type { KanbanCard, KanbanStage } from '@shared/kanban';\nimport { ArrowRight, CalendarClock, Ellipsis, Pencil, Trash2 } from 'lucide-react';\nimport type { KeyboardEvent } from '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 { useCanEdit } from '@/hooks/use-host';\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 — no menu for someone\n * who can only view the app. */\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 const canEdit = useCanEdit();\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; with no menu (someone who\n // can only view the app), Enter or Space opens it.\n const keyboardOpen = canEdit\n ? {}\n : {\n role: 'button',\n tabIndex: 0,\n onKeyDown: (e: KeyboardEvent) => {\n if (e.key !== 'Enter' && e.key !== ' ') return;\n e.preventDefault();\n onOpen(card);\n },\n };\n return (\n <div\n onClick={() => onOpen(card)}\n {...keyboardOpen}\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 {canEdit ? (\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 ) : null}\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
322
  },
323
323
  {
324
324
  "path": "src/blocks/kanban/CardDialog.tsx",
325
325
  "type": "registry:component",
326
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"
327
+ "content": "import type { KanbanCard, KanbanCardInput, KanbanStage } from '@shared/kanban';\nimport { Lock, 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 { useCanEdit } from '@/hooks/use-host';\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; read-only for\n * someone who can only view the app. */\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 readOnly = !useCanEdit();\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 (readOnly || !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={readOnly ? t('cardDetails') : card ? t('editCard') : t('newCard')}\n footer={\n readOnly ? (\n <Button variant=\"outline\" onClick={onClose}>\n {common('close')}\n </Button>\n ) : (\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 >\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 {common('viewOnly')}\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={!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 </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 );\n}\n"
328
328
  },
329
329
  {
330
330
  "path": "src/blocks/kanban/StagesDialog.tsx",
@@ -342,7 +342,7 @@ export const TEMPLATE_BLOCKS = [
342
342
  "path": "src/blocks/kanban/messages.ts",
343
343
  "type": "registry:lib",
344
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"
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 cardDetails: '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 noStagesBodyViewOnly: 'The board has no stages yet.',\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 cardDetails: '卡片详情',\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 noStagesBodyViewOnly: '看板还没有阶段。',\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
346
  },
347
347
  {
348
348
  "path": "shared/kanban.ts",