AIStoreHub Package Vault: Doop
Package Slug: doop
Archetype: mcp_server
Upstream Repository: https://github.com/kgoedecke/doop
Workspace Files & Specifications (68 files)
- aistorehub.json (495 bytes)
{ "name": "Doop", "slug": "doop", "version": "1.0.0", "type": "mcp_server", "description": "The open-source alternative to Paper.design. A multiplayer design canvas where humans and AI agents design together, live. MCP built in.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/kgoedecke/doop", "tags": [ "trending", "typescript", "github", "open-source", "kgoedecke" ], "imported_at": "2026-11-22T00:08:32.806Z" } - CHANGELOG.md (110309 bytes)
# Changelog ## [0.15.0](https://github.com/kgoedecke/doop/compare/v0.14.0...v0.15.0) (2026-11-16) ### Features * **admin:** sign-in policy — email/password sign-up, SSO auto-redirect, default workspace ([#372](https://github.com/kgoedecke/doop/issues/372)) ([5ce1770](https://github.com/kgoedecke/doop/commit/5ce177037c9d28caa4a1302795fc6eeaf26d3d1a)) * **agent:** connect DeepSeek and Kimi keys and a Kimi Code plan ([#453](https://github.com/kgoedecke/doop/issues/453)) ([f4278e2](https://github.com/kgoedecke/doop/commit/f4278e29d5a36a357dc9e8851a96297d30e12f23)) * **agent:** custom providers for any OpenAI- or Anthropic-compatible API ([#498](https://github.com/kgoedecke/doop/issues/498)) ([436215d](https://github.com/kgoedecke/doop/commit/436215d0a5d297e9b85c2168d7e91e2678feee55)) * **agent:** describe uploaded images for agents ([#392](https://github.com/kgoedecke/doop/issues/392)) ([b1b278a](https://github.com/kgoedecke/doop/commit/b1b278afcee8e65c986bca2fdbfc643c938f54b8)) * **agents:** ask agents to style elements inline, with a stylesheet for the rest ([#487](https://github.com/kgoedecke/doop/issues/487)) ([7b98fb6](https://github.com/kgoedecke/doop/commit/7b98fb6d713b074520723f16650cf62dd92ab795)) * **agents:** chat history in the Agents tab ([#511](https://github.com/kgoedecke/doop/issues/511)) ([8042a25](https://github.com/kgoedecke/doop/commit/8042a25cce7b4e2f5bdf844bab7c4f579cfdebba)) * **agents:** custom agents, and switching off or editing the built-in team ([#510](https://github.com/kgoedecke/doop/issues/510)) ([802d7a2](https://github.com/kgoedecke/doop/commit/802d7a2ad61cca3301e70b0584a234fab6596971)) * **agents:** refuse base64 data URIs in frame writes, add upload_font ([#518](https://github.com/kgoedecke/doop/issues/518)) ([443f772](https://github.com/kgoedecke/doop/commit/443f7725de24791a00ec80882016773949fde9ed)) * **agents:** reuse an established canvas's style when adding to it ([#515](https://github.com/kgoedecke/doop/issues/515)) ([4db75e7](https://github.com/kgoedecke/doop/commit/4db75e7b146b5abc67bde88da025a64198ddaff2)) * **agents:** set up a component system before screens, with create_components ([#573](https://github.com/kgoedecke/doop/issues/573)) ([4704080](https://github.com/kgoedecke/doop/commit/47040807d7b2336ef512715353a8b4ae267963f4)) * **agents:** show each agent's client logo, add Grok, opencode and Pi marks ([#507](https://github.com/kgoedecke/doop/issues/507)) ([61aab2e](https://github.com/kgoedecke/doop/commit/61aab2e655c2faef08197b605be96266ad3158cd)) * **agents:** warn at the write about blocks and colours to reuse ([#501](https://github.com/kgoedecke/doop/issues/501)) ([9ad1e46](https://github.com/kgoedecke/doop/commit/9ad1e46d03d9067ffcc12ad8bfb5359eea5a2b47)) * **analytics:** count the newer features in PostHog ([#460](https://github.com/kgoedecke/doop/issues/460)) ([a1edc79](https://github.com/kgoedecke/doop/commit/a1edc79ced4444b63d0f959ffb25fc658f17b3ea)) * **android:** add the native Doop app with shared Blitz rendering ([#556](https://github.com/kgoedecke/doop/issues/556)) ([81952f0](https://github.com/kgoedecke/doop/commit/81952f0119635067f130007b096c78a1d73615c2)) * **billing:** charge for an added seat right away ([#479](https://github.com/kgoedecke/doop/issues/479)) ([10c7fa6](https://github.com/kgoedecke/doop/commit/10c7fa6ce6738be3f15e98c8018832b82bec499a)) * **billing:** make upgrading to Pro easy to find, and give Pro real perks ([#571](https://github.com/kgoedecke/doop/issues/571)) ([8fcdefc](https://github.com/kgoedecke/doop/commit/8fcdefc1118a89dcda1ab0a2e28241cb8ceec4d7)) * **canvas:** action registry with ⌘K palette, main menu and editor shortcuts ([#448](https://github.com/kgoedecke/doop/issues/448)) ([1970798](https://github.com/kgoedecke/doop/commit/1970798b4f13c65c90654116d1dcf0ae634856c0)) * **canvas:** drop Code from the element toolbar ([#558](https://github.com/kgoedecke/doop/issues/558)) ([3e008e3](https://github.com/kgoedecke/doop/commit/3e008e3dfcfdd6c479ecd5e6ee11b922a6aa955e)) * **canvas:** move the way back to the canvases into the main menu ([#479](https://github.com/kgoedecke/doop/issues/479)) ([a25d94c](https://github.com/kgoedecke/doop/commit/a25d94c4f0fcde4a4a628516acf9ec47c34ab7a4)) * **canvas:** pages in the URL, and a library canvas opens on its components ([#505](https://github.com/kgoedecke/doop/issues/505)) ([96bfa8d](https://github.com/kgoedecke/doop/commit/96bfa8de33d59bfb081a77a59171b0ab0d479c1e)) * **canvas:** place hand-drawn layers absolute and group them as flex ([#544](https://github.com/kgoedecke/doop/issues/544)) ([1874364](https://github.com/kgoedecke/doop/commit/187436457e95846ac53f78f06fd40f3438f2a911)) * **comments:** comment on a frame from its name with the Comment tool ([#451](https://github.com/kgoedecke/doop/issues/451)) ([3b135d3](https://github.com/kgoedecke/doop/commit/3b135d3f763a1692ddf56e1132610789e8388628)) * **components:** a frame keeps its sign-off when a component it uses changes ([#532](https://github.com/kgoedecke/doop/issues/532)) ([7c753fa](https://github.com/kgoedecke/doop/commit/7c753fa0a725ed8bff8aead8e23b3af6229a89d5)) * **components:** add reusable components for people and agents ([#423](https://github.com/kgoedecke/doop/issues/423)) ([d641f07](https://github.com/kgoedecke/doop/commit/d641f0718a95b1667e85916a23c3926b6f2e65a5)) * **components:** import from another canvas through a canvas list and picker ([#575](https://github.com/kgoedecke/doop/issues/575)) ([6ae4a74](https://github.com/kgoedecke/doop/commit/6ae4a74d6e1cc3716a2c298177e39a93456b49af)) * **components:** match the component section to the inspector's fields ([#495](https://github.com/kgoedecke/doop/issues/495)) ([9af5ec1](https://github.com/kgoedecke/doop/commit/9af5ec146ee1c9bb947b1b9e94d57e5673a34250)) * **components:** name an instance's layer from its Layers row ([#491](https://github.com/kgoedecke/doop/issues/491)) ([d5f0b47](https://github.com/kgoedecke/doop/commit/d5f0b478ad8393cabda6a7610b8d80a48664c446)) * **components:** rename a component from the editor ([#486](https://github.com/kgoedecke/doop/issues/486)) ([ba2691d](https://github.com/kgoedecke/doop/commit/ba2691d15c7d89e081d0b4defeef1c943fb083a5)) * **components:** search at the bottom of the Components tab, its actions at the top ([#500](https://github.com/kgoedecke/doop/issues/500)) ([1366b1e](https://github.com/kgoedecke/doop/commit/1366b1e54b3508793e770baee3eed5cfe31e172c)) * **components:** workspace component library ([#502](https://github.com/kgoedecke/doop/issues/502)) ([9a18dce](https://github.com/kgoedecke/doop/commit/9a18dceb0000d51724b24555dee73e2f2574e83a)) * **desktop:** ⌘, (Ctrl+, on Windows and Linux) opens Settings ([#541](https://github.com/kgoedecke/doop/issues/541)) ([e5e9e53](https://github.com/kgoedecke/doop/commit/e5e9e53191acade39dc54debd0ef3397843d2b35)) * **desktop:** ⌘1 opens Home and ⌘2…⌘9 switch canvas tabs ([#537](https://github.com/kgoedecke/doop/issues/537)) ([f753ec3](https://github.com/kgoedecke/doop/commit/f753ec38e65211730ca97e7ca70cd622596f0b24)) * **desktop:** choose the Doop server from the sign-in screen ([#452](https://github.com/kgoedecke/doop/issues/452)) ([f98867a](https://github.com/kgoedecke/doop/commit/f98867a0917c36fcb2e1139b2f984a3ef9b4f0da)) * **export:** export a layer from the Design panel and over MCP (export_layer) ([#509](https://github.com/kgoedecke/doop/issues/509)) ([1deb970](https://github.com/kgoedecke/doop/commit/1deb9703685ef7e2ae65450f7823bfca13639247)) * **home:** let the drafts menu take any count ([#561](https://github.com/kgoedecke/doop/issues/561)) ([fbcd23f](https://github.com/kgoedecke/doop/commit/fbcd23f63f72c006b6e1bb8d4729046e523a2059)) * **images:** choose a gpt image model on an openai api key, through the image api ([#550](https://github.com/kgoedecke/doop/issues/550)) ([7177ac2](https://github.com/kgoedecke/doop/commit/7177ac2a96636a73609ae6807dee58e1a32538d1)) * **images:** serve search_images photos from Doop's origin ([#503](https://github.com/kgoedecke/doop/issues/503)) ([3bffc7b](https://github.com/kgoedecke/doop/commit/3bffc7b7983d15f5177ba41f0bbdfc32e902d150)) * **inspector:** number fields double as sliders; icons scrub ([#543](https://github.com/kgoedecke/doop/issues/543)) ([9d26b82](https://github.com/kgoedecke/doop/commit/9d26b8265a086a147b96c3259d6e859551236124)) * **ios:** show agents at work on their frames ([#469](https://github.com/kgoedecke/doop/issues/469)) ([f0ceec6](https://github.com/kgoedecke/doop/commit/f0ceec64e08c6cc747a66ec10a4a2f0f467626b8)) * **logos:** read .ico favicons and store logo favicons as PNG ([#453](https://github.com/kgoedecke/doop/issues/453)) ([a2d5b0d](https://github.com/kgoedecke/doop/commit/a2d5b0d21b5cda9bdfb68041250c6a352e0b48e3)) * **mcp:** let agents set frame approval when a person asks ([#546](https://github.com/kgoedecke/doop/issues/546)) ([debb2e2](https://github.com/kgoedecke/doop/commit/debb2e204add3eaf9ca6c1713eef079cfa632f7a)) * **mcp:** short server instructions, and a main guide with topics on demand ([#567](https://github.com/kgoedecke/doop/issues/567)) ([5f6a6cb](https://github.com/kgoedecke/doop/commit/5f6a6cb99154f2327633100472288457cf8f0315)) * **rail:** agents wear their brand's app tile ([#540](https://github.com/kgoedecke/doop/issues/540)) ([bace84c](https://github.com/kgoedecke/doop/commit/bace84c56732ad071825f4d2676eca1c975a9e76)) * **screenshot:** render in a remote Chrome over CDP (Cloudflare Browser Run) ([#458](https://github.com/kgoedecke/doop/issues/458)) ([653c7ed](https://github.com/kgoedecke/doop/commit/653c7edcfb1abd7eb7b266fb39bfff4793004403)) * **settings:** delete your account from Settings → Your account ([#497](https://github.com/kgoedecke/doop/issues/497)) ([df6a4ca](https://github.com/kgoedecke/doop/commit/df6a4ca4a86966848ac34e41e68d64918c9a8a9a)) * **settings:** reorder the settings rail ([#492](https://github.com/kgoedecke/doop/issues/492)) ([14d9f06](https://github.com/kgoedecke/doop/commit/14d9f063035792686268a75606ea0386b323e583)) * **shell:** suggest the native app from the browser ([#490](https://github.com/kgoedecke/doop/issues/490)) ([74c51f4](https://github.com/kgoedecke/doop/commit/74c51f4f33faded6cf2b3e0aced278a2894130e7)) * **text:** start a list when - , * or 1. is typed at the start of a line ([#496](https://github.com/kgoedecke/doop/issues/496)) ([bf646e4](https://github.com/kgoedecke/doop/commit/bf646e437626d47e488dba91b16bf60c16c70189)) ### Bug Fixes * **agent:** keep the composer from flying to a component's main ([#516](https://github.com/kgoedecke/doop/issues/516)) ([d41d7fe](https://github.com/kgoedecke/doop/commit/d41d7febe14d40e9e1db71d8fb1ac1f9ee46c36a)) * **agent:** raise the resident step limit and finish runs whose work is done ([#517](https://github.com/kgoedecke/doop/issues/517)) ([e17dc2b](https://github.com/kgoedecke/doop/commit/e17dc2b940fb49e18a330cec96008112f2af5233)) * **canvas:** ⌥⇧-drag duplicates the picked layer, not its frame ([#454](https://github.com/kgoedecke/doop/issues/454)) ([8bc1536](https://github.com/kgoedecke/doop/commit/8bc1536c6d8b818064a869423f66c97c2935e88b)) * **canvas:** an open comment thread paints above every frame ([#568](https://github.com/kgoedecke/doop/issues/568)) ([f6f9918](https://github.com/kgoedecke/doop/commit/f6f99182fb6ae13b14577de5dbf0acc9d5291f5d)) * **canvas:** drag every picked layer together, not just the one pressed ([#471](https://github.com/kgoedecke/doop/issues/471)) ([29bd283](https://github.com/kgoedecke/doop/commit/29bd2839594ed06426d9c4848e7da0aed4178cc0)) * **canvas:** draw the frame size badge above neighbouring frames ([#460](https://github.com/kgoedecke/doop/issues/460)) ([9e5b041](https://github.com/kgoedecke/doop/commit/9e5b04156808dfe13ce71ecac7a7de6bc00b0a62)) * **canvas:** drop the light seam along a frame's edge ([#440](https://github.com/kgoedecke/doop/issues/440)) ([b05127f](https://github.com/kgoedecke/doop/commit/b05127f28510a6911c4ad8a0fafa95a61b24c45b)) * **canvas:** frames never show a scrollbar ([#542](https://github.com/kgoedecke/doop/issues/542)) ([24c60f3](https://github.com/kgoedecke/doop/commit/24c60f396681ae7b881f6904710c7908850a7161)) * **canvas:** keep comments and canvas UI above the pixel grid ([#466](https://github.com/kgoedecke/doop/issues/466)) ([6d03257](https://github.com/kgoedecke/doop/commit/6d0325772938eeb411a1b68bc7228d01e7c1a509)) * **canvas:** keep the element panel through a frame drag and relay shortcuts from inside frames ([#411](https://github.com/kgoedecke/doop/issues/411)) ([4391435](https://github.com/kgoedecke/doop/commit/4391435f486dcbf3f0e58b70ba9632d5a8cebf91)) * **canvas:** let a style edit win over a stylesheet rule marked !important ([#484](https://github.com/kgoedecke/doop/issues/484)) ([e78a96a](https://github.com/kgoedecke/doop/commit/e78a96acbbe1bc45e6d089971fbced06cf754ccf)) * **canvas:** panels scroll without a visible scrollbar ([#547](https://github.com/kgoedecke/doop/issues/547)) ([4bbabd8](https://github.com/kgoedecke/doop/commit/4bbabd824d39a523bbfe9908faf98ac9298495d9)) * **canvas:** patch a dragged follower's style by its element ([8440e31](https://github.com/kgoedecke/doop/commit/8440e314c1b60bd044d286e02012f54cc06b9b7e)) * **canvas:** root vector strokes spill past their box; root group picks don't flicker ([#559](https://github.com/kgoedecke/doop/issues/559)) ([f1f2ec4](https://github.com/kgoedecke/doop/commit/f1f2ec4b3d8b6c9611a9bb4618fc660ef018e868)) * **comments:** prevent agent pill outlines from clipping ([#531](https://github.com/kgoedecke/doop/issues/531)) ([2576d9d](https://github.com/kgoedecke/doop/commit/2576d9da3f5184219769e0b7f57b22b75e6b4961)) * **components:** background propagation, work budget, stall watchdog and soft delete ([#519](https://github.com/kgoedecke/doop/issues/519)) ([5f3ebda](https://github.com/kgoedecke/doop/commit/5f3ebda2c5869afde32185825cc04c4f31bb9d14)) * **components:** bind image props by a bare name, report a doop-use that renders nothing ([#504](https://github.com/kgoedecke/doop/issues/504)) ([99bd698](https://github.com/kgoedecke/doop/commit/99bd698d5ea352f0150524620864b7739fc639e4)) * **components:** bring instances a lost propagation left behind up to date after boot ([#536](https://github.com/kgoedecke/doop/issues/536)) ([b237298](https://github.com/kgoedecke/doop/commit/b2372985a87de2360f183f797d06880e0eb3740e)) * **components:** components whose root is a table cell or row ([#535](https://github.com/kgoedecke/doop/issues/535)) ([5d1923d](https://github.com/kgoedecke/doop/commit/5d1923d55bfc530cdcefc98808737f4951943720)) * **components:** expand every instance after a Turkish capital dotted I ([#526](https://github.com/kgoedecke/doop/issues/526)) ([4c61605](https://github.com/kgoedecke/doop/commit/4c61605fe880a14ef6c42d107e8c30dbef51c37e)) * **components:** fix four component review findings: inline fonts, detach, imports, main moves ([2b257e2](https://github.com/kgoedecke/doop/commit/2b257e2b
- CLA.md (3024 bytes)
# Doop Individual Contributor License Agreement Thank you for your interest in contributing to Doop ("the Project"), maintained by Kevin Goedecke ("the Maintainer"). By signing this Contributor License Agreement (CLA) — via the automated check on your pull request — you accept the following terms for your present and future Contributions submitted to the Project. Except for the licenses granted here, **you retain all right, title and interest in your Contributions.** ## 1. Definitions **"Contribution"** means any original work of authorship, including any modifications or additions to existing work, that you intentionally submit to the Project for inclusion in it. **"You"** means the individual (or the legal entity you are authorized to represent) signing this agreement. ## 2. Grant of copyright license You grant the Maintainer and recipients of software distributed by the Project a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, **sublicense and distribute your Contributions and derivative works under any license terms** — including open-source licenses and commercial/proprietary licenses. ## 3. Grant of patent license You grant the Maintainer and recipients of software distributed by the Project a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated below) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer your Contribution, where such license applies only to those patent claims licensable by you that are necessarily infringed by your Contribution alone or in combination with the Project. If any entity institutes patent litigation alleging that the Project or a Contribution constitutes patent infringement, any patent licenses granted to that entity under this agreement terminate. ## 4. Your representations You represent that: - you are legally entitled to grant the above licenses; - each Contribution is your original creation, or you have identified any third-party material and its license in the Contribution; - if your employer has rights to intellectual property you create, you have permission to make the Contribution on its behalf, or your employer has waived such rights. You are not expected to provide support for your Contributions. Unless required by applicable law or agreed to in writing, your Contributions are provided **"AS IS"**, without warranties or conditions of any kind. ## 5. Notice You agree to notify the Maintainer if any of the above representations become inaccurate. --- _Why a CLA? The Project is licensed under AGPL-3.0 and always will be for the code already released. The CLA additionally lets the Maintainer offer the software under other terms (for example a commercial license) and keep the Project sustainable — without having to track down every past contributor for permission. You keep the copyright to your work._ - CLAUDE.md (1978 bytes)
@.context/INDEX.md This is a placeholder. Will need to be updated. https://github.com/kgoedecke/doop # doop Doop is the open-source alternative to Paper.design: a multiplayer design canvas for humans and AI agents. Every design lives on a shareable Canvas (`/c/<id>`) holding Frames - artboards that render real HTML in sandboxed iframes. People edit in the browser; AI agents edit through the built-in MCP server, streaming designs in live. Everyone sees cursors, presence, frame edits, agent status, and an activity feed in realtime over one WebSocket room per canvas. ## Tech stack TypeScript/React/Express/Postgres (drizzle), realtime over `ws`, MCP server for agent access, Tauri desktop shell. Full details in `.context/TECHSTACK.md`, which `.context/INDEX.md` links. Always use the `clean-code:typescript` skill when writing or reviewing TypeScript code in this repo. ## First-time setup after clone ```bash bun install bun run dev # zero-config: embedded Postgres (pglite), server + web concurrently ``` Or self-host via Docker: `docker compose up` (real Postgres, port 4400). ## Project layout ``` src/ - React frontend (Vite entry: index.html) src/components/ui/ - shadcn-generated UI primitives src/pages/ - route-level pages src/hooks/ - React hooks src/lib/ - client-side utilities server/ - Express backend, WebSocket room, MCP server, better-auth server/db/ - drizzle-orm schema (schema.ts, auth-schema.ts) and migrations shared/ - types/utilities shared between server and client desktop/ - Tauri desktop app wrapper desktop/src-tauri/ - Rust side of the desktop app scripts/ - repo maintenance scripts tests/ - vitest test suite ``` ## Language TypeScript. Always use the `clean-code:typescript` skill when writing or reviewing TypeScript code. Formatter and lint rules are captured in `.context/CODESTYLE.md`, which `.context/INDEX.md` links.
- CODE_OF_CONDUCT.md (2662 bytes)
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement by contacting the maintainer through GitHub (a private vulnerability report or direct message to [@kgoedecke](https://github.com/kgoedecke)). All complaints will be reviewed and investigated promptly and fairly. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
- commitlint.config.js (64 bytes)
export default { extends: ['@commitlint/config-conventional'] } - components.json (517 bytes)
{ "$schema": "https://ui.shadcn.com/schema.json", "style": "radix-nova", "rsc": false, "tsx": true, "tailwind": { "config": "", "css": "src/styles.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "iconLibrary": "lucide", "rtl": false, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "menuColor": "default", "menuAccent": "subtle", "registries": {} } - CONTRIBUTING.md (1504 bytes)
# Contributing ## Contributor License Agreement First-time contributors are asked to sign our [CLA](CLA.md) — a bot comments on your first pull request and signing is a single reply (`I have read the CLA Document and I hereby sign the CLA`). In short: **you keep the copyright to your work** and grant the maintainer the right to distribute it under other terms too (e.g. a commercial license). The released code stays AGPL-3.0; the CLA is what keeps dual-licensing possible without chasing every past contributor. Unsigned PRs can't be merged. ## Commit messages Commits follow [Conventional Commits](https://www.conventionalcommits.org/), enforced by commitlint via a git hook: ``` feat: add frame snap guides fix(server): close stale websocket rooms chore: bump dependencies ``` Common types: `feat`, `fix`, `chore`, `refactor`, `style`, `docs`, `test`, `ci`, `perf`. ## Code style - **Prettier** formats everything (`bun run format`); no semicolons, single quotes, 120 columns. - **oxlint** (`bun run lint`, type-aware via tsgolint) covers TS + React hooks; a slim ESLint run adds the `process.env` ban. Warnings fail CI like errors. - **`bun run typecheck`** must pass. A pre-commit hook (husky + lint-staged) runs ESLint and Prettier on staged files, and a commit-msg hook validates the message. Hooks install automatically via `bun install` (the `prepare` script). CI runs typecheck, lint, format check, build and the test suite (in four shards) as parallel jobs on every push and PR.
- cursor-plugin/skills/doop-design/SKILL.md (1955 bytes)
--- name: doop-design description: Create, inspect, and refine HTML designs on a shared Doop canvas. Use when the user asks to work in Doop, provides a Doop canvas URL, or asks to implement a design from a Doop canvas in their codebase. --- # Doop design Use the connected `doop` MCP server for Doop work. The server provides the current tool schemas and design guidance; do not substitute local HTML files for edits the user requested on a shared canvas. 1. Call `get_guide({ topic: "doop-instructions" })` before other Doop tools and follow the returned workflow. Reload it if the conversation has lost that context. 2. Use the canvas ID from the user's `/c/<id>` URL or explicit canvas ID. If they have not identified a canvas, use the available discovery tools and ask them to choose when the target is ambiguous. Do not guess or create a replacement canvas for an existing design. 3. Pick one `agent_name` and keep it consistent. Read the canvas with `get_canvas`, then fetch its relevant guidelines and references before designing. Announce progress with `set_status` as described by the server. 4. Make the requested changes through the available Doop tools. Inspect the rendered result with `get_frame_screenshot`, correct visual issues, and respond to feedback from people on the canvas. Clear your status when finished. 5. When the user asks to implement a Doop design in their codebase, inspect the source frame and its screenshot first, then follow the repository's conventions. Modify the shared canvas only when the user requests design changes. 6. Finish with a link to the canvas and a brief description of the work completed. If Doop tools are missing or authentication fails, ask the user to enable the Doop MCP server in Cursor's Customize panel and complete its browser sign-in. Do not request tokens in chat. This plugin connects to `https://doop.design/mcp`; local and self-hosted Doop instances use their own server connection. - docker-compose.yml (1475 bytes)
# One-command self-host: `docker compose up` → http://localhost:4400 # Set BETTER_AUTH_SECRET (any long random string) before running in earnest: # BETTER_AUTH_SECRET=$(openssl rand -hex 32) docker compose up -d services: doop: build: . ports: - '4400:4400' environment: DATABASE_URL: postgres://doop:doop@db:5432/doop BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:-change-me-please-not-for-production} BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:4400} SIGNUP_EMAIL_DOMAINS: ${SIGNUP_EMAIL_DOMAINS:-} # interface language for anyone who has not picked one: en (default) | pt-BR DEFAULT_LOCALE: ${DEFAULT_LOCALE:-} # optional — see .env.example for everything else (SMTP, ANTHROPIC_API_KEY, …) ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-} CONTEXT_DEV_API_KEY: ${CONTEXT_DEV_API_KEY:-} SMTP_HOST: ${SMTP_HOST:-} SMTP_PORT: ${SMTP_PORT:-} SMTP_USER: ${SMTP_USER:-} SMTP_PASS: ${SMTP_PASS:-} EMAIL_FROM: ${EMAIL_FROM:-} depends_on: db: condition: service_healthy restart: unless-stopped db: image: postgres:16-alpine environment: POSTGRES_USER: doop POSTGRES_PASSWORD: doop POSTGRES_DB: doop volumes: - doop-pg:/var/lib/postgresql/data healthcheck: test: ['CMD-SHELL', 'pg_isready -U doop'] interval: 5s timeout: 3s retries: 10 restart: unless-stopped volumes: doop-pg: - Dockerfile (2577 bytes)
# ---- build the client ---- FROM oven/bun:1 AS build WORKDIR /app COPY package.json bun.lock ./ RUN bun install --frozen-lockfile COPY . . # Vite inlines these at build time, so they must be present *here*, not at # runtime — without them the bundle ships with analytics silently disabled. # Railway matches these ARG names against the service variables and passes # them in; Docker exposes them to RUN, which is where vite reads them. # The project key is a public, write-only token that ships to every visitor # in the JS bundle regardless; it is not a secret. # VITE_POSTHOG_HOST is deliberately left unset: the client then defaults to # the same-origin /relay proxy, which is what defeats ad blockers. Setting # it to a posthog.com host would bypass the relay and resurrect blocking. ARG VITE_POSTHOG_KEY ARG VITE_POSTHOG_HOST # comma-separated email domains whose sessions skip replay (operator accounts) ARG VITE_POSTHOG_INTERNAL_DOMAINS RUN bun run build # ---- runtime dependencies ---- # Installed by bun, but into a plain node_modules the Node runtime below reads # directly — bun is the package manager here, not the runtime. FROM oven/bun:1 AS deps WORKDIR /app COPY package.json bun.lock ./ RUN bun install --frozen-lockfile --production # ---- runtime ---- # Node, not bun: the server runs under tsx, and puppeteer-core, PGlite and ws # are exercised on Node in CI and in every dev session. FROM node:22-slim WORKDIR /app # Chromium for get_frame_screenshot (puppeteer-core drives the system browser). # Its fonts are what screenshots, thumbnails and PDF exports fall back to when a # frame's own font lacks a glyph: Liberation for the metric-compatible basics, # DejaVu for symbols (arrows, geometric shapes, dingbats; without it ✕ □ ⟶ draw # as empty boxes and ↗ as an emoji), Noto Color Emoji for emoji. RUN apt-get update \ && apt-get install -y --no-install-recommends chromium \ fonts-liberation fonts-dejavu-core fonts-noto-color-emoji \ && rm -rf /var/lib/apt/lists/* ENV NODE_ENV=production \ CHROME_PATH=/usr/bin/chromium \ CHROME_NO_SANDBOX=1 \ PORT=4400 COPY package.json ./ COPY --from=deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist COPY server ./server COPY shared ./shared EXPOSE 4400 HEALTHCHECK --interval=30s --timeout=5s CMD node -e "fetch('http://localhost:'+process.env.PORT+'/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" # the installed binary rather than npx: npm is not what resolves packages here CMD ["node_modules/.bin/tsx", "server/index.ts"] - drizzle.config.ts (432 bytes)
import { defineConfig } from 'drizzle-kit' /** Migration generation only: `npx drizzle-kit generate` after editing * server/db/schema.ts or auth-schema.ts. Migrations are applied at boot by * server/db/index.ts (both PGlite and real Postgres), never by drizzle-kit. */ export default defineConfig({ dialect: 'postgresql', schema: ['./server/db/schema.ts', './server/db/auth-schema.ts'], out: './server/db/migrations', }) - eslint.config.js (9798 bytes)
import tseslint from 'typescript-eslint' /* Screens compose primitives from src/components/ui; they do not draw their own buttons, fields or sizes. The dashboard surfaces (Home, the rail, the search palette, Automations, Settings, Community, Integrations) are on the component layer and the rule below holds them there. The files listed here are the canvas editor's chrome and the modals around it, which have not been migrated yet (a separate pass): they are exempt until that pass takes each one off this list. Add nothing new here. */ const LEGACY_CHROME = [ /* the canvas editor and its panels */ 'src/pages/CanvasPage.tsx', 'src/components/ActivityPanel.tsx', 'src/components/CanvasComments.tsx', 'src/components/CanvasDrawing.tsx', 'src/components/CodePanel.tsx', 'src/components/CommentPopovers.tsx', 'src/components/CommentsPanel.tsx', 'src/components/Cursors.tsx', 'src/components/DesktopTabs.tsx', 'src/components/ElementPanel.tsx', 'src/components/FlowOverlay.tsx', 'src/components/FollowFrame.tsx', 'src/components/FrameView.tsx', 'src/components/GhostFrames.tsx', 'src/components/Inspector.tsx', 'src/components/LayersPanel.tsx', 'src/components/LivePresence.tsx', 'src/components/MemoryPanel.tsx', 'src/components/PagesPanel.tsx', 'src/components/PathEditor.tsx', 'src/components/PeerAvatars.tsx', 'src/components/PromptBar.tsx', 'src/components/SideRail.tsx', 'src/components/Stage.tsx', 'src/components/TopBar.tsx', 'src/components/WorkingNow.tsx', 'src/components/ZoomControls.tsx', /* the modals and flows that open over the editor */ 'src/components/ConnectModal.tsx', 'src/components/CursorInstall.tsx', 'src/components/ExportModal.tsx', 'src/components/FrameExportModal.tsx', 'src/components/FrameHistoryModal.tsx', 'src/components/ImportSources.tsx', 'src/components/LocalClaude.tsx', 'src/components/Onboarding.tsx', /* the automation editor */ 'src/pages/AutomationEditor.tsx', /* settings panes and the signed-out screens: small, next in line */ 'src/components/ModelAccount.tsx', 'src/components/TeamAllowance.tsx', 'src/pages/Admin.tsx', 'src/pages/AuthPage.tsx', 'src/pages/DesktopHandoff.tsx', 'src/pages/DesktopSignIn.tsx', 'src/pages/Workspace.tsx', ] const COMPONENT_LAYER_MESSAGE = 'Compose the primitives in src/components/ui (Button, IconButton, Pressable, Input, SearchField, Textarea, Select…) instead of a raw element.' const TYPE_SCALE_MESSAGE = 'Use the named type scale (text-micro … text-display) and corner shapes (rounded-row/control/pill/card/panel) from .context/DESIGN.md, not an arbitrary size.' const STOCK_TYPE_MESSAGE = "Use the named type scale (text-micro … text-display) from .context/DESIGN.md, not Tailwind's stock sizes: text-xs is text-label or text-caption, text-sm is text-body or text-copy, text-lg is text-lead or text-heading." const STOCK_RADIUS_MESSAGE = "Use the named corner shapes (rounded-row/control/pill/card/panel) from .context/DESIGN.md, not Tailwind's stock radii (rounded, rounded-sm/md/lg/xl)." const LINE_MESSAGE = 'Each step of the type scale carries its own line height and tracking; drop leading-[…] and tracking-[…] (a leading modifier such as text-body/4 is the one adjustment, per .context/DESIGN.md).' const WEIGHT_MESSAGE = 'Use 400 for text and font-medium for labels, buttons and emphasis; font-semibold is for card and modal headings only, and nothing goes heavier (.context/DESIGN.md).' const COLOUR_MESSAGE = 'Use a colour token (bg-line, text-ink-soft, bg-brand, bg-success, border-line…) from .context/DESIGN.md, not a hex value: tokens flip with the theme.' const ROLE_MESSAGE = 'Use Pressable (or Button / IconButton) from src/components/ui instead of role="button" or role="link" on a plain element: it brings the keyboard handling and the focus ring.' /* One class-name pattern, matched in string literals and in template-literal chunks alike (className strings, cn() and cva() arguments). The prefix lets a variant (`md:`, `hover:`, `[&>svg]:`) or Tailwind's `!` sit before the utility. esquery reads a regex up to the next slash, so patterns avoid `/`. */ function classSelectors(pattern, message) { const regex = `/(^|[\\s:!])${pattern}/` return [ { selector: `Literal[value=${regex}]`, message }, { selector: `TemplateElement[value.cooked=${regex}]`, message }, ] } /* a stock utility name ends at whitespace, a modifier slash, a quote or the end of the string, so `text-smoke` or `rounded-full` never match */ const END = '($|[^\\w-])' /* the rule: raw elements, a plain element dressed up as a button or link, arbitrary and stock type sizes and radii, hand-set line height and tracking, heavy weights, and hex colours */ const COMPONENT_LAYER_SELECTORS = [ { selector: 'JSXOpeningElement[name.name=/^(button|input|select|textarea)$/]', message: COMPONENT_LAYER_MESSAGE, }, /* role="button", and the braced role={'button'} form */ { selector: "JSXOpeningElement[name.name=/^[a-z]/] > JSXAttribute[name.name='role'][value.value=/^(button|link)$/]", message: ROLE_MESSAGE, }, { selector: "JSXOpeningElement[name.name=/^[a-z]/] > JSXAttribute[name.name='role'][value.expression.value=/^(button|link)$/]", message: ROLE_MESSAGE, }, { selector: "JSXOpeningElement[name.name=/^[a-z]/] > JSXAttribute[name.name='role'] > JSXExpressionContainer > TemplateLiteral[expressions.length=0] > TemplateElement[value.cooked=/^(button|link)$/]", message: ROLE_MESSAGE, }, /* `text-[#…]` is a colour, which the hex selector reports instead */ ...classSelectors('(text|rounded(-[trblse]{1,2})?)-\\[[^#]', TYPE_SCALE_MESSAGE), ...classSelectors(`text-(xs|sm|base|lg|xl|\\dxl)${END}`, STOCK_TYPE_MESSAGE), ...classSelectors(`rounded(-[trblse]{1,2})?(-(sm|md|lg|xl|\\dxl))?${END}`, STOCK_RADIUS_MESSAGE), ...classSelectors('(leading|tracking)-\\[', LINE_MESSAGE), ...classSelectors('font-(bold|extrabold|black|\\[)', WEIGHT_MESSAGE), ...classSelectors('(bg|text|border)-\\[#', COLOUR_MESSAGE), ] /* oxlint (`.oxlintrc.json`) carries the rule set, including the type-aware rules via tsgolint. ESLint stays for what oxlint cannot cover: the `no-restricted-syntax` selector below, and `no-undef` for the plain JavaScript that no type check sees (oxlint's is still a nursery rule). No type information is loaded, so this run is cheap. */ export default tseslint.config( { ignores: [ 'dist/', 'node_modules/', 'desktop/src-tauri/target/', 'desktop/src-tauri-chromium/target/', 'storybook-static/', ], }, { files: ['**/*.{js,mjs,cjs}'], rules: { 'no-undef': 'error' }, }, { files: ['chrome-extension/**/*.js'], languageOptions: { globals: Object.fromEntries( 'chrome window document navigator Node Element getComputedStyle HTMLImageElement HTMLInputElement HTMLTextAreaElement TextEncoder' .split(' ') .map((g) => [g, 'readonly']), ), }, }, { /* repo maintenance scripts, the iOS dev helpers and the desktop release scripts: plain ESM run directly by node or bun, so they get node globals rather than the browser set */ files: ['scripts/**/*.{js,mjs}', 'ios/scripts/**/*.{js,mjs}', 'desktop/scripts/**/*.{js,mjs}'], languageOptions: { globals: Object.fromEntries( 'process console Buffer URL fetch setTimeout clearTimeout setInterval clearInterval' .split(' ') .map((g) => [g, 'readonly']), ), }, }, { /* the embeddable snippet: plain browser JS shipped as-is, no bundling — ES5-flavoured on purpose so it runs wherever the host app does */ files: ['public/**/*.js'], languageOptions: { globals: Object.fromEntries( ( 'window document location history localStorage fetch console setTimeout clearTimeout ' + 'matchMedia URL JSON Date Math FileReader Promise MutationObserver' ) .split(' ') .map((g) => [g, 'readonly']), ), }, }, { /* every environment variable is declared once in server/env.ts, typed and validated at boot; the rest of the server reads `env.X` from there. The Gemini cloud worker is its own process with its own three variables. */ files: ['server/**/*.ts'], ignores: ['server/env.ts', 'server/geminiCloudWorker.ts', 'server/geminiCloudWorkerMain.ts'], languageOptions: { parser: tseslint.parser }, rules: { 'no-restricted-syntax': [ 'error', { selector: "MemberExpression[object.name='process'][property.name='env']", message: 'Read environment variables through `env` from server/env.ts, which validates them at boot.', }, ], }, }, { /* the component layer: a screen under src/pages, src/components or src/integrations uses the ui primitives, not <button>/<input>/<select>/ <textarea> or a role="button" div, sizes type and corners with the named steps (no text-[Npx] / rounded-[Npx], no stock text-sm / rounded-lg, no leading-[…] / tracking-[…]), stops at font-semibold, and colours with tokens, not hex. The primitives themselves (src/components/ui) are where raw elements and exact values belong; the editor chrome waits for its own pass (LEGACY_CHROME above). Stories are the catalogue, not screens. */ files: ['src/pages/**/*.tsx', 'src/components/**/*.tsx', 'src/integrations/**/*.tsx'], ignores: ['src/components/ui/**', ...LEGACY_CHROME], languageOptions: { parser: tseslint.parser }, rules: { 'no-restricted-syntax': ['error', ...COMPONENT_LAYER_SELECTORS] }, }, ) - index.html (2085 bytes)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> <meta name="color-scheme" content="light dark" /> <!-- Paints the saved theme before the bundle loads, so a reload never flashes light. src/lib/theme.ts owns the key and takes over after. --> <script> ;(function () { try { var saved = localStorage.getItem('doop-theme') var dark = saved === 'dark' || (saved !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches) document.documentElement.classList.toggle('dark', dark) document.documentElement.style.colorScheme = dark ? 'dark' : 'light' } catch (e) {} })() </script> <title>Doop — designed by Agents & Humans</title> <meta name="description" content="Doop is a multiplayer design canvas where people and AI agents create side by side. Agents join through MCP as yours — every frame streams in live, with tasks, statuses and feedback flowing both ways." /> <meta property="og:title" content="Doop — designed by Agents & Humans" /> <meta property="og:description" content="A multiplayer design canvas where people and AI agents create side by side. Connect any MCP agent and watch it design live." /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Hanken+Grotesk:wght@300&family=Geist+Mono:wght@400;500&display=swap" rel="stylesheet" /> <link rel="icon" href="/favicon.ico" sizes="32x32" /> <link rel="icon" href="/favicon.png" type="image/png" sizes="96x96" /> <link rel="apple-touch-icon" href="/apple-touch-icon.png" /> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html> - INSTRUCTIONS.md (1955 bytes)
--- name: doop-design description: Create, inspect, and refine HTML designs on a shared Doop canvas. Use when the user asks to work in Doop, provides a Doop canvas URL, or asks to implement a design from a Doop canvas in their codebase. --- # Doop design Use the connected `doop` MCP server for Doop work. The server provides the current tool schemas and design guidance; do not substitute local HTML files for edits the user requested on a shared canvas. 1. Call `get_guide({ topic: "doop-instructions" })` before other Doop tools and follow the returned workflow. Reload it if the conversation has lost that context. 2. Use the canvas ID from the user's `/c/<id>` URL or explicit canvas ID. If they have not identified a canvas, use the available discovery tools and ask them to choose when the target is ambiguous. Do not guess or create a replacement canvas for an existing design. 3. Pick one `agent_name` and keep it consistent. Read the canvas with `get_canvas`, then fetch its relevant guidelines and references before designing. Announce progress with `set_status` as described by the server. 4. Make the requested changes through the available Doop tools. Inspect the rendered result with `get_frame_screenshot`, correct visual issues, and respond to feedback from people on the canvas. Clear your status when finished. 5. When the user asks to implement a Doop design in their codebase, inspect the source frame and its screenshot first, then follow the repository's conventions. Modify the shared canvas only when the user requests design changes. 6. Finish with a link to the canvas and a brief description of the work completed. If Doop tools are missing or authentication fails, ask the user to enable the Doop MCP server in Cursor's Customize panel and complete its browser sign-in. Do not request tokens in chat. This plugin connects to `https://doop.design/mcp`; local and self-hosted Doop instances use their own server connection. - LICENSE (34523 bytes)
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a cons - package.json (3878 bytes)
{ "name": "doop", "version": "0.15.0", "private": true, "type": "module", "packageManager": "[email protected]", "scripts": { "dev": "bun run build:claude-extension && concurrently -n server,web -c yellow,cyan \"tsx watch --env-file-if-exists=.env server/index.ts\" \"vite\"", "build": "bun run build:claude-extension && vite build", "build:claude-extension": "node scripts/build-claude-extension.mjs", "start": "NODE_ENV=production tsx server/index.ts", "typecheck": "tsgo --noEmit", "test": "vitest run", "test:linux": "sh scripts/test-linux.sh", "lint": "oxlint --type-aware --deny-warnings . && eslint . --max-warnings 0", "lint:fix": "oxlint --type-aware --deny-warnings --fix . && eslint . --fix", "format": "prettier --write .", "format:check": "prettier --check .", "doc-lint": "node scripts/doc-lint.mjs", "storybook": "storybook dev -p 6006 --no-open", "build-storybook": "storybook build", "prepare": "husky || true" }, "lint-staged": { "*.{ts,tsx,js}": [ "oxlint --type-aware --deny-warnings", "eslint --max-warnings 0 --no-warn-ignored", "prettier --write" ], "*.{json,css,md,html}": [ "prettier --write" ] }, "dependencies": { "@anthropic-ai/sdk": "^0.115.0", "@aws-sdk/client-s3": "^3.1110.0", "@electric-sql/pglite": "^0.5.4", "@modelcontextprotocol/sdk": "^1.12.0", "@radix-ui/react-alert-dialog": "^1.1.23", "@radix-ui/react-collapsible": "^1.1.20", "@radix-ui/react-context-menu": "^2.3.7", "@radix-ui/react-dialog": "^1.1.23", "@radix-ui/react-dropdown-menu": "^2.1.24", "@radix-ui/react-popover": "^1.3.1", "@radix-ui/react-progress": "^1.1.16", "@radix-ui/react-select": "2.3.7", "@radix-ui/react-slot": "^1.3.3", "@radix-ui/react-switch": "1.3.7", "@radix-ui/react-tabs": "^1.1.21", "@radix-ui/react-toggle-group": "^1.1.19", "@radix-ui/react-tooltip": "^1.2.16", "better-auth": "1.6.26", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "css-select": "5.1.0", "drizzle-orm": "^0.45.2", "envalid": "8.2.0", "express": "^4.19.2", "jose": "6.2.10", "jszip": "^3.10.2", "lucide-react": "^1.59.0", "mupdf": "^1.28.1", "nanoid": "^5.0.7", "nodemailer": "^9.0.5", "parse5": "^8.0.1", "pdf-lib": "1.17.1", "pg": "^8.22.0", "posthog-js": "^1.415.6", "puppeteer-core": "^25.5.0", "react": "^18.3.1", "react-dom": "^18.3.1", "sharp": "0.34.3", "stripe": "21.0.1", "tailwind-merge": "^3.6.0", "tsx": "^4.23.9", "undici": "^8.10.2", "ws": "^8.18.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.25.2", "zustand": "^4.5.4" }, "devDependencies": { "@commitlint/cli": "^21.2.2", "@commitlint/config-conventional": "^21.2.2", "@storybook/addon-a11y": "10.6.3", "@storybook/addon-docs": "10.6.3", "@storybook/react-vite": "10.6.3", "@tailwindcss/vite": "^4.3.3", "@types/express": "^4.17.21", "@types/node": "^20.14.10", "@types/nodemailer": "^8.0.1", "@types/pg": "^8.20.4", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", "@types/ws": "^8.5.10", "@typescript/native-preview": "^7.0.0-dev.20260707.2", "@vitejs/plugin-react": "^6.1.2", "concurrently": "^8.2.2", "drizzle-kit": "0.31.10", "esbuild": "^0.28.2", "eslint": "^10.8.1", "happy-dom": "^20.14.5", "husky": "^9.1.7", "lint-staged": "^17.3.0", "mcp-remote": "0.15.1", "oxlint": "^1.87.0", "oxlint-tsgolint": "^7.0.2003", "prettier": "^3.9.6", "shadcn": "^4.19.0", "storybook": "10.6.3", "tailwindcss": "^4.3.3", "tw-animate-css": "^1.4.0", "typescript": "^5.5.3", "typescript-eslint": "^8.67.0", "vite": "^8.3.4", "vitest": "^5.0.3" } } - README.md (86074 bytes)
<p align="center"> <img src=".github/assets/banner.png" alt="Doop, the open-source alternative to Paper.design: a live canvas where Claude Code streams a pricing section while ChatGPT and Claude Code cursors move across the frames" width="100%"> </p> <p align="center"> <a href="https://github.com/kgoedecke/doop/actions/workflows/ci.yml"><img src="https://github.com/kgoedecke/doop/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0-111110" alt="License: AGPL-3.0"></a> <a href="https://doop.design"><img src="https://img.shields.io/badge/cloud-doop.design-2743EE" alt="Doop Cloud"></a> <a href="CONTRIBUTING.md"><img src="https://img.shields.io/badge/PRs-welcome-111110" alt="PRs welcome"></a> <a href="https://discord.com/invite/3AUfXjgVe"><img src="https://img.shields.io/badge/chat-Discord-5865F2" alt="Discord"></a> </p> **[Doop](https://doop.design/?utm_source=github) is the open-source alternative to [Paper.design](https://paper.design) — a multiplayer design canvas for humans _and_ AI agents.** Every design lives on a shareable **Canvas** (`/c/<id>`) holding **Frames** — artboards that render real HTML in sandboxed iframes. People edit in the browser; AI agents edit through the built-in **MCP server**, streaming their designs in live. Everyone sees everything as it happens: cursors, presence, frame edits, agent status, and an activity feed. Think of it as Claude Design for whichever agent you already use: **Claude Code, Codex, ChatGPT, Cursor, OpenCode** or any other MCP client designs on the same canvas, and the built-in Doop Agent runs on **GPT, Claude, Gemini, DeepSeek, Kimi or Qwen** models ([every agent and model](#works-with-any-agent)). <p align="center"> <img src=".github/assets/canvas.png" alt="A Doop canvas with three frames for a travel app (landing hero, mobile itinerary and a booking card) and two collaborators' live cursors" width="100%"> </p> - **Design with agents, not prompts-and-refresh** — connect Claude Code (or any MCP client) once, then watch it sketch, stream and self-review designs on your canvas, next to your cursor. - **A built-in Doop Agent** — queue a card or @mention a role and it designs on its own, no client to connect. Runs on the model account each user connects (a **ChatGPT subscription**, or an OpenAI, Claude, Gemini, DeepSeek, Kimi or OpenRouter key), or on the server's `ANTHROPIC_API_KEY` for as many free tasks as `RESIDENT_TASK_LIMIT` grants (none by default) ([setup](#the-doop-agent)); the first-canvas welcome performance is scripted and runs without any of it. - **Pages within a canvas** — organize frames into named pages from the Layers panel. Add, rename, drag to reorder, or double-click to rename. Right-click for page actions, including copying a link, without switching away from the open page. Page edits support Undo/Redo; selected frames can move between pages. Agents can list pages with `get_canvas`, manage them with `set_canvas_pages` (passing the original list as `expectedPages` to protect collaborators), and target frames with `pageId`. Each page can wear a canvas colour of its own, as in Figma: with nothing selected, the sliders icon on the right opens the Page panel with its Background swatch (agents: `set_page_background`); cleared, the page shows the theme paper again. - **Clickable prototypes** — wire elements to other frames (click, hover, press, key or delay; navigate, overlay, back, scroll or link, with transitions) in Prototype mode or straight in the HTML, then click through the flow with Play or share `/c/<id>/proto`. Agents use the same `data-doop-*` attributes plus `get_prototype` / `set_prototype_start`. - **A real canvas editor** — draw frames, shapes, pen paths and text, edit any element's fill, type and flex layout, snap to rulers and guides, zoom from 8% to 1600% ([the editor](#the-canvas-editor)). - **True multiplayer** — live cursors, presence, follow mode, per-frame editing indicators, undo/redo, threaded comments on elements or the canvas, and an activity feed, all over one WebSocket room. - **Design memory** — pin exemplar frames, capture decisions, and let the distiller propose durable style rules that every agent follows. - **Private by default** — invite collaborators by email or share a link that can view, comment or edit; agents inherit exactly their human's access. - **Self-host in one command** — `docker compose up`, or `bun run dev` with zero configuration (embedded Postgres, no external services required). ## Works with any agent Doop isn't tied to one model vendor. Every agent below designs through the same MCP server, works as the person who connected it, and shows up live on the canvas with its own cursor, status and tasks. **Connect AI** in the top bar walks you through each one. <p align="center"> <img src=".github/assets/connect-ai.png" alt="The Connect AI dialog: choose Claude Code, Claude, ChatGPT, Codex, Cursor or any other MCP client" width="100%"> </p> | Agent | How it connects | | -------------------------------------------- | ------------------------------------------------------------------------------- | | Claude Code | `claude mcp add`, OAuth in the browser ([setup](#hook-up-claude-code)) | | Claude (web and desktop) | **Add to Claude** in Connect AI ([setup](#connect-claude)) | | Codex (CLI and desktop) | `codex mcp add`, OAuth in the browser ([setup](#connect-an-ai-agent)) | | ChatGPT | A custom MCP server in ChatGPT, guided by **Connect AI → ChatGPT** | | Cursor | **Add to Cursor** in Connect AI | | OpenCode, VS Code Copilot, OpenClaw and more | Any MCP client, over OAuth or with an agent key ([setup](#connect-an-ai-agent)) | | Headless agents (n8n, Mastra, CI) | An agent key as a bearer header ([setup](#headless-agents-agent-keys)) | No agent of your own? The built-in [Doop Agent](#the-doop-agent) runs on the model account you connect: a ChatGPT subscription, or an OpenAI, Claude, Gemini, DeepSeek, Kimi or OpenRouter key. OpenRouter brings Qwen, GLM, MiniMax and more ([details](#past-the-free-tasks-connect-your-own-chatgpt)). ## Quickstart ```bash git clone https://github.com/kgoedecke/doop && cd doop bun install bun run dev ``` Doop builds and installs with [bun](https://bun.sh) (`bun.lock` is the only lockfile); the server itself runs on Node. - Web app: **http://localhost:4300** - API + WebSocket + MCP server: **http://localhost:4400** (the web port proxies `/api`, `/ws`, `/mcp`, `/.well-known`, `/i/`, `/ingest` and `/local-agent` to it) `bun run dev` and `bun run build` also package the Claude Desktop extension with a Node script, so Node must be on your `PATH` as well. Everything works with no configuration: data persists to an embedded Postgres (PGlite) in `data/pg`, and every optional integration (SMTP, stock photos, object storage, analytics) degrades gracefully until its variable in [.env.example](.env.example) is set ([the ones that matter](#environment-variables)). The built-in [Doop Agent](#the-doop-agent) runs once a user connects a model account in Settings (or on the server's `ANTHROPIC_API_KEY` if you raise `RESIDENT_TASK_LIMIT`) — agents you connect yourself over MCP need no key. Or self-host the production build with Docker: ```bash BETTER_AUTH_SECRET=$(openssl rand -hex 32) docker compose up -d # app + Postgres on :4400 ``` Production build without Docker: `bun run build && bun run start` (single server on :4400 serving everything). Set `DATABASE_URL` to use a real Postgres — same code path as PGlite. Prefer not to run anything? **[doop.design](https://doop.design)** is the hosted version. Once you sign in, Home is where you start: describe what you want and Doop makes a canvas with drafts queued for the Doop Agent, or pick up one of your canvases, workspaces and connected agents. <p align="center"> <img src=".github/assets/home.png" alt="Doop's home: the agent prompt with suggestion chips over a gradient wave, the canvas grid, and a rail with workspaces and connected agents" width="100%"> </p> ## The canvas editor The bottom toolbar holds the tools; every one has a single-key shortcut. Shapes drawn on the canvas become standalone elements, and shapes drawn inside a frame become positioned HTML/SVG layers of that frame, so agents read and edit them like any other markup. | Tool | Key | What it does | | ----------- | --- | ------------------------------------------------------------------------------------- | | Select | V | Click to select, drag the background for a marquee, ⇧/⌘-click to add to the selection | | Hand | H | Pan (Space or the middle button pans from any tool) | | Frame | F | Draw an empty frame | | Rectangle | R | Draw a rectangle | | Circle | O | Draw a circle or ellipse | | Vector path | P | Bézier pen: snaps to its own anchors, previews closing the path; Alt skips snapping | | Text | T | Place a text layer | | Comment | C | Pin a comment to an element or to the canvas | - **Frames** — drag to move, pull the corner handle to resize, snap to neighbours and guides. The Inspector edits name, position, size and the raw HTML, marks the frame ready for dev, exports it, and pins it as a style reference; **Version history…** in the frame menu previews and restores earlier designs. - **Elements inside a frame** — click to select, drag a corner grip or edge to resize (⇧ keeps the ratio; a `W × H` badge shows the size), drag the element to move it within or across frames. The **Design** tab edits fill, stroke, text (font, size, weight, alignment), opacity, corner radius, rotation, position, flex layout (direction, gap, padding, wrap, alignment) and image fills; **HTML** shows its source; **Prototype** wires interactions. The floating toolbar adds Comment, **Ask AI** (pre-fills an `@mention`), Code, Edit text and Copy link. - **Rich text** — double-click text to edit it. Select words and use the formatting toolbar for bold, italic, underline, strikethrough, bulleted lists or numbered lists. ⌘/Ctrl+B, I and U toggle inline formatting; ⌘/Ctrl+⇧+7 or 8 toggles numbered or bulleted lists. Enter continues a list; Enter on an empty item leaves it. With a text layer selected on the canvas, ⌘/Ctrl+B, I, U and ⌘/Ctrl+⇧+X toggle the whole layer and ⌘/Ctrl+⇧+7 or 8 make it a list, as in Figma. Esc finishes editing; formatting saves with the frame and supports undo/redo. With words selected, the Design panel's font, size, weight and colour edit that run alone; selecting the whole layer shows **Mixed** where its runs differ, and a value set there applies to all of them, as in Figma. - **Path editing** — double-click a path to drag its anchors and Bézier handles, switch points between corner and curve, or delete them. Alt moves one handle on its own; ⇧ constrains its angle. - **Layers** — a searchable tree of pages, frames and elements: drag to reorder or reparent, hide, lock, collapse, and right-click an element for copy, paste, duplicate, Copy HTML, Copy selector and Copy link to element. - **Rulers and guides** — ⇧R shows rulers; drag out of one to add a guide. Guides belong to the page, undo like any edit, and everything snaps to them within 8 screen pixels. - **Zoom** — 8% to 1600%. Wheel pans, ⌘/Ctrl + wheel or a pinch zooms; a 1px pixel grid fades in from 300%. The zoom menu has 50/100/200% presets and the rulers toggle. - **Panels** — the right side panel has **Agents**, **Comments**, **Activity** and **Memory** tabs; Layers and the side panel can be resized. Drag the divider between Pages and Layers to change their split; arrow keys move it, Home and End reach its limits, and Doop remembers it per canvas. Pages starts compact until you resize it. ⌘. hides all UI. - **Themes** — Light, Dark or System under Settings → Appearance. - **Phones** — the canvas works on a phone: one-finger pan, pinch zoom, tap to comment, and bottom sheets for canvas actions, Layers and the Inspector. | Shortcut | Action | | ---------------- | ------------------------------------------------------ | | ⌘Z / ⌘⇧Z (or ⌘Y) | Undo / redo your own edits | | ⌘C / ⌘V / ⌘D | Copy, paste, duplicate frames or layers | | ⌫ | Delete the selected element, else the selected frames | | ⌘⇧H / ⌘⇧L | Hide / lock the selection | | ⌥↑ / ⌥↓ | Move a layer up or down (Layers panel) | | ⇧1 / ⇧2 | Zoom to fit everything / the selection | | ⌘0 / ⌘+ / ⌘− | Zoom to 100%, in, out | | ⇧R | Toggle rulers | | ⌘. | Hide or show all UI | | ⌘⌥↩ | Present from the selected frame (Ctrl+Alt+↩ elsewhere) | | ⌘K | Open the Agents composer (on Home: the search palette) | | Esc | Deselect, stop following | Click a collaborator's avatar to follow their viewport; an agent's avatar flies you to what it is working on. Placeholder frames show where an agent that has picked up a card is about to design. ## Comments, imports and exports Comment on any element or anywhere on the canvas. The **Comments** tab lists the page's threads (open or resolved) with their replies. `@mention` an agent role in a comment or a reply (for example `@doop`) to queue a design card; the agent's answer comes back in the thread. People who miss a comment get an email digest (opt out under Settings → Account), and canvases opened through a view-only or comment-only link show a badge and disable editing. The import source picker offers **Website** (one page, or discover a whole site and pick its pages), **Live app** (the [sync snippet](#design-sync-push-an-apps-live-screens-onto-a-canvas)), and **GitHub repo** (through the GitHub App or a fine-grained token: Doop reviews the repo's screens and components and queues cards for the Doop Agent to
- release-please-config.json (1624 bytes)
{ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", "separate-pull-requests": true, "bump-minor-pre-major": true, "include-v-in-tag": true, "changelog-sections": [ { "type": "feat", "section": "Features" }, { "type": "fix", "section": "Bug Fixes" }, { "type": "perf", "section": "Performance" }, { "type": "revert", "section": "Reverts" }, { "type": "docs", "section": "Documentation" }, { "type": "refactor", "section": "Refactors", "hidden": true }, { "type": "chore", "section": "Chores", "hidden": true }, { "type": "ci", "section": "CI", "hidden": true }, { "type": "build", "section": "Build", "hidden": true }, { "type": "test", "section": "Tests", "hidden": true }, { "type": "style", "section": "Style", "hidden": true } ], "packages": { ".": { "release-type": "node", "package-name": "doop", "include-component-in-tag": false, "exclude-paths": ["desktop"] }, "desktop": { "release-type": "node", "package-name": "doop-desktop", "component": "desktop", "include-component-in-tag": true, "skip-github-release": true, "extra-files": [ { "type": "json", "path": "src-tauri/tauri.conf.json", "jsonpath": "$.version" }, { "type": "toml", "path": "src-tauri/Cargo.toml", "jsonpath": "$.package.version" }, { "type": "json", "path": "src-tauri-chromium/tauri.conf.json", "jsonpath": "$.version" }, { "type": "toml", "path": "src-tauri-chromium/Cargo.toml", "jsonpath": "$.package.version" } ] } } } - release/chrome-store/reviewer-instructions.md (1450 bytes)
# Reviewer test instructions Doop Capture captures page content locally without an extension login. Importing the result requires signing into Doop and opening a canvas with edit access. 1. Open a normal HTTPS webpage (not a Chrome internal page or the Chrome Web Store). 2. Click the Doop Capture toolbar icon, then Select a section. 3. Move the pointer over page elements; a blue outline indicates the section. Click a section. 4. In the capture toolbar, click Copy to Doop. Wait for the Copied confirmation. 5. Sign in at https://doop.design and open or create an editable canvas. 6. Click the canvas background, then press Cmd+V on macOS or Ctrl+V elsewhere. Expect a new editable HTML frame. 7. Undo removes the imported frame. 8. Repeat using Capture entire page. Only content currently loaded by the website is captured; scrolling first may load additional lazy content. 9. Escape cancels section selection. Close dismisses the capture toolbar. No background capture, remote executable code, clipboard reading, or automated content upload is performed by the extension. Images remain remote references and may be unavailable if they require authentication. Unsupported content and capture size limits are described in the listing. Release gate: verify steps 5–7 against deployed production Doop before submitting these instructions. Do not provide reviewer credentials until a dedicated test account is available if Google requires one.
- SECURITY.md (829 bytes)
# Security Policy ## Reporting a vulnerability Please **do not open a public issue** for security problems. Use GitHub's private reporting — **Security → Report a vulnerability** on this repository. Include what you found, how to reproduce it, and the impact you believe it has. You'll get an acknowledgement within a few days; please give us a reasonable window to ship a fix before disclosing publicly. ## Scope notes for self-hosters - Canvases are private by default; sharing is by invite or an explicit per-canvas link toggle. - `/i/<frameId>.png` frame images and `/a/<assetId>` uploads are intentionally public-by-unguessable-id (they power og:images and cross-origin embeds). - Set `BETTER_AUTH_SECRET` and run behind TLS in any real deployment; without SMTP configured, signup is open (no email verification).
- SKILL.md (1955 bytes)
--- name: doop-design description: Create, inspect, and refine HTML designs on a shared Doop canvas. Use when the user asks to work in Doop, provides a Doop canvas URL, or asks to implement a design from a Doop canvas in their codebase. --- # Doop design Use the connected `doop` MCP server for Doop work. The server provides the current tool schemas and design guidance; do not substitute local HTML files for edits the user requested on a shared canvas. 1. Call `get_guide({ topic: "doop-instructions" })` before other Doop tools and follow the returned workflow. Reload it if the conversation has lost that context. 2. Use the canvas ID from the user's `/c/<id>` URL or explicit canvas ID. If they have not identified a canvas, use the available discovery tools and ask them to choose when the target is ambiguous. Do not guess or create a replacement canvas for an existing design. 3. Pick one `agent_name` and keep it consistent. Read the canvas with `get_canvas`, then fetch its relevant guidelines and references before designing. Announce progress with `set_status` as described by the server. 4. Make the requested changes through the available Doop tools. Inspect the rendered result with `get_frame_screenshot`, correct visual issues, and respond to feedback from people on the canvas. Clear your status when finished. 5. When the user asks to implement a Doop design in their codebase, inspect the source frame and its screenshot first, then follow the repository's conventions. Modify the shared canvas only when the user requests design changes. 6. Finish with a link to the canvas and a brief description of the work completed. If Doop tools are missing or authentication fails, ask the user to enable the Doop MCP server in Cursor's Customize panel and complete its browser sign-in. Do not request tokens in chat. This plugin connects to `https://doop.design/mcp`; local and self-hosted Doop instances use their own server connection. - src/App.tsx (12021 bytes)
import { startLocalAgent } from './lib/localAgent' import { navigate } from './lib/navigate' import { useEffect, useRef, useState } from 'react' import { Home } from './pages/Home' import { Community } from './pages/Community' import { Settings } from './pages/Settings' import { CanvasPage } from './pages/CanvasPage' import { PrototypePage } from './pages/PrototypePage' import { AuthPage } from './pages/AuthPage' import { DesktopHandoff } from './pages/DesktopHandoff' import { DesktopSignIn } from './pages/DesktopSignIn' import { DesktopConnect } from './pages/DesktopConnect' import { DESKTOP_CONNECT_PATH } from '../shared/desktopConnect' import { DesktopCodexSetup } from './pages/DesktopCodexSetup' import { CODEX_SETUP_PATH } from './lib/codexConnection' import { OAuthConsent } from './pages/OAuthConsent' import { DESKTOP_HANDOFF_PATH, DESKTOP_SIGNIN_PATH } from './lib/desktopAuth' import { Admin } from './pages/Admin' import { Automations } from './pages/Automations' import { AutomationEditor } from './pages/AutomationEditor' import { Integrations } from './pages/Integrations' import { Workspace } from './pages/Workspace' import { UpgradeHost } from './components/UpgradeHost' import { authClient } from './lib/auth' import { useStore } from './lib/store' import { setName } from './lib/identity' import { posthog, setSupportWidgetVisible, syncReplayForUser, suspendAnalyticsWhileImpersonating } from './lib/posthog' import { useMe } from './lib/me' import { adminApi } from './lib/api' import { Button } from './components/ui/button' import { AuthScreen } from './components/ui/screen' import { DesktopTabs, ShellDragBar } from './components/DesktopTabs' import { WindowControls } from './components/WindowControls' import { useWindowFrame } from './lib/windowFrame' import { cn } from './lib/utils' import { setTabsUser } from './lib/desktop' import { isDesktopShell } from './lib/shell' import { SIGNUP_PARAM, parseSignupMethod } from '../shared/firstCanvas' import { useT } from './lib/i18n' export { navigate } /* A provider sign-in that created the account lands here carrying ?signup=<method> (shared/firstCanvas.ts); the email form reports its own signups at submit. Report it once the person is identified, then take the marker off the URL so a reload or a shared link cannot count it twice. */ function reportProviderSignup() { const url = new URL(location.href) const method = parseSignupMethod(url.searchParams.get(SIGNUP_PARAM)) if (!url.searchParams.has(SIGNUP_PARAM)) return url.searchParams.delete(SIGNUP_PARAM) history.replaceState(history.state, '', url) if (method) posthog.capture('account_signed_up', { method }) } export function App() { const [route, setRoute] = useState(location.pathname + location.search) const path = route.split('?')[0]! const { data: session, isPending } = authClient.useSession() /* a signed-out guest on a share link asked for the sign-in form */ const [guestAuth, setGuestAuth] = useState<'signin' | 'signup' | null>(null) const signInRequired = useStore((s) => s.signInRequired) const me = useMe(session?.user.id) const identifiedUserId = useRef<string | null>(null) useEffect(() => { const onPop = () => setRoute(location.pathname + location.search) window.addEventListener('popstate', onPop) return () => window.removeEventListener('popstate', onPop) }, []) /* Reaching /admin mid "view as" — usually the Back button, since /admin stays in history when impersonation starts — can only mean "return to being the admin": the borrowed session has no admin access, so rendering the page would show its not-found screen. End the impersonation and arrive as the admin instead. */ const canvasId = path.match(/^\/c\/([^/]+)/)?.[1] /* the support chat bubble stays off the editor, where it would cover the zoom bar; every other page keeps it */ useEffect(() => setSupportWidgetVisible(!canvasId), [canvasId]) const returningToAdmin = !!me?.impersonating && path.startsWith('/admin') useEffect(() => { if (!returningToAdmin) return adminApi .stopImpersonating() .then(() => location.assign('/admin')) .catch(() => location.assign('/')) }, [returningToAdmin]) /* The session is the auth boundary: this covers both successful login and restoring an existing session after a page refresh. */ useEffect(() => { const user = session?.user if (!user) { if (identifiedUserId.current) { posthog.reset() identifiedUserId.current = null } return } /* Wait for /api/me before identifying anyone. Impersonation swaps the session cookie, so `user` here is the person being VIEWED — identifying them would write an admin's support session into that customer's profile and replay timeline. Only /api/me can tell the two apart. */ if (!me) return if (me.impersonating) { suspendAnalyticsWhileImpersonating() identifiedUserId.current = null return } if (identifiedUserId.current === user.id) return if (identifiedUserId.current) posthog.reset() posthog.identify(user.id, { email: user.email, name: user.name }) syncReplayForUser(user.email) identifiedUserId.current = user.id reportProviderSignup() }, [session?.user, me]) /* the account name is the identity shown on cursors and in the feed */ useEffect(() => { if (session?.user?.name) setName(session.user.name) }, [session?.user?.name]) /* the desktop tab strip is per-account state: restore this user's tabs, and clear the strip the moment the session goes away */ useEffect(() => { if (!isPending) setTabsUser(session?.user?.id ?? null) }, [isPending, session?.user?.id]) const localAgentUser = !isPending && me && !me.impersonating ? session?.user.id : undefined useEffect(() => { if (localAgentUser) return startLocalAgent(localAgentUser) }, [localAgentUser]) if (isPending) return ( <> <ShellDragBar /> <AuthScreen /> </> ) /* the desktop app sent this browser here to begin a provider sign-in on its behalf (src/lib/desktopAuth.ts) — signed in or not, the page itself decides where to go next */ if (path === DESKTOP_SIGNIN_PATH) return ( <> <ShellDragBar /> <DesktopSignIn signedIn={!!session} /> </> ) /* a provider sent the system browser back for a connection the desktop app started (shared/desktopConnect.ts) — the app finishes it under its own account, so this browser's session does not matter */ if (path === DESKTOP_CONNECT_PATH) return ( <> <ShellDragBar /> <DesktopConnect /> </> ) /* signed out on a canvas link: the canvas itself, read-only, as long as the owner shared it by link (server: guestCanvasRole); a private one refuses the join and lands on the sign-in form below. The prototype player stays behind sign-in. */ if (!session && canvasId && !path.includes('/proto') && !signInRequired && !guestAuth) return ( <ShellDragBar> <CanvasPage canvasId={canvasId} key={canvasId} guest onSignUp={() => setGuestAuth('signup')} onSignIn={() => setGuestAuth('signin')} /> </ShellDragBar> ) /* signed out: every path lands on the sign-in form. The marketing site is a separate service (see server/marketing.ts) that owns `/` for visitors; share links (/c/…) and interrupted MCP OAuth redirects keep their URL so the deep link / resume logic survives the sign-in. */ if (!session) return ( <> <ShellDragBar /> <AuthPage initialMode={guestAuth ?? undefined} /> </> ) /* /admin waits for /api/me: before it answers we can't tell an admin from a borrowed "view as" session, and rendering Admin in the latter flashes its not-found screen. Also blank while the effect above swaps the session back and reloads. */ if (path.startsWith('/admin') && (!me || returningToAdmin)) return <div className="auth-page" /> /* /c/<id>/proto: the prototype player, full page */ const prototypeOf = path.match(/^\/c\/([^/]+)\/proto\/?$/)?.[1] const screen = prototypeOf ? ( <PrototypePage canvasId={prototypeOf} key={prototypeOf} /> ) : canvasId ? ( <CanvasPage canvasId={canvasId} key={canvasId} /> ) : path === CODEX_SETUP_PATH ? ( <DesktopCodexSetup key={route} /> ) : path === DESKTOP_HANDOFF_PATH ? ( <DesktopHandoff /> ) : path === '/oauth/consent' ? ( <OAuthConsent email={session.user.email} /> ) : path.startsWith('/admin') ? ( <Admin /> ) : path.startsWith('/settings') ? ( <Settings /> ) : path.startsWith('/community') ? ( <Community /> ) : path.startsWith('/integrations') ? ( <Integrations /> ) : path.match(/^\/w\/([^/]+)/) ? ( <Workspace workspaceId={path.match(/^\/w\/([^/]+)/)![1]!} key={path} /> ) : path.match(/^\/automations\/([^/]+)/) ? ( <AutomationEditor automationId={path.match(/^\/automations\/([^/]+)/)![1]!} key={path} /> ) : path.startsWith('/automations') ? ( <Automations /> ) : ( <Home /> ) const page = ( <> {screen} <UpgradeHost /> </> ) /* The banner is not decoration: an impersonated session looks exactly like being signed in as that person, and forgetting you are in one is how support tools cause incidents. */ return me?.impersonating ? ( <> <ImpersonationBanner name={session.user.name} /> {/* --app-inset is the contract with fixed-position screens: the canvas workspace is `fixed inset-0` and ignores this padding, so it offsets itself by the same variable instead of hardcoding the banner height */} <div className="h-dvh overflow-auto pt-14 [--app-inset:56px] sm:pt-10 sm:[--app-inset:40px]">{page}</div> </> ) : isDesktopShell() ? ( /* the desktop shell's tab strip uses the same --app-inset contract as the banner: fixed screens (the canvas workspace) offset themselves */ <> <DesktopTabs path={path} /> <div className="h-dvh overflow-auto pt-10 [--app-inset:40px]">{page}</div> </> ) : ( page ) } function ImpersonationBanner({ name }: { name: string }) { const t = useT() const [leaving, setLeaving] = useState(false) const customFrame = useWindowFrame((s) => s.custom) /* the banner is the top of the window while it shows, so on Windows it is also the drag handle and carries the caption buttons (windowFrame.ts). Both sides reserve the buttons' width, so the centred content never slides under them and a long name truncates instead. */ return ( <div data-tauri-drag-region className={cn( 'fixed inset-x-0 top-0 z-900 flex min-h-14 items-center justify-between gap-2 border-b border-accent-ink px-2.5 py-[7px] text-[11.5px] leading-tight text-accent-ink backdrop-blur-[6px] [background:repeating-linear-gradient(-45deg,rgba(208,52,31,0.16)_0_10px,rgba(208,52,31,0.08)_10px_20px)] sm:h-10 sm:min-h-0 sm:justify-center sm:gap-4 sm:text-[13px]', customFrame && 'sm:px-36.5', )} > <span className="min-w-0 truncate"> {t('auth.viewingAsBefore')} <strong>{name}</strong> {t('auth.viewingAsAfter')} </span> <Button variant="ghost" size="sm" className="shrink-0" disabled={leaving} onClick={() => { setLeaving(true) /* the cookie swaps back to the admin's own session; reload rather than reconcile every piece of per-user state in memory */ adminApi .stopImpersonating() .then(() => location.assign('/admin')) .catch(() => location.assign('/')) }} > {leaving ? t('auth.leaving') : t('auth.stopViewing')} </Button> <WindowControls className="absolute inset-y-0 right-0" /> </div> ) } - src/assets/fonts/inter-LICENSE.txt (4366 bytes)
Copyright (c) 2016-2018 The Inter Project Authors ([email protected]) This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION AND CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
- src/components/AccessBanner.tsx (2045 bytes)
import { useState } from 'react' import { useStore, roleOf } from '../lib/store' import { useT } from '../lib/i18n' import { cn } from '../lib/utils' import { Button } from './ui/button' import { IconButton } from './ui/icon-button' import { EyeIcon, XIcon } from './ui/icons' const bannerClass = 'pointer-events-auto absolute bottom-3.5 left-1/2 z-30 flex max-w-[calc(100%-32px)] -translate-x-1/2 items-center gap-3 rounded-panel bg-surface py-1.5 pr-1.5 pl-3.5 text-body text-ink shadow-pop max-md:bottom-[72px]' /** The note at the foot of a canvas someone can only look at, as Figma * shows it: a signed-out guest is asked to sign up, a signed-in viewer or * commenter is told what their link allows and may put it away. */ export function AccessBanner({ guest, onSignUp, onSignIn, className, }: { guest: boolean onSignUp?: () => void onSignIn?: () => void className?: string }) { const t = useT() const role = useStore(roleOf) const loaded = useStore((s) => !!s.canvas) const [dismissed, setDismissed] = useState(false) if (!loaded || role === 'edit' || dismissed) return null if (guest) return ( <div role="status" className={cn(bannerClass, className)}> <span className="min-w-0">{t('canvas.guestBanner')}</span> <span className="flex flex-none items-center gap-1.5"> <Button size="sm" onClick={onSignIn}> {t('auth.signIn')} </Button> <Button size="sm" variant="primary" onClick={onSignUp}> {t('auth.signUp')} </Button> </span> </div> ) return ( <div role="status" className={cn(bannerClass, className)}> <EyeIcon size="rail" className="flex-none text-ink-soft" /> <span className="min-w-0"> {role === 'comment' ? t('canvas.readOnlyCommentBanner') : t('canvas.readOnlyViewBanner')} </span> <IconButton size="sm" aria-label={t('canvas.dismissBanner')} onClick={() => setDismissed(true)}> <XIcon size="rail" /> </IconButton> </div> ) } - src/components/AccountSettings.tsx (12365 bytes)
import { useCallback, useEffect, useRef, useState } from 'react' import { authClient } from '../lib/auth' import { api } from '../lib/api' import type { NotificationSettings } from '../../shared/notifications' import { AVATAR_ACCEPT, MAX_AVATAR_BYTES, avatarUrl } from '../../shared/avatar' import { colorFor } from '../../shared/types' import { posthog } from '../lib/posthog' import { useT, type PlainMessageKey, type Translate } from '../lib/i18n' import { Avatar } from './ui/avatar' import { Button } from './ui/button' import { Input } from './ui/input' import { Badge } from './ui/badge' import { Note } from './ui/note' import { Checkbox } from './ui/checkbox' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' import { DeleteAccountCard } from './DeleteAccount' /* settings fields are a fixed column on desktop and full width on a phone */ /* A message kept in state: our own as a key, translated where it renders so a language switch reaches it too; the server's as the text it sent. */ type Notice = { key: PlainMessageKey } | { text: string } function noticeText(t: Translate, notice: Notice): string { return 'key' in notice ? t(notice.key) : notice.text } /** The server's message when it sent one, else our own fallback. */ function errorNotice(message: string | undefined, fallback: PlainMessageKey): Notice { return message ? { text: message } : { key: fallback } } /** The "Your account" pane of /settings: who you are on a canvas, how you * get back into one, and, last, deleting the account. Mostly better-auth's * own account surface. */ export function AccountSettings() { const t = useT() const { data: session, refetch: refetchSession } = authClient.useSession() const user = session?.user const photo = avatarUrl(user?.image) /* the photo: bytes go to /api/me/avatar, then the session is re-read so every face on the page (the account menu included) turns at once */ const photoInput = useRef<HTMLInputElement>(null) const [savingPhoto, setSavingPhoto] = useState(false) const [photoNote, setPhotoNote] = useState<Notice | null>(null) const [photoError, setPhotoError] = useState<Notice | null>(null) /* null while untouched, so the field tracks the session until you type */ const [draft, setDraft] = useState<string | null>(null) const name = draft ?? user?.name ?? '' const dirty = name.trim().length > 0 && name.trim() !== (user?.name ?? '') const [savingName, setSavingName] = useState(false) const [nameNote, setNameNote] = useState<Notice | null>(null) const [nameError, setNameError] = useState<Notice | null>(null) const [current, setCurrent] = useState('') const [next, setNext] = useState('') const [savingPw, setSavingPw] = useState(false) const [pwNote, setPwNote] = useState<Notice | null>(null) const [pwError, setPwError] = useState<Notice | null>(null) const [verifyNote, setVerifyNote] = useState<Notice | null>(null) /* null until the server has answered — the switch renders inert meanwhile */ const [notify, setNotify] = useState<NotificationSettings | null>(null) const [notifyError, setNotifyError] = useState<Notice | null>(null) /* one save at a time: two in flight could land out of order and show the older choice */ const [savingNotify, setSavingNotify] = useState(false) const refreshNotify = useCallback(() => { api.notificationSettings().then(setNotify, () => {}) }, []) useEffect(refreshNotify, [refreshNotify]) async function uploadPhoto(file: File) { setPhotoNote(null) setPhotoError(null) if (file.size > MAX_AVATAR_BYTES) return setPhotoError({ key: 'account.photoTooLarge' }) setSavingPhoto(true) try { await api.uploadAvatar(file) await refetchSession() posthog.capture('account_photo_changed') setPhotoNote({ key: 'account.photoSaved' }) } catch (e) { setPhotoError(errorNotice(e instanceof Error ? e.message : undefined, 'account.photoSaveFailed')) } finally { setSavingPhoto(false) } } async function removePhoto() { setPhotoNote(null) setPhotoError(null) setSavingPhoto(true) try { await api.removeAvatar() await refetchSession() posthog.capture('account_photo_removed') setPhotoNote({ key: 'account.photoRemoved' }) } catch (e) { setPhotoError(errorNotice(e instanceof Error ? e.message : undefined, 'account.photoSaveFailed')) } finally { setSavingPhoto(false) } } async function saveName() { setSavingName(true) setNameNote(null) setNameError(null) const { error } = await authClient.updateUser({ name: name.trim() }) setSavingName(false) if (error) return setNameError(errorNotice(error.message, 'account.nameSaveFailed')) posthog.capture('account_name_changed') setDraft(null) setNameNote({ key: 'account.nameSaved' }) } async function savePassword() { setSavingPw(true) setPwNote(null) setPwError(null) /* revoking is the point: a password change you make because you fear a device is compromised is useless if that device stays signed in */ const { error } = await authClient.changePassword({ currentPassword: current, newPassword: next, revokeOtherSessions: true, }) setSavingPw(false) if (error) return setPwError(errorNotice(error.message, 'account.passwordChangeFailed')) posthog.capture('account_password_changed') setCurrent('') setNext('') setPwNote({ key: 'account.passwordUpdated' }) } async function setCommentEmails(on: boolean) { if (!notify || savingNotify) return setSavingNotify(true) setNotify({ ...notify, commentEmails: on }) setNotifyError(null) try { setNotify(await api.setNotificationPrefs({ commentEmails: on })) posthog.capture('comment_emails_toggled', { on }) } catch { setNotifyError({ key: 'account.notifySaveFailed' }) refreshNotify() } finally { setSavingNotify(false) } } async function resendVerification() { if (!user?.email) return setVerifyNote(null) const { error } = await authClient.sendVerificationEmail({ email: user.email }) setVerifyNote( error ? errorNotice(error.message, 'account.verificationSendFailed') : { key: 'account.verificationSent' }, ) } return ( <> <SettingsCard> <CardHeader> <CardTitle>{t('account.profileTitle')}</CardTitle> <CardDescription>{t('account.profileDescription')}</CardDescription> </CardHeader> <CardRow label={t('account.photoRow')} action={ <> <Button size="sm" disabled={savingPhoto} onClick={() => photoInput.current?.click()}> {savingPhoto ? t('account.uploadingPhoto') : photo ? t('account.changePhoto') : t('account.uploadPhoto')} </Button> {photo && ( <Button size="sm" variant="ghost" disabled={savingPhoto} onClick={removePhoto}> {t('account.removePhoto')} </Button> )} </> } > <Avatar name={user?.name ?? ''} image={photo} color={colorFor(user?.id ?? '')} size={48} /> <Input ref={photoInput} type="file" accept={AVATAR_ACCEPT} aria-label={t('account.choosePhotoAria')} className="hidden" onChange={(event) => { const [file] = event.currentTarget.files ?? [] event.currentTarget.value = '' if (file) void uploadPhoto(file) }} /> {photoError ? ( <Note tone="error">{noticeText(t, photoError)}</Note> ) : photoNote ? ( <Note tone="success">{noticeText(t, photoNote)}</Note> ) : ( <Note>{t('account.photoHint')}</Note> )} </CardRow> <CardRow label={t('account.nameRow')} action={ <Button size="sm" disabled={!dirty || savingName} onClick={saveName}> {savingName ? t('account.saving') : t('common.save')} </Button> } control={ <Input value={name} onChange={(e) => { setDraft(e.target.value) setNameNote(null) setNameError(null) }} maxLength={60} aria-label={t('account.displayNameAria')} /> } > {nameError ? ( <Note tone="error">{noticeText(t, nameError)}</Note> ) : nameNote ? ( <Note tone="success">{noticeText(t, nameNote)}</Note> ) : dirty ? ( <Note>{t('account.nameUnsaved')}</Note> ) : null} </CardRow> <CardRow label={t('account.emailRow')} action={ user?.emailVerified ? ( <Note>{t('account.emailNotChangeable')}</Note> ) : ( <Button size="sm" onClick={resendVerification}> {t('account.resendVerification')} </Button> ) } > <span className="min-w-0 font-mono text-body [overflow-wrap:anywhere]">{user?.email}</span> {user?.emailVerified ? ( <Badge tone="success">{t('account.verified')}</Badge> ) : ( <Badge>{t('account.unverified')}</Badge> )} {verifyNote && <Note tone="success">{noticeText(t, verifyNote)}</Note>} </CardRow> </SettingsCard> <SettingsCard> <CardHeader> <CardTitle>{t('account.notificationsTitle')}</CardTitle> <CardDescription>{t('account.notificationsDescription')}</CardDescription> </CardHeader> <CardRow label={t('account.commentEmailsRow')}> <label className="relative flex cursor-pointer items-center gap-2.5 text-body text-ink"> <Checkbox checked={notify?.commentEmails ?? true} disabled={!notify || !notify.emailConfigured || savingNotify} onChange={(e) => void setCommentEmails(e.target.checked)} aria-label={t('account.commentEmailsAria')} /> <span>{t('account.commentEmailsLabel')}</span> </label> {notify && !notify.emailConfigured ? ( <Note>{t('account.emailNotConfigured')}</Note> ) : notifyError ? ( <Note tone="error">{noticeText(t, notifyError)}</Note> ) : null} </CardRow> </SettingsCard> <SettingsCard> <CardHeader> <CardTitle>{t('account.passwordTitle')}</CardTitle> <CardDescription>{t('account.passwordDescription')}</CardDescription> </CardHeader> <CardRow label={t('account.currentPassword')} control={ <Input type="password" value={current} onChange={(e) => { setCurrent(e.target.value) setPwError(null) }} autoComplete="current-password" aria-label={t('account.currentPassword')} /> } /> <CardRow label={t('account.newPassword')} action={ <Button size="sm" disabled={savingPw || !current || next.length < 8} onClick={savePassword}> {savingPw ? t('account.updatingPassword') : t('account.updatePassword')} </Button> } control={ <Input type="password" value={next} onChange={(e) => { setNext(e.target.value) setPwError(null) }} autoComplete="new-password" aria-label={t('account.newPassword')} /> } > {pwError ? ( <Note tone="error">{noticeText(t, pwError)}</Note> ) : pwNote ? ( <Note tone="success">{noticeText(t, pwNote)}</Note> ) : ( <Note>{t('account.passwordMinLength')}</Note> )} </CardRow> </SettingsCard> <DeleteAccountCard /> </> ) } - src/components/ActionMenuItem.tsx (3006 bytes)
import type { ReactNode } from 'react' import type { Frame } from '../../shared/types' import { canvasPages, framePageId } from '../../shared/pages' import { chordHint, firstChord } from '../lib/actions/chords' import { actionById, isEnabled, runAction } from '../lib/actions/registry' import { useT } from '../lib/i18n' import { moveFramesToPage } from '../lib/pageEdits' import { canEditOpenCanvas, useStore } from '../lib/store' import { ContextMenuItem, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger } from './ui/context-menu' import { MenuHint } from './ui/menu' /** The chord a registry command is bound to, as a menu row's trailing hint. */ export function ActionHint({ id }: { id: string }) { const chord = firstChord(actionById(id).keys) return chord ? <MenuHint>{chordHint(chord)}</MenuHint> : null } /** A context-menu row that runs a registry command on the selection: its * name, chord and enabled state come from the registry, so the menu, the * keyboard and the main menu cannot drift apart. The right-click picked the * layer or frame first, so the selection is what was clicked. */ export function ActionMenuItem({ id, label, disabled, tone, }: { id: string label?: ReactNode /** greyed for a reason the registry cannot see (a locked layer) */ disabled?: boolean tone?: 'danger' }) { const t = useT() const action = actionById(id) return ( <ContextMenuItem tone={tone} disabled={disabled || !isEnabled(action)} onSelect={() => runAction(action)}> {label ?? t(action.label)} <ActionHint id={id} /> </ContextMenuItem> ) } /** "Move to page ▸": every other page of the canvas, as Figma lists them. * Locked frames stay where they are; nothing shows on a one-page canvas or * for a reader. */ export function MoveToPageMenu({ frames }: { frames: readonly Frame[] }) { const t = useT() const canvas = useStore((s) => s.canvas) const editable = useStore((s) => canEditOpenCanvas(s)) if (!canvas || !editable) return null const movable = frames.filter((f) => !f.locked) const here = new Set(frames.map((f) => framePageId(canvas, f))) const pages = canvasPages(canvas).filter((page) => !(here.size === 1 && here.has(page.id))) if (canvasPages(canvas).length < 2 || !pages.length) return null const move = (pageId: string) => { moveFramesToPage( canvas, movable.map((f) => f.id), pageId, ).catch(() => { if (useStore.getState().canvas?.id === canvas.id) useStore.getState().pushNotice(t('panels.pagesMoveFailed')) }) } return ( <ContextMenuSub> <ContextMenuSubTrigger disabled={!movable.length}>{t('stage.moveToPage')}</ContextMenuSubTrigger> <ContextMenuSubContent> {pages.map((page) => ( <ContextMenuItem key={page.id} onSelect={() => move(page.id)}> <span className="min-w-0 flex-1 truncate">{page.name}</span> </ContextMenuItem> ))} </ContextMenuSubContent> </ContextMenuSub> ) } - src/components/ActivityPanel.tsx (19195 bytes)
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react' import type { AgentTask } from '../../shared/types' import { canEditOpenCanvas, useStore } from '../lib/store' import { api } from '../lib/api' import { timeAgo } from '../lib/time' import { cn } from '@/lib/utils' import { AgentIcon } from './AgentIcon' import { MemoryPanel } from './MemoryPanel' import { Panel, type PanelResize, type PanelSurface, PanelBody, PanelClose, PanelHeader, PanelIconTab, PanelTabPanel, PanelTabs, PanelTabsRoot, } from './ui/panel' import { Button } from './ui/button' import { BookOpenIcon, CheckIcon, ChevronDownIcon, CommentIcon, PulseIcon, SparkIcon } from './ui/icons' import { DotMatrix } from './ui/dot-matrix' import { Dot } from './ui/dot' import { isResidentLimit } from './TeamAllowance' import { CommentsPanel } from './CommentsPanel' import { PromptBar } from './PromptBar' import { AgentChat } from './AgentChat' import { isChatCard } from '../lib/agentChat' import { clampRecentHeight, MIN_CHAT_PX, MIN_RECENT_PX, readRecentHeight, writeRecentHeight } from '../lib/agentsSplit' import { taskFrameId } from '../lib/taskFrame' import { useOpenThreadCount } from '../lib/comments' import { useT } from '@/lib/i18n' const emptyNote = 'px-4 py-6 text-center text-[12px] text-ink-faint' /* Radix mounts a tab's content on switch, so this plays once per switch */ const tabEnter = 'data-[state=active]:animate-in data-[state=active]:fade-in-0 data-[state=active]:slide-in-from-right-1 data-[state=active]:duration-200 motion-reduce:animate-none' /* feedback and retries are metered like any other resident task — a 403 here means the free tier ran out, so raise the connect wall */ function reportLimit(err: unknown) { if (isResidentLimit(err)) useStore.getState().setLimitWall(true) else console.error(err) } function duration(t: AgentTask): string { const end = t.endedAt ?? Date.now() const s = Math.max(1, Math.round((end - t.startedAt) / 1000)) if (s < 60) return `${s}s` const m = Math.floor(s / 60) if (m < 60) return `${m}m ${s % 60 ? `${s % 60}s` : ''}`.trim() return `${Math.floor(m / 60)}h ${m % 60}m` } export function ActivityPanel({ canvasId, onClose, surface = 'floating', className, style, resize, }: { canvasId: string onClose: () => void /* 'inline' when the panel is filling a mobile Sheet rather than floating */ surface?: PanelSurface className?: string /** carries `right` while floating — the panel always hugs the right edge */ style?: CSSProperties resize?: PanelResize }) { const setTab = useStore((s) => s.setPanelTab) const canEdit = useStore(canEditOpenCanvas) /* someone who cannot edit sees the comments only (PanelTabButtons) */ const tab = useStore((s) => (canEdit ? s.panelTab : 'comments')) const [, tick] = useState(0) const openThreads = useOpenThreadCount() const working = useStore((s) => s.tasks.filter((t) => t.agentName && !t.endedAt && !t.failedAt).length) const hasChat = useStore((s) => s.tasks.some(isChatCard)) const t = useT() /* refresh relative timestamps and running durations */ useEffect(() => { const timer = window.setInterval(() => tick((n) => n + 1), 5000) return () => window.clearInterval(timer) }, []) return ( <Panel surface={surface} resize={resize} className={cn( surface === 'floating' && 'top-2.5 bottom-3.5 w-[280px] transition-[right] duration-150', surface === 'docked' && 'w-[280px] border-l', className, )} style={style} > <PanelTabsRoot value={tab} onValueChange={(next) => setTab(next as typeof tab)}> <PanelHeader className="pl-2"> <PanelTabs aria-label={t('panels.activityPanelAria')}> {canEdit && ( <PanelIconTab value="tasks" icon={<SparkIcon />} title={t('panels.activityAgents')}> {t('panels.activityAgents')} {working > 0 && ( <em className="ml-[7px] text-[11px] font-normal not-italic text-ink-faint">{working}</em> )} </PanelIconTab> )} <PanelIconTab value="comments" icon={<CommentIcon />} title={ openThreads ? t('panels.activityCommentsOpen', { count: openThreads }) : t('panels.activityCommentsTitle') } /* open threads on this page: a count on the tab itself */ badge={ openThreads > 0 && ( <span className="absolute -top-1 -right-1 grid h-[14px] min-w-[14px] place-items-center rounded-lg bg-brand px-[3px] font-mono text-[8px] font-medium text-white"> {openThreads > 99 ? '99+' : openThreads} </span> ) } > {t('panels.activityComments')} </PanelIconTab> {canEdit && ( <> <PanelIconTab value="activity" icon={<PulseIcon />} title={t('panels.activityActivity')}> {t('panels.activityActivity')} </PanelIconTab> <PanelIconTab value="memory" icon={<BookOpenIcon />} title={t('panels.activityMemoryTitle')}> {t('panels.activityMemory')} </PanelIconTab> </> )} </PanelTabs> <PanelClose label={t('panels.activityClosePanel')} onClick={onClose} /> </PanelHeader> {/* the Agents tab is a column: what the agents are doing on top, the conversation with them under it, the prompt composer docked below */} <PanelTabPanel value="tasks" className={tabEnter}> {hasChat ? ( <AgentsSplit /> ) : ( <div className="flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain"> <RecentTasks /> </div> )} {/* the composer briefs agents to change frames: editors only */} {canEdit && <PromptBar canvasId={canvasId} />} </PanelTabPanel> <PanelTabPanel value="comments" className={tabEnter}> <CommentsPanel /> </PanelTabPanel> <PanelTabPanel value="activity" className={tabEnter}> <ActivityList /> </PanelTabPanel> <PanelTabPanel value="memory" className={tabEnter}> <MemoryPanel /> </PanelTabPanel> </PanelTabsRoot> </Panel> ) } /** How far one arrow key moves the line between Recent tasks and the chat. */ const SPLIT_STEP_PX = 16 /* Recent tasks over the chat, with a line between them to drag: up gives the chat more room, down gives it to the tasks. Until someone drags it, Recent tasks takes what it needs up to 45%; a double-click goes back to that. */ function AgentsSplit() { const column = useRef<HTMLDivElement>(null) const recent = useRef<HTMLDivElement>(null) /* where the line started, and where the latest move put it: a release can land before React renders that move, so it saves this, not the state */ const drag = useRef<{ y: number; height: number; placed?: number } | null>(null) const [height, setHeight] = useState<number | null>(readRecentHeight) /* the rendered sizes, for the separator's value and range: the line also moves when the panel or Recent tasks changes height, not only on a drag */ const [sizes, setSizes] = useState({ recent: 0, column: 0 }) const t = useT() useEffect(() => { const col = column.current const top = recent.current if (!col || !top) return const measure = () => setSizes({ recent: top.offsetHeight, column: col.clientHeight }) const observer = new ResizeObserver(measure) observer.observe(col) observer.observe(top) return () => observer.disconnect() }, []) const place = (next: number) => { const placed = clampRecentHeight(next, column.current?.clientHeight ?? 0) setHeight(placed) if (drag.current) drag.current.placed = placed return placed } const endDrag = () => { if (drag.current?.placed !== undefined) writeRecentHeight(drag.current.placed) drag.current = null } return ( <div ref={column} className="flex min-h-0 flex-1 flex-col"> <div ref={recent} className={cn( 'flex min-h-0 flex-none flex-col overflow-y-auto overscroll-contain', height === null && 'max-h-[45%]', )} style={height === null ? undefined : { height, maxHeight: `calc(100% - ${MIN_CHAT_PX}px)` }} > <RecentTasks /> </div> <div role="separator" tabIndex={0} aria-label={t('panels.chatResize')} title={t('panels.chatResize')} aria-orientation="horizontal" aria-valuemin={MIN_RECENT_PX} aria-valuemax={Math.max(MIN_RECENT_PX, sizes.column - MIN_CHAT_PX)} aria-valuenow={sizes.recent} className="group relative z-[1] -my-[3px] flex h-[7px] flex-none touch-none cursor-row-resize items-center focus-visible:outline-none" onPointerDown={(e) => { if (e.button !== 0) return e.preventDefault() drag.current = { y: e.clientY, height: recent.current?.offsetHeight ?? 0 } e.currentTarget.setPointerCapture(e.pointerId) }} onPointerMove={(e) => { if (drag.current) place(drag.current.height + e.clientY - drag.current.y) }} onPointerUp={(e) => { endDrag() if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId) }} onLostPointerCapture={endDrag} onPointerCancel={endDrag} onDoubleClick={() => { setHeight(null) writeRecentHeight(null) }} onKeyDown={(e) => { const current = height ?? recent.current?.offsetHeight ?? 0 let next: number if (e.key === 'ArrowUp') next = current - SPLIT_STEP_PX else if (e.key === 'ArrowDown') next = current + SPLIT_STEP_PX else if (e.key === 'Home') next = MIN_RECENT_PX else if (e.key === 'End') next = Number.MAX_SAFE_INTEGER else return e.preventDefault() writeRecentHeight(place(next)) }} > {/* the hairline, which thickens while hovered, dragged or focused */} <span className="h-px w-full bg-line-soft transition-[height,background-color] group-hover:h-[3px] group-hover:bg-line group-focus-visible:h-[3px] group-focus-visible:bg-brand group-active:h-[3px] group-active:bg-brand" /> </div> <AgentChat className="flex-1" /> </div> ) } /** How many tasks the strip shows before "Show all". */ const RECENT_SHOWN = 3 /* The "Recent tasks" strip at the top of the Agents tab: what each agent is working on or just finished, and for whom. "Show all" opens the whole history in the same rows, split into what is running and what is done. */ function RecentTasks() { const tasks = useStore((s) => s.tasks) const [all, setAll] = useState(false) /* unclaimed board cards have no agent yet, so they are not activity */ const claimed = useMemo(() => tasks.filter((t) => t.agentName), [tasks]) const working = useMemo(() => claimed.filter((t) => !t.endedAt && !t.failedAt), [claimed]) const finished = useMemo(() => claimed.filter((t) => t.endedAt || t.failedAt), [claimed]) const t = useT() return ( <section aria-label={t('panels.activityRecentTasks')} className="flex flex-none flex-col pt-1.5 pb-1"> <h3 className="flex h-7 flex-none items-center px-3 text-[11.5px] font-normal text-ink-faint"> {t('panels.activityRecentTasks')} </h3> {claimed.length === 0 ? ( <p className="px-3 pb-2 text-[12px] leading-[1.45] text-ink-faint">{t('panels.activityNoTasks')}</p> ) : all ? ( <> {working.length > 0 && <TaskGroup label={t('panels.activityWorkingOn')} tasks={working} />} {finished.length > 0 && <TaskGroup label={t('panels.activityWorkedOn')} tasks={finished} />} </> ) : ( claimed.slice(0, RECENT_SHOWN).map((task) => <RecentTaskRow key={task.id} task={task} />) )} {claimed.length > RECENT_SHOWN && ( <Button variant="bare" className="mx-1.5 mt-0.5 h-[26px] flex-none justify-start gap-1.5 self-start rounded-[7px] px-1.5 text-[11.5px] font-normal text-ink-soft" aria-expanded={all} onClick={() => setAll((v) => !v)} > {all ? t('panels.activityShowLess') : t('panels.activityShowAll')} <ChevronDownIcon className={cn('size-3 text-ink-faint transition-transform', all && 'rotate-180')} /> </Button> )} </section> ) } /** A labelled run of rows in the expanded list. */ function TaskGroup({ label, tasks }: { label: string; tasks: AgentTask[] }) { return ( <> <h4 className="flex h-6 flex-none items-center px-3 pt-1 text-[11px] font-normal text-ink-faint">{label}</h4> {tasks.map((t) => ( <RecentTaskRow key={t.id} task={t} /> ))} </> ) } /** The one figure a row shows at its right end: how far a job has got, how * long a running task has been at it, or how long ago a finished one ended. */ function taskTime(task: AgentTask): string { if (task.failedAt) return timeAgo(task.failedAt) if (task.endedAt) return timeAgo(task.endedAt) return duration(task) } /** One task: who, for whom, one time figure; then its mark and what it is doing. * Clicking it selects the frame where the agent is (or was) working and flies * the camera there, so the click shows even when the frame is already in view. */ function RecentTaskRow({ task }: { task: AgentTask }) { const canvasId = useStore((s) => s.canvas?.id) const canEdit = useStore(canEditOpenCanvas) const frameId = useStore((s) => taskFrameId(task, s)) const frameName = useStore((s) => s.canvas?.frames.find((f) => f.id === frameId)?.name) const goToFrame = () => { if (!frameId) return const s = useStore.getState() s.select(frameId) s.requestFlyTo(frameId) } const t = useT() const running = !task.endedAt && !task.failedAt const failed = !!task.failedAt const reason = task.failureReason ?? t('panels.activityTaskUnfinished') /* a job's status already is its reason; a card's status is its brief */ const separateReason = failed && reason !== task.status return ( <div role={frameId ? 'button' : undefined} tabIndex={frameId ? 0 : undefined} title={frameName ? t('panels.activityGoTo', { name: frameName }) : undefined} onClick={goToFrame} onKeyDown={(e) => { if (e.target !== e.currentTarget) return if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() goToFrame() } }} className={cn( 'mx-1.5 grid animate-[chip-in_0.25s_ease] grid-cols-[minma - src/components/AgentChat.tsx (3545 bytes)
import { useLayoutEffect, useMemo, useRef } from 'react' import { useStore } from '../lib/store' import { authClient } from '../lib/auth' import { cn } from '@/lib/utils' import { useT } from '@/lib/i18n' import { AgentIcon } from './AgentIcon' import { DotMatrix } from './ui/dot-matrix' import { chatTurns, chatTurnsKey, type ChatTurn } from '../lib/agentChat' /** How close to the bottom still counts as reading the latest answer. */ const STICK_PX = 48 /* The Agents tab's conversation: each prompt sent from the composer (or feedback left on one) and the agent's answer under it, oldest at the top, kept scrolled to the newest unless the reader has scrolled up. */ export function AgentChat({ className }: { className?: string }) { const tasks = useStore((s) => s.tasks) const feedback = useStore((s) => s.feedback) const { data: session } = authClient.useSession() const userId = session?.user.id const turns = useMemo(() => chatTurns(tasks, feedback, userId), [tasks, feedback, userId]) const key = chatTurnsKey(turns) const scroller = useRef<HTMLDivElement>(null) const stuck = useRef(true) const t = useT() /* follow the conversation while the reader is at its end */ useLayoutEffect(() => { const el = scroller.current if (el && stuck.current) el.scrollTop = el.scrollHeight }, [key]) if (turns.length === 0) return null return ( <section ref={scroller} aria-label={t('panels.chatLabel')} onScroll={(e) => { const el = e.currentTarget stuck.current = el.scrollHeight - el.scrollTop - el.clientHeight < STICK_PX }} className={cn('flex min-h-0 flex-col gap-3 overflow-y-auto overscroll-contain px-3 py-3', className)} > {turns.map((turn) => ( <ChatExchange key={turn.id} turn={turn} /> ))} </section> ) } function ChatExchange({ turn }: { turn: ChatTurn }) { const t = useT() return ( <> <div className="flex max-w-[85%] flex-col items-end gap-1 self-end"> {!turn.mine && <span className="text-caption text-ink-faint">{turn.from}</span>} <p className="rounded-card bg-sub px-2.5 py-1.5 text-body break-words whitespace-pre-line text-ink"> {turn.text} </p> </div> {turn.state === 'queued' ? ( <p className="text-caption text-ink-faint">{t('panels.chatQueued')}</p> ) : ( <div className="flex flex-col gap-1 text-body text-ink-soft"> <span className="flex items-center gap-1.5 font-medium text-ink"> <AgentIcon name={turn.agentName} size={14} /> {turn.agentName} </span> <AgentAnswer turn={turn} /> </div> )} </> ) } function AgentAnswer({ turn }: { turn: ChatTurn }) { const t = useT() /* a retry or the next stage of a pipeline keeps the last run's answer on the card until its own replaces it; while it runs, that one is stale */ if (turn.state === 'working') return ( <span className="flex items-center gap-2 text-ink-faint"> <DotMatrix /> {t('panels.chatWorking')} </span> ) const failure = turn.state === 'failed' && ( <p className="break-words text-accent-ink">{turn.failureReason ?? t('panels.activityTaskUnfinished')}</p> ) if (turn.reply) return ( <> <p className="break-words whitespace-pre-line">{turn.reply}</p> {failure} </> ) /* finished before answers were kept */ return failure || <p className="text-ink-faint">{t('panels.chatDone')}</p> } - src/components/AgentIcon.tsx (2503 bytes)
/** Brand icons for well-known agents; the Doop mark otherwise. The marks * themselves come from the BrandMark registry — this only knows which agent * wears which brand. */ import { agentBrandOf, type AgentBrand } from '../../shared/agentBrand' import { useStore } from '../lib/store' import { AppIcon, BrandMark, type AppIconBrand } from './ui/brand-mark' import { DoopMark, Logo } from './Logo' export function AgentIcon({ name, brand, size = 13, color, }: { name: string /** the brand its presence carries (read from its MCP client); unset, the * presence of an agent by this name on the open canvas is asked, then the name */ brand?: AgentBrand size?: number color?: string }) { const present = useStore((s) => { if (brand) return undefined for (const p of Object.values(s.presences)) if (p.kind === 'agent' && p.name === name && p.brand) return p.brand return undefined }) const shown = brand ?? present ?? agentBrandOf(name) /* Anything else is a Doop agent (the built-in roles, or an unknown MCP client) and wears the brand's own mark, as on the marketing site. */ if (!shown) return <DoopMark size={size} color={color} /> return <BrandMark brand={shown} size={size} color={color} className="mr-px inline-block align-[-2px]" /> } /* the agent brands that have an app icon of their own; the rest sit on a plain tile */ const AGENT_APP_ICONS: Partial<Record<AgentBrand, AppIconBrand>> = { claude: 'claude', openai: 'openai', cursor: 'cursor', gemini: 'gemini', github: 'github', kimi: 'kimi', } /** An agent as an app icon: its brand's own tile and colours (Claude's orange, * ChatGPT's knot on white), Doop's black tile for a Doop agent, and the brand * mark on a plain tile for a client without an icon of its own. */ export function AgentTile({ name, brand, size = 18 }: { name: string; brand?: AgentBrand; size?: number }) { const shown = brand ?? agentBrandOf(name) if (!shown) return ( <span aria-hidden className="flex-none" style={{ width: size, height: size }}> <Logo className="block size-full" /> </span> ) const app = AGENT_APP_ICONS[shown] if (app) return <AppIcon brand={app} size={size} /> return ( <span aria-hidden className="grid flex-none place-items-center bg-white shadow-ring" style={{ width: size, height: size, borderRadius: '23%' }} > <BrandMark brand={shown} size={Math.round(size * 0.56)} color="#111" /> </span> ) } - src/components/AgentKeys.tsx (6133 bytes)
import { useEffect, useState } from 'react' import { api, errorMessage, type AgentKeyInfo } from '../lib/api' import { posthog } from '../lib/posthog' import { timeAgo } from '../lib/time' import { t as translate, useT } from '../lib/i18n' import { ConfirmDialog } from './ui/alert-dialog' import { Button } from './ui/button' import { Input } from './ui/input' import { Note } from './ui/note' import { CodeBlock } from './ui/code-block' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' import { TrashIcon } from './ui/icons' /* same fixed-column-on-desktop rhythm as the other settings cards */ /** The MCP config a headless client needs, with the key in place. Shown once, * right after minting — the moment the person actually has the secret. */ function headlessConfig(secret: string): string { return JSON.stringify( { mcpServers: { doop: { type: 'http', url: `${location.origin}/mcp`, headers: { Authorization: `Bearer ${secret}` } }, }, }, null, 2, ) } /** The "Agent keys" pane of /settings: mint, list and revoke the bearer * credentials headless MCP clients (Mastra, n8n, CI) connect with. The * secret appears exactly once, in the mint response — after that the list * knows only each key's first characters. */ export function AgentKeys() { const t = useT() const [keys, setKeys] = useState<AgentKeyInfo[] | null>(null) const [name, setName] = useState('') const [minting, setMinting] = useState(false) const [error, setError] = useState('') /* the one moment the full secret exists client-side */ const [minted, setMinted] = useState<{ id: string; secret: string } | null>(null) /* the key awaiting "are you sure" — an in-app dialog, since window.confirm is a silent "cancel" in the desktop shell's webview */ const [confirmRevoke, setConfirmRevoke] = useState<AgentKeyInfo | null>(null) /* `keys === null` is "still loading", and minting stays disabled until it resolves: a list request in flight would otherwise land after the key it doesn't know about and drop it from the list. A failed load still opens the pane — an empty list you can mint into beats a dead card. */ useEffect(() => { api.listAgentKeys().then(setKeys, (e: unknown) => { console.error(e) setKeys([]) /* the free translator: the effect runs once, and useT's `t` is new every render */ setError(errorMessage(e, translate('agentKeys.loadFailed'))) }) }, []) async function mint() { setMinting(true) setError('') try { const { secret, ...info } = await api.createAgentKey(name) posthog.capture('agent_key_created') setName('') setMinted({ id: info.id, secret }) setKeys((current) => [info, ...(current ?? [])]) } catch (e) { setError(errorMessage(e, t('agentKeys.createFailed'))) } finally { setMinting(false) } } async function revoke(key: AgentKeyInfo) { try { await api.deleteAgentKey(key.id) posthog.capture('agent_key_revoked') setKeys((current) => current?.filter((k) => k.id !== key.id) ?? null) if (minted?.id === key.id) setMinted(null) } catch (e) { setError(errorMessage(e, t('agentKeys.revokeFailed'))) } } return ( <SettingsCard> <CardHeader> <CardTitle>{t('agentKeys.title')}</CardTitle> <CardDescription>{t('agentKeys.description')}</CardDescription> </CardHeader> <CardRow label={t('agentKeys.newKeyRow')} action={ <Button size="sm" disabled={minting || keys === null} onClick={mint}> {minting ? t('agentKeys.creating') : t('agentKeys.createKey')} </Button> } control={ <Input value={name} onChange={(e) => { setName(e.target.value) setError('') }} placeholder={t('agentKeys.namePlaceholder')} maxLength={60} aria-label={t('agentKeys.nameAria')} /> } > {error && <Note tone="error">{error}</Note>} </CardRow> {minted && ( <CardRow label={t('agentKeys.yourNewKey')}> <div className="min-w-0 flex-1"> <Note tone="success">{t('agentKeys.copyNow')}</Note> <CodeBlock className="mt-2" text={minted.secret} /> <p className="mb-1.5 mt-3 text-caption font-medium text-ink-faint">{t('agentKeys.headlessConfigLabel')}</p> <CodeBlock text={headlessConfig(minted.secret)} /> </div> </CardRow> )} {keys?.map((key) => ( <CardRow key={key.id} label={key.name} action={ <Button size="sm" variant="ghost" aria-label={t('agentKeys.revokeAria', { name: key.name })} onClick={() => setConfirmRevoke(key)} > <TrashIcon /> {t('agentKeys.revoke')} </Button> } > <span className="font-mono text-body text-ink-soft">{key.start}…</span> <Note> {key.lastUsedAt ? t('agentKeys.createdLastUsed', { created: timeAgo(key.createdAt), used: timeAgo(key.lastUsedAt) }) : t('agentKeys.createdNeverUsed', { created: timeAgo(key.createdAt) })} </Note> </CardRow> ))} {keys && keys.length === 0 && !minted && ( <CardRow label={t('agentKeys.noKeysRow')}> <Note>{t('agentKeys.noKeysNote')}</Note> </CardRow> )} <ConfirmDialog open={!!confirmRevoke} onOpenChange={(open) => !open && setConfirmRevoke(null)} title={t('agentKeys.revokeConfirmTitle', { name: confirmRevoke?.name ?? '' })} description={t('agentKeys.revokeConfirmDescription')} confirmLabel={t('agentKeys.revokeConfirm')} destructive onConfirm={() => { const target = confirmRevoke setConfirmRevoke(null) if (target) void revoke(target) }} /> </SettingsCard> ) } - src/components/AppearanceSettings.tsx (1815 bytes)
import { useTheme } from '../lib/theme' import { useT } from '../lib/i18n' import { ThemePicker } from './ThemePicker' import { PanelLayoutPicker } from './PanelLayoutPicker' import { usePanelLayout } from '../lib/panelLayout' import { Note } from './ui/note' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' /** The "Appearance" pane of /settings. The theme and the canvas panel * layout are properties of this browser rather than the * account — how the device looks and reads, like zoom — so nothing here * touches the server. */ export function AppearanceSettings() { const { theme, resolved } = useTheme() const t = useT() const panelLayout = usePanelLayout() return ( <> <SettingsCard> <CardHeader> <CardTitle>{t('settings.themeTitle')}</CardTitle> <CardDescription>{t('settings.themeDescription')}</CardDescription> </CardHeader> <CardRow label={t('settings.themeRow')}> <ThemePicker /> <Note> {theme === 'system' ? t('settings.themeFollowingSystem', { resolved: t(resolved === 'dark' ? 'settings.themeResolvedDark' : 'settings.themeResolvedLight'), }) : t('settings.themeSetByHand')} </Note> </CardRow> </SettingsCard> <SettingsCard> <CardHeader> <CardTitle>{t('settings.panelsTitle')}</CardTitle> <CardDescription>{t('settings.panelsDescription')}</CardDescription> </CardHeader> <CardRow label={t('settings.panelsRow')}> <PanelLayoutPicker /> <Note>{t(panelLayout === 'docked' ? 'settings.panelsDockedNote' : 'settings.panelsFloatingNote')}</Note> </CardRow> </SettingsCard> </> ) } - src/components/AppRail.tsx (22539 bytes)
import { useEffect, useLayoutEffect, useMemo, useState, type ReactNode } from 'react' import type { CanvasMeta, WorkspaceSummary } from '../../shared/types' import { api } from '../lib/api' import { authClient } from '../lib/auth' import { navigate } from '../lib/navigate' import { useRailDrawer } from '../lib/railDrawer' import { timeAgo } from '../lib/time' import { openCanvasTab } from '../lib/desktop' import { useT } from '../lib/i18n' import { cn } from '@/lib/utils' import { AgentTile } from './AgentIcon' import { AccountMenu } from './DashShell' import { offersUpgrade, useMe } from '../lib/me' import { openUpgrade } from '../lib/upgrade' import { CanvasSearchModal } from './CanvasSearchModal' import { ConnectModal } from './ConnectModal' import { NativeAppCard } from './NativeAppPromo' import { DashNavItem, DashSectionLabel, DashSidebar, DashSidebarBrand } from './ui/dash' import { Dot } from './ui/dot' import { IconButton } from './ui/icon-button' import { Button } from './ui/button' import { Sheet, SheetContent, SheetTitle } from './ui/sheet' import { BlocksIcon, BuildingIcon, CirclePlusIcon, CreditCardIcon, FolderPlusIcon, GearIcon, GridIcon, LockIcon, PanelCollapseIcon, PanelExpandIcon, SearchIcon, TextIcon, BotIcon, BookOpenIcon, UserIcon, UsersIcon, WebIcon, WorkflowIcon, RocketIcon, } from './ui/icons' /** * The signed-in shell's rail, as the home design draws it: canvases, * workspaces, explore, resources and agents in 12.5px rows, a search palette * and a collapse control up top, and the account face at the bottom. Every * dashboard page mounts the same one, so the chrome cannot drift between * Home, Automations, Integrations, Community, Workspace and Admin. Its rows * are the rail density of the dash primitives (ui/dash.tsx), which Settings * also draws its own rail from. * * It owns the search palette, the connect-an-agent modal and its collapsed * state (remembered per browser). A page that needs its own group — the * admin indexes — passes it as children, and it lands after Resources. * * The workspace in view opens under its row: its canvases, people and fonts, * plus plan & billing and settings for its owner and admins. On the * Workspace page those rows switch its pane in place (onWorkspacePane); * anywhere else they go to /w/<id>?pane=…. * * Below md the same rail slides in as a drawer over the page; the header's * brand row (DashBrand) opens it, and any row that leads somewhere closes it. */ /** which row is lit: a home scope, a workspace, or one of the other pages */ export type RailActive = 'all' | 'mine' | 'shared' | 'automations' | 'integrations' | 'community' | `ws:${string}` | null /** the Workspace page's panes, in the order the rail lists them */ export type WorkspacePane = 'members' | 'fonts' | 'agents' | 'libraries' | 'billing' | 'general' const WORKSPACE_PANES: readonly WorkspacePane[] = ['members', 'fonts', 'agents', 'libraries', 'billing', 'general'] /** the panes a workspace role may open: billing and settings are for its owner and admins */ export function workspacePanesFor(role: WorkspaceSummary['role'] | undefined): WorkspacePane[] { return WORKSPACE_PANES.filter((p) => role !== 'member' || (p !== 'billing' && p !== 'general')) } /** an agent that worked this recently is treated as still at the desk */ const LIVE_WINDOW = 5 * 60 * 1000 const RAIL_STORAGE_KEY = 'doop-rail' type RailLists = { canvases: CanvasMeta[]; workspaces: WorkspaceSummary[] } /* the lists the last rail showed: moving between pages remounts the rail, and starting from these instead of empty keeps its rows from blinking out until the next fetch answers */ let lastLists: RailLists | null = null function readRailOpen(): boolean { try { return localStorage.getItem(RAIL_STORAGE_KEY) !== 'narrow' } catch { return true } } export function AppRail({ active, canvases, workspaces, onScope, onCreateWorkspace, workspacePane, onWorkspacePane, searchShortcut = true, children, }: { active: RailActive /** the lists the rail reads agents and the search palette from: fetched here when a page passes none * (undefined); null while the page is still loading its own, which shows the last lists drawn */ canvases?: CanvasMeta[] | null workspaces?: WorkspaceSummary[] | null /** Home filters in place; any other page goes home with the scope in the URL */ onScope?: (scope: 'all' | 'mine' | 'shared' | `ws:${string}`) => void onCreateWorkspace?: () => void /** the pane the Workspace page shows; unset elsewhere, where the workspace's canvases are in view */ workspacePane?: WorkspacePane /** the Workspace page switches panes in place; any other page goes to it */ onWorkspacePane?: (pane: WorkspacePane) => void /** off on a page whose own search owns ⌘K (the community gallery) */ searchShortcut?: boolean children?: ReactNode }) { const t = useT() const { data: session } = authClient.useSession() const me = useMe(session?.user.id) const offerUpgrade = offersUpgrade(me) const [own, setOwn] = useState<RailLists | null>(() => lastLists) const needsOwn = canvases === undefined || workspaces === undefined useEffect(() => { if (!needsOwn) return Promise.all([api.listCanvases(), api.listWorkspaces()]) .then(([c, w]) => setOwn({ canvases: c, workspaces: w.workspaces })) .catch(console.error) }, [needsOwn]) const list = useMemo(() => canvases ?? own?.canvases ?? [], [canvases, own]) const spaces = useMemo(() => workspaces ?? own?.workspaces ?? [], [workspaces, own]) /* only real lists are kept: a page still loading passes null, never an empty stand-in */ useEffect(() => { if ((canvases ?? own?.canvases) && (workspaces ?? own?.workspaces)) lastLists = { canvases: list, workspaces: spaces } }, [canvases, workspaces, own, list, spaces]) const [open, setOpen] = useState(readRailOpen) const drawer = useRailDrawer((s) => s.open) const setDrawer = useRailDrawer((s) => s.setOpen) const upgrade = () => { setDrawer(false) openUpgrade({ source: 'rail' }) } const setMounted = useRailDrawer((s) => s.setMounted) /* tells DashHeader a rail is here to open; before paint, so the phone's brand row does not pop in a frame after the rest of the header */ useLayoutEffect(() => { setMounted(true) return () => setMounted(false) }, [setMounted]) /* widening past md hides the drawer panel but not its backdrop, so the drawer closes the moment the desktop rail takes over */ useEffect(() => { const desktop = window.matchMedia('(min-width: 56.25rem)') function onChange(e: MediaQueryListEvent) { if (e.matches) setDrawer(false) } desktop.addEventListener('change', onChange) return () => desktop.removeEventListener('change', onChange) }, [setDrawer]) const [searching, setSearching] = useState(false) const [connecting, setConnecting] = useState(false) /* a clock the render can read: an agent that just worked shows as live */ const [now, setNow] = useState(0) useEffect(() => { const start = window.setTimeout(() => setNow(Date.now()), 0) const tick = window.setInterval(() => setNow(Date.now()), 30_000) return () => { window.clearTimeout(start) window.clearInterval(tick) } }, []) /* ⌘K opens the search palette from anywhere in the shell */ useEffect(() => { if (!searchShortcut) return function onKey(e: KeyboardEvent) { if (e.key === 'k' && (e.metaKey || e.ctrlKey)) { e.preventDefault() setSearching(true) } } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, [searchShortcut]) /* the fade belongs to the collapse toggle, not to arriving on a page */ const [toggled, setToggled] = useState(false) function setRail(next: boolean) { setOpen(next) setToggled(true) try { localStorage.setItem(RAIL_STORAGE_KEY, next ? 'wide' : 'narrow') } catch { /* private mode: the choice lives for this page only */ } } /* every row that leads somewhere also puts the phone drawer away */ function go(path: string) { setDrawer(false) navigate(path) } function scope(next: 'all' | 'mine' | 'shared' | `ws:${string}`) { setDrawer(false) if (onScope) onScope(next) else navigate(next === 'all' ? '/' : `/?scope=${encodeURIComponent(next)}`) } function createWorkspace() { setDrawer(false) if (onCreateWorkspace) onCreateWorkspace() else navigate('/?workspace=new') } function openPane(workspaceId: string, pane: WorkspacePane) { setDrawer(false) if (onWorkspacePane) onWorkspacePane(pane) else navigate(`/w/${workspaceId}?pane=${pane}`) } /* the workspace in view, which opens its rows under its own */ const openWorkspace = active?.startsWith('ws:') ? active.slice(3) : null const paneRows = { members: { label: t('rail.workspacePeople'), icon: <UsersIcon size="rail" /> }, fonts: { label: t('rail.workspaceFonts'), icon: <TextIcon size="rail" /> }, agents: { label: t('rail.workspaceAgents'), icon: <BotIcon size="rail" /> }, libraries: { label: t('rail.workspaceLibraries'), icon: <BookOpenIcon size="rail" /> }, billing: { label: t('rail.workspaceBilling'), icon: <CreditCardIcon size="rail" /> }, general: { label: t('rail.workspaceSettings'), icon: <GearIcon size="rail" /> }, } satisfies Record<WorkspacePane, { label: string; icon: ReactNode }> function openSearch() { setDrawer(false) setSearching(true) } function connect() { setDrawer(false) setConnecting(true) } function openCanvas(c: CanvasMeta) { if (!openCanvasTab(c.id, c.name)) navigate(`/c/${c.id}`) } /* every agent that has worked on these canvases, aggregated across them */ const agents = useMemo(() => { const map = new Map<string, { name: string; lastAt: number; canvases: number }>() for (const c of list) { for (const a of c.agents ?? []) { const e = map.get(a.name) if (e) { e.canvases += 1 e.lastAt = Math.max(e.lastAt, a.lastAt ?? 0) } else map.set(a.name, { name: a.name, lastAt: a.lastAt ?? 0, canvases: 1 }) } } return [...map.values()].sort((x, y) => y.lastAt - x.lastAt).slice(0, 5) }, [list]) const modals = ( <> {connecting && <ConnectModal onClose={() => setConnecting(false)} />} {searching && ( <CanvasSearchModal canvases={list} onClose={() => setSearching(false)} onOpen={(c) => { setSearching(false) openCanvas(c) }} /> )} </> ) const narrow = ( <div key="narrow" data-icon-motion className={cn( 'flex min-h-full w-full flex-col items-center', toggled && 'animate-[fade-in_0.25s_ease] motion-reduce:animate-none', )} > <DashSidebarBrand onHome={() => go('/')} /> <IconButton aria-label={t('rail.showSidebar')} onClick={() => setRail(true)}> <PanelExpandIcon width={15} height={15} /> </IconButton> <IconButton aria-label={t('rail.searchCanvasesShortcut')} onClick={openSearch}> <SearchIcon width={15} height={15} /> </IconButton> <Rule /> <IconButton aria-label={t('rail.allCanvases')} on={active === 'all'} onClick={() => scope('all')}> <GridIcon size="rail" /> </IconButton> <IconButton aria-label={t('rail.ownedByMe')} on={active === 'mine'} onClick={() => scope('mine')}> <UserIcon size="rail" /> </IconButton> <IconButton aria-label={t('rail.sharedWithMe')} on={active === 'shared'} onClick={() => scope('shared')}> <UsersIcon size="rail" /> </IconButton> <Rule /> {spaces.map((w) => ( <div key={w.id} className="contents"> <IconButton aria-label={w.name} on={active === `ws:${w.id}` && !workspacePane} onClick={() => scope(`ws:${w.id}`)} > <BuildingIcon size="rail" /> </IconButton> {openWorkspace === w.id && workspacePanesFor(w.role).map((p) => ( <IconButton key={p} aria-label={`${w.name}: ${paneRows[p].label}`} on={workspacePane === p} onClick={() => openPane(w.id, p)} > {paneRows[p].icon} </IconButton> ))} </div> ))} <IconButton aria-label={t('rail.newWorkspace')} onClick={createWorkspace}> <FolderPlusIcon size="rail" /> </IconButton> <Rule /> <IconButton aria-label={t('rail.community')} on={active === 'community'} onClick={() => go('/community')}> <WebIcon size="rail" /> </IconButton> <IconButton aria-label={t('rail.automations')} on={active === 'automations'} onClick={() => go('/automations')}> <WorkflowIcon size="rail" /> </IconButton> <IconButton aria-label={t('rail.integrations')} on={active === 'integrations'} onClick={() => go('/integrations')} > <BlocksIcon size="rail" /> </IconButton> <Rule /> {agents.map((a) => ( <span key={a.name} className="grid size-8 place-items-center" title={a.name}> <AgentTile name={a.name} /> </span> ))} <IconButton aria-label={t('rail.connectAgent')} onClick={connect}> <CirclePlusIcon size="rail" /> </IconButton> {children ? ( <> <Rule /> {/* the page's own group, as glyphs: labels stay for screen readers */} <div data-rail="narrow" className="flex w-full flex-col items-center gap-0.5"> {children} </div> </> ) : null} <div className="mt-auto flex flex-col items-center gap-2 pt-4"> {offerUpgrade && ( <IconButton aria-label={t('plans.upgradeToPro')} title={t('plans.upgradeToPro')} onClick={upgrade}> <RocketIcon size="rail" className="text-brand" /> </IconButton> )} <AccountMenu face side="top" align="start" /> </div> </div> ) /* the full rail; in the phone drawer the hide control closes the drawer instead of narrowing the rail */ const wide = (inDrawer: boolean) => ( <div key="wide" data-icon-motion className={cn( 'flex min-h-full w-full flex-col', toggled && 'animate-[fade-in_0.25s_ease] motion-reduce:animate-none', )} > <DashSidebarBrand onHome={() => go('/')}> <span className="ml-auto flex items-center gap-2.5 text-ink-soft"> <IconButton size="sm" aria-label={t('rail.searchCanvasesShortcut')} onClick={openSearch}> <SearchIcon width={15} height={15} /> </IconButton> <IconButton size="sm" - src/components/AutomateShell.tsx (10681 bytes)
import type { SVGProps } from 'react' import { AGENT_ROLES, roleById } from '../../shared/agents' import { RoleMark } from './RoleMark' import { BrandMark } from './ui/brand-mark' import { Dot } from './ui/dot' import { CheckIcon, ClockIcon } from './ui/icons' import { cn } from '@/lib/utils' import { clientIntegrations } from '../integrations' import type { AutomationExample, Schedule } from '../../shared/automations' import { getLocale, useT, type PlainMessageKey, type Translate } from '@/lib/i18n' /** * Pieces the Automations and Integrations pages share: the provider and * trigger marks and the run status dot. Controls come from `ui/` (Switch, * Select). The rail itself is the shell's AppRail. Visual reference: the * "Automations 0/1/5" frames on the Doop Dashboard canvas. */ /* ---- marks ---- */ /** The trigger's mark: a clock on an ink tile. */ export function ClockTile({ size = 24, className }: { size?: number; className?: string }) { const icon = Math.round(size * 0.58) return ( <span className={cn('inline-grid flex-none place-items-center rounded-row bg-ink', className)} style={{ width: size, height: size, borderRadius: Math.round(size * 0.29) }} aria-hidden > <ClockIcon width={icon} height={icon} strokeWidth={1.9} className="text-paper" /> </span> ) } /** Meta's mark on a paper tile — the provider's own identity, not a Doop role. */ export function MetaTile({ size = 24, className }: { size?: number; className?: string }) { const icon = Math.round(size * 0.58) return ( <span className={cn('inline-grid flex-none place-items-center bg-paper-deep', className)} style={{ width: size, height: size, borderRadius: Math.round(size * 0.29) }} aria-hidden > <MetaLogo width={icon} height={icon} /> </span> ) } /** Meta's mark, from the BrandMark registry; the square it fills is `width`. */ export function MetaLogo({ width = 16, className }: Pick<SVGProps<SVGSVGElement>, 'width' | 'height' | 'className'>) { return <BrandMark brand="meta" size={Number(width)} className={className} /> } export function ApprovalTile({ size = 24 }: { size?: number }) { return ( <span /* white on the green fill, like text on brand: success-ink nearly matches the fill in dark mode */ className="inline-grid flex-none place-items-center rounded-row bg-success text-white" style={{ width: size, height: size }} aria-hidden > <CheckIcon width={size * 0.6} height={size * 0.6} strokeWidth={2.25} /> </span> ) } type MarkStep = { type: 'pull'; provider?: string } | { type: 'agent'; roles: string[] } | { type: 'slack' | 'linear' } /** The chain that summarises an automation: clock, then a Meta tile per * pull and a role mark per agent, joined by short dashes when `joined`. */ export function StepChain({ steps, size = 26, joined = true, className, approval = false, }: { steps: MarkStep[] size?: number joined?: boolean className?: string approval?: boolean }) { const marks: React.ReactNode[] = [ approval ? <ApprovalTile key="approval" size={size} /> : <ClockTile key="clock" size={size} />, ] steps.forEach((s, i) => { if (s.type === 'pull') marks.push(<PullMark key={`p${i}`} provider={s.provider} size={size} className="border border-line bg-surface" />) else if (s.type === 'slack' || s.type === 'linear') marks.push(<PullMark key={`d${i}`} provider={s.type} size={size} />) else if (s.type === 'agent') marks.push( <span key={`a${i}`} className="flex"> {s.roles.map((id, j) => ( <RoleMark key={id} /* a custom agent wears the neutral mark here: a list spans canvases */ role={roleById(id, AGENT_ROLES)} size={size} className={cn(j > 0 && 'ring-[1.5px] ring-surface')} style={j > 0 ? { marginLeft: -Math.round(size * 0.3) } : undefined} /> ))} </span>, ) }) const dash = <span className="h-px w-3 flex-none bg-line" aria-hidden /> return ( <span className={cn('inline-flex items-center', joined ? 'gap-1.5' : 'gap-1', className)}> {marks.map((m, i) => ( <span key={i} className="inline-flex items-center gap-1.5"> {i > 0 && joined && dash} {m} </span> ))} </span> ) } /** The status dot a run row leads with: the shared Dot, toned by the run's outcome. */ const RUN_TONE = { running: 'running', ok: 'done', failed: 'failed' } as const const RUN_STATUS_LABEL = { running: 'automations.statusRunning', ok: 'automations.statusOk', failed: 'automations.statusFailed', } as const satisfies Record<keyof typeof RUN_TONE, PlainMessageKey> export function RunDot({ status, className }: { status: keyof typeof RUN_TONE; className?: string }) { const t = useT() return ( <Dot tone={RUN_TONE[status]} className={className} role="img" aria-hidden={false} aria-label={t(RUN_STATUS_LABEL[status])} /> ) } /** "Mon, Sep 8 · 9:00 AM" — in the app's language, so the clock reads the * way the rest of the screen does. Called while rendering, so it follows a * language switch with the component that shows it. */ export function formatRunTime(at: number): string { const d = new Date(at) const locale = getLocale() const day = d.toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' }) const time = d.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }) return `${day} · ${time}` } /* ---- schedules, reasons and examples, as the screens say them ---- */ const WEEKLY_LABEL = [ 'automations.scheduleWeekly0', 'automations.scheduleWeekly1', 'automations.scheduleWeekly2', 'automations.scheduleWeekly3', 'automations.scheduleWeekly4', 'automations.scheduleWeekly5', 'automations.scheduleWeekly6', ] as const satisfies readonly PlainMessageKey[] /** The clock in the app's language: "9:00 AM" or "09:00". */ export function clockText(hour: number, minute: number): string { return new Date(2000, 0, 1, hour, minute).toLocaleTimeString(getLocale(), { hour: 'numeric', minute: '2-digit' }) } /** "Every Monday 9:00 AM", or "every Monday 9:00 AM" for the middle of a * sentence (`lower`; "Weekdays" keeps its capital, as it always has). */ export function scheduleText(t: Translate, s: Pick<Schedule, 'kind' | 'weekday' | 'hour' | 'minute'>, lower = false) { let when = s.kind === 'daily' ? t('automations.scheduleDaily') : s.kind === 'weekdays' ? t('automations.scheduleWeekdays') : t(WEEKLY_LABEL[s.weekday] ?? 'automations.scheduleWeekly1') if (lower && s.kind !== 'weekdays') when = when.charAt(0).toLocaleLowerCase(getLocale()) + when.slice(1) return t('automations.scheduleWhenTime', { when, time: clockText(s.hour, s.minute) }) } /** "Mon" — a weekday's short name in the app's language. */ export function weekdayShort(weekday: number): string { /* 2023-01-01 was a Sunday, so day 1 + n is weekday n */ return new Date(2023, 0, 1 + weekday).toLocaleDateString(getLocale(), { weekday: 'short' }) } /* incompleteReason (shared with the server) answers in English; the screens say it in the app's language, and show anything unknown as it came */ const INCOMPLETE_LABEL: Record<string, PlainMessageKey> = { 'Pick a canvas to watch for approvals': 'automations.incompleteApprovalCanvas', 'Add a step': 'automations.incompleteAddStep', 'Pick a canvas for every step': 'automations.incompleteStepCanvas', 'Pick a Meta ad account': 'automations.incompleteMetaAccount', 'Write what the agent should do': 'automations.incompleteAgentPrompt', 'Enter a Slack channel ID': 'automations.incompleteSlackChannel', 'Write a Slack message': 'automations.incompleteSlackMessage', 'Choose a Linear team': 'automations.incompleteLinearTeam', 'Write a Linear ticket title': 'automations.incompleteLinearTitle', } export function incompleteText(t: Translate, reason: string): string { const key = INCOMPLETE_LABEL[reason] return key ? t(key) : reason } /* what an example's card says; its brief stays English, for the agent */ const EXAMPLE_LABEL: Record<string, { name: PlainMessageKey; blurb: PlainMessageKey }> = { 'approved-sizes': { name: 'automations.exampleApprovedSizesName', blurb: 'automations.exampleApprovedSizesBlurb', }, 'approved-localization': { name: 'automations.exampleApprovedLocalizationName', blurb: 'automations.exampleApprovedLocalizationBlurb', }, 'approved-assets': { name: 'automations.exampleApprovedAssetsName', blurb: 'automations.exampleApprovedAssetsBlurb', }, 'weekly-creatives': { name: 'automations.exampleWeeklyCreativesName', blurb: 'automations.exampleWeeklyCreativesBlurb', }, 'ad-variants': { name: 'automations.exampleAdVariantsName', blurb: 'automations.exampleAdVariantsBlurb' }, 'friday-ux': { name: 'automations.exampleFridayUxName', blurb: 'automations.exampleFridayUxBlurb' }, 'brand-a11y': { name: 'automations.exampleBrandA11yName', blurb: 'automations.exampleBrandA11yBlurb' }, 'copy-pass': { name: 'automations.exampleCopyPassName', blurb: 'automations.exampleCopyPassBlurb' }, 'nightly-polish': { name: 'automations.exampleNightlyPolishName', blurb: 'automations.exampleNightlyPolishBlurb', }, } export function exampleName(t: Translate, example: AutomationExample): string { const label = EXAMPLE_LABEL[example.id] return label ? t(label.name) : example.name } export function exampleBlurb(t: Translate, example: AutomationExample): string { const label = EXAMPLE_LABEL[example.id] return label ? t(label.blurb) : example.blurb } /** The pulling integration's mark. Meta's without a provider (older rows), * a registered integration's own tile, and a neutral paper tile for one * that registered none — never another integration's logo. */ export function PullMark({ provider, size = 24, className }: { provider?: string; size?: number; className?: string }) { if (!provider || provider === 'meta') return <MetaTile size={size} className={className} /> const Tile = clientIntegrations.find((i) => i.id === provider)?.Tile if (Tile) return <Tile size={size} className={className} /> return ( <span className={cn('inline-grid flex-none place-items-center bg-paper-deep font-mono text-ink-soft', className)} style={{ width: size, height: size, borderRadius: Math.round(size * 0.29), fontSize: Math.round(size * 0.45) }} aria-hidden > {provider.slice(0, 1).toUpperCase()} </span> ) } - src/components/CanvasComments.tsx (8850 bytes)
import { useCallback, useEffect, useRef, useState } from 'react' import type { ElementComment } from '../../shared/types' import { colorFor } from '../../shared/types' import { canvasPages } from '../../shared/pages' import { isCanvasComment, type CanvasComment } from '../../shared/comments' import { useStore } from '../lib/store' import { api } from '../lib/api' import { getIdentity } from '../lib/identity' import type { ComposerPlacement } from '../lib/composerPlacement' import { posthog } from '../lib/posthog' import { isResidentLimit } from './TeamAllowance' import { CommentComposer, CommentPin, CommentThread, PIN_SCALE } from './CommentPopovers' import { cn } from '@/lib/utils' import { CommentIcon } from './ui/icons' import { useT } from '../lib/i18n' /** Where the Comment tool was clicked on empty canvas: a world point on the * active page. `at` makes a second click on the same spot a new request. */ export interface CanvasComposeAt { x: number y: number /** which side of the pin the composer hangs on, and how far to slide it * along x to stay on the stage (src/lib/composerPlacement.ts) */ placement: ComposerPlacement at: number } /* the composer hangs off its anchor point and counter-scales from it, so it keeps its screen size at every zoom like the pins */ const ANCHOR_SCALE = 'origin-top-left [transform:scale(calc(1/var(--zoom,1)))]' /* the wall explains a hit limit; anything else is logged */ function reportLimit(err: unknown) { if (isResidentLimit(err)) useStore.getState().setLimitWall(true) else console.error(err) } /** Comments pinned to the canvas itself — a point on the page rather than * an element: their pins on the active page, the thread that is open, and * the composer the Comment tool opens where the canvas was clicked. Lives * in the world layer so pins stay glued to their point as the camera * moves; the pins and popovers counter-scale through `--zoom`. */ export function CanvasComments({ composeAt, onComposeDone, }: { composeAt: CanvasComposeAt | null /** the composer posted or was cancelled */ onComposeDone: () => void }) { const t = useT() const canvasId = useStore((s) => s.canvas?.id) const pageId = useStore((s) => (s.canvas ? (s.activePageId ?? canvasPages(s.canvas)[0]!.id) : null)) const all = useStore((s) => s.comments) /* only thread roots get a pin; replies live inside the root's popover */ const roots = all.filter( (c): c is CanvasComment => isCanvasComment(c) && c.pageId === pageId && !c.parentId && !c.resolvedAt, ) const [openThread, setOpenThread] = useState<string | null>(null) /* ⇧C hides the pins (an open thread stays); the Comment tool shows them */ const pinsShown = useStore((s) => s.viewOptions.comments || s.tool === 'comment') const rootRef = useRef<HTMLDivElement>(null) /* a pin being dragged, from this layer or out of a frame: its ghost rides the pointer here, above every frame, where no frame surface clips it */ const drag = useStore((s) => s.commentDrag) const dragRoot = drag ? all.find((c) => c.id === drag.id) : undefined /* the Comments panel asked for one of these threads to open: the request is consumed once the thread is up, so a page switch back never reopens it */ const threadRequest = useStore((s) => s.threadRequest) const requested = threadRequest && roots.some((c) => c.id === threadRequest.id) ? threadRequest : null const [seenRequest, setSeenRequest] = useState<typeof requested>(null) if (requested !== seenRequest) { setSeenRequest(requested) if (requested) setOpenThread(requested.id) } useEffect(() => { if (requested) useStore.getState().clearThreadRequest() }, [requested]) /* a fresh compose point takes over from whatever thread was open */ const [seenCompose, setSeenCompose] = useState(composeAt) if (composeAt !== seenCompose) { setSeenCompose(composeAt) if (composeAt) setOpenThread(null) } const close = useCallback(() => { setOpenThread(null) onComposeDone() }, [onComposeDone]) /* Esc, or a press anywhere outside the popovers, closes them. The press is watched in the capture phase: a frame stops it before it would reach the Stage, and a click on empty canvas opens a new composer after. */ const anyOpen = composeAt !== null || openThread !== null useEffect(() => { if (!anyOpen) return function onKey(e: KeyboardEvent) { if (e.key === 'Escape') close() } function onPress(e: PointerEvent) { if (rootRef.current?.contains(e.target as Node)) return /* an open thread is portalled out of this root (CommentPin) */ if (e.target instanceof Element && e.target.closest('[data-comment-thread-anchor]')) return close() } window.addEventListener('keydown', onKey) window.addEventListener('pointerdown', onPress, true) return () => { window.removeEventListener('keydown', onKey) window.removeEventListener('pointerdown', onPress, true) } }, [anyOpen, close]) function post(text: string, mentions: string[]) { if (!canvasId || !pageId || !composeAt) return api .addCanvasComment(canvasId, { pageId, x: composeAt.x, y: composeAt.y, text, mentions }) .then(() => posthog.capture('canvas_comment_created')) .catch(reportLimit) onComposeDone() } return ( /* `data-comment-ui`: the Comment tool's cursor is forced over the whole stage except inside the comment UI, which keeps its own cursors */ <div ref={rootRef} data-comment-ui className="pointer-events-none absolute left-0 top-0 z-[6]"> {roots.map((c) => { const replies = all.filter((r) => r.parentId === c.id).sort((a, b) => a.at - b.at) const thread: [ElementComment, ...ElementComment[]] = [c, ...replies] const open = openThread === c.id /* a pin being dragged stays mounted: its release listeners live on it */ if (!pinsShown && !open && drag?.id !== c.id) return null return ( <CommentPin key={c.id} thread={thread} open={open} left={c.x} top={c.y} onToggle={() => { onComposeDone() setOpenThread(open ? null : c.id) }} > <CommentThread thread={thread} onReply={(text, mentions) => api .replyComment(c.id, text, mentions) .then(() => posthog.capture('element_comment_replied')) .catch((err) => { /* the wall explains a hit limit; anything else surfaces in the thread so the draft survives */ if (isResidentLimit(err)) useStore.getState().setLimitWall(true) throw err }) } onResolve={() => { api .resolveComment(c.id) .then(() => posthog.capture('element_comment_resolved')) .catch(console.error) setOpenThread(null) }} onRetry={(id) => api.retryComment(id).catch(reportLimit)} /> </CommentPin> ) })} {drag && dragRoot && ( <div data-comment-drag className={cn( 'pointer-events-none absolute z-[8] grid h-[26px] w-[26px] place-items-center rounded-[50%_50%_50%_4px] border-2 border-white text-[13px] text-white shadow-pop', PIN_SCALE, )} style={{ left: drag.x, top: drag.y, background: colorFor(dragRoot.from) }} > <CommentIcon size={14} /> </div> )} {composeAt && canvasId && ( <div className={cn('pointer-events-auto absolute z-[7]', ANCHOR_SCALE)} style={{ left: composeAt.x, top: composeAt.y }} onPointerDown={(e) => e.stopPropagation()} > {/* the pin this comment will get, so the point reads before it is posted */} <div className="absolute grid h-[26px] w-[26px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-[50%_50%_50%_4px] border-2 border-white text-[13px] text-white shadow-card animate-[chip-in_0.25s_ease]" style={{ background: colorFor(getIdentity().name) }} > <CommentIcon size={14} /> </div> <div className={cn('absolute -top-[13px]', composeAt.placement.side === 'left' ? 'right-[20px]' : 'left-[20px]')} style={composeAt.placement.shift ? { transform: `translateX(${composeAt.placement.shift}px)` } : undefined} > <CommentComposer placeholder={t('stage.commentHere')} onSubmit={post} onCancel={close} /> </div> </div> )} </div> ) } - src/components/CanvasDrawing.tsx (16294 bytes)
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type RefObject } from 'react' import { useStore } from '../lib/store' import { isDrawingTool, resolvePointerAction, type DrawingTool } from '../lib/tools' import { gesture } from '../lib/gesture' import { visibleGuides } from '../lib/guides' import { snapPointToGuides } from '../lib/snap' import { isTypingTarget } from '../lib/keys' import { useT } from '../lib/i18n' import { usePaper } from '../lib/paper' import { defaultDrawing, drawingBounds, drawingTarget, nearestPathAnchor, pathData, pathDrawing, saveDrawing, DRAWING_FILL, drawingInk, type Drawing, type DrawingTarget, type Point, } from '../lib/drawing' interface Draft { drawing: Drawing target: DrawingTarget typing?: boolean } /** Stage owns the pointer capture, including presses over a frame's shield. * The preview lives in world space, so pan/zoom use the same transform as frames. */ export function useCanvasDrawing(stage: RefObject<HTMLDivElement>) { const [draft, renderDraft] = useState<Draft | null>(null) const draftRef = useRef<Draft | null>(null) const cleanup = useRef<(() => void) | null>(null) const lastPathPress = useRef(0) const [hover, setHover] = useState<(Point & { unsnapped?: boolean }) | null>(null) const setDraft = useCallback((value: Draft | null) => { draftRef.current = value renderDraft(value) }, []) const cancel = useCallback(() => { cleanup.current?.() cleanup.current = null lastPathPress.current = 0 setDraft(null) setHover(null) }, [setDraft]) const finish = useCallback( (closed = false) => { const current = draftRef.current if (!current) return let drawing = current.drawing if (drawing.tool === 'path') { if (!drawing.points || drawing.points.length < 2) return drawing = pathDrawing(drawing.points, closed) } cancel() useStore.getState().setTool('select') if (drawing.tool === 'text' && !drawing.text?.trim()) return void saveDrawing(drawing, current.target) }, [cancel], ) useEffect(() => { const unsub = useStore.subscribe((s, prev) => { if (s.tool !== prev.tool || s.activePageId !== prev.activePageId || s.canvas?.id !== prev.canvas?.id) cancel() }) function onKey(e: KeyboardEvent) { const current = draftRef.current if (!current) return if (e.isComposing || (isTypingTarget(e.target) && !e.target.matches('textarea[data-drawing-input]'))) return if (e.key === 'Alt') { setHover((at) => (at ? { ...at, unsnapped: true } : null)) } else if (e.key === 'Escape') { e.preventDefault() e.stopImmediatePropagation() // Esc leaves text editing the way a blur does: what was typed stays // (an empty draft still vanishes); a shape or path mid-gesture is dropped. if (current.typing) finish() else { cancel() useStore.getState().setTool('select') } } else if ( e.key === 'Enter' && (current.drawing.tool === 'path' || (current.typing && (e.metaKey || e.ctrlKey))) ) { e.preventDefault() e.stopImmediatePropagation() finish() } else if (!current.typing && (e.key === 'Backspace' || e.key === 'Delete')) { e.preventDefault() e.stopImmediatePropagation() const points = current.drawing.points if (points && points.length > 1) setDraft({ ...current, drawing: pathDrawing(points.slice(0, -1)) }) else cancel() } } function onBlur() { // Keep a text draft if focus moved to another application. if (!draftRef.current?.typing) cancel() } function onKeyUp(e: KeyboardEvent) { if (e.key === 'Alt') setHover((at) => (at ? { ...at, unsnapped: false } : null)) } window.addEventListener('keydown', onKey, true) window.addEventListener('keyup', onKeyUp, true) window.addEventListener('blur', onBlur) return () => { unsub() window.removeEventListener('keydown', onKey, true) window.removeEventListener('keyup', onKeyUp, true) window.removeEventListener('blur', onBlur) cleanup.current?.() } }, [cancel, finish, setDraft]) function toWorld(clientX: number, clientY: number): Point { const rect = stage.current!.getBoundingClientRect() const vp = useStore.getState().viewport return { x: (clientX - rect.left - vp.x) / vp.zoom, y: (clientY - rect.top - vp.y) / vp.zoom } } /** The world point under the pointer, pulled onto the ruler guides unless * Alt is held — the same bypass as the pen's anchor snapping. */ function snappedWorld(ev: { clientX: number; clientY: number; altKey: boolean }): Point { const at = toWorld(ev.clientX, ev.clientY) return ev.altKey ? at : snapPointToGuides(at, visibleGuides(), useStore.getState().viewport.zoom) } function onPointerDown(e: ReactPointerEvent<HTMLDivElement>) { if ((e.target as Element).closest('[data-comment-ui]')) { cancel() return } if ((e.target as Element).closest('[data-drawing-input], [data-ruler]')) return if (!e.isPrimary || gesture.pinching) { if (!draftRef.current?.typing) cancel() return } const s = useStore.getState() const tool = s.tool if ( !isDrawingTool(tool) || resolvePointerAction({ tool, target: 'background', button: e.button, pointerType: e.pointerType, spaceHeld: s.panMode, }) !== 'draw' ) return e.preventDefault() e.stopPropagation() if (draftRef.current?.typing) { finish() return } const start = snappedWorld(e) const target = draftRef.current?.target ?? drawingTarget(start, tool) if (!target) return s.setFollowing(null) if (tool === 'path') { const points = draftRef.current?.drawing.points ?? [] const zoom = s.viewport.zoom /* the path's own anchors pull harder than the guides do */ const snapped = e.altKey ? null : nearestPathAnchor(points, toWorld(e.clientX, e.clientY), zoom) const placed = snapped === null ? start : { x: points[snapped]!.x, y: points[snapped]!.y } const closing = points.length >= 2 && snapped === 0 const last = points.at(-1) const repeated = last && Math.hypot(placed.x - last.x, placed.y - last.y) * zoom <= 2 // Preventing pointerdown's default suppresses native dblclick in some // browsers. Recognize the second press here, including a double tap. if (repeated && points.length >= 2 && e.timeStamp - lastPathPress.current < 400) { finish() return } lastPathPress.current = e.timeStamp if (repeated && !closing) return const anchors = closing ? points : [...points, placed] const index = closing ? 0 : anchors.length - 1 const anchor = anchors[index]! setDraft({ target, drawing: pathDrawing(anchors, closing) }) setHover(null) const el = e.currentTarget const pointerId = e.pointerId el.setPointerCapture(pointerId) function moveHandle(ev: PointerEvent) { if (ev.pointerId !== pointerId) return if (gesture.pinching) return cancel() const at = toWorld(ev.clientX, ev.clientY) let dx = at.x - start.x let dy = at.y - start.y if (Math.hypot(dx, dy) * useStore.getState().viewport.zoom < 3) return if (ev.shiftKey) { const angle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4) const length = Math.hypot(dx, dy) dx = Math.cos(angle) * length dy = Math.sin(angle) * length } lastPathPress.current = 0 const next = anchors.map((p, i) => (i === index ? { ...anchor, handle: { x: dx, y: dy } } : p)) setDraft({ target: target!, drawing: pathDrawing(next, closing) }) } function upHandle(ev: PointerEvent) { if (ev.pointerId !== pointerId) return cleanup.current?.() cleanup.current = null if (gesture.pinching) return cancel() if (closing) finish(true) } function cancelHandle(ev: PointerEvent) { if (ev.pointerId === pointerId) cancel() } cleanup.current = () => { window.removeEventListener('pointermove', moveHandle) window.removeEventListener('pointerup', upHandle) window.removeEventListener('pointercancel', cancelHandle) el.removeEventListener('lostpointercapture', cancelHandle) if (el.hasPointerCapture(pointerId)) el.releasePointerCapture(pointerId) } window.addEventListener('pointermove', moveHandle) window.addEventListener('pointerup', upHandle) window.addEventListener('pointercancel', cancelHandle) el.addEventListener('lostpointercapture', cancelHandle) return } cancel() const drawTool: DrawingTool = tool setDraft({ target, drawing: drawingBounds(tool, start, start) }) const el = e.currentTarget const pointerId = e.pointerId el.setPointerCapture(pointerId) function move(ev: PointerEvent) { if (ev.pointerId !== pointerId) return if (gesture.pinching) return cancel() setDraft({ target: target!, drawing: drawingBounds(drawTool, start, snappedWorld(ev), ev.shiftKey), }) } function up(ev: PointerEvent) { if (ev.pointerId !== pointerId) return if (gesture.pinching) return cancel() const end = snappedWorld(ev) const clicked = Math.hypot(end.x - start.x, end.y - start.y) * useStore.getState().viewport.zoom < 3 const drawing = clicked ? defaultDrawing(drawTool, start) : drawingBounds(drawTool, start, end, ev.shiftKey) cleanup.current?.() cleanup.current = null if (drawing.width < 1 || drawing.height < 1) return cancel() setDraft({ target: target!, drawing, typing: tool === 'text' }) if (tool !== 'text') finish() } function cancelled(ev: PointerEvent) { if (ev.pointerId === pointerId) cancel() } cleanup.current = () => { window.removeEventListener('pointermove', move) window.removeEventListener('pointerup', up) window.removeEventListener('pointercancel', cancelled) el.removeEventListener('lostpointercapture', cancelled) if (el.hasPointerCapture(pointerId)) el.releasePointerCapture(pointerId) } window.addEventListener('pointermove', move) window.addEventListener('pointerup', up) window.addEventListener('pointercancel', cancelled) el.addEventListener('lostpointercapture', cancelled) } const preview = draft && ( <DrawingPreview draft={draft} hover={hover} onText={(text, height) => setDraft({ ...draft, drawing: { ...draft.drawing, text, height } })} onFinish={() => finish()} /> ) const penZoom = useStore((s) => s.viewport.zoom) /* what the pen's badge says a press would do: close the path, land on an anchor it already placed, or just add the next point */ const penCursor = (() => { const points = draft?.drawing.tool === 'path' ? (draft.drawing.points ?? []) : [] const snapped = hover && !hover.unsnapped && points.length ? nearestPathAnchor(points, hover, penZoom) : null if (snapped === null) return 'pen' as const return snapped === 0 && points.length >= 2 ? ('pen-close' as const) : ('pen-anchor' as const) })() return { preview, penCursor, pathActive: draft?.drawing.tool === 'path', canFinishPath: (draft?.drawing.points?.length ?? 0) >= 2, finish: () => finish(), cancel, onPointerDown, onPointerMove: (e: ReactPointerEvent) => { if (draftRef.current?.drawing.tool === 'path' && !cleanup.current && !useStore.getState().panMode) setHover({ ...toWorld(e.clientX, e.clientY), unsnapped: e.altKey }) }, onDoubleClick: (e: React.MouseEvent) => { if (draftRef.current?.drawing.tool !== 'path') return e.preventDefault() e.stopPropagation() finish() }, onTouchStart: (e: React.TouchEvent) => { if (e.touches.length >= 2 && !draftRef.current?.typing) cancel() }, } } function DrawingPreview({ draft, hover, onText, onFinish, }: { draft: Draft hover: (Point & { unsnapped?: boolean }) | null onText: (text: string, height: number) => void onFinish: () => void }) { const zoom = useStore((s) => s.viewport.zoom) const t = useT() const paper = usePaper() const d = draft.drawing const ink = drawingInk(draft.target, paper.tone) if (draft.typing) return ( <textarea data-drawing-input aria-label={t('stage.textInputLabel')} autoFocus placeholder={t('stage.textPlaceholder')} value={d.text ?? ''} onChange={(e) => onText(e.target.value, Math.max(d.height, e.target.scrollHeight))} onBlur={onFinish} /* the box is see-through, like the text it becomes: the ring and the placeholder are all that mark it on the canvas */ className="absolute z-30 resize-none border-0 bg-transparent p-0 outline-2 outline-brand placeholder:text-ink-faint" style={{ color: ink, left: d.x, top: d.y, width: d.width, height: Math.max(34, d.height), font: '24px/1.4 Arial,sans-serif', overflowWrap: 'anywhere', }} /> ) if (d.tool === 'path') { const points = d.points ?? [] const snapped = hover && !hover.unsnapped ? nearestPathAnchor(points, hover, zoom) : null const closing = snapped === 0 && points.length >= 2 const at = snapped === null ? hover : { x: points[snapped]!.x, y: points[snapped]!.y } const preview = pathDrawing(at && !d.closed && !closing ? [...points, at] : points, d.closed || closing) return ( <svg data-path-preview className="pointer-events-none absolute z-20 overflow-visible" style={{ left: preview.x, top: preview.y }} width={preview.width} height={preview.height} > <path d={pathData(preview)} fill="none" stroke={ink} strokeWidth={2} strokeLinejoin="round" /> {points .filter((p) => p.handle) .map((p, i) => ( <g key={`handle-${i}`} stroke="var(--brand)" strokeWidth="calc(0.75px / var(--zoom, 1))"> <line x1={p.x - p.handle!.x - preview.x} y1={p.y - p.handle!.y - preview.y} x2={p.x + p.handle!.x - preview.x} y2={p.y + p.handle!.y - preview.y} /> {[-1, 1].map((side) => ( <circle key={side} cx={p.x + side * p.handle!.x - preview.x} cy={p.y + side * p.handle!.y - preview.y} r="calc(2px / var(--zoom, 1))" fill="var(--brand)" /> ))} - src/components/CanvasSearchModal.tsx (3805 bytes)
import { useMemo, useRef, useState, type KeyboardEvent } from 'react' import type { CanvasMeta } from '../../shared/types' import { cn } from '@/lib/utils' import { useT } from '../lib/i18n' import { timeAgo } from '../lib/time' import { FrameThumb } from './FramePreview' import { Modal } from './ui/modal' import { Pressable } from './ui/pressable' import { SearchField } from './ui/search-field' /** * The rail's search: a palette over the page with one field and the * matching canvases under it, each with its preview. Arrow keys move the * highlight, Enter opens, Escape closes — the keyboard path ⌘K people expect. */ const MAX_RESULTS = 8 export function CanvasSearchModal({ canvases, onOpen, onClose, }: { canvases: CanvasMeta[] onOpen: (canvas: CanvasMeta) => void onClose: () => void }) { const t = useT() const [query, setQuery] = useState('') const [cursor, setCursor] = useState(0) const inputRef = useRef<HTMLInputElement>(null) const results = useMemo(() => { const q = query.trim().toLowerCase() if (!q) return canvases.slice(0, MAX_RESULTS) return canvases.filter((c) => c.name.toLowerCase().includes(q)).slice(0, MAX_RESULTS) }, [canvases, query]) /* the highlight follows the list: a shorter result set cannot leave it past the end */ const active = Math.min(cursor, Math.max(results.length - 1, 0)) function onKeyDown(e: KeyboardEvent<HTMLInputElement>) { if (e.key === 'ArrowDown') { e.preventDefault() setCursor((i) => Math.min(i + 1, results.length - 1)) } else if (e.key === 'ArrowUp') { e.preventDefault() setCursor((i) => Math.max(i - 1, 0)) } else if (e.key === 'Enter') { const hit = results[active] if (hit) onOpen(hit) } } return ( <Modal size="lg" onClose={onClose} className="p-0 sm:p-0" aria-label={t('rail.searchCanvases')} /* the field takes the keyboard as it opens: left to Radix, focus lands on the × */ onOpenAutoFocus={(e) => { e.preventDefault() inputRef.current?.focus() }} > <SearchField ref={inputRef} variant="bar" value={query} onChange={(e) => { setQuery(e.target.value) setCursor(0) }} onKeyDown={onKeyDown} placeholder={t('rail.searchCanvases')} aria-label={t('rail.searchCanvases')} inputClassName="text-copy md:text-copy" /> <div className="max-h-[60vh] overflow-y-auto p-2" role="listbox" aria-label={t('rail.results')}> {results.length === 0 ? ( <p className="px-3 py-6 text-center text-body text-ink-faint">{t('rail.noMatch', { query: query.trim() })}</p> ) : ( results.map((c, i) => ( <Pressable key={c.id} role="option" aria-selected={i === active} focus="none" onMouseEnter={() => setCursor(i)} onClick={() => onOpen(c)} className={cn( 'flex items-center gap-3 rounded-pill px-2.5 py-2 transition-colors', i === active ? 'bg-paper-deep' : 'hover:bg-paper', )} > <FrameThumb frameId={c.previewFrameId} /> <span className="min-w-0 flex-1"> <span className="block truncate text-body font-medium text-ink">{c.name}</span> <span className="mt-px block text-caption text-ink-faint"> {t('rail.frameCount', { count: c.frameCount })} · {t('rail.edited', { time: timeAgo(c.updatedAt) })} {c.shared ? ` · ${t('rail.sharedWithYou')}` : ''} </span> </span> </Pressable> )) )} </div> </Modal> ) } - src/components/ClaudeDesktopInstall.tsx (1977 bytes)
import { useState } from 'react' import { addToClaudeDesktop, canAddToClaudeDesktop } from '../lib/claudeConnection' import { posthog } from '../lib/posthog' import { Button } from './ui/button' import { InstallBlock } from './ui/install-block' import { useT } from '../lib/i18n' export function ClaudeDesktopInstall({ mcpUrl }: { mcpUrl: string }) { const t = useT() const [state, setState] = useState<'idle' | 'opening' | 'opened'>('idle') const [error, setError] = useState('') async function connect() { setState('opening') setError('') try { await addToClaudeDesktop(mcpUrl) setState('opened') posthog.capture('claude_extension_opened') } catch (err) { setState('idle') setError(err instanceof Error ? err.message : String(err)) } } return ( <InstallBlock action={ canAddToClaudeDesktop() ? ( <Button variant="solid" disabled={state === 'opening'} onClick={() => void connect()}> {state === 'opening' ? t('workspace.claudeOpening') : state === 'opened' ? t('workspace.claudeOpenAgain') : t('workspace.claudeAdd')} </Button> ) : ( <p>{t('workspace.claudeNeedsDesktop')}</p> ) } status={state === 'opened' && t('workspace.claudeConfirm')} error={error} manualLabel={t('workspace.installManually')} manual={ <p> <a className="underline underline-offset-2" href="/claude-extension/doop.mcpb" download="doop.mcpb"> {t('workspace.downloadExtension')} </a> {t('workspace.claudeManualOpen')} <strong>Doop server URL</strong> {t('workspace.claudeManualTo')}{' '} <code className="break-all">{mcpUrl}</code> {t('workspace.claudeManualFallback')}{' '} <strong>Settings → Extensions → Advanced settings → Install Extension</strong>. </p> } /> ) } - src/components/CodexInstall.tsx (2135 bytes)
import { useState } from 'react' import { addToCodex, canAddToCodex, codexDesktopLink } from '../lib/codexConnection' import { isDesktopShell } from '../lib/shell' import { posthog } from '../lib/posthog' import { Button } from './ui/button' import { CodeBlock } from './ui/code-block' import { InstallBlock } from './ui/install-block' import { useT } from '../lib/i18n' export function CodexInstall({ mcpUrl, canvasId }: { mcpUrl: string; canvasId?: string }) { const t = useT() const [state, setState] = useState<'idle' | 'adding' | 'added'>('idle') const [error, setError] = useState('') async function connect() { setState('adding') setError('') try { await addToCodex() setState('added') posthog.capture('codex_connection_configured') } catch (err) { setState('idle') setError(err instanceof Error ? err.message : String(err)) } } const manual = ( <> <p>{t('workspace.codexManual')}</p> <CodeBlock text={`codex mcp add doop --url ${mcpUrl}`} className="mt-2" /> </> ) if (canAddToCodex()) { return ( <InstallBlock action={ <Button variant="solid" disabled={state !== 'idle'} onClick={() => void connect()}> {state === 'adding' ? t('workspace.codexAdding') : state === 'added' ? t('workspace.codexAdded') : t('workspace.codexAdd')} </Button> } status={state === 'added' && t('workspace.codexConfigured')} error={error} manual={manual} /> ) } if (isDesktopShell()) { return <InstallBlock action={<p>{t('workspace.codexUpdateDesktop')}</p>} manual={manual} /> } return ( <InstallBlock action={ <Button asChild variant="solid"> <a href={codexDesktopLink(new URL(mcpUrl).origin, canvasId)} onClick={() => posthog.capture('codex_desktop_setup_opened')} > {t('workspace.openDesktop')} </a> </Button> } status={t('workspace.codexNeedsDesktop')} manual={manual} /> ) } - src/components/CommandPalette.tsx (3505 bytes)
import { useMemo, useState } from 'react' import { useT } from '../lib/i18n' import { chordHint, firstChord } from '../lib/actions/chords' import { ACTIONS, MENUS, isEnabled, runAction, type CanvasAction } from '../lib/actions/registry' import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut, } from './ui/command' import { CheckIcon, SparkIcon } from './ui/icons' import { Modal } from './ui/modal' /** * ⌘K: every canvas command that can run right now, searchable by name and * grouped by the menu it lives in, each with its chord. Text that names no * command can go to the agent instead, as a prompt. */ export function CommandPalette({ onClose, onAsk }: { onClose: () => void; onAsk: ((prompt: string) => void) | null }) { const t = useT() const [query, setQuery] = useState('') /* what can run is read once, as the palette opens: the selection does not change under it */ const [groups] = useState(() => MENUS.map((menu) => ({ menu, actions: ACTIONS.filter((a) => a.menu === menu.id && a.id !== 'palette' && isEnabled(a)), })).filter((g) => g.actions.length), ) const ask = useMemo(() => (onAsk && query.trim() ? query.trim() : null), [onAsk, query]) function choose(action: CanvasAction) { onClose() /* after the modal lets go of focus, so a command that opens a field keeps it */ window.setTimeout(() => runAction(action), 0) } return ( <Modal size="lg" onClose={onClose} className="p-0 sm:p-0" aria-label={t('actions.palette')}> <Command loop> <CommandInput autoFocus value={query} onValueChange={setQuery} placeholder={t('actions.palettePlaceholder')} aria-label={t('actions.palette')} /> <CommandList> <CommandEmpty>{t('actions.paletteEmpty')}</CommandEmpty> {groups.map(({ menu, actions }) => ( <CommandGroup key={menu.id} heading={t(menu.label)}> {actions.map((action) => { const chord = firstChord(action.keys) const on = action.checked?.() return ( <CommandItem key={action.id} value={`${t(action.label)} ${t(menu.label)} ${action.id}`} onSelect={() => choose(action)} > <span className="flex size-3.5 flex-none items-center text-ink"> {on && <CheckIcon width={14} height={14} aria-hidden />} </span> <span className="min-w-0 flex-1 truncate">{t(action.label)}</span> {chord && <CommandShortcut>{chordHint(chord)}</CommandShortcut>} </CommandItem> ) })} </CommandGroup> ))} {ask && onAsk && ( <CommandGroup heading={t('actions.askAgent')} forceMount> <CommandItem forceMount value={`ask ${ask}`} onSelect={() => { onClose() onAsk(ask) }} > <SparkIcon width={14} height={14} aria-hidden className="flex-none text-brand" /> <span className="min-w-0 flex-1 truncate">{t('actions.paletteAsk', { query: ask })}</span> </CommandItem> </CommandGroup> )} </CommandList> </Command> </Modal> ) } - src/components/CommentPopovers.tsx (22168 bytes)
import { useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react' import { createPortal } from 'react-dom' import type { ElementComment } from '../../shared/types' import { colorFor } from '../../shared/types' import { DEFAULT_ROLE_NAME } from '../../shared/agents' import { useRoster } from '../hooks/use-roster' import { cn } from '@/lib/utils' import { canCommentOpenCanvas, canEditOpenCanvas, useStore } from '../lib/store' import { clientToWorld, dropComment, DRAG_THRESHOLD_PX } from '../lib/commentMove' import { Button } from './ui/button' import { Textarea } from './ui/textarea' import { CheckIcon, CommentIcon, LinkIcon, SparkIcon, SyncIcon } from './ui/icons' import { IconButton } from './ui/icon-button' import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from './ui/context-menu' import { MentionText, useAgentMention, useMentionPicker } from './MentionPicker' import { copyCommentLink } from '../lib/commentLink' import { RoleMark } from './RoleMark' import { useSkillMenu } from './SkillMenu' import { useT, type Translate } from '../lib/i18n' import { CommentThreadLayer } from './FrameLabelLayer' /* The comment UI — pins, the composer, an open thread — is shared by the frames (element comments, FrameView) and the canvas itself (canvas comments, CanvasComments). It is not capped like other counter-scaled chrome: it is screen UI the user reads and types in, so it keeps its size at every zoom, the way Figma's comment pins do. */ export const PIN_SCALE = '[transform:translate(-50%,-50%)_scale(calc(1/var(--zoom,1)))]' /** A thread's pin, coloured by its author and reflecting the newest agent * request in the thread (a speech bubble for a note, a spark while an agent is on it, ! when it failed). The * open thread popover renders as its child, so it inherits the pin's * counter-scale. `left`/`top` are in the parent's coordinate space. * * Anyone who may comment can drag the pin somewhere else: the pin hides * and a ghost rides the pointer in the world layer (CanvasComments), above * every frame, since this pin may sit inside a frame that clips it. On * release the thread is re-pinned to whatever is under the pointer * (src/lib/commentMove.ts); Esc puts it back. A press that moves less than * the threshold is the click that toggles the thread. * * Under a Stage the open thread is portalled into its screen-space layer * (`CommentThreadLayer`), above the frames' size badges, and kept on its * pin as the camera pans and zooms, as Figma's thread is. */ export function CommentPin({ thread, open, left, top, onToggle, children, }: { /** root comment first, then its replies oldest → newest */ thread: [ElementComment, ...ElementComment[]] open: boolean left: number top: number onToggle: () => void children?: ReactNode }) { const [root] = thread const agentItem = [...thread].reverse().find((x) => x.forAgent && !x.resolvedAt) const working = agentItem?.claimedBy && !agentItem.failedAt const movable = useStore(canCommentOpenCanvas) const dragged = useStore((s) => s.commentDrag?.id === root.id) /* the click after a drag's release must not toggle the thread */ const suppressClick = useRef(false) /* a press under way, dropped if the pin goes away first (resolved by someone else, hidden with ⇧C): its listeners would outlive it */ const abandonPress = useRef<(() => void) | null>(null) useEffect(() => () => abandonPress.current?.(), []) const t = useT() const threadLayer = useContext(CommentThreadLayer) const pinRef = useRef<HTMLDivElement>(null) const anchorRef = useRef<HTMLDivElement>(null) const showThread = open && !dragged useLayoutEffect(() => { const pin = pinRef.current const anchor = anchorRef.current if (!showThread || !threadLayer || !pin || !anchor) return /* the anchor is the pin's box in the layer, the thread hangs under it */ const place = () => { const p = pin.getBoundingClientRect() const l = threadLayer.getBoundingClientRect() anchor.style.left = `${p.left - l.left}px` anchor.style.top = `${p.top - l.top}px` anchor.style.width = `${p.width}px` anchor.style.height = `${p.height}px` } place() /* the pin's pop-in animates its transform, which drops its centring while it runs: a thread opened mid-pop is placed again once it ends */ let live = true for (const a of pin.getAnimations()) void a.finished.then(() => live && place()).catch(() => {}) let raf = 0 const unsub = useStore.subscribe((s, prev) => { /* a frame moved or resized (a drag, a peer's edit): measured once the pin has been drawn where it now is */ if (s.canvas !== prev.canvas) { cancelAnimationFrame(raf) raf = requestAnimationFrame(place) } const v = s.viewport const u = prev.viewport if (v === u) return /* the pin is drawn in the world (screen = world × zoom + offset) at a constant screen size, so its centre moves with the camera. Worked out here rather than measured: the Stage may not have moved the world for this camera yet */ const cx = parseFloat(anchor.style.left) + anchor.offsetWidth / 2 const cy = parseFloat(anchor.style.top) + anchor.offsetHeight / 2 anchor.style.left = `${parseFloat(anchor.style.left) + ((cx - u.x) / u.zoom) * v.zoom + v.x - cx}px` anchor.style.top = `${parseFloat(anchor.style.top) + ((cy - u.y) / u.zoom) * v.zoom + v.y - cy}px` }) return () => { live = false unsub() cancelAnimationFrame(raf) } }, [showThread, threadLayer, left, top]) function onPointerDown(e: React.PointerEvent<HTMLDivElement>) { e.stopPropagation() /* a press inside the open thread (its reply field, its buttons) is the thread's own: capturing it here would retarget the click at the pin */ if (!movable || e.button !== 0 || (e.target as Element).closest('[data-comment-popover]')) return const pin = e.currentTarget const origin = { x: e.clientX, y: e.clientY } let moving = false pin.setPointerCapture(e.pointerId) const stop = () => { pin.removeEventListener('pointermove', onMove) pin.removeEventListener('pointerup', onUp) pin.removeEventListener('pointercancel', onCancel) window.removeEventListener('keydown', onKey, true) document.body.style.cursor = '' abandonPress.current = null } const onMove = (ev: PointerEvent) => { if (!moving) { if (Math.abs(ev.clientX - origin.x) + Math.abs(ev.clientY - origin.y) <= DRAG_THRESHOLD_PX) return moving = true document.body.style.cursor = 'grabbing' } useStore.getState().setCommentDrag({ id: root.id, ...clientToWorld(ev.clientX, ev.clientY) }) } const onUp = (ev: PointerEvent) => { stop() if (!moving) return suppressClick.current = true window.setTimeout(() => (suppressClick.current = false), 0) /* the ghost stays until the move has landed (or was refused), so the pin never flashes back to its old place first */ void dropComment(root, clientToWorld(ev.clientX, ev.clientY)).finally(() => useStore.getState().setCommentDrag(null), ) } const onCancel = () => { stop() if (moving) { /* the pointer is still down: the click its release fires must not toggle the thread, and the flag must not outlive that release */ suppressClick.current = true pin.addEventListener('pointerup', () => window.setTimeout(() => (suppressClick.current = false), 0), { once: true, }) } useStore.getState().setCommentDrag(null) } const onKey = (ev: KeyboardEvent) => { if (ev.key !== 'Escape') return ev.stopPropagation() onCancel() } pin.addEventListener('pointermove', onMove) pin.addEventListener('pointerup', onUp) pin.addEventListener('pointercancel', onCancel) window.addEventListener('keydown', onKey, true) abandonPress.current = () => { stop() if (moving) useStore.getState().setCommentDrag(null) } } return ( <ContextMenu> <ContextMenuTrigger asChild> <div className={cn( 'pointer-events-auto absolute z-[4] grid h-[26px] w-[26px] cursor-pointer place-items-center rounded-[50%_50%_50%_4px] border-2 border-white text-[13px] text-white animate-[chip-in_0.25s_ease]', PIN_SCALE, dragged && 'opacity-0', agentItem?.failedAt ? 'bg-accent-ink! font-extrabold shadow-[0_0_0_3px_rgba(208,52,31,0.2),var(--shadow-card)]' : 'shadow-card', working && "after:absolute after:-inset-1.5 after:rounded-[inherit] after:border-2 after:border-current after:opacity-50 after:content-[''] after:[animation:stream-pulse_1.1s_ease-in-out_infinite]", )} ref={pinRef} style={{ left, top, background: colorFor(root.from) }} onPointerDown={onPointerDown} /* the pin's own menu: stopped here so the frame's or the canvas's menu, whose triggers wrap this one, does not open behind it */ onContextMenu={(e) => e.stopPropagation()} onClick={() => { if (suppressClick.current) { suppressClick.current = false return } onToggle() }} title={`${root.from}: ${root.text}${thread.length > 1 ? t('stage.pinReplies', { count: thread.length - 1 }) : ''}`} > {agentItem?.failedAt ? '!' : working ? <SparkIcon size={14} /> : <CommentIcon size={14} />} {showThread && (threadLayer ? createPortal( <div ref={anchorRef} data-comment-thread-anchor className="pointer-events-none absolute *:pointer-events-auto" > {children} </div>, threadLayer, ) : children)} </div> </ContextMenuTrigger> <ContextMenuContent> <ContextMenuItem onSelect={() => void copyCommentLink(root)}> <LinkIcon size="rail" /> {t('stage.copyCommentLink')} </ContextMenuItem> </ContextMenuContent> </ContextMenu> ) } export function CommentComposer({ onSubmit, onCancel, initialText = '', placeholder, }: { /** `mentions`: the people picked from the @ list (server/canvasPeople.ts) */ onSubmit: (text: string, mentions: string[]) => void onCancel: () => void initialText?: string placeholder?: string }) { const t = useT() const [text, setText] = useState(initialText) const taRef = useRef<HTMLTextAreaElement>(null) useEffect(() => taRef.current?.focus(), []) const mentions = useMentionPicker({ value: text, onChange: setText, fieldRef: taRef }) const send = () => text.trim() && onSubmit(text, mentions.picked(text)) const canvasId = useStore((s) => s.canvas?.id) const skillMenu = useSkillMenu({ from: canvasId ? { canvasId } : undefined, text, setText, inputRef: taRef }) /* @mention a resident agent to route the comment to it; without one the comment is a note for the humans in the room. Asking one takes edit. */ const roster = useRoster() const canAskAgents = useStore(canEditOpenCanvas) const mentioned = useAgentMention(text, mentions.picked(text)) return ( <div className="w-[240px] rounded-[10px] border border-line bg-surface p-2 shadow-pop animate-[chip-in_0.18s_ease]"> <div className="relative"> {skillMenu.menu} <Textarea ref={taRef} variant="bare" className="min-h-[58px] md:text-[13px]" value={text} placeholder={placeholder ?? t('stage.commentOnElement')} {...skillMenu.inputProps} {...mentions.fieldProps} onChange={(e) => { skillMenu.inputProps.onChange(e) mentions.onCaret(e) }} onSelect={(e) => { skillMenu.inputProps.onSelect(e) mentions.onCaret(e) }} onKeyDown={(e) => { if (skillMenu.onKeyDown(e) || mentions.onKeyDown(e)) return /* keys that finish an IME composition belong to it */ if (e.nativeEvent.isComposing || e.keyCode === 229) return if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) send() if (e.key === 'Escape') onCancel() }} /> {mentions.list} </div> {!mentioned && canAskAgents && ( /* Leave room inside the scrollport for the pills' shadow outlines and focus rings. */ <div className="-mx-1 mb-2 flex max-h-[124px] flex-wrap gap-1 overflow-y-auto p-1"> {roster.map((role) => ( <Button key={role.id} variant="ghost" size="pill" className="border-dashed px-2 text-[11px] font-semibold text-ink-soft hover:border-brand hover:bg-transparent hover:text-brand" title={`${role.name} — ${role.blurb}`} onClick={() => setText((current) => (current ? current.replace(/\s*$/, ' ') : '') + `@${role.id} `)} > <RoleMark role={role} size={13} /> @{role.id} </Button> ))} </div> )} <div className="flex items-center justify-end gap-2"> {mentioned && ( <span className="mr-auto inline-flex items-center gap-1 text-[11px] font-semibold text-brand"> <RoleMark role={mentioned} size={13} /> {t('stage.willPickUp', { name: mentioned.name })} </span> )} <Button variant="solid" size="pill" className="px-3.5 py-[5px] text-xs" disabled={!text.trim()} onClick={send}> {t('stage.post')} </Button> </div> </div> ) } /** Where an @agent request in the thread stands, or null for a human note. */ function agentStatus(c: ElementComment, t: Translate): ReactNode { const target = c.targetAgent ?? DEFAULT_ROLE_NAME if (c.failedAt) return t('stage.agentStopped', { name: target }) if (c.resolvedAt) return c.forAgent ? ( <> <CheckIcon size={12} /> {c.resolvedBy ?? target} </> ) : null if (c.claimedBy) return ( <> <SparkIcon size={12} /> {t('stage.isOnIt', { name: c.claimedBy })} </> ) return c.forAgent ? ( <> <SparkIcon size={12} /> {t('stage.waitingFor', { name: target })} </> ) : null } export function CommentThread({ thread, onReply, onResolve, onRetry, }: { /** root comment first, then its replies oldest → newest */ thread: ElementComment[] /** rejects when the reply did not land — the draft is kept for a retry */ /** `mentions`: the people picked fro - src/components/CommentsPanel.tsx (11052 bytes)
import { useMemo, useRef, useState } from 'react' import { colorFor } from '../../shared/types' import { canCommentOpenCanvas, useStore } from '../lib/store' import { api } from '../lib/api' import { posthog } from '../lib/posthog' import { timeAgo } from '../lib/time' import { isComposingEnter } from '../lib/keys' import { isCanvasComment } from '../../shared/comments' import { pageThreads, threadState, type CommentThreadGroup, type ThreadState } from '../lib/comments' import { cn } from '@/lib/utils' import { Button } from './ui/button' import { Input } from './ui/input' import { PanelBody } from './ui/panel' import { CheckIcon, LinkIcon } from './ui/icons' import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from './ui/context-menu' import { MentionText, useMentionPicker } from './MentionPicker' import { copyCommentLink } from '../lib/commentLink' import { Disclosure } from './ui/collapsible' import { isResidentLimit } from './TeamAllowance' import { useT } from '../lib/i18n' const emptyNote = 'px-4 py-6 text-center text-[12px] leading-[1.45] text-ink-faint' /** Every comment thread on the current page — pinned to a frame or to the * canvas itself — open ones first. Clicking a thread flies to its pin and * opens it; replying and resolving work from here too, so a review pass * never has to hunt pins across the canvas. */ export function CommentsPanel() { const comments = useStore((s) => s.comments) const canvas = useStore((s) => s.canvas) const activePageId = useStore((s) => s.activePageId) const [filter, setFilter] = useState<ThreadState>('open') const t = useT() const threads = useMemo(() => pageThreads(comments, canvas, activePageId), [comments, canvas, activePageId]) const counts = { open: 0, resolved: 0 } for (const thread of threads) counts[threadState(thread)] += 1 const shown = threads.filter((thread) => threadState(thread) === filter) if (threads.length === 0) { return ( <PanelBody className="py-2"> <div className={emptyNote}>{t('stage.noComments')}</div> </PanelBody> ) } return ( <PanelBody className="pb-2"> {/* the same quiet segmented switch as the panel's own tabs */} <div role="group" aria-label={t('stage.commentFilter')} className="flex gap-0.5 px-3 pt-2 pb-1"> <FilterTab active={filter === 'open'} count={counts.open} onClick={() => setFilter('open')}> {t('stage.filterOpen')} </FilterTab> <FilterTab active={filter === 'resolved'} count={counts.resolved} onClick={() => setFilter('resolved')}> {t('stage.filterResolved')} </FilterTab> </div> {shown.length === 0 ? ( <div className={emptyNote}>{t(filter === 'open' ? 'stage.noOpenThreads' : 'stage.noResolvedThreads')}</div> ) : ( shown.map((thread) => <ThreadRow key={thread.root.id} thread={thread} />) )} </PanelBody> ) } function FilterTab({ active, count, children, onClick, }: { active: boolean count: number children: string onClick: () => void }) { return ( <button type="button" aria-pressed={active} onClick={onClick} className={cn( 'flex h-[26px] items-center gap-1.5 rounded-[7px] px-2 text-[12px] transition-colors', active ? 'bg-paper-deep font-medium text-ink' : 'text-ink-soft hover:bg-sub hover:text-ink', )} > {children} <span className={cn('text-[11px] tabular-nums', active ? 'text-ink-soft' : 'text-ink-faint')}>{count}</span> </button> ) } /* replies and resolves are metered like any other resident task when they @mention an agent — a 403 means the free tier ran out, so raise the wall */ function reportLimit(err: unknown) { if (isResidentLimit(err)) useStore.getState().setLimitWall(true) else console.error(err) } /** One thread, in the same shape as a task row: who and when on the first * line, the comment under it, then where it is pinned and how many replies. * Open threads carry a reply field and a Resolve action. */ function ThreadRow({ thread }: { thread: CommentThreadGroup }) { const { root, frame } = thread const resolved = threadState(thread) === 'resolved' /* a view link reads threads; it neither replies nor resolves */ const canComment = useStore(canCommentOpenCanvas) const t = useT() const [draft, setDraft] = useState('') const [sending, setSending] = useState(false) const [failed, setFailed] = useState(false) const fieldRef = useRef<HTMLInputElement>(null) const mentions = useMentionPicker({ value: draft, onChange: setDraft, fieldRef }) /* fly to the pin (its frame, or its point on the canvas) and pop it — the pin shows the whole conversation, this row is the index entry */ const goToThread = () => { const s = useStore.getState() if (frame) { s.select(frame.id) s.requestFlyTo(frame.id) } else if (isCanvasComment(root)) { s.select(null) s.setActivePage(root.pageId) s.requestFlyToPoint(root.x, root.y) } if (!resolved) s.requestOpenThread(root.id) } async function reply() { const text = draft.trim() if (!text || sending) return setSending(true) setFailed(false) try { await api.replyComment(root.id, text, mentions.picked(text)) posthog.capture('element_comment_replied') setDraft((current) => (current === draft ? '' : current)) } catch (err) { setFailed(true) reportLimit(err) } finally { setSending(false) } } function resolve() { api .resolveComment(root.id) .then(() => posthog.capture('element_comment_resolved')) .catch(reportLimit) } return ( <div className="mx-1.5 py-1"> <ContextMenu> {/* a resolved thread has no pin for a link to open */} <ContextMenuTrigger asChild disabled={resolved}> <div role="button" tabIndex={0} title={frame ? t('stage.goToFrame', { name: frame.name }) : t('stage.goToPin')} onClick={goToThread} onKeyDown={(e) => { if (e.target !== e.currentTarget) return if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() goToThread() } }} className="grid cursor-pointer grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 gap-y-[2px] rounded-[8px] px-1.5 py-2 text-[12px] leading-[18px] hover:bg-sub focus-visible:bg-sub focus-visible:outline-none" > <span className="flex min-w-0 items-center gap-1.5 whitespace-nowrap"> <span aria-hidden className="grid size-4 flex-none place-items-center rounded-full text-[8px] leading-none font-medium text-white" style={{ background: colorFor(root.from) }} > {root.from.slice(0, 1).toUpperCase()} </span> <b className="truncate font-medium text-ink">{root.from}</b> </span> <span className="text-[11px] text-ink-faint tabular-nums">{timeAgo(root.at)}</span> {/* open threads clamp (the pin shows the whole conversation); a resolved one has no pin to open, so it reads in full here */} <span className={cn('col-span-2 min-w-0 break-words pl-[22px] text-ink-soft', !resolved && 'line-clamp-3')}> <MentionText text={root.text} /> </span> {(frame || resolved) && ( <span className="col-span-2 flex min-w-0 items-center gap-[7px] pl-[22px] text-[11px] text-ink-faint"> {resolved && ( <span className="grid size-3 flex-none place-items-center rounded-full bg-ink text-paper"> <CheckIcon className="size-[8px]" strokeWidth={2.4} /> </span> )} {frame && ( <span className="min-w-0 truncate" title={frame.name}> {frame.name} </span> )} {resolved && root.resolvedBy && ( <span className="min-w-0 truncate"> {frame ? '· ' : ''} {t('stage.resolvedBy', { name: root.resolvedBy })} </span> )} </span> )} </div> </ContextMenuTrigger> <ContextMenuContent> <ContextMenuItem onSelect={() => void copyCommentLink(root)}> <LinkIcon size="rail" /> {t('stage.copyCommentLink')} </ContextMenuItem> </ContextMenuContent> </ContextMenu> {resolved && thread.replies.length > 0 && ( <Disclosure label={t('stage.replies', { count: thread.replies.length })} className="py-1 pr-1.5 pl-[28px] text-label text-ink-soft" > <ol className="space-y-3" aria-label={t('stage.resolvedReplies')}> {thread.replies.map((reply) => ( <li key={reply.id}> <div className="flex items-center justify-between gap-2"> <span className="truncate font-medium text-ink">{reply.from}</span> <span className="shrink-0 text-caption text-ink-faint">{timeAgo(reply.at)}</span> </div> <p className="whitespace-pre-wrap break-words"> <MentionText text={reply.text} /> </p> </li> ))} </ol> </Disclosure> )} {!resolved && canComment && ( <div className="flex items-center gap-1.5 py-1 pr-1.5 pl-[28px]"> <div className="relative min-w-0 flex-1"> <Input ref={fieldRef} variant="bare" inputSize="auto" className="h-7 w-full min-w-0 rounded-[7px] bg-surface px-2.5 shadow-ring focus:shadow-elevation-1-focus md:text-[12px]" placeholder={t('stage.replyPanelPlaceholder')} aria-label={t('stage.replyTo', { name: root.from })} value={draft} disabled={sending} onChange={(e) => { setDraft(e.target.value) mentions.onCaret(e) }} {...mentions.fieldProps} onKeyDown={(e) => { if (mentions.onKeyDown(e)) return if (e.key === 'Enter' && !isComposingEnter(e)) void reply() }} /> {mentions.list} </div> <Button variant="bare" className="h-7 flex-none gap-1 rounded-[7px] px-2 text-[12px] font-normal" title={t('stage.markResolved')} onClick={resolve} > <CheckIcon className="size-3.5" /> {t('stage.resolve')} </Button> </div> )} {failed && <div className="pl-[28px] text-[11px] leading-[1.4] text-accent-ink">{t('stage.replyFailed')}</div>} </div> ) } - src/components/ComponentImport.tsx (10506 bytes)
import { useMemo, useState } from 'react' import { api, type ComponentLibrary } from '../lib/api' import { useT } from '../lib/i18n' import { useStore } from '../lib/store' import { timeAgo } from '../lib/time' import { cn } from '@/lib/utils' import { ComponentThumb } from './ComponentThumb' import { FramePreview, FrameThumb } from './FramePreview' import { Button } from './ui/button' import { Checkbox } from './ui/checkbox' import { ChevronLeftIcon, ComponentIcon } from './ui/icons' import { Modal, ModalActions, ModalSpacer, ModalTitle } from './ui/modal' import { Pressable } from './ui/pressable' import { SearchField } from './ui/search-field' type Source = ComponentLibrary type Entry = Source['components'][number] /** "Edited 5h ago", or "Shared · edited 5h ago" for a canvas someone else owns. */ function useEditedLine() { const t = useT() return (source: Source) => { if (!source.updatedAt) return '' const time = timeAgo(source.updatedAt) return source.shared ? t('components.importSharedEdited', { time }) : t('components.importEdited', { time }) } } /** * The Components panel while importing: every canvas this person can open, one * per row with its preview, as Home lists them. "‹ Components" goes back to the * overview; a canvas with components opens the picker for it. */ export function ImportCanvasList({ sources, onBack, onPick, }: { /** null while the list loads */ sources: Source[] | null onBack: () => void onPick: (source: Source) => void }) { const t = useT() const edited = useEditedLine() const [query, setQuery] = useState('') const shown = useMemo(() => { const wanted = query.trim().toLowerCase() return (sources ?? []).filter((source) => !wanted || source.name.toLowerCase().includes(wanted)) }, [sources, query]) return ( <div className="flex min-h-0 flex-1 flex-col" data-slot="import-canvas-list"> <div className="flex flex-none flex-col gap-2 px-2.5 pt-2.5 pb-2"> <Button variant="bare" size="sm" className="self-start bg-paper-deep pl-1 text-ink" onClick={onBack}> <ChevronLeftIcon size="rail" aria-hidden /> {t('components.importBack')} </Button> <SearchField autoFocus value={query} placeholder={t('components.importSearchCanvases')} aria-label={t('components.importSearchCanvases')} onChange={(event) => setQuery(event.target.value)} /> </div> <div className="flex min-h-0 flex-1 flex-col gap-2.5 overflow-y-auto overscroll-contain px-2.5 pb-3"> {sources?.length === 0 && <p className="px-0.5 text-caption text-ink-soft">{t('components.noLibraries')}</p>} {sources && sources.length > 0 && shown.length === 0 && ( <p className="px-0.5 text-caption text-ink-soft">{t('components.importNoCanvasMatch')}</p> )} {shown.map((source) => { const count = source.components.length return ( <Pressable key={source.id} disabled={count === 0} aria-label={t('components.importCanvasAria', { name: source.name, count })} className={cn( 'overflow-hidden rounded-card bg-sub shadow-ring transition-shadow hover:shadow-ring-hover', count === 0 && 'cursor-default opacity-45 hover:shadow-ring', )} data-import-canvas={source.name} onClick={() => onPick(source)} > <span className="relative block h-28 overflow-hidden bg-paper-deep"> <FramePreview frameId={source.previewFrameId} className="text-caption" /> {count > 0 && ( <span className="absolute right-1.5 bottom-1.5 flex items-center gap-1 rounded-tag bg-black/70 px-1.5 py-0.5 font-mono text-micro text-white"> <ComponentIcon size={10} aria-hidden /> {count} </span> )} </span> <span className="flex flex-col px-2.5 py-2"> <span className="truncate text-body font-medium text-ink">{source.name}</span> <span className="truncate text-caption text-ink-faint"> {count === 0 ? t('components.importNoComponents') : edited(source)} </span> </span> </Pressable> ) })} </div> </div> ) } /** * One canvas's components to bring in: a preview each, ticked to pick, the ones * already here greyed. Importing keeps them linked to that canvas. Closing goes * back to the canvas list, not out of the import. */ export function ImportComponentsModal({ canvasId, source, onBack, onDone, }: { canvasId: string source: Source onBack: () => void onDone: () => void }) { const t = useT() const components = useStore((s) => s.canvas?.components) /* an import keeps the component's id, so one with that id here came from there already */ const here = useMemo( () => new Set((components ?? []).filter((def) => def.status !== 'deleted').map((def) => def.id)), [components], ) const [query, setQuery] = useState('') const [picked, setPicked] = useState<ReadonlySet<string>>(new Set()) const [busy, setBusy] = useState(false) const count = source.components.length const shown = useMemo(() => { const wanted = query.trim().toLowerCase() return source.components.filter( (entry) => !wanted || `${entry.name} ${entry.description ?? ''}`.toLowerCase().includes(wanted), ) }, [source, query]) const available = shown.filter((entry) => !here.has(entry.id)) /* what Import brings: the ticked ones not here yet. One that arrived in an earlier, partly failed run stays ticked in `picked` but is no longer counted or sent */ const chosen = source.components.filter((entry) => picked.has(entry.id) && !here.has(entry.id)) const toggle = (entry: Entry) => setPicked((current) => { const next = new Set(current) if (next.has(entry.id)) next.delete(entry.id) else next.add(entry.id) return next }) async function importPicked() { if (!chosen.length) return setBusy(true) const notice = useStore.getState().pushNotice let done = 0 try { /* one at a time: an import can bring the components this one is built from */ for (const entry of chosen) { await api.importComponent(canvasId, source.id, entry.id) done++ } notice( done === 1 ? t('components.imported', { name: chosen[0]!.name }) : t('components.importedMany', { count: done }), ) onDone() } catch (error) { notice(error instanceof Error ? error.message : t('components.importFailed')) setBusy(false) } } return ( /* not dismissable mid-import: the run would carry on and its onDone close a later picker */ <Modal size="xl" onClose={() => { if (!busy) onBack() }} showClose={!busy} data-slot="import-components" > <div className="flex items-center gap-3 pr-8"> <FrameThumb frameId={source.previewFrameId} empty={null} /> <ModalTitle className="min-w-0 flex-1 truncate pr-0">{source.name}</ModalTitle> </div> <div className="mt-4 flex items-center gap-3"> <SearchField className="flex-1" value={query} placeholder={t('components.importSearchComponents', { count })} aria-label={t('components.importSearchComponents', { count })} onChange={(event) => setQuery(event.target.value)} /> <Button variant="bare" size="sm" disabled={!available.length} onClick={() => setPicked(new Set([...picked, ...available.map((entry) => entry.id)]))} > {t('components.importSelectAll')} </Button> </div> <ul className="mt-4 grid grid-cols-1 gap-x-4 gap-y-5 sm:grid-cols-2 md:grid-cols-3"> {shown.map((entry) => { const already = here.has(entry.id) const on = picked.has(entry.id) && !already return ( <li key={entry.id} data-import-component={entry.name}> <label className={cn('flex flex-col gap-1.5', already ? 'cursor-default' : 'cursor-pointer')}> <span className={cn( 'relative block rounded-row', on && 'ring-2 ring-brand ring-offset-0', already && 'opacity-45', )} > <ComponentThumb title={t('components.previewTitle', { name: entry.name })} sheetKey={`${source.id}:${entry.id}:${entry.signature}`} load={() => api.componentPreview(source.id, entry.id)} height={176} /> {!already && ( <span className="absolute top-1.5 left-1.5 flex"> <Checkbox checked={on} onChange={() => toggle(entry)} aria-label={entry.name} boxClassName="text-white peer-checked:border-brand peer-checked:bg-brand" /> </span> )} </span> <span className={cn('truncate text-body', already ? 'text-ink-faint' : 'text-ink')}>{entry.name}</span> {already && ( <span className="-mt-1 text-caption text-ink-faint">{t('components.importAlreadyHere')}</span> )} </label> </li> ) })} </ul> <ModalActions className="items-center border-t border-line-soft pt-4"> {chosen.length > 0 && ( <span className="text-body text-ink-soft">{t('components.importSelected', { count: chosen.length })}</span> )} <ModalSpacer /> <Button onClick={onBack} disabled={busy}> {t('components.importBackToCanvases')} </Button> <Button variant="primary" disabled={!chosen.length || busy} onClick={() => void importPicked()}> {busy ? t('components.importing') : chosen.length ? t('components.importAction', { count: chosen.length }) : t('components.importNone')} </Button> </ModalActions> </Modal> ) } - src/components/ComponentSection.tsx (9131 bytes)
import { useMemo, useState } from 'react' import { BIND_ATTR, SLOT_ATTR, isDeleted, type ComponentProp } from '../../shared/components' import type { Frame } from '../../shared/types' import { api } from '../lib/api' import { changeInstance, componentContextOf, exposeOnMain, restoreDeletedComponent, templateValue, type ComponentContext, } from '../lib/components' import { useT } from '../lib/i18n' import { isLayerLocked } from '../lib/layerEdits' import { canEditOpenCanvas, useStore } from '../lib/store' import { Button } from './ui/button' import { ComponentIcon, InstanceIcon } from './ui/icons' import { ImagePicker } from './ImageFill' import { PropertyRow, SelectField, TextField } from './ui/property-field' import { Switch } from './ui/switch' import { Textarea } from './ui/textarea' /** The Design panel's head when the selection belongs to a component. */ export function ComponentSection({ frame, selector }: { frame: Frame; selector: string }) { const t = useT() const defs = useStore((s) => s.canvas?.components) const context = useMemo(() => componentContextOf(frame.html, selector, defs ?? []), [frame.html, selector, defs]) if (!context) return null return ( <section data-slot="component-section" className="flex flex-col border-b border-line-soft px-3 pt-3 pb-2.5"> <header className="mb-[5px] flex min-h-5 min-w-0 items-center gap-1.5 text-body font-medium text-ink"> {context.kind === 'main' ? ( <ComponentIcon size="rail" className="flex-none text-brand" data-component-icon="main" /> ) : ( <InstanceIcon size="rail" className="flex-none text-brand" data-component-icon="instance" /> )} <span className="truncate">{context.def.name}</span> <span className="ml-auto flex-none text-caption font-normal text-ink-faint"> {context.kind === 'main' ? t('components.main') : t('components.instance')} </span> </header> {context.kind === 'main' ? ( <MainControls key={context.def.id} frame={frame} context={context} /> ) : isDeleted(context.def) ? ( <DeletedInstanceControls frame={frame} context={context} /> ) : ( <InstanceControls frame={frame} context={context} /> )} </section> ) } /** An instance whose component was deleted: it keeps its look and follows nothing, until the * component is restored (every instance is linked again) or this one is detached. */ function DeletedInstanceControls({ frame, context, }: { frame: Frame context: Extract<ComponentContext, { kind: 'instance' }> }) { const { def, instanceId, rootSelector } = context const t = useT() const canEdit = useStore(canEditOpenCanvas) const locked = isLayerLocked(frame, rootSelector) return ( <div data-slot="deleted-component" className="flex flex-col gap-2"> <p className="text-caption font-medium text-ink">{t('components.mainDeleted')}</p> <p className="text-caption text-ink-soft">{t('components.mainDeletedHint')}</p> {canEdit && ( <div className="flex flex-wrap gap-1.5"> <Button size="sm" onClick={() => void restoreDeletedComponent(def)}> {t('components.restoreComponent')} </Button> <Button size="sm" disabled={locked} onClick={() => { const current = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) if (current) void changeInstance(current, { instanceId, detach: true }) }} > {t('components.detach')} </Button> </div> )} </div> ) } function InstanceControls({ frame, context, }: { frame: Frame context: Extract<ComponentContext, { kind: 'instance' }> }) { const { def, instanceId, isRoot, rootSelector, selector } = context const locked = isLayerLocked(frame, selector) const t = useT() return ( <> {!isRoot && ( <Button size="inline" variant="link" className="self-start" onClick={() => useStore.getState().setSelectedElement({ frameId: frame.id, selector: rootSelector })} > {t('components.selectInstance')} </Button> )} {def.props.map((prop) => ( <PropField key={`${instanceId}:${prop.name}`} canvasId={frame.canvasId} prop={prop} disabled={locked} value={context.props[prop.name]} fallback={prop.default ?? (prop.type === 'boolean' ? 'true' : templateValue(def, prop.name))} onChange={(value) => { /* the frame as it is now: an image pick waits on an upload, and undo's baseline and the lock check must not be the design from before it */ const current = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) if (!current || isLayerLocked(current, selector)) return void changeInstance(current, { instanceId, props: { [prop.name]: value } }) }} /> ))} </> ) } function PropField({ canvasId, prop, value, fallback, disabled, onChange, }: { canvasId: string prop: ComponentProp disabled: boolean value: string | undefined fallback: string onChange: (value: string) => void }) { const shown = value ?? fallback return <PropertyRow label={prop.name}>{propControl()}</PropertyRow> function propControl() { switch (prop.type) { case 'boolean': return ( <Switch size="sm" className="my-auto" disabled={disabled} checked={shown !== 'false'} onCheckedChange={(checked) => onChange(checked ? 'true' : 'false')} aria-label={prop.name} /> ) case 'enum': return ( <SelectField label={prop.name} value={shown} disabled={disabled} options={(prop.options ?? []).map((option) => ({ value: option, label: option }))} onChange={onChange} /> ) case 'image': return ( <ImagePicker canvasId={canvasId} src={shown} label={prop.name} disabled={disabled} className="h-[26px] min-w-0 flex-1 gap-1.5 rounded-row px-[3px] text-caption" onPick={async (resolve) => { const url = await resolve() if (url !== shown) onChange(url) }} onClear={() => onChange('')} /> ) case 'text': case 'link': return ( <TextField label={prop.name} value={shown} disabled={disabled} className={prop.type === 'text' ? 'font-sans' : undefined} placeholder={prop.type === 'link' ? 'https://…' : undefined} onCommit={onChange} /> ) } } } function MainControls({ frame, context }: { frame: Frame; context: Extract<ComponentContext, { kind: 'main' }> }) { const { def, isRoot, selector } = context const t = useT() const locked = isLayerLocked(frame, selector) const [description, setDescription] = useState(def.description) /* a collaborator's or agent's change to the description takes the field over, so a blur here never writes the older text back over it */ const [seen, setSeen] = useState(def.description) if (seen !== def.description) { setSeen(def.description) setDescription(def.description) } const instances = useStore( (s) => s.canvas?.frames.reduce((total, f) => total + (f.html.split(` data-doop-instance="${def.id}"`).length - 1), 0) ?? 0, ) const save = () => { if (description === def.description) return api .updateComponent(frame.canvasId, def.id, { description }) .catch(() => useStore.getState().pushNotice(t('components.descriptionFailed'))) } return ( <div className="flex flex-col gap-2.5"> <p className="text-caption text-ink-soft"> {instances === 0 ? t('components.noInstances') : t('components.reachesInstances', { count: instances })} </p> <Textarea value={description} placeholder={t('components.descriptionPlaceholder')} aria-label={t('components.descriptionAria')} rows={2} onChange={(event) => setDescription(event.target.value)} onBlur={save} /> {def.props.length > 0 && ( <p className="text-caption text-ink-soft"> {t('components.propsLabel')}{' '} <span className="font-mono text-ink">{def.props.map((prop) => prop.name).join(', ')}</span> </p> )} {!isRoot && ( <div className="flex flex-wrap gap-1.5"> <Button size="sm" disabled={locked} onClick={() => exposeOnMain(frame, selector, BIND_ATTR)}> {t('components.makeProp')} </Button> <Button size="sm" disabled={locked} onClick={() => exposeOnMain(frame, selector, SLOT_ATTR)}> {t('components.makeSlot')} </Button> </div> )} </div> ) } - src/components/ComponentsPanel.tsx (13575 bytes)
import { useMemo, useRef, useState } from 'react' import { activeComponents, type ComponentDef } from '../../shared/components' import { api, type ComponentLibrary } from '../lib/api' import { COMPONENT_DRAG_TYPE, goToMain, placeComponent, removeComponent, renameComponent } from '../lib/components' import { useT } from '../lib/i18n' import { useCanvasLibrary } from '../lib/library' import { useLibraryResume } from '../lib/libraryResume' import { cn } from '@/lib/utils' import { canEditOpenCanvas, useStore } from '../lib/store' import { ImportCanvasList, ImportComponentsModal } from './ComponentImport' import { ComponentThumb, useTokenStamp } from './ComponentThumb' import { LibraryNotices, LibrarySection, LibraryUpgradeFlow, PublishLibraryDialog } from './LibrarySection' import { ConfirmDialog } from './ui/alert-dialog' import { Button } from './ui/button' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from './ui/dropdown-menu' import { BookOpenIcon, ComponentIcon, MoreHorizontalIcon } from './ui/icons' import { IconButton } from './ui/icon-button' import { Input } from './ui/input' import { PanelSearch } from './ui/panel' /** The card's name as a field: Enter or a blur saves, Escape puts it back. */ function ComponentNameInput({ def, onDone }: { def: ComponentDef; onDone: () => void }) { const t = useT() const finished = useRef(false) function finish(input: HTMLInputElement, save: boolean) { if (finished.current) return finished.current = true if (save) void renameComponent(def, input.value) onDone() } return ( <Input autoFocus aria-label={t('components.nameAria')} variant="bare" inputSize="auto" className="h-5 min-w-0 flex-1 bg-surface px-1 text-ink shadow-elevation-1-focus md:text-body" defaultValue={def.name} onFocus={(event) => event.target.select()} onBlur={(event) => finish(event.currentTarget, true)} onKeyDown={(event) => { event.stopPropagation() if (event.nativeEvent.isComposing || (event.key !== 'Enter' && event.key !== 'Escape')) return event.preventDefault() finish(event.currentTarget, event.key === 'Enter') }} /> ) } /** The library rail: what this canvas has, what it could turn into components, * and what other canvases offer. */ export function ComponentsPanel() { const t = useT() const canvasId = useStore((s) => s.canvas?.id) const components = useStore((s) => s.canvas?.components) const canvasName = useStore((s) => s.canvas?.name) const canEdit = useStore(canEditOpenCanvas) const tokenStamp = useTokenStamp() const shared = useCanvasLibrary(canvasId ?? '', canEdit) /* the publish dialog (`only` = opened from that component's menu) and the way to a library */ const [publishing, setPublishing] = useState<{ only?: string } | null>(null) const [wall, setWall] = useState<{ workspaceId?: string; reason: string; only?: string } | null>(null) /* back from checkout: the publish dialog they were on the way to */ useLibraryResume({ canvasId, canEdit, status: shared.status, reload: shared.reload, onPublish: (only) => setPublishing(only ? { only } : {}), }) const [query, setQuery] = useState('') /* importing: the panel lists the other canvases, and one picked opens its components */ const [browsing, setBrowsing] = useState(false) const [libraries, setLibraries] = useState<ComponentLibrary[] | null>(null) const [picking, setPicking] = useState<ComponentLibrary | null>(null) const [confirmDelete, setConfirmDelete] = useState<ComponentDef | null>(null) const [renaming, setRenaming] = useState<string | null>(null) /* Rename picked from the menu opens the field once the menu has closed, in place of the focus it would hand back to its trigger, which would blur the new field at once */ const renameFromMenu = useRef(false) const shown = useMemo(() => { const wanted = query.trim().toLowerCase() return activeComponents(components) .filter((def) => !wanted || `${def.name} ${def.description}`.toLowerCase().includes(wanted)) .sort((a, b) => a.name.localeCompare(b.name)) }, [components, query]) if (!canvasId) return null const status = shared.status const updates = new Set(status?.updates.map((update) => update.id)) /* publish this component: the dialog where the canvas may have a library, else the way to one */ const share = (def?: ComponentDef) => { if (!status) return if (status.entitled) return setPublishing(def ? { only: def.id } : {}) setWall({ ...(status.blocked === 'plan_required' ? { workspaceId: status.workspaceId } : {}), reason: def ? t('components.libraryWallReasonOne', { name: def.name }) : t('components.libraryWallReason'), ...(def ? { only: def.id } : {}), }) } const browse = () => { setBrowsing(true) setLibraries(null) api .componentLibraries(canvasId) .then((all) => setLibraries(all.filter((library) => !library.library))) .catch((error: unknown) => { console.error(error) setLibraries([]) }) } if (browsing) return ( <> <ImportCanvasList sources={libraries} onBack={() => setBrowsing(false)} onPick={setPicking} /> {picking && ( <ImportComponentsModal canvasId={canvasId} source={picking} onBack={() => setPicking(null)} onDone={() => { setPicking(null) setBrowsing(false) }} /> )} </> ) return ( <> <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto overscroll-contain px-3 pt-2 pb-3" data-slot="components-panel" > <LibraryNotices canvasId={canvasId} canEdit={canEdit} status={status} onPublish={() => share()} /> {canEdit && ( <div className="flex flex-col border-b border-line-soft pb-2.5"> <Button size="sm" onClick={browse}> {t('components.importFromCanvas')} </Button> </div> )} {shown.length === 0 && ( <p className="px-0.5 text-caption text-ink-soft"> {components?.length ? t('components.noMatch') : t('components.empty')} </p> )} {shown.map((def) => ( <article key={def.id} className="flex flex-col gap-1.5" data-component-card={def.name}> {/* the card is picked up and dropped onto the canvas; the menu holds the rest */} <div draggable={canEdit && renaming !== def.id} aria-label={canEdit ? t('components.dragHint', { name: def.name }) : def.name} className={cn('flex w-full flex-col gap-1.5 text-left', canEdit && 'cursor-grab active:cursor-grabbing')} onDragStart={(event) => { event.dataTransfer.setData(COMPONENT_DRAG_TYPE, def.id) event.dataTransfer.effectAllowed = 'copy' }} > <ComponentThumb title={t('components.previewTitle', { name: def.name })} sheetKey={`${def.id}:${def.rev}:${tokenStamp}`} load={() => api.componentPreview(canvasId, def.id)} /> <span className="flex min-w-0 items-center gap-1.5 text-body text-ink"> {def.source?.library ? ( <BookOpenIcon size="rail" className="flex-none text-brand" aria-label={t('components.libraryLinked')} /> ) : ( <ComponentIcon size="rail" className="flex-none text-brand" /> )} {renaming === def.id ? ( <ComponentNameInput def={def} onDone={() => setRenaming(null)} /> ) : ( <span className="truncate" onDoubleClick={canEdit && !def.source?.library ? () => setRenaming(def.id) : undefined} > {def.name} </span> )} <DropdownMenu> <DropdownMenuTrigger asChild> <IconButton size="sm" className="ml-auto flex-none" aria-label={t('components.moreActions', { name: def.name })} data-component-menu > <MoreHorizontalIcon size="rail" aria-hidden /> </IconButton> </DropdownMenuTrigger> <DropdownMenuContent align="end" width="md" onCloseAutoFocus={(event) => { if (!renameFromMenu.current) return renameFromMenu.current = false event.preventDefault() setRenaming(def.id) }} > {canEdit && ( <DropdownMenuItem onSelect={() => void placeComponent(def)}> {t('components.insertInstance')} </DropdownMenuItem> )} {canEdit && !def.source?.library && ( <DropdownMenuItem onSelect={() => { renameFromMenu.current = true }} > {t('components.rename')} </DropdownMenuItem> )} <DropdownMenuItem onSelect={() => goToMain(def)}> {def.source?.library ? t('components.libraryOpen') : t('components.goToMain')} </DropdownMenuItem> {canEdit && !def.source && def.rev > 0 && status?.canPublish && (status.entitled || status.billing) && ( <DropdownMenuItem onSelect={() => share(def)}> {t('components.libraryPublishOne')} </DropdownMenuItem> )} {canEdit && def.source && (!def.source.library || updates.has(def.id)) && ( <DropdownMenuItem onSelect={() => { api .syncComponent(canvasId, def.id) .then(({ updated }) => useStore .getState() .pushNotice( updated ? t('components.pulled', { name: def.name }) : t('components.upToDate'), ), ) .catch(console.error) }} > {t('components.pullUpdate')} </DropdownMenuItem> )} {canEdit && ( <> <DropdownMenuSeparator /> <DropdownMenuItem className="text-accent-ink data-[highlighted]:text-accent-ink" onSelect={() => setConfirmDelete(def)} > {t('components.deleteComponent')} </DropdownMenuItem> </> )} </DropdownMenuContent> </DropdownMenu> </span> </div> {def.description && <p className="line-clamp-2 text-caption text-ink-soft">{def.description}</p>} </article> ))} <LibrarySection canvasId={canvasId} canEdit={canEdit} query={query} status={status} libraries={shared.libraries} onPublish={() => share()} onWall={(next) => setWall({ ...next, reason: t('components.libraryWallReason') })} /> {publishing && status && ( <PublishLibraryDialog canvasId={canvasId} status={status} only={publishing.only} onClose={() => setPublishing(null)} onDone={() => { setPublishing(null) shared.reload() }} /> )} {wall && ( <LibraryUpgradeFlow canvas={{ id: canvasId, name: canvasName ?? '' }} wall={wall} reason={wall.reason} only={wall.only} onClose={() => setWall(null)} onDone={() => { setWall(null) shared.reload() }} /> )} <ConfirmDialog open={!!confirmDelete} onOpenChange={(open) => !open && setConfirmDelete(null)} title={t('components.deleteConfirmTitle', { name: confirmDelete?.name ?? '' })} description={t('components.deleteConfirmDescription')} confirmLabel={t('components.deleteComponent')} destructive onConfirm={() => { const target = confirmDelete setConfirmDelete(null) if (target) void removeComponent(target) }} /> </div> <PanelSearch value={query} placeholder={t('components.search')} onChange={setQuery} /> </> ) } - src/components/ComponentThumb.tsx (3081 bytes)
import { useEffect, useMemo, useRef, useState } from 'react' import { useStore } from '../lib/store' /** A short fingerprint of a string, to key a refetch on content rather than identity. */ function stamp(text: string): string { let hash = 0 for (let i = 0; i < text.length; i++) hash = (Math.imul(hash, 31) + text.charCodeAt(i)) | 0 return (hash >>> 0).toString(36) } /** The open canvas's token values as a key part: a sheet carries them, so a * token edit redraws a preview the way a new revision does. */ export function useTokenStamp(): string { const tokens = useStore((s) => s.canvas?.tokens) const themes = useStore((s) => s.canvas?.tokenThemes) return useMemo(() => stamp(JSON.stringify([tokens ?? [], themes ?? []])), [tokens, themes]) } export interface PreviewSheet { html: string width: number height: number } /** A component's sheet in an inert iframe: no scripts, no clicks, fitted into a * well of a fixed `height` and centred, so a list of them never moves while the * sheets load (the well is there, empty, from the first frame). `sheetKey` names * what is drawn, so a new revision asks again. */ export function ComponentThumb({ title, sheetKey, load, height = 96, }: { title: string sheetKey: string load: () => Promise<PreviewSheet> /** the well's height in px; the sheet is scaled down to fit inside it */ height?: number }) { const [sheet, setSheet] = useState<({ key: string } & PreviewSheet) | null>(null) /* the panel is resizable, so the sheet scales to the card it is in */ const box = useRef<HTMLDivElement>(null) const [boxWidth, setBoxWidth] = useState(0) const loader = useRef(load) useEffect(() => { loader.current = load }) useEffect(() => { if (!box.current) return const observer = new ResizeObserver(([entry]) => { if (entry) setBoxWidth(entry.contentRect.width) }) observer.observe(box.current) return () => observer.disconnect() }, []) useEffect(() => { let live = true loader .current() .then((next) => { if (live) setSheet({ key: sheetKey, ...next }) }) .catch(console.error) return () => { live = false } }, [sheetKey]) const ready = sheet?.key === sheetKey && boxWidth > 0 /* contain: the whole sheet shows, never wider than the well nor taller */ const scale = ready ? Math.min(boxWidth / sheet.width, height / sheet.height) : 1 return ( <div ref={box} className="relative w-full overflow-hidden rounded-row bg-paper-deep shadow-ring" style={{ height }} data-component-thumb={ready ? 'ready' : 'loading'} > {ready && ( <iframe title={title} sandbox="" srcDoc={sheet.html} tabIndex={-1} className="pointer-events-none absolute top-1/2 left-1/2 origin-center border-0 bg-surface" style={{ width: sheet.width, height: sheet.height, transform: `translate(-50%, -50%) scale(${scale})`, }} /> )} </div> ) } - src/components/ConnectionTable.tsx (10755 bytes)
import type { ReactNode } from 'react' import { useT } from '@/lib/i18n' import { cn } from '@/lib/utils' import { Badge } from './ui/badge' import { IconButton } from './ui/icon-button' import { MenuButton } from './ui/menu-button' import { Switch } from './ui/switch' import { StepSlider } from './ui/step-slider' import { CheckIcon, MoreHorizontalIcon } from './ui/icons' import { DropdownMenu, DropdownMenuCaption, DropdownMenuContent, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from './ui/dropdown-menu' /** * Settings → Doop Agent as two grouped lists. "Connected" holds a row per * connection: its tile, the name with a Default (or Off) badge, a * short line, and on the right the model dropdown (models, then the effort * as tabs), the on/off switch and a "…" menu (Make default, the provider's * own extras, Disconnect). "Add a connection" lists the rest, each with * Connect; the one being connected shows its key field or sign-in under it. * Shared by the model account rows (ModelAccount.tsx) and the Claude Plan * (LocalClaude.tsx). */ /** Where a connection stands: never connected, connected and in use, or * connected but switched off (its credential kept). */ export type ConnectionState = 'none' | 'on' | 'off' /** One of the two lists, under its heading. */ export function ConnectionSection({ title, className, children, }: { title: string className?: string children: ReactNode }) { return ( <section aria-label={title} className={cn('max-w-[1000px]', className)}> <h3 className="mb-[10px] ml-1 text-copy font-medium">{title}</h3> <div role="list" className="overflow-hidden rounded-panel bg-surface shadow-ring"> {children} </div> </section> ) } /* tile · name and line · controls, then whatever opens under the row */ const rowClass = 'border-b border-line-soft last:border-b-0' const rowLine = 'flex items-center gap-[14px] px-4 py-3 max-md:flex-wrap max-md:gap-y-2' function RowName({ name, sub, badges }: { name: string; sub?: ReactNode; badges?: ReactNode }) { return ( <div className="min-w-0 flex-1"> <div className="flex items-center gap-2"> <span className="truncate text-copy font-medium">{name}</span> {badges} </div> {sub && <div className="truncate text-label text-ink-faint">{sub}</div>} </div> ) } /** What opens under a row, indented to its name. */ function RowPanel({ children }: { children: ReactNode }) { return <div className="pb-[14px] pl-[66px] pr-4 text-label text-ink-soft max-md:pl-4">{children}</div> } /** A connected provider. */ export function ConnectionRow({ mark, name, sub, state, isDefault, busy, model, onToggle, onMakeDefault, onDisconnect, menuItems = [], panel, error, }: { mark: ReactNode name: string sub?: ReactNode /** in use, or switched off with its credential kept */ state: Exclude<ConnectionState, 'none'> isDefault: boolean busy: boolean /** the model dropdown */ model: ReactNode onToggle: (on: boolean) => void onMakeDefault?: () => void onDisconnect: () => void /** the provider's own actions, between Make default and Disconnect */ menuItems?: { label: string; onSelect: () => void }[] /** what opens under the row: a key to replace, a task under way */ panel?: ReactNode /** why the last change to this connection failed, shown under it */ error?: string | undefined }) { const t = useT() const off = state === 'off' return ( <div role="listitem" className={rowClass}> <div className={rowLine}> <span aria-hidden className={cn('flex-none', off && 'opacity-55')}> {mark} </span> <RowName name={name} sub={sub} badges={ <> {isDefault && <Badge tone="brand">{t('models.isDefault')}</Badge>} {off && <Badge>{t('models.off')}</Badge>} </> } /> <div className="w-[220px] flex-none max-md:order-last max-md:w-full">{model}</div> <Switch size="sm" aria-label={t('models.useConnection', { name })} checked={!off} disabled={busy} onCheckedChange={onToggle} /> <DropdownMenu> <DropdownMenuTrigger asChild> <IconButton aria-label={t('models.moreActions', { name })} disabled={busy}> <MoreHorizontalIcon size="rail" aria-hidden /> </IconButton> </DropdownMenuTrigger> <DropdownMenuContent align="end" width="lg"> {/* on the default it is done: greyed, with a check where a choice shows its pick */} <DropdownMenuItem disabled={isDefault || off || !onMakeDefault} onSelect={() => onMakeDefault?.()}> <span className="flex w-full items-center justify-between gap-3"> {t('models.makeDefault')} {isDefault && <CheckIcon size={14} className="text-ink" aria-label={t('models.isDefault')} />} </span> </DropdownMenuItem> {menuItems.map((item) => ( <DropdownMenuItem key={item.label} onSelect={item.onSelect}> {item.label} </DropdownMenuItem> ))} <DropdownMenuSeparator /> <DropdownMenuItem className="text-accent-ink data-[highlighted]:text-accent-ink" onSelect={onDisconnect}> {t('models.disconnect')} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </div> {(panel || error) && ( <RowPanel> {panel} <FieldError className={panel ? undefined : 'mt-0'}>{error}</FieldError> </RowPanel> )} </div> ) } /** Why a field or a connection's last change failed, directly under it; * nothing at all while there is no message. */ export function FieldError({ id, className, children }: { id?: string; className?: string; children?: string }) { if (!children) return null return ( <p id={id} role="alert" className={cn('mt-1.5 text-label text-accent-ink', className)}> {children} </p> ) } /** A provider not connected yet: its tile, name, a short line and Connect. * While it is being connected (`open`) its `panel` shows under it. */ export function AvailableRow({ mark, name, sub, action, panel, open = false, }: { mark: ReactNode name: string sub?: ReactNode action?: ReactNode panel?: ReactNode open?: boolean }) { return ( <div role="listitem" className={cn(rowClass, open && panel && 'bg-sub')}> <div className={rowLine}> <span aria-hidden className="flex-none"> {mark} </span> <RowName name={name} sub={sub} /> {action && <div className="flex-none">{action}</div>} </div> {panel && open && <RowPanel>{panel}</RowPanel>} </div> ) } /** A model a row can run, as its dropdown lists it. */ export interface ModelChoice { id: string name: string blurb?: string /** false: the model cannot see screenshots, so designs go unreviewed */ vision?: boolean } /** * The model dropdown in a connected row: the models, then (where the * provider has the dial) the effort. Closed, it reads the model and, in a * lighter tone, the effort. */ export function ModelSelect({ name, models, model, onModel, efforts, effort, onEffort, disabled, }: { /** the provider, for the trigger's label */ name: string models: ModelChoice[] model: string | undefined onModel: (id: string) => void efforts?: { id: string; name: string; blurb?: string }[] effort?: string onEffort?: (id: string) => void | Promise<unknown> disabled?: boolean }) { const t = useT() const current = models.find((m) => m.id === model) const label = current?.name ?? model ?? t('models.pickModel') /* the CLI's own setting is no pick, so the closed dropdown names none */ const effortName = effort === 'default' ? undefined : efforts?.find((e) => e.id === effort)?.name return ( <DropdownMenu> <DropdownMenuTrigger asChild> <MenuButton disabled={disabled} aria-label={t('models.modelFor', { name })} className="w-full min-w-0 justify-start text-ink [&>svg:last-child]:ml-auto" > <span className="truncate font-medium">{label}</span> {effortName && <span className="flex-none text-ink-faint">{effortName}</span>} {current?.vision === false && <NoVisionBadge />} </MenuButton> </DropdownMenuTrigger> <DropdownMenuContent align="start" width="auto"> <DropdownMenuCaption>{t('models.model')}</DropdownMenuCaption> <DropdownMenuRadioGroup value={model ?? ''} onValueChange={onModel}> {models.map((m) => ( <DropdownMenuRadioItem key={m.id} value={m.id} title={m.blurb}> <span className="flex items-center gap-2"> {m.name} {m.vision === false && <NoVisionBadge />} </span> </DropdownMenuRadioItem> ))} {/* a pinned id or server override outside the menu still has to show */} {model && !current && <DropdownMenuRadioItem value={model}>{model}</DropdownMenuRadioItem>} </DropdownMenuRadioGroup> {efforts && efforts.length > 0 && onEffort && ( <> <DropdownMenuSeparator /> <EffortSlider efforts={efforts} effort={effort} onEffort={onEffort} /> </> )} </DropdownMenuContent> </DropdownMenu> ) } /** The effort at the foot of a model dropdown, as tabs rather than a list: * one row, the picked one raised. A long name gets its short form; the * blurb rides on the tab's title. */ /** The effort at the foot of a model dropdown: a stepped slider, the level * named above it; each level's blurb rides on its name's title. */ export function EffortSlider({ efforts, effort, onEffort, }: { efforts: { id: string; name: string; blurb?: string }[] effort: string | undefined onEffort: (id: string) => void | Promise<unknown> }) { const t = useT() return ( <div className="px-2.5 pb-2.5 pt-1"> <DropdownMenuCaption className="px-0">{t('models.reasoningEffort')}</DropdownMenuCaption> <StepSlider label={t('models.reasoningEffort')} steps={efforts.map((e) => ({ id: e.id, name: e.name, ...(e.blurb ? { title: e.blurb } : {}) }))} value={effort} onValueChange={onEffort} /> </div> ) } export function NoVisionBadge() { const t = useT() return <Badge className="flex-none">{t('models.noVisualReview')}</Badge> } - src/components/ConnectModal.tsx (20381 bytes)
import { useMemo, useState } from 'react' import type { ReactNode } from 'react' import { navigate } from '../App' import { useStore } from '../lib/store' import { roleByAgentName } from '../../shared/agents' import { useRoster } from '../hooks/use-roster' import { posthog } from '../lib/posthog' import { useT, type PlainMessageKey, type Translate } from '../lib/i18n' import { canUseChatGPTPublicEndpoint, CHATGPT_CONNECTION_GUIDE, CHATGPT_PLUGINS_URL } from '../lib/chatgptConnection' import { ClaudeDesktopInstall } from './ClaudeDesktopInstall' import { canAddToClaudeDesktop, claudeConnectorInstallUrl } from '../lib/claudeConnection' import { CursorInstall } from './CursorInstall' import { CodexInstall } from './CodexInstall' import { AppIcon, type AppIconBrand } from './ui/brand-mark' import { Button } from './ui/button' import { ChoiceList, ChoiceRow } from './ui/choice-list' import { CodeBlock } from './ui/code-block' import { Disclosure } from './ui/collapsible' import { Dot } from './ui/dot' import { CheckIcon, ChevronLeftIcon } from './ui/icons' import { Modal, ModalActions, ModalLede, ModalSpacer, ModalTitle } from './ui/modal' import { cn } from '@/lib/utils' import { isDesktopShell } from '../lib/shell' /** * "Connect AI" is about agents that join the canvas from outside: Claude Code, * Codex, Cursor, the Claude or ChatGPT apps, or any MCP client. Pick the agent, * then follow its own three steps. Running the built-in Doop Agent on your own * ChatGPT or Claude plan is an account setting and lives in Settings, next to * the prompt bar's allowance meter — not here. */ type AgentId = 'claude-code' | 'claude' | 'chatgpt' | 'codex' | 'cursor' | 'mcp' | 'headless' type View = 'agents' | AgentId type ClaudeConnection = 'desktop' | 'web' /** how a generic MCP client signs in: a person approves it in a browser, or it sends an agent key */ type McpConnection = 'browser' | 'key' /** a product's own name stays as it is; the generic client is named in the reader's language */ type AgentOption = { id: AgentId blurb: PlainMessageKey /** its app icon, as Settings → Doop Agent shows the providers */ icon: AppIconBrand } & ({ name: string } | { nameKey: PlainMessageKey }) const AGENTS: AgentOption[] = [ { id: 'claude-code', name: 'Claude Code', blurb: 'connect.blurbClaudeCode', icon: 'claude-code' }, { id: 'claude', name: 'Claude', blurb: 'connect.blurbClaude', icon: 'claude' }, { id: 'chatgpt', name: 'ChatGPT', blurb: 'connect.blurbChatgpt', icon: 'openai' }, { id: 'codex', name: 'Codex', blurb: 'connect.blurbCodex', icon: 'codex' }, { id: 'cursor', name: 'Cursor', blurb: 'connect.blurbCursor', icon: 'cursor' }, { id: 'mcp', nameKey: 'connect.otherClientName', blurb: 'connect.blurbOtherClient', icon: 'mcp' }, { id: 'headless', nameKey: 'connect.headlessName', blurb: 'connect.blurbHeadless', icon: 'headless' }, ] const agentById = (id: AgentId): AgentOption => AGENTS.find((agent) => agent.id === id) ?? AGENTS[0]! const agentName = (agent: AgentOption, t: Translate): string => ('name' in agent ? agent.name : t(agent.nameKey)) /** `canvasId` is optional: opened from the home dashboard there is no canvas to * suggest a prompt for, and no presence connection to watch for an arrival. */ export function ConnectModal({ canvasId, onClose, initialAgent, showAgentStatus = true, }: { canvasId?: string onClose: () => void initialAgent?: AgentId /** Standalone setup can suggest a canvas without subscribing to its presence. */ showAgentStatus?: boolean }) { const [view, setView] = useState<View>(initialAgent ?? 'agents') return ( <Modal size="lg" className="flex flex-col overflow-hidden p-0 sm:p-0" onClose={onClose}> {view === 'agents' ? ( <AgentPicker onPick={setView} /> ) : ( <AgentSteps agent={view} canvasId={canvasId} showAgentStatus={showAgentStatus} onBack={() => setView('agents')} onClose={onClose} /> )} </Modal> ) } /* ---------- pick the agent, then its three steps ---------- */ function AgentPicker({ onPick }: { onPick: (agent: AgentId) => void }) { const t = useT() return ( <div className={body}> <ModalTitle>{t('connect.chooseTitle')}</ModalTitle> <ModalLede>{t('connect.chooseLede')}</ModalLede> <ChoiceList className="mt-5"> {AGENTS.map((option) => ( <ChoiceRow key={option.id} icon={<AppIcon brand={option.icon} />} title={agentName(option, t)} description={t(option.blurb)} onClick={() => { posthog.capture('connect_ai_agent_chosen', { agent: option.id }) onPick(option.id) }} /> ))} </ChoiceList> </div> ) } interface Step { title: string body: ReactNode code?: string action?: ReactNode } interface StepOptions { claudeConnection: ClaudeConnection mcpConnection: McpConnection canvasId?: string | undefined /** opens Settings → Agent keys, coming back to this canvas */ openAgentKeys: () => void } /** An agent with no browser to sign in with: an agent key, sent as a bearer header. */ function agentKeySteps(t: Translate, mcpUrl: string, pointAt: Step, openAgentKeys: () => void) { const config = JSON.stringify( { mcpServers: { doop: { type: 'http', url: mcpUrl, headers: { Authorization: 'Bearer dpk_…' } } } }, null, 2, ) return { lede: t('connect.agentKeyLede'), steps: [ { title: t('connect.agentKeyCreateTitle'), body: t('connect.agentKeyCreateBody'), action: ( <Button variant="solid" className="mt-2.5" onClick={openAgentKeys}> {t('connect.agentKeyOpen')} </Button> ), }, { title: t('connect.agentKeySendTitle'), body: t('connect.agentKeySendBody'), code: config }, pointAt, ], } } function agentSteps( t: Translate, agent: AgentId, mcpUrl: string, prompt: string, { claudeConnection, mcpConnection, canvasId, openAgentKeys }: StepOptions, ): { lede: string; steps: Step[] } { const jsonConfig = JSON.stringify({ mcpServers: { doop: { type: 'http', url: mcpUrl } } }, null, 2) const pointAt: Step = { title: t('connect.pointAtTitle'), body: prompt ? t('connect.pointAtWithPrompt') : t('connect.pointAtNoPrompt'), code: prompt || undefined, } switch (agent) { case 'claude-code': return { lede: t('connect.claudeCodeLede'), steps: [ { title: t('connect.claudeCodeAddTitle'), body: ( <> {t('connect.claudeCodeAddBefore')} <code>doop</code> {t('connect.claudeCodeAddAfter')} </> ), code: `claude mcp add --transport http doop "${mcpUrl}"`, }, { title: t('connect.claudeCodeSignInTitle'), body: ( <> {t('connect.claudeCodeSignInBefore')} <code>/mcp</code> {t('connect.claudeCodeSignInPick')} <strong>doop</strong> {t('connect.claudeCodeSignInThen')} {/* Claude Code's own menu label, which it shows in English */} <strong>Authenticate</strong> {t('connect.claudeCodeSignInAfter')} </> ), }, pointAt, ], } case 'claude': if (claudeConnection === 'desktop') { return { lede: t('connect.claudeDesktopLede'), steps: [ { title: t('connect.claudeDesktopAddTitle'), body: t('connect.claudeDesktopAddBody'), action: <ClaudeDesktopInstall mcpUrl={mcpUrl} />, }, { title: t('connect.claudeDesktopConnectTitle'), body: t('connect.claudeDesktopConnectBody'), }, { ...pointAt, body: prompt ? t('connect.claudeDesktopPointWithPrompt') : t('connect.claudeDesktopPointNoPrompt'), }, ], } } if (!claudeConnectorInstallUrl(mcpUrl)) { return { lede: t('connect.claudePublicLede'), steps: [ { title: t('connect.claudeLocalTitle'), body: t('connect.claudeLocalBody'), }, ], } } return { lede: t('connect.claudeWebLede'), steps: [ { title: t('connect.claudeWebAddTitle'), body: t('connect.claudeWebAddBody'), action: ( <Button asChild variant="solid" className="mt-2.5"> <a href={claudeConnectorInstallUrl(mcpUrl)!} target="_blank" rel="noopener noreferrer" onClick={() => posthog.capture('claude_connector_opened')} > {t('connect.addToClaude')} </a> </Button> ), }, { title: t('connect.approveSignInTitle'), body: t('connect.claudeWebApproveBody'), }, { ...pointAt, body: prompt ? t('connect.claudeWebPointWithPrompt') : t('connect.claudeWebPointNoPrompt'), }, ], } case 'chatgpt': if (!canUseChatGPTPublicEndpoint(mcpUrl)) { return { lede: t('connect.chatgptPublicLede'), steps: [ { title: t('connect.chatgptReachTitle'), body: t('connect.chatgptReachBody'), code: mcpUrl, action: ( <Button asChild variant="solid" className="mt-2.5"> <a href={CHATGPT_CONNECTION_GUIDE} target="_blank" rel="noopener noreferrer"> {t('connect.chatgptGuide')} </a> </Button> ), }, ], } } return { lede: t('connect.chatgptLede'), steps: [ { title: t('connect.chatgptOpenTitle'), body: ( <> {t('connect.chatgptOpenBefore')} <strong>+</strong> {t('connect.chatgptOpenMiddle')} {/* ChatGPT's own menu label */} <strong>Add custom MCP server</strong> {t('connect.chatgptOpenAfter')} </> ), action: ( <Button asChild variant="solid" className="mt-2.5"> <a href={CHATGPT_PLUGINS_URL} target="_blank" rel="noopener noreferrer" onClick={() => posthog.capture('chatgpt_connection_opened')} > {t('connect.chatgptOpenButton')} </a> </Button> ), }, { title: t('connect.chatgptAddTitle'), body: ( <> {t('connect.chatgptAddBefore')} <strong>Doop</strong> {t('connect.chatgptAddDescribe')} <strong>OAuth</strong> {t('connect.chatgptAddReview')} {/* ChatGPT's own button label */} <strong>Create as a plugin</strong> {t('connect.chatgptAddAfter')} </> ), code: mcpUrl, }, { ...pointAt, body: prompt ? t('connect.chatgptPointWithPrompt') : t('connect.chatgptPointNoPrompt'), }, ], } case 'codex': return { lede: t('connect.codexLede'), steps: [ { title: t('connect.codexAddTitle'), body: t('connect.codexAddBody'), action: <CodexInstall mcpUrl={mcpUrl} canvasId={canvasId} />, }, { title: t('connect.codexSignInTitle'), body: t('connect.codexSignInBody'), code: 'codex mcp login doop', }, pointAt, ], } case 'cursor': return { lede: t('connect.cursorLede'), steps: [ { title: t('connect.cursorAddTitle'), body: t('connect.cursorAddBody'), action: <CursorInstall mcpUrl={mcpUrl} />, }, { title: t('connect.approveSignInTitle'), body: t('connect.cursorApproveBody'), }, { ...pointAt, body: prompt ? t('connect.cursorPointWithPrompt') : t('connect.cursorPointNoPrompt'), }, ], } case 'headless': return agentKeySteps(t, mcpUrl, pointAt, openAgentKeys) case 'mcp': if (mcpConnection === 'key') return agentKeySteps(t, mcpUrl, pointAt, openAgentKeys) return { lede: t('connect.mcpLede'), steps: [ { title: t('connect.mcpConfigTitle'), body: ( <> {t('connect.mcpConfigBefore')} <code>doop</code> {t('connect.mcpConfigAfter')} </> ), code: jsonConfig, }, { title: t('connect.approveSignInTitle'), body: t('connect.mcpApproveBody'), }, pointAt, ], } } } function AgentSteps({ agent, canvasId, showAgentStatus, onBack, onClose, }: { agent: AgentId canvasId?: string showAgentStatus: boolean onBack: () => void onClose: () => void }) { const t = useT() const option = agentById(agent) const name = agentName(option, t) const mcpUrl = `${location.origin}/mcp` const [claudeConnection, setClaudeConnection] = useState<ClaudeConnection>(() => canAddToClaudeDesktop() || !claudeConnectorInstallUrl(mcpUrl) ? 'desktop' : 'web', ) /* Deliberately thin: the MCP server ships its own INSTRUCTIONS on connect and the rest lives behind get_guide. The only thing this prompt knows that they don't is which canvas the human is looking at. */ const prompt = canvasId ? `Work on Doop canvas ${canvasId}. Start with get_guide({ topic: "doop-instructions" }) and follow it.` : '' const [mcpConnection, setMcpConnection] = useState<McpConnection>('browser') /* a browser keeps these steps open beside the new tab; the desktop shell's tabs hold canvases only, and the system browser may not be signed in, so there it goes in place and Settings' back link returns to the canvas */ const openAgentKeys = () => { const from = canvasId ? `&from=${encodeURIComponent(`/c/${canvasId}`)}` : '' if (isDesktopShell()) navigate(`/settings?pane=keys${from}`) else window.open('/settings?pane=keys', '_blank', 'noopener') } const { lede, steps } = agentSteps(t, agent, mcpUrl, prompt, { claud - src/components/CursorInstall.tsx (932 bytes)
import { cursorMcpInstallUrl } from '../lib/cursorConnection' import { Button } from './ui/button' import { CodeBlock } from './ui/code-block' import { InstallBlock } from './ui/install-block' import { useT } from '../lib/i18n' export function CursorInstall({ mcpUrl }: { mcpUrl: string }) { const t = useT() return ( <InstallBlock action={ <Button asChild variant="solid"> <a href={cursorMcpInstallUrl(mcpUrl)}>{t('workspace.cursorAdd')}</a> </Button> } manualLabel={t('workspace.connectionHelp')} manual={ <> <p> {t('workspace.cursorHelpBefore')} <strong>Customize</strong> {t('workspace.cursorHelpMiddle')}{' '} <code>doop</code> {t('workspace.cursorHelpAfter')} </p> <CodeBlock text={JSON.stringify({ mcpServers: { doop: { url: mcpUrl } } }, null, 2)} className="mt-2.5" /> </> } /> ) } - src/components/Cursors.tsx (1953 bytes)
import { memo } from 'react' import { useStore } from '../lib/store' import { getIdentity } from '../lib/identity' import { AgentIcon } from './AgentIcon' /* Counter-scaling comes from the `--zoom` CSS variable (see .remote-cursor), so viewport changes never re-render this component. */ export const Cursors = memo(function Cursors() { const cursors = useStore((s) => s.cursors) const presences = useStore((s) => s.presences) const peerViewports = useStore((s) => s.peerViewports) const activePageId = useStore((s) => s.activePageId) const me = getIdentity().clientId return ( <> {Object.entries(cursors).map(([clientId, pos]) => { if (clientId === me) return null const p = presences[clientId] const pageId = peerViewports[clientId]?.pageId if (!p || (pageId && pageId !== activePageId)) return null return ( <div key={clientId} className="pointer-events-none absolute z-30 origin-top-left [transition:transform_0.06s_linear]" style={{ transform: `translate(${pos.x}px, ${pos.y}px) scale(calc(1 / var(--zoom, 1)))` }} > <svg width="18" height="20" viewBox="0 0 18 20"> <path d="M1 1 L16 8.5 L9 10.5 L6.5 18 Z" fill={p.color} stroke="#fff" strokeWidth="1.4" strokeLinejoin="round" /> </svg> <span className="absolute left-3.5 top-4 whitespace-nowrap rounded-[999px_999px_999px_4px] px-2 py-[3px] text-[11px] font-medium text-white" style={{ background: p.color }} > {p.kind === 'agent' && ( <> <AgentIcon name={p.name} brand={p.brand} size={9} color="#fff" />{' '} </> )} {p.name} </span> </div> ) })} </> ) }) - src/components/CustomAgents.tsx (16042 bytes)
import { useEffect, useId, useRef, useState } from 'react' import { api, errorMessage } from '../lib/api' import { useT } from '../lib/i18n' import { posthog } from '../lib/posthog' import { DEFAULT_ROLE_ID } from '../../shared/agents' import { CUSTOM_AGENT_COLORS, MAX_AGENT_BLURB, MAX_AGENT_BRIEF, MAX_AGENT_NAME, MAX_CUSTOM_AGENTS, handleFor, type BuiltInAgent, type CustomAgent, } from '../../shared/customAgents' import { RoleMark } from './RoleMark' import { useSkillMenu } from './SkillMenu' import { ConfirmDialog } from './ui/alert-dialog' import { Badge } from './ui/badge' import { Button } from './ui/button' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' import { EmptyState } from './ui/empty-state' import { Field } from './ui/field' import { EditIcon, PlusIcon, TrashIcon } from './ui/icons' import { Input } from './ui/input' import { Modal, ModalActions, ModalLede, ModalSpacer, ModalTitle } from './ui/modal' import { Note } from './ui/note' import { Pressable } from './ui/pressable' import { Switch } from './ui/switch' import { Textarea } from './ui/textarea' import { cn } from '../lib/utils' /** What the agent form is open on: a new custom agent, one that exists, or a * built-in agent this team is changing. */ type Editing = { kind: 'new' } | { kind: 'custom'; agent: CustomAgent } | { kind: 'builtin'; agent: BuiltInAgent } /** * A team's Doop Agent roster as a settings card: the built-in agents, each * switchable off (Doop excepted) and editable, then the custom agents this * team added. `workspaceId` picks a workspace's team (on its canvases); * without it the card manages the person's own, on their personal canvases. */ export function CustomAgents({ workspaceId }: { workspaceId?: string }) { const t = useT() const [builtIns, setBuiltIns] = useState<BuiltInAgent[] | null>(null) const [agents, setAgents] = useState<CustomAgent[] | null>(null) const [error, setError] = useState('') const [editing, setEditing] = useState<Editing | null>(null) const [removing, setRemoving] = useState<CustomAgent | null>(null) useEffect(() => { let live = true Promise.all([api.listBuiltInAgents(workspaceId), api.listCustomAgents(workspaceId)]).then( ([team, custom]) => { if (!live) return setBuiltIns(team) setAgents(custom) }, (e: unknown) => { if (!live) return setBuiltIns([]) setAgents([]) setError(errorMessage(e, t('agents.loadFailed'))) }, ) return () => { live = false } }, [workspaceId, t]) function replaceBuiltIn(agent: BuiltInAgent) { setBuiltIns((list) => list?.map((a) => (a.id === agent.id ? agent : a)) ?? null) } async function toggle(agent: BuiltInAgent, enabled: boolean) { setError('') /* flips at once; a refusal puts it back */ replaceBuiltIn({ ...agent, enabled }) try { replaceBuiltIn(await api.updateBuiltInAgent(agent.id, { disabled: !enabled }, workspaceId)) } catch (e) { replaceBuiltIn(agent) setError(errorMessage(e, t('agents.saveFailed'))) } } async function remove(agent: CustomAgent) { setError('') try { await api.deleteCustomAgent(agent.id, workspaceId) setAgents((list) => list?.filter((a) => a.id !== agent.id) ?? null) } catch (e) { setError(errorMessage(e, t('agents.removeFailed'))) } } function saved(agent: CustomAgent | BuiltInAgent) { if ('enabled' in agent) replaceBuiltIn(agent) else if (editing?.kind === 'new') setAgents((list) => [...(list ?? []), agent]) else setAgents((list) => list?.map((a) => (a.id === agent.id ? agent : a)) ?? null) setEditing(null) } const full = (agents?.length ?? 0) >= MAX_CUSTOM_AGENTS const addButton = ( <Button size="sm" disabled={agents === null || full} onClick={() => setEditing({ kind: 'new' })}> <PlusIcon /> {t('agents.add')} </Button> ) return ( <SettingsCard> <CardHeader> <CardTitle>{t('agents.title')}</CardTitle> <CardDescription> {workspaceId ? t('agents.descriptionWorkspace') : t('agents.descriptionPersonal')}{' '} {t('agents.descriptionRest')} </CardDescription> </CardHeader> <CardRow label={t('agents.builtIn')}> {error ? <Note tone="error">{error}</Note> : <Note>{t('agents.builtInNote')}</Note>} </CardRow> {builtIns?.map((agent) => ( <AgentRow key={agent.id} agent={agent} off={!agent.enabled} badge={ !agent.enabled ? ( <Badge tone="outline">{t('agents.off')}</Badge> ) : agent.edited ? ( <Badge tone="outline">{t('agents.edited')}</Badge> ) : null } actions={ <> <Button size="sm" variant="bare" onClick={() => setEditing({ kind: 'builtin', agent })}> <EditIcon size="rail" /> {t('agents.edit')} </Button> <Switch size="sm" checked={agent.enabled} /* everything addressed to no one, and to an agent that is off, goes to Doop */ disabled={agent.id === DEFAULT_ROLE_ID} title={agent.id === DEFAULT_ROLE_ID ? t('agents.defaultStaysOn') : undefined} aria-label={t('agents.toggle', { name: agent.name })} onCheckedChange={(on) => void toggle(agent, on)} /> </> } /> ))} {agents?.length === 0 ? ( <div className="flex flex-col gap-2 px-4 py-5 sm:px-[22px]"> <EmptyState variant="dashed" className="border" title={t('agents.emptyTitle')} description={workspaceId ? t('agents.emptyWorkspace') : t('agents.emptyPersonal')} action={addButton} /> </div> ) : ( <CardRow label={t('agents.yours')} action={addButton}> <Note> {agents === null ? t('agents.loading') : full ? t('agents.full', { count: MAX_CUSTOM_AGENTS }) : t('agents.count', { count: agents.length })} </Note> </CardRow> )} {agents?.map((agent) => ( <AgentRow key={agent.id} agent={agent} actions={ <> <Button size="sm" variant="bare" onClick={() => setEditing({ kind: 'custom', agent })}> <EditIcon size="rail" /> {t('agents.edit')} </Button> <Button size="sm" variant="bare" onClick={() => setRemoving(agent)}> <TrashIcon size="rail" /> {t('agents.remove')} </Button> </> } /> ))} {editing && ( <AgentForm editing={editing} workspaceId={workspaceId} onClose={() => setEditing(null)} onSaved={saved} /> )} <ConfirmDialog open={removing !== null} onOpenChange={(open) => !open && setRemoving(null)} title={removing ? t('agents.removeTitle', { name: removing.name }) : ''} description={t('agents.removeDescription')} confirmLabel={t('agents.remove')} destructive onConfirm={() => { if (removing) void remove(removing) setRemoving(null) }} /> </SettingsCard> ) } /** One agent on the card: its mark and name, its handle and one-liner. */ function AgentRow({ agent, off = false, badge, actions, }: { agent: CustomAgent | BuiltInAgent off?: boolean badge?: React.ReactNode actions: React.ReactNode }) { const t = useT() return ( <CardRow label={ <span className={cn('inline-flex min-w-0 items-center gap-2', off && 'opacity-50')}> <RoleMark role={agent} size={16} /> <span className="truncate">{agent.name}</span> </span> } action={<div className="flex items-center gap-2">{actions}</div>} > <div className={cn('flex min-w-0 basis-full flex-col gap-0.5', off && 'opacity-50')}> <p className="flex min-w-0 items-center gap-2 text-body text-ink"> <span className="truncate"> <span className="font-mono text-ink-soft">@{agent.id}</span> · {agent.blurb} </span> {badge} </p> {agent.reviewer && <p className="text-caption text-ink-faint">{t('agents.reviewerBadge')}</p>} </div> </CardRow> ) } /** Add an agent, or edit one. The name and handle of an existing agent stay: * open comments and cards point at them. */ function AgentForm({ editing, workspaceId, onClose, onSaved, }: { editing: Editing workspaceId?: string onClose: () => void onSaved: (agent: CustomAgent | BuiltInAgent) => void }) { const t = useT() const ids = useId() const agent = editing.kind === 'new' ? undefined : editing.agent const [name, setName] = useState(agent?.name ?? '') /* the handle follows the name until someone types one of their own */ const [handle, setHandle] = useState(agent?.id ?? '') const [handleTouched, setHandleTouched] = useState(!!agent) const [color, setColor] = useState<string>(agent?.color ?? CUSTOM_AGENT_COLORS[2]) const [blurb, setBlurb] = useState(agent?.blurb ?? '') const [brief, setBrief] = useState(agent?.brief ?? '') const briefRef = useRef<HTMLTextAreaElement>(null) /* no "New skill" row, since leaving for the skills card would lose this half-edited form */ const skillMenu = useSkillMenu({ from: { scope: workspaceId ? { workspaceId } : { personal: true } }, text: brief, setText: setBrief, inputRef: briefRef, }) const [reviewer, setReviewer] = useState(agent?.reviewer ?? false) const [saving, setSaving] = useState(false) const [error, setError] = useState('') const shownHandle = handleTouched ? handle : handleFor(name) async function run(work: () => Promise<CustomAgent | BuiltInAgent>) { setSaving(true) setError('') try { onSaved(await work()) } catch (e) { setError(errorMessage(e, t('agents.saveFailed'))) setSaving(false) } } function save() { const fields = { color, blurb, brief, reviewer } return run(async () => { if (editing.kind === 'builtin') return api.updateBuiltInAgent(editing.agent.id, fields, workspaceId) if (editing.kind === 'custom') return api.updateCustomAgent(editing.agent.id, fields, workspaceId) const created = await api.createCustomAgent({ name, handle: shownHandle, ...fields }, workspaceId) posthog.capture('custom_agent_created_ui', { workspace: !!workspaceId, reviewer }) return created }) } return ( <Modal onClose={onClose} size="lg" /* the dialog hears Escape before the field does; while the skill menu is open it closes only the menu */ onEscapeKeyDown={(e) => { if (skillMenu.menu && e.target === briefRef.current) e.preventDefault() }} > <ModalTitle>{agent ? t('agents.editTitle', { name: agent.name }) : t('agents.addTitle')}</ModalTitle> <ModalLede>{editing.kind === 'builtin' ? t('agents.builtInLede') : t('agents.formLede')}</ModalLede> <form className="mt-4 flex flex-col gap-3.5" onSubmit={(e) => { e.preventDefault() void save() }} > <div className="grid gap-3.5 sm:grid-cols-2"> <Field label={t('agents.name')} labelVariant="form" htmlFor={`${ids}-name`} hint={agent ? t('agents.fixedHint') : undefined} > <Input id={`${ids}-name`} variant="well" value={name} maxLength={MAX_AGENT_NAME} disabled={!!agent} placeholder={t('agents.namePlaceholder')} onChange={(e) => setName(e.target.value)} autoFocus={!agent} /> </Field> <Field label={t('agents.handle')} labelVariant="form" htmlFor={`${ids}-handle`}> <Input id={`${ids}-handle`} variant="well" className="font-mono" value={shownHandle ? `@${shownHandle}` : ''} disabled={!!agent} placeholder="@seo" onChange={(e) => { setHandleTouched(true) setHandle( e.target.value .replace(/^@+/, '') .toLowerCase() .replace(/[^a-z0-9]/g, ''), ) }} /> </Field> </div> <Field label={t('agents.blurb')} labelVariant="form" htmlFor={`${ids}-blurb`}> <Input id={`${ids}-blurb`} variant="well" value={blurb} maxLength={MAX_AGENT_BLURB} placeholder={t('agents.blurbPlaceholder')} onChange={(e) => setBlurb(e.target.value)} /> </Field> <Field label={t('agents.brief')} labelVariant="form" htmlFor={`${ids}-brief`} hint={t('agents.briefHint', { used: brief.length, max: MAX_AGENT_BRIEF })} > <div className="relative"> {skillMenu.menu} <Textarea ref={briefRef} id={`${ids}-brief`} variant="well" className="min-h-[150px]" value={brief} maxLength={MAX_AGENT_BRIEF} placeholder={t('agents.briefPlaceholder')} {...skillMenu.inputProps} onKeyDown={skillMenu.onKeyDown} /> </div> </Field> <Field label={t('agents.color')} labelVariant="form"> <div className="flex flex-wrap gap-2" role="radiogroup" aria-label={t('agents.color')}> {[...new Set([...(agent ? [agent.color.toUpperCase()] : []), ...CUSTOM_AGENT_COLORS])].map((swatch) => ( <Pressable key={swatch} layout="inline" focus="ring" role="radio" aria-checked={color.toUpperCase() === swatch.toUpperCase()} aria-label={swatch} className={cn( 'rounded-full p-0.5', color.toUpperCase() === swatch.toUpperCase() && 'shadow-[0_0_0_2px_var(--ink)]', )} onClick={() => setColor(swatch)} > <RoleMark role={{ color: swatch }} size={22} /> </Pressable> ))} </div> </Field> <label className="flex items-start gap-3" htmlFor={`${ids}-reviewer`}> <Switch id={`${ids}-reviewer`} checked={reviewer} onCheckedChange={setReviewer} className="mt-0.5" /> <span className="flex flex-col"> <span className="text-body font-medium text-ink" - src/components/CustomProviderForm.tsx (16041 bytes)
import { useId, useState } from 'react' import { api } from '../lib/api' import type { CustomProviderInput, ModelAccounts, ModelAccountStatus } from '../lib/api' import { useT } from '../lib/i18n' import { headersFromText, isCustomProviderKind, parseCustomProviderConfig, type CustomApiType, type CustomProviderKind, type CustomTokenParam, } from '../../shared/customProvider' import { Button } from './ui/button' import { Disclosure } from './ui/collapsible' import { Field } from './ui/field' import { IconButton } from './ui/icon-button' import { PlusIcon, TrashIcon } from './ui/icons' import { Input } from './ui/input' import { Modal, ModalActions, ModalLede, ModalTitle } from './ui/modal' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select' import { Switch } from './ui/switch' import { Textarea } from './ui/textarea' import { FieldError } from './ConnectionTable' /** * Settings → Doop Agent → Custom provider: any OpenAI- or Anthropic- * compatible API by its base URL, an optional key and the models it should * offer, each with whether it sees images and how much it may write per * turn. Fetch models asks the endpoint for its list; Test runs one turn that * has to call a tool, which is how the agent does all its work. * * On an edit the stored key and headers are never shown: blank fields keep * them, and each has its own Remove. */ interface ModelRow { key: number id: string maxOutputTokens: string vision: boolean } let nextRowKey = 0 const row = (id = '', vision = false, maxOutputTokens = ''): ModelRow => ({ key: nextRowKey++, id, maxOutputTokens, vision, }) export function CustomProviderForm({ provider, onSaved, onClose, }: { /** the provider being edited; a new one when unset */ provider?: ModelAccountStatus onSaved: (view: ModelAccounts) => void onClose: () => void }) { const t = useT() const ids = useId() const stored = provider?.custom const kind: CustomProviderKind | undefined = isCustomProviderKind(provider?.kind) ? provider.kind : undefined const [name, setName] = useState(stored?.name ?? '') const [apiType, setApiType] = useState<CustomApiType>(stored?.apiType ?? 'openai-chat') const [baseUrl, setBaseUrl] = useState(stored?.baseUrl ?? '') const [apiKey, setApiKey] = useState('') const [clearKey, setClearKey] = useState(false) const [models, setModels] = useState<ModelRow[]>( stored?.models.map((m) => row(m.id, m.vision, m.maxOutputTokens ? String(m.maxOutputTokens) : '')) ?? [row()], ) const [headersText, setHeadersText] = useState('') const [clearHeaders, setClearHeaders] = useState(false) const [tokenParam, setTokenParam] = useState<CustomTokenParam>(stored?.tokenParam ?? 'max_tokens') const [echoReasoning, setEchoReasoning] = useState(stored?.echoReasoning ?? false) const [discovered, setDiscovered] = useState<string[] | null>(null) const [busy, setBusy] = useState<'save' | 'fetch' | 'test' | null>(null) const [error, setError] = useState('') const [tested, setTested] = useState('') const savedHeaders = clearHeaders ? [] : (stored?.headerNames ?? []) const keySaved = Boolean(stored?.hasKey) && !clearKey const failWith = (e: unknown) => { const body = (e as { body?: { error?: string } })?.body setError(body?.error || (e instanceof Error ? e.message : t('models.failedRetry'))) } /** What the form says, checked as the server will check it. */ function input(): CustomProviderInput | null { const config = parseCustomProviderConfig({ name, apiType, baseUrl, models: models .filter((m) => m.id.trim()) .map((m) => ({ id: m.id, vision: m.vision, maxOutputTokens: m.maxOutputTokens.trim() || undefined })), tokenParam, echoReasoning, }) if (!config.ok) { setError(config.error) return null } const headers = headersFromText(headersText) if (!headers.ok) { setError(headers.error) return null } const key = apiKey.trim() return { ...config.value, /* left out on an edit = keep what is stored */ ...(key ? { apiKey: key } : clearKey || !kind ? { apiKey: '' } : {}), ...(Object.keys(headers.value).length ? { headers: headers.value } : clearHeaders ? { headers: {} } : {}), } } /** The key and headers a set-up request should carry: what was typed, else * (on an edit) the server uses the stored ones for `kind`. */ function probeSecrets() { const headers = headersFromText(headersText) const key = apiKey.trim() return { ...(key ? { apiKey: key } : clearKey ? { apiKey: '' } : {}), ...(headers.ok && Object.keys(headers.value).length ? { headers: headers.value } : clearHeaders ? { headers: {} } : {}), ...(kind ? { kind } : {}), } } async function save() { setError('') const body = input() if (!body) return setBusy('save') try { onSaved(kind ? await api.updateCustomProvider(kind, body) : await api.addCustomProvider(body)) } catch (e) { failWith(e) } finally { setBusy(null) } } async function fetchModels() { setError('') setBusy('fetch') try { const { models: listed } = await api.discoverCustomModels({ apiType, baseUrl, ...probeSecrets() }) setDiscovered(listed) if (!listed.length) setError(t('models.customNoModelsListed')) } catch (e) { failWith(e) } finally { setBusy(null) } } async function test() { setError('') setTested('') const body = input() const first = body?.models[0] if (!body || !first) return setBusy('test') try { const result = await api.testCustomProvider({ ...body, ...probeSecrets(), model: first.id }) setTested(t('models.customTestPassed', { model: result.model })) } catch (e) { failWith(e) } finally { setBusy(null) } } const updateRow = (key: number, patch: Partial<ModelRow>) => setModels((rows) => rows.map((m) => (m.key === key ? { ...m, ...patch } : m))) const addDiscovered = (id: string) => setModels((rows) => { if (rows.some((m) => m.id === id)) return rows /* the empty row a new form starts with takes the first pick */ const blank = rows.find((m) => !m.id.trim()) return blank ? rows.map((m) => (m === blank ? { ...m, id } : m)) : [...rows, row(id)] }) const unlisted = discovered?.filter((id) => !models.some((m) => m.id === id)) ?? [] return ( <Modal size="xl" onClose={onClose}> <ModalTitle> {kind ? t('models.customEditTitle', { name: stored?.name ?? '' }) : t('models.customTitle')} </ModalTitle> <ModalLede>{t('models.customLede')}</ModalLede> <div className="mt-5 grid gap-4"> <div className="grid gap-3 sm:grid-cols-2"> <Field label={t('models.customName')} labelVariant="form" htmlFor={`${ids}-name`}> <Input id={`${ids}-name`} variant="well" value={name} onChange={(e) => setName(e.target.value)} placeholder={t('models.customNamePlaceholder')} autoFocus /> </Field> <Field label={t('models.customApiType')} labelVariant="form"> <Select value={apiType} onValueChange={(next) => setApiType(next as CustomApiType)}> <SelectTrigger aria-label={t('models.customApiType')} className="w-full"> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="openai-chat">{t('models.customApiOpenai')}</SelectItem> <SelectItem value="anthropic">{t('models.customApiAnthropic')}</SelectItem> </SelectContent> </Select> </Field> </div> <Field label={t('models.customBaseUrl')} labelVariant="form" htmlFor={`${ids}-url`} hint={apiType === 'anthropic' ? t('models.customBaseUrlAnthropicHint') : t('models.customBaseUrlOpenaiHint')} > <Input id={`${ids}-url`} variant="well" className="font-mono" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={apiType === 'anthropic' ? 'https://api.example.com' : 'https://api.example.com/v1'} spellCheck={false} inputMode="url" /> </Field> <Field label={t('models.customApiKey')} labelVariant="form" htmlFor={`${ids}-key`} hint={keySaved ? t('models.customKeySavedHint') : t('models.customKeyHint')} > <div className="flex gap-2"> <Input id={`${ids}-key`} variant="well" className="flex-1 font-mono" type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder={keySaved ? t('models.customKeySavedPlaceholder') : t('models.customKeyPlaceholder')} spellCheck={false} autoComplete="off" /> {keySaved && ( <Button variant="ghost" onClick={() => setClearKey(true)}> {t('models.customRemoveKey')} </Button> )} </div> </Field> <div> <div className="mb-1.5 flex items-center justify-between gap-3"> <span className="text-label font-medium text-ink-soft">{t('models.customModels')}</span> <Button size="sm" variant="ghost" onClick={() => void fetchModels()} disabled={busy !== null || !baseUrl.trim()} > {busy === 'fetch' ? t('models.customFetching') : t('models.customFetchModels')} </Button> </div> <div role="list" className="grid gap-2"> {models.map((m, index) => ( <div role="listitem" key={m.key} className="flex flex-wrap items-center gap-2"> <Input variant="well" className="min-w-[180px] flex-[2] font-mono" value={m.id} onChange={(e) => updateRow(m.key, { id: e.target.value })} placeholder={t('models.customModelIdPlaceholder')} aria-label={t('models.customModelId', { n: index + 1 })} spellCheck={false} /> <Input variant="well" className="w-[150px] flex-1 font-mono" value={m.maxOutputTokens} onChange={(e) => updateRow(m.key, { maxOutputTokens: e.target.value.replace(/[^\d]/g, '') })} placeholder={t('models.customMaxTokensPlaceholder')} aria-label={t('models.customMaxTokens', { n: index + 1 })} inputMode="numeric" /> <label className="flex flex-none items-center gap-2 text-label text-ink-soft"> <Switch size="sm" checked={m.vision} onCheckedChange={(vision) => updateRow(m.key, { vision })} aria-label={t('models.customVisionFor', { n: index + 1 })} /> {t('models.customVision')} </label> <IconButton aria-label={t('models.customRemoveModel', { n: index + 1 })} disabled={models.length === 1} onClick={() => setModels((rows) => rows.filter((r) => r.key !== m.key))} > <TrashIcon size="rail" aria-hidden /> </IconButton> </div> ))} </div> <div className="mt-2 flex flex-wrap items-center gap-2"> <Button size="sm" variant="ghost" onClick={() => setModels((rows) => [...rows, row()])}> <PlusIcon size="rail" aria-hidden /> {t('models.customAddModel')} </Button> {unlisted.length > 0 && ( <Select value="" onValueChange={addDiscovered}> <SelectTrigger size="sm" className="w-[260px] max-w-full" aria-label={t('models.customAddListed')}> <SelectValue placeholder={t('models.customAddListed')} /> </SelectTrigger> <SelectContent> {unlisted.map((id) => ( <SelectItem key={id} value={id}> {id} </SelectItem> ))} </SelectContent> </Select> )} </div> <p className="mt-1.5 text-caption text-ink-faint">{t('models.customModelsHint')}</p> </div> <Disclosure label={t('models.customAdvanced')} triggerClassName="text-label font-medium text-ink-soft"> <div className="grid gap-4"> <Field label={t('models.customHeaders')} labelVariant="form" htmlFor={`${ids}-headers`} hint={ savedHeaders.length ? t('models.customHeadersSaved', { names: savedHeaders.join(', ') }) : t('models.customHeadersHint') } > <Textarea id={`${ids}-headers`} variant="well" className="font-mono" rows={3} value={headersText} onChange={(e) => setHeadersText(e.target.value)} placeholder="X-Gateway-Tenant: design" spellCheck={false} /> {savedHeaders.length > 0 && ( <Button size="sm" variant="ghost" className="mt-2" onClick={() => setClearHeaders(true)}> {t('models.customRemoveHeaders')} </Button> )} </Field> {apiType === 'openai-chat' && ( <> <Field label={t('models.customTokenParam')} labelVariant="form" hint={t('models.customTokenParamHint')}> <Select value={tokenParam} onValueChange={(next) => setTokenParam(next as CustomTokenParam)}> <SelectTrigger aria-label={t('models.customTokenParam')} className="w-full sm:w-[280px]"> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="max_tokens">max_tokens</SelectItem> <SelectItem value="max_completion_tokens">max_completion_tokens</SelectItem> </SelectContent> </Select> </Field> <label className="flex items-start gap-3 text-label text-ink-soft"> <Switch size="sm" checked={echoReasoning} onCheckedChange= - src/components/DashShell.tsx (6867 bytes)
import * as React from 'react' import { authClient } from '../lib/auth' import { navigate } from '../App' import { posthog } from '../lib/posthog' import { offersUpgrade, useMe } from '../lib/me' import { isDesktopShell } from '../lib/shell' import { isTheme, useTheme } from '../lib/theme' import { useT } from '../lib/i18n' import { colorFor } from '../../shared/types' import { avatarUrl } from '../../shared/avatar' import { themeOptions } from './ThemePicker' import { Badge } from './ui/badge' import { Avatar } from './ui/avatar' import { IconButton } from './ui/icon-button' import { Pressable } from './ui/pressable' import { PersonRow } from './ui/list' import { DropdownMenu, DropdownMenuCaption, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from './ui/dropdown-menu' import { DesktopIcon, ExportIcon, GearIcon, HelpIcon, LogOutIcon, MailIcon, RocketIcon, ShieldIcon } from './ui/icons' import { openUpgrade } from '../lib/upgrade' import { PRIORITY_SUPPORT } from '../../shared/billing' import { DOWNLOAD_URL, WEBSITE_URL } from '../lib/siteLinks' /** The account menu the signed-in shell repeats on every page: in the rail * and in the settings header. It lives here so they cannot drift apart. */ export function AccountMenu({ face = false, side, align, }: { /** the round presence face the editor's rail wears, instead of the ink square */ face?: boolean side?: React.ComponentProps<typeof DropdownMenuContent>['side'] align?: React.ComponentProps<typeof DropdownMenuContent>['align'] } = {}) { const { data: session } = authClient.useSession() const me = useMe(session?.user.id) const { theme, setTheme } = useTheme() const t = useT() const name = session?.user.name ?? '' const image = avatarUrl(session?.user.image) return ( <DropdownMenu> <DropdownMenuTrigger asChild> {face ? ( <IconButton aria-label={t('shell.account')} title={name} shape="round" className="size-7 hover:bg-transparent focus-visible:ring-ink-faint data-[state=open]:ring-2 data-[state=open]:ring-ink-faint" > <Avatar name={name} image={image} color={colorFor(session?.user.id ?? name)} size={28} className="shadow-none" /> </IconButton> ) : ( <Pressable aria-label={t('shell.account')} title={name} layout="inline" focus="ring" className="flex-none rounded-full" > <Avatar tone="ink" name={name} image={image} size={34} /> </Pressable> )} </DropdownMenuTrigger> <DropdownMenuContent side={side} align={align} width="lg"> <DropdownMenuLabel className="px-2.5 pb-2.5 pt-2"> <PersonRow avatar={ <Avatar name={name} image={image} color={colorFor(session?.user.id ?? name)} size={32} className="shadow-none" /> } name={name} detail={me?.email ?? session?.user.email} /> </DropdownMenuLabel> {/* the plan is a workspace thing; this line says which side of it the account is on — a member of a live paid workspace is on Pro */} <div className="mx-2.5 mb-2 flex items-center gap-[7px] text-caption text-ink-soft"> {me?.plan === 'team' ? ( <> <Badge tone="accent">pro</Badge> {t('plans.proPlan')} </> ) : ( <> <Badge>free</Badge> {t('plans.freePlan')} </> )} </div> {offersUpgrade(me) && ( <DropdownMenuItem onSelect={() => openUpgrade({ source: 'account-menu' })}> <RocketIcon size="rail" /> {t('plans.upgradeToPro')} </DropdownMenuItem> )} <DropdownMenuSeparator /> <DropdownMenuItem onSelect={() => navigate('/settings')}> <GearIcon size="rail" /> {t('shell.settings')} </DropdownMenuItem> {me?.admin && ( <DropdownMenuItem onSelect={() => navigate('/admin')}> <ShieldIcon size="rail" /> {t('shell.admin')} </DropdownMenuItem> )} {me?.billing && me.plan === 'team' && ( <DropdownMenuItem asChild> <a href={PRIORITY_SUPPORT}> <MailIcon size="rail" /> {t('plans.prioritySupport')} </a> </DropdownMenuItem> )} <DropdownMenuItem asChild> <a href="/docs" target="_blank" rel="noopener noreferrer"> <HelpIcon size="rail" /> {t('shell.helpDocs')} </a> </DropdownMenuItem> {/* new tabs, which the desktop shell hands to the system browser (initDesktopShell); the desktop app has nothing to download */} {!isDesktopShell() && ( <DropdownMenuItem asChild> <a href={DOWNLOAD_URL} target="_blank" rel="noopener noreferrer"> <DesktopIcon size="rail" /> {t('shell.desktopApp')} </a> </DropdownMenuItem> )} <DropdownMenuItem asChild> <a href={WEBSITE_URL} target="_blank" rel="noopener noreferrer"> <ExportIcon size="rail" /> {t('shell.website')} </a> </DropdownMenuItem> <DropdownMenuSeparator /> {/* the theme is one click from every page; picking one keeps the menu open so the change can be seen, and judged, before it closes */} <DropdownMenuCaption>{t('shell.appearance')}</DropdownMenuCaption> <DropdownMenuRadioGroup value={theme} onValueChange={(next) => isTheme(next) && setTheme(next)}> {themeOptions.map(({ value, label, Icon }) => ( <DropdownMenuRadioItem key={value} value={value} onSelect={(e) => e.preventDefault()}> <Icon size="rail" /> {t(label)} </DropdownMenuRadioItem> ))} </DropdownMenuRadioGroup> <DropdownMenuSeparator /> <DropdownMenuItem tone="danger" onSelect={() => authClient.signOut().then(() => { posthog.reset() /* the shell has no marketing site: a signed-out reload of / would show the landing page, so it goes to the sign-in form the shell opens on (main.rs) */ if (isDesktopShell()) location.assign('/auth') else location.reload() }) } > <LogOutIcon size="rail" /> {t('shell.logOut')} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) } - src/components/DeleteAccount.tsx (5480 bytes)
import { useState } from 'react' import { authClient } from '../lib/auth' import { posthog } from '../lib/posthog' import { isDesktopShell } from '../lib/shell' import { useT } from '../lib/i18n' import { Button } from './ui/button' import { Input } from './ui/input' import { Field } from './ui/field' import { Note } from './ui/note' import { Modal, ModalActions, ModalLede, ModalTitle } from './ui/modal' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' /** Whether this account can prove itself with a password: one that only ever * signed in through Google / Microsoft / Apple / SSO has none, and better-auth * then accepts a fresh session instead. Throws rather than guessing, as the * iOS app does: a lookup that failed must not drop the password. */ async function accountHasPassword(): Promise<boolean> { const { data, error } = await authClient.listAccounts() if (error) throw new Error(error.message) return data.some((account) => account.providerId === 'credential') } /** After the account is gone the session is too: leave for the signed-out * page the way logging out does (the desktop shell opens on /auth). */ function leaveDeletedAccount() { posthog.reset() location.assign(isDesktopShell() ? '/auth' : '/') } /** The last card of Settings → Your account: deleting the account through * better-auth's `POST /api/auth/delete-user`, the same call the iOS app * makes. The server's `beforeDelete` hook (`server/accountDeletion.ts`) * removes canvases only this person could reach first. */ export function DeleteAccountCard() { const t = useT() const [checking, setChecking] = useState(false) const [error, setError] = useState<string | null>(null) /* null while the dialog is closed; otherwise whether it asks for a password */ const [asking, setAsking] = useState<{ password: boolean } | null>(null) async function begin() { setChecking(true) setError(null) try { setAsking({ password: await accountHasPassword() }) } catch (e) { setError(e instanceof Error && e.message ? e.message : t('account.deleteCheckFailed')) } finally { setChecking(false) } } return ( <SettingsCard> <CardHeader> <CardTitle>{t('account.deleteTitle')}</CardTitle> <CardDescription>{t('account.deleteDescription')}</CardDescription> </CardHeader> <CardRow label={t('account.deleteRow')} action={ <Button size="sm" variant="danger" disabled={checking} onClick={() => void begin()}> {t('account.deleteButton')} </Button> } > {error ? <Note tone="error">{error}</Note> : <Note>{t('account.deleteHint')}</Note>} </CardRow> {asking && <DeleteAccountDialog askPassword={asking.password} onClose={() => setAsking(null)} />} </SettingsCard> ) } function DeleteAccountDialog({ askPassword, onClose }: { askPassword: boolean; onClose: () => void }) { const t = useT() const [password, setPassword] = useState('') const [deleting, setDeleting] = useState(false) const [error, setError] = useState<string | null>(null) async function confirm() { setDeleting(true) setError(null) /* a request that never got an answer (offline, a dropped connection) rejects rather than returning an error; it must not leave the dialog stuck on Deleting… with every way out disabled */ const { error: failed } = await authClient .deleteUser(askPassword ? { password } : {}) .catch(() => ({ error: { status: 0, message: '' } })) if (failed) { setDeleting(false) /* without a password better-auth wants a session younger than its freshAge (a day); an older one is refused with a 400 */ if (!askPassword && failed.status === 400) return setError(t('account.deleteNeedsFreshSession')) return setError(failed.message || t('account.deleteFailed')) } posthog.capture('account_deleted') leaveDeletedAccount() } return ( <Modal size="sm" onClose={() => !deleting && onClose()}> <ModalTitle>{t('account.deleteDialogTitle')}</ModalTitle> <ModalLede>{t('account.deleteDialogLede')}</ModalLede> <form onSubmit={(event) => { event.preventDefault() void confirm() }} > {askPassword && ( <Field className="mt-5" label={t('account.deletePasswordLabel')} labelVariant="form" htmlFor="delete-password" > <Input id="delete-password" variant="well" type="password" autoComplete="current-password" autoFocus value={password} onChange={(e) => { setPassword(e.target.value) setError(null) }} /> </Field> )} {error && ( <Note tone="error" className="mt-3 block"> {error} </Note> )} <ModalActions> <Button type="button" variant="ghost" disabled={deleting} onClick={onClose}> {t('common.cancel')} </Button> <Button type="submit" variant="danger-solid" disabled={deleting || (askPassword && !password)}> {deleting ? t('account.deleting') : t('account.deleteConfirm')} </Button> </ModalActions> </form> </Modal> ) } - src/components/DesktopTabs.tsx (14863 bytes)
import { useEffect, useRef } from 'react' import type { PointerEvent as ReactPointerEvent, ReactNode } from 'react' import { api } from '../lib/api' import { posthog } from '../lib/posthog' import { navigate } from '../App' import { Logo } from './Logo' import { XIcon } from './ui/icons' import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger, } from './ui/context-menu' import { cn } from '@/lib/utils' import { TAB_SHORTCUTS, closeAllTabs, closeOtherTabs, closeTab, ensureTab, moveTab, openCanvasTab, openExternal, useTabs, } from '../lib/desktop' import { chordHint } from '../lib/actions/chords' import { hasInsetTrafficLights, isDesktopShell } from '../lib/shell' import { useWindowFrame } from '../lib/windowFrame' import { WindowControls } from './WindowControls' import type { CanvasTab } from '../lib/desktop' import { useT } from '../lib/i18n' /** * Figma-style tab strip, desktop shell only. It sits where the title bar * would be (the shell's title bar is an overlay: just the traffic lights, * floating over this strip) — so the strip doubles as the window's drag * handle via data-tauri-drag-region, which Tauri only honours on the exact * element carrying the attribute, leaving the tabs themselves clickable. * On Windows the page replaces the native frame too (src/lib/windowFrame.ts) * and the strip ends in the caption buttons. */ export function DesktopTabs({ path }: { path: string }) { const t = useT() const tabs = useTabs((s) => s.tabs) const activeId = path.match(/^\/c\/([^/]+)/)?.[1] ?? null const listRef = useRef<HTMLDivElement>(null) const cancelDrag = useRef<(() => void) | null>(null) /* deep links and back/forward can land on a canvas the strip never opened */ useEffect(() => { if (activeId) ensureTab(activeId) }, [activeId]) /* an unmount mid-drag drops the document listeners the gesture added */ useEffect(() => () => cancelDrag.current?.(), []) if (!isDesktopShell()) return null async function newCanvas() { const canvas = await api.createCanvas('Untitled canvas') posthog.capture('canvas_created') openCanvasTab(canvas.id, canvas.name) } /* Reordering is a pointer gesture, not HTML5 drag-and-drop: the shell's webview drag-drop handler swallows those events on Linux and Windows. The DOM never reorders mid-gesture — siblings slide by transform to open the gap and the drop commits moveTab — so a cancel has nothing to undo. Listeners live on the document because the drag only starts (and captures the pointer) after a 4px move, by which point the pointer may already be off the tab. */ function onTabPointerDown(e: ReactPointerEvent<HTMLDivElement>, tab: CanvasTab, index: number) { /* only the primary button drags: middle click stays Close, right click stays the context menu, and a touch keeps scrolling the strip */ if (e.button !== 0 || e.pointerType === 'touch') return /* the close button is the tab's only button — a press there is its own gesture */ if ((e.target as Element).closest('button')) return if (!listRef.current) return const list = listRef.current cancelDrag.current?.() const el = e.currentTarget const d = { id: tab.id, from: index, target: index, startX: e.clientX, x: e.clientX, startScroll: 0, pointerId: e.pointerId, width: 0, min: 0, max: 0, mids: [] as number[], dragging: false, } /* Drop geometry is worked in content coordinates (clientX + scrollLeft) so a strip scroll mid-drag shifts nothing: the midpoints and the clamp bounds were frozen at drag start and stay valid */ function place(clientX: number) { const cx = clientX + list.scrollLeft const dx = Math.min(Math.max(cx - (d.startX + d.startScroll), d.min), d.max) el.style.transform = `translateX(${dx}px)` /* the drop slot counts the sibling midpoints the pointer has passed */ d.target = d.mids.filter((m) => cx > m).length for (const [i, child] of Array.from(list.children).entries()) { if (i === d.from) continue const shift = d.target > d.from && i > d.from && i <= d.target ? -d.width : d.target < d.from && i >= d.target && i < d.from ? d.width : 0 ;(child as HTMLElement).style.transform = shift ? `translateX(${shift}px)` : '' } } function scrolled() { place(d.x) } function move(ev: PointerEvent) { d.x = ev.clientX if (!d.dragging) { /* inside the threshold the gesture is still a candidate click */ if (Math.abs(ev.clientX - d.startX) < 4) return el.setPointerCapture(ev.pointerId) const rect = el.getBoundingClientRect() const rects = Array.from(list.children, (c) => c.getBoundingClientRect()) const first = rects[0] const last = rects[rects.length - 1] if (!first || !last) return d.startScroll = list.scrollLeft d.width = rect.width d.min = first.left - rect.left d.max = last.right - rect.right d.mids = rects.filter((_, i) => i !== d.from).map((r) => r.left + r.width / 2 + d.startScroll) d.dragging = true el.style.zIndex = '1' for (const [i, child] of Array.from(list.children).entries()) if (i !== d.from) (child as HTMLElement).style.transition = 'transform 150ms ease-out' list.addEventListener('scroll', scrolled) } place(d.x) } function finish(commit: boolean) { document.removeEventListener('pointermove', move) document.removeEventListener('pointerup', up) document.removeEventListener('pointercancel', cancel) document.removeEventListener('keydown', key, true) list.removeEventListener('scroll', scrolled) unsub() cancelDrag.current = null for (const child of Array.from(list.children) as HTMLElement[]) { child.style.transition = '' child.style.transform = '' child.style.zIndex = '' } if (!d.dragging) return if (el.hasPointerCapture(d.pointerId)) el.releasePointerCapture(d.pointerId) if (commit) moveTab(d.id, d.target) /* the click that lands after a drop — or after a cancelled drag's release — must not navigate; it can be over a different tab by then. A committed drop's click shares its pointerup's task; a cancelled one arrives with the press's own later release, and if that release produced no click (outside the window) the next press or release retires the eater rather than letting it swallow a real click */ const eat = (ev: MouseEvent) => { ev.preventDefault() ev.stopPropagation() } const disarm = () => { /* the pointerup's click companion is dispatched in the same task, ahead of this timer, so the eater still sees it */ setTimeout(() => document.removeEventListener('click', eat, true), 0) } const disarmNow = () => document.removeEventListener('click', eat, true) document.addEventListener('click', eat, { capture: true, once: true }) document.addEventListener('pointerup', disarm, { capture: true, once: true }) document.addEventListener('pointerdown', disarmNow, { capture: true, once: true }) } function up() { finish(true) } function cancel() { finish(false) } function key(ev: KeyboardEvent) { if (ev.key !== 'Escape') return /* a drag's Esc is ours: keep it from the canvas, where it would also deselect or stop following. An Esc before the threshold is not ours */ if (d.dragging) { ev.preventDefault() ev.stopPropagation() } finish(false) } document.addEventListener('pointermove', move) document.addEventListener('pointerup', up) document.addEventListener('pointercancel', cancel) document.addEventListener('keydown', key, true) /* the strip can change under the gesture — ⌘W closes a tab, a deep link opens one — and the frozen geometry would land the drop on the wrong slot; a rename keeps the same ids and must not cancel */ const unsub = useTabs.subscribe((s, prev) => { if (s.tabs.length !== prev.tabs.length || s.tabs.some((t, i) => t.id !== prev.tabs[i]?.id)) finish(false) }) cancelDrag.current = cancel } return ( <div data-tauri-drag-region className="fixed inset-x-0 top-0 z-[800] flex h-10 items-end gap-[3px] border-b border-line bg-paper-deep px-2" > {hasInsetTrafficLights() && <div data-tauri-drag-region className="w-[70px] flex-none" />} <button className={cn( 'mb-[4px] grid size-[30px] flex-none place-items-center rounded-lg border-0 bg-transparent text-ink-soft transition-colors hover:bg-ink/[0.06] hover:text-ink', !activeId && 'bg-ink/[0.08] text-ink', )} onClick={() => navigate('/')} title={withShortcut(t('canvas.allCanvases'), 0)} > <Logo className="size-[18px]" /> </button> <div ref={listRef} role="tablist" aria-label={t('canvas.openCanvases')} className="flex min-w-0 items-end overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" > {tabs.map((tab, index) => { const on = tab.id === activeId return ( <ContextMenu key={tab.id}> <ContextMenuTrigger asChild> <div role="tab" aria-selected={on} tabIndex={0} title={withShortcut(tab.name, index + 1)} className={cn( 'group relative -mb-px flex h-[36px] min-w-[110px] max-w-[210px] flex-1 basis-[210px] cursor-default select-none items-center gap-1 rounded-t-[9px] border border-b-0 border-transparent pb-[2px] pl-3 pr-1.5 text-[12.5px] text-ink-soft', on ? 'border-line bg-surface text-ink' : 'transition-colors hover:bg-ink/[0.04]', )} onPointerDown={(e) => onTabPointerDown(e, tab, index)} onClick={() => navigate(`/c/${tab.id}`)} onKeyDown={(e) => e.key === 'Enter' && navigate(`/c/${tab.id}`)} onAuxClick={(e) => e.button === 1 && closeTab(tab.id, path)} > <span className="min-w-0 flex-1 truncate">{tab.name}</span> <button className={cn( 'grid size-[18px] flex-none place-items-center rounded-[5px] border-0 bg-transparent p-0 text-ink-faint opacity-0 transition-opacity hover:bg-ink/[0.08] hover:text-ink group-hover:opacity-100', on && 'opacity-100', )} onClick={(e) => { e.stopPropagation() closeTab(tab.id, path) }} title={t('canvas.closeTab')} > <XIcon className="size-3" /> </button> </div> </ContextMenuTrigger> <TabContextMenu tab={tab} path={path} /> </ContextMenu> ) })} </div> <button className="mb-[4px] grid size-[30px] flex-none place-items-center rounded-lg border-0 bg-transparent text-[16px] leading-none text-ink-soft transition-colors hover:bg-ink/[0.06] hover:text-ink" onClick={newCanvas} title={t('canvas.newCanvas')} > + </button> <WindowControls className="-mr-2 ml-auto" /> </div> ) } /** A tooltip with its ⌘1…⌘9 shortcut, when the slot has one. */ function withShortcut(label: string, slot: number): string { const chord = TAB_SHORTCUTS[slot] return chord ? `${label} (${chordHint(chord)})` : label } /** Right-click menu on a tab: the browser-tab basics (Figma has the same * set). Its content is portalled to the body, so it needs to clear the * strip's own z-index to overlap it. */ function TabContextMenu({ tab, path }: { tab: CanvasTab; path: string }) { const t = useT() const url = `${location.origin}/c/${tab.id}` const on = path === `/c/${tab.id}` return ( <ContextMenuContent className="z-[850]"> <ContextMenuItem onSelect={() => navigator.clipboard.writeText(url)}>{t('canvas.copyLink')}</ContextMenuItem> {/* a full load of that canvas: the tab's own page when it's current, otherwise a hard navigation there (tabs are in-page routes, so there is nothing else to refresh) */} <ContextMenuItem onSelect={() => (on ? location.reload() : location.assign(url))}> {t('canvas.reload')} </ContextMenuItem> {/* the shell's opener IPC hands the URL to the system browser; without it (a plain browser, or a pre-0.1.2 shell) a new tab is the closest thing */} <ContextMenuItem onSelect={() => openExternal(url) || window.open(url, '_blank', 'noopener')}> {t('canvas.openInBrowser')} </ContextMenuItem> <ContextMenuSeparator /> <ContextMenuItem onSelect={() => closeTab(tab.id, path)}>{t('common.close')}</ContextMenuItem> <ContextMenuItem onSelect={() => closeOtherTabs(tab.id, path)}>{t('canvas.closeOtherTabs')}</ContextMenuItem> <ContextMenuItem onSelect={closeAllTabs}>{t('canvas.closeAllTabs')}</ContextMenuItem> </ContextMenuContent> ) } /** Invisible drag handle for shell screens without the tab strip (signed * out): the overlay title bar has no native drag area of its own. On * Windows, once the page owns the frame, it also carries the caption * buttons — these screens would otherwise have no way to close the window. * A fixed-position screen passed as `children` (the guest canvas, whose * toolbar sits 14px from the top) is moved below that bar through the * --app-inset contract (App.tsx) instead of having its toolbar covered. */ export function ShellDragBar({ children }: { children?: ReactNode }) { const customFrame = useWindowFrame((s) => s.custom) if (customFrame) return ( <> <div data-tauri-drag-region className={cn( 'fixed inset-x-0 top-0 z-[950] flex h-8 justify-end', children && 'border-b border-line bg-paper-deep', )} > <WindowControls /> </div> {children && <div className="[--app-inset:32px]">{children}</div>} </> ) return ( <> {hasInsetTrafficLights() && <div data-tauri-drag-region className="fixed inset-x-0 top-0 z-[950] h-6" />} {children} </> ) } - src/components/ElementContextMenu.tsx (15140 bytes)
import { useRef, useState } from 'react' import type { Frame } from '../../shared/types' import { copyElementLink } from '../lib/elementLink' import { copyElementPng, type ElementTarget } from '../lib/frameExport' import { useExportSettings } from '../lib/exportSettings' import { copyPicked, hasElementClip, pasteLayer } from '../lib/elementClipboard' import { writeCanvasClipboard } from '../lib/canvasClipboard' import { hasFrameClip, pasteFrameCentered } from '../lib/frameClipboard' import { deleteLayers, setFramesHidden, setFramesLocked, setLayerHidden, setLayerLocked, standaloneSelector, } from '../lib/layerEdits' import { elementExportTarget, elementHtml, isElementHidden, isElementLocked } from '../lib/layers' import { MOD_KEY } from '../lib/keys' import { canEditOpenCanvas, pickedSelectors, useStore } from '../lib/store' import { useT } from '../lib/i18n' import { changeInstance, componentContextOf, goToMain, restoreDeletedComponent } from '../lib/components' import { isDeleted } from '../../shared/components' import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, } from './ui/context-menu' import { ActionHint, ActionMenuItem, MoveToPageMenu } from './ActionMenuItem' import { MenuHint } from './ui/menu' import { FrameExportModal } from './FrameExportModal' import { trackPngCopy } from '../lib/exportEvents' /** What the live document said about a right-clicked element; a Layers row * has none, its selector comes from the saved HTML itself. */ export interface LiveHit { snippet: string elementId?: string } /** Shared by a layer row and the element under a canvas right-click. */ type ElementMenuProps = { frame: Frame; selector: string | null; hit?: LiveHit; onRename?: () => void } /** The items also ask for the export dialog, which outlives the menu. */ type ElementItemsProps = ElementMenuProps & { onExport: (target: ElementTarget) => void } export function ElementContextMenu({ frame, selector, hit, onRename }: ElementMenuProps) { const renameRequested = useRef(false) const [exporting, setExporting] = useState<ElementTarget | null>(null) return ( <> <ContextMenuContent onCloseAutoFocus={(event) => { // The export dialog owns focus once the menu closes. if (exporting) return event.preventDefault() if (!renameRequested.current) return event.preventDefault() renameRequested.current = false /* off the Layers panel, its row for this layer takes the rename */ if (onRename) onRename() else if (selector) useStore.getState().requestRename(frame.id, selector) }} > <ElementMenuItems frame={frame} selector={selector} hit={hit} onExport={setExporting} onRename={() => { renameRequested.current = true }} /> </ContextMenuContent> {exporting && <FrameExportModal frame={frame} element={exporting} onClose={() => setExporting(null)} />} </> ) } /** Copy the elements, then remove them once the clipboard took the copy. The * menu writes the clipboard asynchronously; a selector is a position in the * frame's HTML, so if the frame changed meanwhile the element stays, rather * than deleting whatever now sits at that position. */ function cutLayers(frame: Frame, selectors: string[]) { writeCanvasClipboard( () => copyPicked(frame, selectors), undefined, () => { const live = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) if (live?.html === frame.html) deleteLayers(live, selectors) }, ) } /** Radix mounts these children only while the menu is open. Closed layer * rows must not parse their frame HTML just to render a dormant menu. * * The order follows Figma's and Paper's layer menus: selection, clipboard, * structure, stacking, transform, visibility. Commands that act on the * selection are registry rows (`ActionMenuItem`); the right-click picked the * layer first, or kept the multi-pick it landed in. */ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementItemsProps) { const hidden = selector ? isElementHidden(frame.html, selector) : null const exists = hidden !== null const locked = !!frame.locked || (selector ? isElementLocked(frame.html, selector) : false) const t = useT() const state = useStore.getState() const component = selector ? componentContextOf(frame.html, selector, state.canvas?.components ?? []) : null const { scale } = useExportSettings() /* a copied standalone shape is a frame on the clipboard: its paste lands a second element on the canvas, as ⌘V does, not a layer in this frame */ const frameClip = hasFrameClip() const readOnly = useStore((s) => !canEditOpenCanvas(s)) /* the multi-pick the right-click landed in, else the clicked layer alone */ const picked = state.selectedElement?.frameId === frame.id ? pickedSelectors(state) : [] const selectors = selector && picked.includes(selector) ? picked : selector ? [selector] : [] /* the Hide / Lock labels say what the toggle does to the whole pick; one layer reuses what was read above, so a menu parses its frame no more */ const others = selectors.filter((s) => s !== selector) const allPickedHidden = !!hidden && others.every((s) => isElementHidden(frame.html, s)) const ownLock = selector ? isElementLocked(frame.html, selector, true) : false const allPickedLocked = ownLock && others.every((s) => isElementLocked(frame.html, s, true)) /* a standalone shape is its frame: it moves between pages, stacks on the page and is selected with the other shapes the selection holds */ const standalone = !!selector && standaloneSelector(frame) === selector const shapeFrames = standalone ? (state.canvas?.frames.filter((f) => f.id === frame.id || state.selectedIds.includes(f.id)) ?? [frame]) : [] return ( <> <ContextMenuItem disabled={!exists} onSelect={() => { if (selectors.length) writeCanvasClipboard(() => copyPicked(frame, selectors)) }} > {t('common.copy')} <MenuHint>{MOD_KEY}C</MenuHint> </ContextMenuItem> {!readOnly && ( <ContextMenuItem disabled={!exists || locked} onSelect={() => { if (selectors.length) cutLayers(frame, selectors) }} > {t('common.cut')} <MenuHint>{MOD_KEY}X</MenuHint> </ContextMenuItem> )} {selector && exists && ( <ContextMenuSub> <ContextMenuSubTrigger>{t('stage.copyPasteAs')}</ContextMenuSubTrigger> <ContextMenuSubContent> <ContextMenuItem onSelect={() => void copyElementLink(frame, { selector, ...hit })}> {t('stage.copyLinkToElement')} <ActionHint id="copy-link" /> </ContextMenuItem> <ContextMenuItem onSelect={() => { const html = elementHtml(frame.html, selector) if (html) navigator.clipboard.writeText(html).catch(console.error) }} > {t('stage.copyHtml')} </ContextMenuItem> <ContextMenuItem onSelect={() => navigator.clipboard.writeText(selector).catch(console.error)}> {t('stage.copySelector')} </ContextMenuItem> <ContextMenuItem onSelect={() => { trackPngCopy('element', 'element_menu') void copyElementPng(frame, elementExportTarget(frame, selector), scale) }} > {t('stage.copyAsPng')} <ActionHint id="copy-as-png" /> </ContextMenuItem> <ContextMenuSeparator /> <ActionMenuItem id="copy-properties" /> <ActionMenuItem id="paste-properties" disabled={locked} /> </ContextMenuSubContent> </ContextMenuSub> )} {!readOnly && ( <> <ContextMenuItem disabled={frameClip ? false : locked || !hasElementClip() || (!!selector && !exists)} onSelect={() => { if (frameClip) pasteFrameCentered(frame.canvasId) else pasteLayer(frame, selector) }} > {t('stage.paste')} <MenuHint>{MOD_KEY}V</MenuHint> </ContextMenuItem> {selector && exists && ( <> <ActionMenuItem id="paste-replace" disabled={locked} /> <ActionMenuItem id="duplicate" disabled={locked} /> </> )} </> )} {selector && exists && !readOnly && ( <> <ContextMenuSeparator /> {onRename && ( <ContextMenuItem disabled={locked} onSelect={onRename}> {t('panels.layersRename')} </ContextMenuItem> )} <ActionMenuItem id="group" disabled={locked} /> <ActionMenuItem id="ungroup" disabled={locked} /> {!standalone && <ActionMenuItem id="auto-layout" disabled={locked} />} {!component && !standalone && ( <ActionMenuItem id="create-component" label={t('components.create')} disabled={locked} /> )} {component && !isDeleted(component.def) && ( <ContextMenuItem onSelect={() => goToMain(component.def)}> {t('components.goToMainComponent')} </ContextMenuItem> )} {component && isDeleted(component.def) && ( <ContextMenuItem onSelect={() => void restoreDeletedComponent(component.def)}> {t('components.restoreComponent')} </ContextMenuItem> )} {component?.kind === 'instance' && ( <> {component.part && component.overriddenParts.includes(component.part) && ( <ContextMenuItem disabled={locked} onSelect={() => void changeInstance(frame, { instanceId: component.instanceId, reset: [component.part!] }) } > {t('components.resetElement')} </ContextMenuItem> )} <ContextMenuItem disabled={locked || isDeleted(component.def)} onSelect={() => void changeInstance(frame, { instanceId: component.instanceId, reset: true })} > {t('components.resetOverrides')} </ContextMenuItem> <ContextMenuItem disabled={locked} onSelect={() => void changeInstance(frame, { instanceId: component.instanceId, detach: true })} > {t('components.detachInstance')} </ContextMenuItem> </> )} <ContextMenuSeparator /> {standalone && <MoveToPageMenu frames={shapeFrames} />} <ActionMenuItem id="bring-to-front" disabled={locked} /> <ActionMenuItem id="bring-forward" disabled={locked} /> <ActionMenuItem id="send-backward" disabled={locked} /> <ActionMenuItem id="send-to-back" disabled={locked} /> <ContextMenuSeparator /> <ActionMenuItem id="flip-horizontal" disabled={locked} /> <ActionMenuItem id="flip-vertical" disabled={locked} /> <ContextMenuSeparator /> {standalone ? ( <ShapeVisibilityItems frames={shapeFrames} /> ) : ( <> {/* the label says what the toggle does to the whole pick: it shows (unlocks) only once every picked layer is hidden (locked) */} <ActionMenuItem id="toggle-hidden" label={allPickedHidden ? t('stage.show') : t('stage.hide')} disabled={!!frame.locked} /> <ActionMenuItem id="toggle-locked" label={allPickedLocked ? t('stage.unlock') : t('stage.lock')} disabled={!!frame.locked} /> </> )} </> )} {selector && exists && ( <> <ContextMenuSeparator /> <ContextMenuItem onSelect={() => onExport(elementExportTarget(frame, selector))}> {t('stage.exportEllipsis')} </ContextMenuItem> </> )} {selector && exists && !readOnly && ( <> <ContextMenuSeparator /> <ActionMenuItem id="delete" label={t('stage.deleteElement')} tone="danger" disabled={locked} /> </> )} {/* an element a script made is not in the saved HTML, but one wearing an id in the live document can still be linked */} {selector && !exists && hit?.elementId && ( <> <ContextMenuSeparator /> <ContextMenuItem onSelect={() => void copyElementLink(frame, { selector, ...hit })}> {t('stage.copyLinkToElement')} </ContextMenuItem> </> )} </> ) } /** Hide and Lock for shapes on the canvas, as their Layers rows' eye and lock * work: a shape is hidden (locked) by its frame or its own attribute, the * menu shows (unlocks) once every shape is, clearing both, and otherwise * hides (locks) the frames. A locked shape can be unlocked from here. */ function ShapeVisibilityItems({ frames }: { frames: Frame[] }) { const t = useT() const own = (frame: Frame, read: (html: string, selector: string) => boolean | null) => { const selector = standaloneSelector(frame) return !!selector && !!read(frame.html, selector) } const ownHidden = (f: Frame) => own(f, isElementHidden) const ownLocked = (f: Frame) => own(f, (html, s) => isElementLocked(html, s, true)) const allHidden = frames.every((f) => f.hidden || ownHidden(f)) const allLocked = frames.every((f) => f.locked || ownLocked(f)) return ( <> <ContextMenuItem disabled={frames.some((f) => f.locked)} onSelect={() => { if (!allHidden) return setFramesHidden(frames, true) for (const f of frames) { const selector = standaloneSelector(f) if (selector && ownHidden(f)) setLayerHidden(f, selector, false) } setFramesHidden( frames.filter((f) => f.hidden), false, ) }} > {allHidden ? t('stage.show') : t('stage.hide')} <ActionHint id="toggle-hidden" /> </ContextMenuItem> <ContextMenuItem onSelect={() => { if (!allLocked) return setFramesLocked(frames, true) for (const f of frames) { const selector = standaloneSelector(f) if (selector && ownLocked(f)) setLayerLocked(f, selector, false) } setFramesLocked( frames.filter((f) => f.locked), false, ) }} > - src/components/ElementMove.tsx (32697 bytes)
import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react' import { frameDesignPoint, frameWorldPoint, rotateVector, turnedDropRect } from '../../shared/frameRotation' import { createPortal } from 'react-dom' import type { Frame } from '../../shared/types' import { isCanvasElement } from '../lib/drawing' import { standaloneSelector } from '../lib/layerEdits' import { elementPath } from '../lib/layers' import { drawingDropFrame, drawingPreview, movableDrawing, moveDrawing, placeDrawing, type DrawingHit, type DrawingRect, } from '../lib/drawingMove' import { editElementGeometry, elementMoveTarget, frameShows, noteFrameDocument, requestFrame, styleGesture, type ElementInfo, type LayoutDrop, } from '../lib/frameBridge' import { gesture } from '../lib/gesture' import { iframeBleed } from '../lib/frameBleed' import { FRAME_DOCUMENTS_TAKE_ZOOM_AS_DENSITY, counterZoom } from '../lib/layoutZoom' import { visibleGuides } from '../lib/guides' import { snapFrame } from '../lib/snap' import { useT } from '../lib/i18n' import { copyLayerOut, dropLayer, dropLayerCopy, layerCopyDocument, styledCopy, type WorldRect, } from '../lib/layerEdits' import { currentPageCanvas } from '../lib/pages' import { pickedSelectors, useStore } from '../lib/store' interface Preview { rect: DrawingRect html: string target: Frame | null world: Element /** the gesture drawing it, so a finished drag cannot clear the next one's */ owner: object /** the drawing in its frame, hidden once this copy has painted */ selector: string } type Press = ReactPointerEvent<HTMLDivElement> type Fallback = (press: Press, move: PointerEvent | null, released: boolean) => void export interface ElementMoveHit { selector: string tag: string text: string snippet: string rect: DrawingRect sizable?: boolean locked?: boolean /** the parent box and siblings, in design px, for snapping */ snapRects?: DrawingRect[] } /** Hit testing happens inside the iframe. Buffer pointer events while it * answers so even a fast drag follows the visible element under the press. */ export function useElementMove(frame: Frame, layoutZoom: number) { const t = useT() const [preview, setPreview] = useState<Preview | null>(null) /* the gesture under way: its element's outline, grips and size badge stay hidden until it lands, so only the element itself shows */ const [movingOwner, setMovingOwner] = useState<object | null>(null) const [layoutDrop, setLayoutDrop] = useState<{ drop: LayoutDrop world: Element origin: { x: number; y: number } } | null>(null) const cleanup = useRef<(() => void) | null>(null) const hiddenBy = useRef<object | null>(null) const ended = useRef(new WeakSet<object>()) const finishing = useRef<Promise<void>>(Promise.resolve()) const lastClick = useRef<{ selector: string; at: number; x: number; y: number } | null>(null) useEffect(() => () => cleanup.current?.(), []) /* the drawing follows the pointer as a copy over the canvas (it may leave its frame, which clips), so the original is hidden while the copy shows */ function hideDrawing(owner: object, selector: string) { if (ended.current.has(owner)) return hiddenBy.current = owner void requestFrame(frame.id, 'doop:drawing-moving', { selector }) } function endPreview(owner: object) { ended.current.add(owner) setPreview((current) => (current?.owner === owner ? null : current)) setMovingOwner((current) => (current === owner ? null : current)) if (hiddenBy.current !== owner) return hiddenBy.current = null void requestFrame(frame.id, 'doop:drawing-moving', { selector: null }) } function start( e: Press, fallback: Fallback, onDoubleClick: (selector: string) => void, onLayerHit: (hit: ElementMoveHit) => void, ): boolean { const s = useStore.getState() /* ⌥⇧-drag with a layer of this frame picked copies the layer, not the frame: the copy rides the pointer, the original stays (with its id, so its comments and links stay put) */ const duplicating = e.altKey && e.shiftKey && s.selectedElement?.frameId === frame.id if ((e.altKey && !duplicating) || !e.isPrimary || !frame.html) return false if (!e.shiftKey && s.selectedIds.includes(frame.id) && s.selectedIds.length > 1) return false const standalone = isCanvasElement(frame.html) const shell = standalone ? standaloneSelector(frame) : null /* a standalone element is moved like a frame — live under the pointer, snapping to guides, one undo step — by the frame drag, which hands a drop over a frame on to moveDrawing; once a layer inside it is picked (a group entered), a press inside is that level's, as in a frame */ const entered = standalone && s.selectedElement?.frameId === frame.id && !!shell && pickedSelectors(s).some((selector) => selector !== shell) if (standalone && !entered) return false const surface = e.currentTarget const stage = surface.closest('.stage') const world = stage?.querySelector('.world') if (!stage || !world) return false const toWorld = (clientX: number, clientY: number) => { const box = stage.getBoundingClientRect() const vp = useStore.getState().viewport return { x: (clientX - box.left - vp.x) / vp.zoom, y: (clientY - box.top - vp.y) / vp.zoom } } const origin = toWorld(e.clientX, e.clientY) /* where the document sits inside the frame, in design px: the frame's border. Read off the iframe's centre, which a turned frame's bounds still share, rather than its top-left, which a turn moves */ const iframe = surface.querySelector('iframe') const contentOffset = (() => { if (!iframe) return { x: 0, y: 0 } const b = iframe.getBoundingClientRect() const centre = frameDesignPoint(toWorld(b.left + b.width / 2, b.top + b.height / 2), frame) /* the iframe reaches its bleed margin past the document on every side */ const margin = iframeBleed(iframe) return { x: centre.x - iframe.offsetWidth / 2 + margin, y: centre.y - iframe.offsetHeight / 2 + margin } })() /* the document's top-left corner on the canvas, for the layout drop marks */ const contentOrigin = frameWorldPoint(contentOffset, frame) const press: Press = { ...e, currentTarget: surface, preventDefault: () => e.preventDefault(), stopPropagation: () => e.stopPropagation(), } e.preventDefault() e.stopPropagation() cleanup.current?.() const pageId = s.activePageId const owner = {} const pointerId = e.pointerId const startX = e.clientX const startY = e.clientY let closed = false let moved = false let lastMove: PointerEvent | null = null let released: PointerEvent | null = null let hit: DrawingHit | null = null let bounds: DrawingRect | null = null let rect: DrawingRect | null = null let html = '' let target: Frame | null = null let layer: ElementMoveHit | null = null /* the rest of a multi-pick that holds the layer pressed: they travel with it, as one gesture and one undo step */ let followers: string[] = [] let layerReady: Promise<ElementInfo | null> | null = null let layerPoint: { x: number; y: number; pointerX: number; pointerY: number } | null = null let layerWork: Promise<void> = Promise.resolve() let inFlight = false let picked = false /* an ⌥⇧ drag's copy, once it is in the live document: the gesture moves it in place of the layer pressed */ let copy: { selector: string; html: string } | null = null const movingSelector = () => copy?.selector ?? layer!.selector /* the copy's document beside the original, worked out once */ const planCopy = () => { if (copy || !layer) return copy const duplicated = styledCopy(frame.html, layer.selector) if (duplicated) copy = duplicated return copy } /* an ⌥⇧ copy dragged past its frame's edge rides over the canvas as a floating preview (the frame would clip it) and lands where it is let go: in the frame under the pointer, else on the canvas */ let dropOut: { rect: WorldRect; into: Frame | null } | null = null /* the layer's box on the canvas, around the spot its centre has in its (maybe turned) frame and unturned: a copy leaving the frame leaves the frame's turn behind */ let canvasBox: DrawingRect | null = null const outsideBox = (hitLayer: ElementMoveHit): DrawingRect => { if (canvasBox) return canvasBox const { width, height } = hitLayer.rect const centre = frameWorldPoint( { x: contentOffset.x + hitLayer.rect.x + width / 2, y: contentOffset.y + hitLayer.rect.y + height / 2 }, frame, ) canvasBox = { x: centre.x - width / 2, y: centre.y - height / 2, width, height } return canvasBox } let outsidePreview: string | null = null /* the frame and, once the hit test names the element, its parent and siblings, in world px */ let snapTargets: DrawingRect[] = [frame] const toSnapTargets = (rects: DrawingRect[] | undefined) => [ frame, ...(rects ?? []).map((r) => ({ ...r, x: frame.x + r.x, y: frame.y + r.y })), ] function pickHit() { if (picked) return picked = true useStore.getState().select(frame.id) if (layer) { /* a drag of one of several picked layers keeps the pick, the pressed layer now its primary */ if (followers.length) useStore.getState().pickElements(frame.id, [...followers, layer.selector]) else useStore.getState().pickElement({ frameId: frame.id, selector: layer.selector }) onLayerHit(layer) } else if (hit && !standalone) useStore.getState().pickElement({ frameId: frame.id, selector: hit.selector }) } function sourceUnchanged(next = useStore.getState()) { const live = next.canvas?.frames.find((f) => f.id === frame.id) return ( next.canvas?.id === frame.canvasId && next.activePageId === pageId && next.tool === 'select' && !next.panMode && !!live && !live.locked && !live.hidden && live.html === frame.html && live.x === frame.x && live.y === frame.y && live.width === frame.width && live.height === frame.height ) } function updateLayer(info: ElementInfo | null) { const state = useStore.getState() const live = state.canvas?.frames.find((f) => f.id === frame.id) if (info && layer && live?.html === frame.html && state.selectedElement?.selector === movingSelector()) onLayerHit({ ...layer, selector: movingSelector(), rect: info.rect }) } /** Put a copy of the layer right after it in the live document only: the * store keeps the original until the gesture commits, so the copy and * its move land as one undo step, and a cancelled drag leaves nothing */ async function insertCopy(): Promise<string | null> { const planned = planCopy() if (!planned) return null noteFrameDocument(frame.id, null) if (!(await requestFrame(frame.id, 'doop:html', { html: planned.html }))) return null noteFrameDocument(frame.id, planned.html) return planned.selector } /* back over its own frame, the copy shows in the document again */ function leaveOutside() { dropOut = null setPreview((current) => (current?.owner === owner ? null : current)) if (hiddenBy.current !== owner) return hiddenBy.current = null void requestFrame(frame.id, 'doop:drawing-moving', { selector: null }) } /** Show the store's document again after a copy that did not land */ async function removeCopy() { const html = useStore.getState().canvas?.frames.find((f) => f.id === frame.id)?.html if (html === undefined) return noteFrameDocument(frame.id, null) if (await requestFrame(frame.id, 'doop:html', { html })) noteFrameDocument(frame.id, html) } /* where the pressed layer may go: a layout drop (a new place in the flow) is for one layer alone, so several picked layers always move freely, by translation */ const moveTarget = (selector: string, pointerX: number, pointerY: number) => followers.length ? Promise.resolve({ free: true, drop: null }) : elementMoveTarget(frame.id, selector, pointerX, pointerY) function previewLayer() { if (closed || !layer || !layerPoint || inFlight) return if (!layerReady) { const selector = layer.selector layerReady = finishing.current.then(async () => { if (!sourceUnchanged()) return null const moving = duplicating ? await insertCopy() : selector return moving ? styleGesture(frame.id, moving, 'begin', followers) : null }) } inFlight = true const point = layerPoint layerWork = layerReady.then(async (info) => { if (closed) return if (!info) return cancel() const selector = movingSelector() updateLayer(await editElementGeometry(frame.id, selector, { kind: 'move', x: point.x, y: point.y })) if (closed) return const result = await moveTarget(selector, point.pointerX, point.pointerY) if (closed) return if (layerPoint === point) setLayoutDrop(result?.drop && !dropOut ? { drop: result.drop, world: world!, origin: contentOrigin } : null) inFlight = false if (layerPoint !== point) previewLayer() }) } /** `landed` holds the moved copy in place until the save it waits on shows */ function cancel(commit = false, landed?: Promise<void>) { if (closed) return closed = true unsubscribe() window.removeEventListener('pointermove', onMove) window.removeEventListener('pointerup', onUp) window.removeEventListener('pointercancel', onCancel) window.removeEventListener('keydown', onKey, true) window.removeEventListener('blur', onBlur) surface.removeEventListener('lostpointercapture', onLostCapture) if (surface.hasPointerCapture(pointerId)) surface.releasePointerCapture(pointerId) cleanup.current = null if (landed) void landed.then(() => endPreview(owner)) else endPreview(owner) setLayoutDrop(null) useStore.getState().setSnapGuides([]) // Finish after the asynchronous begin, even if a flick or Escape beat it. if (layerReady && layer) { const pressed = layer.selector const final = layerPoint finishing.current = layerReady.then(async (info) => { if (!info) { if (copy) await removeCopy() return } const selector = movingSelector() // Drain a preview before restoring styles or saving. A slow hit - src/components/ElementPanel.tsx (54137 bytes)
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react' import type { Frame } from '../../shared/types' import { useStore } from '../lib/store' import { editElementGeometry, inspectElement, onFrameChange, onTextSelection, styleElement, styleGesture, type ElementInfo, type GeometryEdit, type StylePatch, } from '../lib/frameBridge' import { ancestorsOf, buildLayerTree, elementHtml, findLayer, layerName } from '../lib/layers' import { replaceLayerHtml } from '../lib/layerEdits' import { aspectRatio, borderSummary, colorAlpha, colorWithAlpha, lengthValue, rgbToHex, sizeMode, type SizeMode, } from '../lib/cssValues' import { flexSizeAxis } from '../lib/flexLayout' import { cn } from '@/lib/utils' import { LayerKindIcon } from './LayerKindIcon' import { FlexLayoutControls, PaddingControls } from './FlexLayoutControls' import { Panel, PanelBody, PanelClose, PanelHeader, PanelTab, PanelTabPanel, PanelTabs, PanelTabsRoot, type PanelSurface, } from './ui/panel' import { Button } from './ui/button' import { Textarea } from './ui/textarea' import { ImageFill } from './ImageFill' import { InteractionsPanel } from './InteractionsPanel' import { ComponentSection } from './ComponentSection' import { Tooltip } from './ui/tooltip' import { familyWeights, fontStack, libraryFamilies } from '../../shared/fonts' import { WEB_FONTS, webFontStack } from '../../shared/webFonts' import { useCanvasFonts } from '../lib/customFonts' import { DEVICE_FONTS } from '../lib/deviceFonts' import { aliasOf, effectiveValue, frameTheme, isTokenName, nextTokenName, normalizeTokenName, resolveToken, sortTokens, tokenLabel, type DesignToken, type TokenType, } from '../../shared/designTokens' import { TOKEN_TYPE_LABEL, TokenSwatch } from './TokensPanel' import { api } from '../lib/api' import { Popover, PopoverContent, PopoverTrigger } from './ui/popover' import { BracesIcon, PlusIcon } from './ui/icons' import type { FieldToken } from './ui/property-field' import { AlignCenterIcon, AlignJustifyIcon, AlignLeftIcon, AlignRightIcon, ArrowUpIcon, LinkIcon, UnlinkIcon, AlignStartVerticalIcon, AlignCenterVerticalIcon, AlignEndVerticalIcon, AlignStartHorizontalIcon, AlignCenterHorizontalIcon, AlignEndHorizontalIcon, FlipHorizontal2Icon, FlipVertical2Icon, RotationIcon, TextSizeIcon, StrokeWidthIcon, ColumnGapIcon, RowGapIcon, DropletIcon, RadiusIcon, EyeIcon, EyeClosedIcon, } from './ui/icons' import { Switch } from './ui/switch' import { Segmented, SegmentedItem } from './ui/segmented' import { ColorField, FieldUnit, NumberField, LengthField, PropertyScrubContext, PropertyRow, PropertySection, SelectField, StaticField, } from './ui/property-field' import { useT, type PlainMessageKey } from '../lib/i18n' import { LayerExportSection } from './LayerExportSection' const TAB_KEY = 'doop:element-panel-tab' /* Only refreshes wait for streaming chunks to settle; a new selection is inspected immediately. */ const INSPECT_DELAY_MS = 120 /* how long the previous element's values may stand in (inert) for the next one's before the panel admits it is still reading: most reads land within a frame or two, and a skeleton flashed in between reads as the panel closing and reopening */ const STALE_GRACE_MS = 400 const HTML_SAVE_DELAY_MS = 700 /* the corner radius slider's span; a typed value may go past it */ const RADIUS_SLIDE = [0, 100] as const type Tab = 'design' | 'html' function readTab(): Tab { try { return localStorage.getItem(TAB_KEY) === 'html' ? 'html' : 'design' } catch { return 'design' } } /** The element properties rail — the second panel at the right, opened from * a Layers row. Reads the element's computed styles out of the live frame * and writes edits back as inline styles; the HTML tab edits its markup. */ export function ElementPanel({ frame, selector, surface = 'floating', className, style, }: { frame: Frame selector: string surface?: Exclude<PanelSurface, 'inline'> className?: string /** carries `right`, so it opens beside the Agents panel at the edge */ style?: CSSProperties }) { /* the tab sticks across elements and visits: walking the tree in HTML view must not snap back to Design on every row */ const t = useT() const [tab, setTab] = useState<Tab>(readTab) const prototypeMode = useStore((s) => s.prototypeMode) /* Values belong to their element. A newly selected one keeps the previous values on screen, inert, until its own read lands (loading placeholders only once that takes a while), so old values are never edited and the panel does not blink between two layers. */ const [read, setRead] = useState<{ frameId: string; selector: string; info: ElementInfo } | null>(null) const info = read?.frameId === frame.id && read.selector === selector ? read.info : null const [slowFor, setSlowFor] = useState<string | null>(null) const target = `${frame.id}:${selector}` /* the grace belongs to one visit: once the read lands, a later return to this layer gets its grace again */ if (info && slowFor !== null) setSlowFor(null) const standIn = !info && read && slowFor !== target ? read : null useEffect(() => { if (info) return const timer = window.setTimeout(() => setSlowFor(target), STALE_GRACE_MS) return () => window.clearTimeout(timer) }, [info, target]) const inspected = useRef<{ frameId: string; selector: string; ready: boolean } | null>(null) const tree = useMemo(() => buildLayerTree(frame.html), [frame.html]) const node = useMemo(() => findLayer(tree, selector), [tree, selector]) const parentNode = useMemo(() => ancestorsOf(tree, selector)?.at(-1) ?? null, [tree, selector]) const hasText = useMemo(() => { if (info) return info.hasText try { const element = new DOMParser().parseFromString(frame.html, 'text/html').querySelector(selector) return Array.from(element?.childNodes ?? []).some( (child) => child.nodeType === Node.TEXT_NODE && /\S/.test(child.textContent ?? ''), ) } catch { return false } }, [frame.html, selector, info]) /* re-read after every html change — remote edits and our own saves alike — and when the runtime finishes rendering or loading fonts */ useEffect(() => { let live = true let timer: number | null = null let request = 0 if (inspected.current?.frameId !== frame.id || inspected.current.selector !== selector) { inspected.current = { frameId: frame.id, selector, ready: false } } const read = () => { if (timer) window.clearTimeout(timer) const currentRequest = ++request inspectElement(frame.id, selector) .then((next) => { if (!live || currentRequest !== request || !next) return inspected.current = { frameId: frame.id, selector, ready: true } setRead({ frameId: frame.id, selector, info: next }) }) .catch(console.error) } /* a burst of render and font-load events shares one delayed read */ const refresh = () => { if (timer) window.clearTimeout(timer) timer = window.setTimeout(read, INSPECT_DELAY_MS) } if (inspected.current.ready) refresh() else read() const off = onFrameChange(frame.id, refresh) const offSelection = onTextSelection(frame.id, refresh) return () => { live = false off() offSelection() if (timer) window.clearTimeout(timer) } }, [frame.id, frame.html, selector]) function updateRead(request: Promise<ElementInfo | null>) { request .then((next) => { if (next) setRead((r) => r && (r.frameId !== frame.id || r.selector !== selector) ? r : { frameId: frame.id, selector, info: next }, ) }) .catch(console.error) } function apply(styles: StylePatch) { if (info) updateRead(styleElement(frame.id, selector, styles)) } function editGeometry(edit: GeometryEdit) { if (info) updateRead(editElementGeometry(frame.id, selector, edit)) } function scrub(phase: 'begin' | 'commit' | 'cancel') { updateRead(styleGesture(frame.id, selector, phase)) } function selectTab(next: Tab) { setTab(next) try { localStorage.setItem(TAB_KEY, next) } catch { /* private mode: the choice just doesn't stick */ } } /* closing the panel is only that: the element stays picked, its outline and grips in place, and a second click on it opens the panel again */ function close() { useStore.getState().setElementPanelOpen(false) } const name = node ? layerName(node) : selector.split(' > ').at(-1) const parentLabel = parentNode ? `${parentNode.tag}${parentNode.detail}` : 'body' return ( <Panel surface={surface} className={cn( 'w-[244px]', surface === 'floating' ? 'top-2.5 max-h-[calc(100%-24px)] transition-[right] duration-150' : 'border-l', className, )} style={style} > <PanelTabsRoot value={prototypeMode ? 'prototype' : tab} onValueChange={(v) => { /* the Prototype tab is Prototype mode: picking it (or the tool rail's mode switch) turns the canvas connectors on as well */ useStore.getState().setPrototypeMode(v === 'prototype') if (v !== 'prototype') selectTab(v === 'html' ? 'html' : 'design') }} > <PanelHeader className="pl-2"> <PanelTabs> <PanelTab value="design">{t('inspector.tabDesign')}</PanelTab> <PanelTab value="html">{t('inspector.tabHtml')}</PanelTab> <PanelTab value="prototype">{t('inspector.tabPrototype')}</PanelTab> </PanelTabs> <PanelClose onClick={close} /> </PanelHeader> <div className="flex flex-none items-center gap-[7px] border-b border-line-soft px-3 py-2.5"> <span className="grid size-5 flex-none place-items-center text-ink-faint"> <LayerKindIcon kind={node?.kind ?? 'box'} /> </span> <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-ink"> {name} <small className="ml-[5px] text-[11px] font-normal text-ink-faint"> {t('inspector.inParent', { parent: parentLabel })} </small> </span> {parentNode && ( <Tooltip label={t('inspector.selectParent')} side="bottom" align="end"> <Button variant="bare" size="icon-sm" className="size-[22px] text-ink-faint hover:bg-paper-deep hover:text-ink" aria-label={t('inspector.selectParent')} onClick={() => useStore.getState().setSelectedElement({ frameId: frame.id, selector: parentNode.selector }) } > <ArrowUpIcon className="size-3.5" /> </Button> </Tooltip> )} </div> <PanelTabPanel value="design"> <PanelBody> <ComponentSection frame={frame} selector={selector} /> {info ? ( <PropertyScrubContext.Provider value={{ onStart: () => scrub('begin'), onEnd: (cancel) => scrub(cancel ? 'cancel' : 'commit') }} > <DesignTab key={`${frame.id}:${selector}`} frame={frame} selector={selector} info={info} apply={apply} editGeometry={editGeometry} /> </PropertyScrubContext.Provider> ) : standIn ? ( /* React 18 does not know `inert`, so it goes on by hand */ <div aria-busy="true" ref={(el) => el?.setAttribute('inert', '')}> <DesignTab key={`${standIn.frameId}:${standIn.selector}`} frame={frame} selector={standIn.selector} info={standIn.info} apply={() => {}} editGeometry={() => {}} /> </div> ) : ( <Waiting hasText={hasText} /> )} <LayerExportSection frame={frame} target={{ selector, name: name ?? 'element' }} /> </PanelBody> </PanelTabPanel> <PanelTabPanel value="html"> <HtmlTab key={`${frame.id}:${selector}`} frame={frame} selector={selector} /> </PanelTabPanel> <PanelTabPanel value="prototype"> <PanelBody> <InteractionsPanel frame={frame} selector={selector} /> </PanelBody> </PanelTabPanel> </PanelTabsRoot> </Panel> ) } const LOADING_SECTIONS: { title: PlainMessageKey; rows: PlainMessageKey[] }[] = [ { title: 'inspector.sectionPosition', rows: ['inspector.rowType', 'inspector.rowOrder'] }, { title: 'inspector.sectionLayout', rows: ['inspector.rowMinWidth', 'inspector.rowDisplay', 'inspector.rowGap'] }, { title: 'inspector.sectionAppearance', rows: ['inspector.rowOpacity', 'inspector.rowRadius'] }, { title: 'inspector.sectionFill', rows: ['inspector.rowColor'] }, { title: 'inspector.sectionStroke', rows: ['inspector.rowColor', 'inspector.rowWidth'] }, { title: 'inspector.sectionText', rows: ['inspector.rowFont', 'inspector.rowSize', 'inspector.rowWeight', 'inspector.rowColor', 'inspector.rowAlign'], }, ] function Waiting({ hasText }: { hasText: boolean }) { const t = useT() return ( <div aria-busy="true"> <span role="status" className="sr-only"> {t('inspector.readingElement')} </span> <div aria-hidden="true"> {LOADING_SECTIONS.filter((section) => section.title !== 'inspector.sectionText' || hasText).map((section) => ( <PropertySection key={section.title} title={t(section.title)}> {section.rows.map((label) => ( <PropertyRow key={label} label={t(label)}> <StaticField> <span className="h-1.5 w-1/2 rounded-tag bg-ink/10" /> </StaticField> </PropertyRow> ))} </PropertySection> ))} </div> </div> ) } /* ---- Design tab ---- */ const DISPLAYS: { value: string; label: string }[] = [ { value: 'block', label: 'block' }, { value: 'flex', label: 'flex' }, { value: 'grid', label: 'grid' }, { value: 'inline-block', label: 'inline-block' }, { value: 'inline-flex', label: 'inline-flex' }, { value: 'inline', label: 'inline' }, { value: 'none', label: 'none' }, ] const POSITIONS = ['static', 'relative', 'absolute', 'fixed', 'sticky'] const WEIGHTS = ['100', '200', '300', '400', '500', '600', '700', '800', '900'] const LAYER_ALIGNS = [ { axis: 'x', edge: 'start', label: 'inspector.alignLayerLeft', Icon: AlignStartVerticalIcon }, { axis: 'x', edge: - src/components/ElementResizeHandles.tsx (19783 bytes)
import { useEffect, useRef } from 'react' import type { Frame } from '../../shared/types' import { pointerAngle, rotatedBy } from '../../shared/frameRotation' import { useStore } from '../lib/store' import { gesture } from '../lib/gesture' import { visibleGuides } from '../lib/guides' import { guideDelta } from '../lib/snap' import { flexSizeAxis } from '../lib/flexLayout' import { editElementGeometry, styleElement, styleGesture, type ElementInfo, type StylePatch } from '../lib/frameBridge' import { RESIZE_CORNERS, RESIZE_EDGES, handleAnchor, handleCursor, movesHeight, movesWidth, resizePatch, resizedSize, sizeLabel, type ResizeHandle, type Size, } from '../lib/elementResize' import { derotateDelta, selectionBox, type Box } from '../lib/elementRotate' import { ROTATE_CORNERS, ROTATE_ZONE_INSET_PX, ROTATE_ZONE_PX, rotateCursor, rotateZoneSide } from '../lib/frameRotate' import { useT, type PlainMessageKey } from '../lib/i18n' export interface ElementRect { x: number y: number width: number height: number } /** What the furniture is drawn around: the element's rendered bounds, its * own turn and its box before that turn (the bounds when unturned). */ export interface ElementGeometry { rect: ElementRect rotation: number box: Box } /* on-screen pixels, divided by the Stage's `--zoom` so a grip stays the same size at every zoom, like the outline's hairline */ const GRIP_PX = 6 const EDGE_PX = 6 const GRIP_SIZE = `calc(${GRIP_PX}px / var(--zoom, 1))` const EDGE_SIZE = `calc(${EDGE_PX}px / var(--zoom, 1))` const ROTATE_ZONE_SIZE = `calc(${ROTATE_ZONE_PX}px / var(--zoom, 1))` const ROTATE_ZONE_INSET = `calc(${ROTATE_ZONE_INSET_PX}px / var(--zoom, 1))` /* a corner grip: a white square on a one-pixel ring of the selection blue, the outline's own rgb(60,130,246) (FrameView). Tailwind only emits classes it finds spelled out, so these stay literal strings. */ const CORNER_CLASS = 'pointer-events-auto absolute touch-none bg-white shadow-[0_0_0_calc(1px/var(--zoom,1))_rgb(60,130,246)]' /* the size badge under the element: centred, counter-scaled, never in the way */ const BADGE_CLASS = 'pointer-events-none absolute top-full left-1/2 origin-top whitespace-nowrap rounded-tag bg-[rgb(60,130,246)] px-2 py-1 text-label font-medium text-white tabular-nums' /* a press that travels less than this is a click, not a resize */ const MOVE_THRESHOLD_PX = 2 /** A grip's accessible name: which way it resizes. Shared with the frame's * grips (FrameResizeHandles). */ export function handleLabelKey(handle: ResizeHandle): PlainMessageKey { if (!movesHeight(handle)) return 'stage.resizeWidth' if (!movesWidth(handle)) return 'stage.resizeHeight' return 'stage.resize' } /** The furniture an element's runtime info describes. */ export function geometryOf(info: ElementInfo): ElementGeometry { return { rect: info.rect, rotation: info.geometry.rotation ?? 0, box: info.box ?? info.rect } } /** The selection furniture of an element inside a frame, the way Paper draws * it: a square grip in each corner, grabbable (unmarked) edges, the box's * size on a badge underneath, and just outside each corner a zone that * shows the rotate cursor. A resize drag previews inline `width` / * `height` in the live frame on every move and commits once on release, so * a gesture is one discrete undo step; Shift keeps the aspect ratio. A * rotate drag turns the element about its centre the same way, Shift * snapping to 15°. Esc puts the element back. The furniture turns with the * element, so a turned layer keeps its grips. */ export function ElementResizeHandles({ frame, selector, geometry, sizable = true, onGeometry, onResizing, }: { frame: Frame selector: string /** the element's bounds, turn and box in frame px, where the furniture is drawn */ geometry: ElementGeometry /** whether a width/height applies to the box: the resize grips show only then */ sizable?: boolean /** the geometry after each applied move, so the outline follows the element */ onGeometry: (geometry: ElementGeometry) => void onResizing: (resizing: boolean) => void }) { /* an unmount mid-drag (the frame deselected, the tool switched, the element gone) must not leave window listeners behind, nor an unsaved size in the live document */ const stop = useRef<(() => void) | null>(null) useEffect(() => () => stop.current?.(), []) const t = useT() const furniture = useRef<HTMLDivElement>(null) const { rect, rotation, box } = geometry /* how the element's axes sit on screen: its own turn plus its frame's */ const screenTurn = rotation + (frame.rotation ?? 0) function start(e: React.PointerEvent, handle: ResizeHandle) { if (e.button !== 0) return /* the frame under the grip would otherwise start moving */ e.stopPropagation() e.preventDefault() onResizing(true) /* the drag's baseline: finger position and element size the deltas are measured from. Re-anchored while a pinch owns the finger, so the drag resumes from where the finger is (at the zoom it is now) rather than jumping by the pinch's displacement, the way a frame drag does */ let origin = { x: e.clientX, y: e.clientY } /* the rendered box's far edges in world px, where a drag starts: flow layout grows the box right and down whichever side is pulled */ let edges = { right: frame.x + rect.x + rect.width, bottom: frame.y + rect.y + rect.height } const pointerId = e.pointerId /* the computed size is what the inline value has to express: a content-box element's width excludes its padding, its rect does not */ let base: Size | null = null /* the size the live document shows after the last applied move */ let current: Size | null = null let original: StylePatch | null = null let flexAxis: 'width' | 'height' | null = null /* a scaled element renders larger than its layout box: the pointer's travel is divided by that scale so the box follows the pointer */ let scale = { x: 1, y: 1 } /* the runtime opens a style gesture: every style it gets until the gesture ends is a preview, committed as one discrete save on release or cancelled back to the element's own CSS */ const ready = styleGesture(frame.id, selector, 'begin').then((info) => { if (!info) return false base = { width: info.width ?? info.rect.width, height: info.height ?? info.rect.height } original = Object.fromEntries( ['width', 'height', 'flex-grow', 'flex-shrink', 'flex-basis'].map((key) => [key, info.inline[key] ?? null]), ) flexAxis = flexSizeAxis(info) scale = info.scale return true }) /* where the pointer is now: a flick that outruns the gesture's opening is applied the moment the base size lands */ let last: { x: number; y: number; shift: boolean; alt: boolean } | null = null let latest: StylePatch | null = null let inFlight = false let moved = false let done = false /* Shift was held at some point: letting go must also put the axis the ratio moved back where it was */ let ratioUsed = false function send(patch: StylePatch) { inFlight = true styleElement(frame.id, selector, patch) .then((info: ElementInfo | null) => { inFlight = false if (info) { current = { width: info.width ?? info.rect.width, height: info.height ?? info.rect.height } onGeometry(geometryOf(info)) } /* the move that arrived while this one was out */ if (!done) flush() }) .catch(console.error) } function flush() { if (!latest || inFlight) return const patch = latest latest = null send(patch) } /** the styles the pointer's current place asks for; null before the * gesture has travelled far enough to count as a drag */ function patchFor(pos: { x: number; y: number; shift: boolean; alt: boolean }): StylePatch | null { if (!base || !moved) return null const zoom = useStore.getState().viewport.zoom /* the pointer's travel along the element's own axes; a turned element has no edge lying along a ruler guide, so it does not snap */ const travel = derotateDelta({ dx: (pos.x - origin.x) / zoom, dy: (pos.y - origin.y) / zoom }, screenTurn) const world = screenTurn ? travel : snapToGuides(travel, zoom, pos.alt) const delta = { dx: world.dx / scale.x, dy: world.dy / scale.y } const keepRatio = pos.shift if (keepRatio) ratioUsed = true const patch = resizePatch(handle, resizedSize(handle, base, delta, { keepRatio }), { keepRatio, flexAxis }) if (ratioUsed && !keepRatio && original) { if (!movesWidth(handle)) patch.width = original.width ?? null if (!movesHeight(handle)) patch.height = original.height ?? null if ((flexAxis === 'width' && !movesWidth(handle)) || (flexAxis === 'height' && !movesHeight(handle))) { for (const key of ['flex-grow', 'flex-shrink', 'flex-basis']) patch[key] = original[key] ?? null } } return patch } /** The pointer's travel (world px) adjusted so a growing edge lands on * a ruler guide it comes close to; ⌥ resizes freely. A pull on a west * or north side grows the box the other way, so its sign flips. */ function snapToGuides(world: { dx: number; dy: number }, zoom: number, free: boolean) { if (free) return world const guides = visibleGuides() const sx = handle.includes('w') ? -1 : 1 const sy = handle.includes('n') ? -1 : 1 return { dx: movesWidth(handle) ? world.dx + sx * guideDelta(edges.right + sx * world.dx, guides, 'v', zoom) : world.dx, dy: movesHeight(handle) ? world.dy + sy * guideDelta(edges.bottom + sy * world.dy, guides, 'h', zoom) : world.dy, } } function preview() { if (done || !last) return const patch = patchFor(last) if (!patch) return latest = patch flush() } void ready.then(preview) /* Pointer travel counts even while the runtime is still opening the gesture. */ function trackPointer(ev: PointerEvent) { last = { x: ev.clientX, y: ev.clientY, shift: ev.shiftKey, alt: ev.altKey } if (Math.abs(ev.clientX - origin.x) + Math.abs(ev.clientY - origin.y) >= MOVE_THRESHOLD_PX) moved = true } function onMove(ev: PointerEvent) { if (ev.pointerId !== pointerId) return if (gesture.pinching) { origin = { x: ev.clientX, y: ev.clientY } if (current && base) { edges = { right: edges.right + (current.width - base.width) * scale.x, bottom: edges.bottom + (current.height - base.height) * scale.y, } base = current } last = null return } trackPointer(ev) preview() } function finish() { done = true stop.current = null window.removeEventListener('pointermove', onMove) window.removeEventListener('pointerup', onUp) window.removeEventListener('pointercancel', onUp) window.removeEventListener('keydown', onKey) onResizing(false) } /* messages reach the runtime in order, so the final size sent just before the commit is part of what it files */ function end(phase: 'commit' | 'cancel') { void ready.then((open) => { if (!open) return if (phase === 'commit') { const final = last ? patchFor(last) : null if (final) send(final) } styleGesture(frame.id, selector, phase) .then((info) => { if (info) onGeometry(geometryOf(info)) }) .catch(console.error) }) } function onUp(ev: PointerEvent) { if (ev.pointerId !== pointerId) return if (ev.type === 'pointercancel') { cancel() return } // Release can carry a position/modifier change newer than the last move. if (!gesture.pinching) trackPointer(ev) finish() end(moved ? 'commit' : 'cancel') } /* Esc, or the grips leaving mid-drag: the element goes back to the size it had, nothing is saved */ function cancel() { finish() end('cancel') } function onKey(ev: KeyboardEvent) { if (ev.key !== 'Escape') return ev.stopPropagation() cancel() } window.addEventListener('pointermove', onMove) window.addEventListener('pointerup', onUp) window.addEventListener('pointercancel', onUp) window.addEventListener('keydown', onKey) stop.current = cancel } /** A press on a rotate zone: the element turns about the centre of its * bounds with the pointer, through the same style gesture a resize uses * (one preview per move, one discrete save on release). The runtime's * rotate edit sets the element's whole turn, transform angle included. */ function startRotate(e: React.PointerEvent) { if (e.button !== 0) return e.stopPropagation() e.preventDefault() onResizing(true) const pointerId = e.pointerId /* the turn is about the element's centre, which its bounds share whatever the turn (the runtime's rotate turns about the box's centre) */ const bounds = furniture.current?.getBoundingClientRect() const center = bounds ? { x: bounds.left + bounds.width / 2, y: bounds.top + bounds.height / 2 } : { x: e.clientX, y: e.clientY } const startAngle = pointerAngle(center, { x: e.clientX, y: e.clientY }) const startRotation = rotation const ready = styleGesture(frame.id, selector, 'begin').then((info) => !!info) let last: { x: number; y: number; shift: boolean } | null = null let latest: number | null = null let inFlight = false let moved = false let done = false function send(value: number) { inFlight = true editElementGeometry(frame.id, selector, { kind: 'rotate', value }) .then((info) => { inFlight = false if (info) onGeometry(geometryOf(info)) if (!done) flush() }) .catch(console.error) } function flush() { if (latest === null || inFlight) return const value = latest latest = null send(value) } function turnFor(pos: { x: number; y: number; shift: boolean }): number | null { if (!moved) return null return rotatedBy(startRotation, startAngle, pointerAngle(center, pos), { snap: pos.shift }) } function preview() { if (done || !last) return const value = turnFor(last) if (value === null) return latest = value flush() } void ready.then(preview) function trackPointer(ev: PointerEvent) { last = { x: ev.clientX, y: ev.clientY, shift: ev.shiftKey } if (Math.abs(ev.clientX - e.clientX) + Math.abs(ev.clientY - e.c - src/components/ExportModal.tsx (5247 bytes)
import { useState } from 'react' import type { Frame } from '../../shared/types' import { readingOrder } from '../../shared/frameOrder' import { MAX_PDF_FRAMES } from '../../shared/pdfLimits' import { downloadFramesPdf } from '../lib/frameExport' import { ImportStepHeader } from './ImportSources' import { Button } from './ui/button' import { FrameThumb } from './FramePreview' import { Checkbox } from './ui/checkbox' import { AppIcon } from './ui/brand-mark' import { Modal, ModalActions, ModalLede, ModalTitle } from './ui/modal' import { SelectionBar, SelectionBarAction } from './ui/selection-bar' import { useT } from '@/lib/i18n' import { cn } from '@/lib/utils' import { trackExport } from '../lib/exportEvents' /** * The top bar's Export: the page's frames as a checklist (the canvas * selection pre-checked, or every frame when nothing is selected), bound * into one PDF, a vector page per frame. The pages follow reading order, * which the checklist shows and numbers; the outcome lands in the canvas * toast. A frame's own PNG and JPG live in its context menu. */ export function ExportModal({ frames, initialSelection, onClose, }: { /** every frame on the current page, in layer order */ frames: Frame[] /** frame ids checked when the modal opens; empty checks them all */ initialSelection: string[] onClose: () => void }) { const [selected, setSelected] = useState<Set<string>>( () => new Set(initialSelection.length ? initialSelection : frames.map((frame) => frame.id)), ) /* the PDF takes the checked frames in the listed order (re-sorting only the checked ones could regroup the rows) */ const listed = readingOrder(frames) const chosen = listed.filter((frame) => selected.has(frame.id)) /* the server refuses a longer PDF: keep the checklist open until it fits */ const overPdfLimit = chosen.length > MAX_PDF_FRAMES const extra = chosen.length - MAX_PDF_FRAMES const t = useT() function toggle(frameId: string) { setSelected((current) => { const next = new Set(current) if (next.has(frameId)) next.delete(frameId) else next.add(frameId) return next }) } function run() { const [first] = chosen if (!first || overPdfLimit) return trackExport('pdf', chosen.length, 'export_modal') void downloadFramesPdf(first.canvasId, chosen) onClose() } if (!frames.length) { return ( <Modal size="sm" onClose={onClose}> <ModalTitle>{t('panels.exportNothing')}</ModalTitle> <ModalLede>{t('panels.exportNothingLede')}</ModalLede> <ModalActions> <Button variant="ghost" onClick={onClose}> {t('common.close')} </Button> </ModalActions> </Modal> ) } return ( <Modal size="lg" onClose={onClose}> <ImportStepHeader icon={<AppIcon brand="pdf" size={40} />} title={t('panels.exportPdfTitle')} lede={t('panels.exportPdfLede')} /> <SelectionBar className="mt-5" count={chosen.length} total={frames.length} actions={ <> <SelectionBarAction onClick={() => setSelected(new Set(frames.map((frame) => frame.id)))}> {t('panels.exportSelectAll')} </SelectionBarAction> <SelectionBarAction onClick={() => setSelected(new Set())}>{t('panels.exportClear')}</SelectionBarAction> </> } /> <div className="max-h-[calc(100dvh-390px)] overflow-y-auto rounded-panel bg-surface shadow-ring sm:max-h-[min(350px,calc(100vh-390px))]" role="group" aria-label={t('panels.exportFramesAria')} > {listed.map((frame) => ( <label key={frame.id} className="relative grid min-h-[60px] cursor-pointer grid-cols-[20px_64px_minmax(0,1fr)] items-center gap-3 border-b border-line-soft px-4 py-2.5 transition-colors last:border-b-0 hover:bg-sub" > <Checkbox checked={selected.has(frame.id)} onChange={() => toggle(frame.id)} /> <FrameThumb frameId={frame.id} /> <span className="min-w-0"> <span className="block truncate text-copy font-medium text-ink"> {frame.name || t('panels.exportUntitled')} </span> <span className="block font-mono text-caption text-ink-faint"> {Math.round(frame.width)} × {Math.round(frame.height)} </span> </span> </label> ))} </div> <p className={cn('mt-2 px-0.5 text-caption', overPdfLimit ? 'text-accent-ink' : 'text-ink-faint')}> {overPdfLimit ? `${t('panels.exportPdfMax', { count: MAX_PDF_FRAMES })} ${t('panels.exportUncheck', { count: extra })}` : t('panels.exportPdfHint')} </p> <ModalActions> <Button variant="ghost" onClick={onClose}> {t('common.cancel')} </Button> <Button variant="primary" disabled={!chosen.length || overPdfLimit} onClick={run}> {chosen.length > 1 ? t('panels.exportDownloadPdfPages', { count: chosen.length }) : t('panels.exportDownloadPdf')} </Button> </ModalActions> </Modal> ) } - src/components/ExportOptions.tsx (4800 bytes)
import { useState } from 'react' import { EXPORT_SCALE_PRESETS, formatExportScale, parseExportScale } from '../../shared/exportScale' import type { ExportPickFormat, ExportSettings } from '../lib/exportSettings' import { useT } from '../lib/i18n' import { Input } from './ui/input' import { Select, SelectContent, SelectItem, SelectSeparator, SelectTrigger, SelectValue } from './ui/select' /** A layer's formats; a whole frame adds PDF. */ export const IMAGE_FORMATS: readonly ExportPickFormat[] = ['png', 'jpg', 'svg'] export const FRAME_FORMATS: readonly ExportPickFormat[] = [...IMAGE_FORMATS, 'pdf'] const FORMAT_LABEL: Record<ExportPickFormat, string> = { png: 'PNG', jpg: 'JPG', svg: 'SVG', pdf: 'PDF' } /* vector files have no pixel density */ const isVector = (format: ExportPickFormat) => format === 'svg' || format === 'pdf' /* the scale menu's own value for "type a multiplier"; never a preset's */ const CUSTOM = 'custom' const isPreset = (scale: number) => (EXPORT_SCALE_PRESETS as readonly number[]).includes(scale) /** * Figma's export row: a density (the presets or a typed multiplier) and a * format. An SVG or PDF has no density: the scale reads 1x and is set * aside while it is picked. Without `withFormat` it is the scale alone, for * a list whose rows are the formats. A pick `formats` lacks (a PDF, in a * layer's menu) shows as the first of them, which is what that export uses. */ export function ExportOptions({ value, onChange, withFormat = true, formats = IMAGE_FORMATS, compact = false, }: { value: ExportSettings onChange: (patch: Partial<ExportSettings>) => void withFormat?: boolean /** the formats offered; PDF only where a whole frame exports */ formats?: readonly ExportPickFormat[] /** the Inspector's 26px property wells instead of the modal's ring controls */ compact?: boolean }) { const triggerSize = compact ? 'field' : 'sm' const t = useT() /* picking Custom shows the field even while the scale is still a preset */ const [typing, setTyping] = useState(false) const custom = typing || !isPreset(value.scale) const format = formats.includes(value.format) ? value.format : (formats[0] ?? 'png') const vector = withFormat && isVector(format) /** A readable multiplier is the scale; anything else puts the field back * to the scale exports use, so it never shows one they ignore. */ function commitCustom(field: HTMLInputElement) { const scale = parseExportScale(field.value) if (scale === null) field.value = String(value.scale) else if (scale !== value.scale) onChange({ scale }) else field.value = String(scale) } return ( <div className="grid gap-1.5"> <div className="flex gap-1.5"> <Select value={custom ? CUSTOM : String(value.scale)} disabled={vector} onValueChange={(next) => { if (next === CUSTOM) return setTyping(true) setTyping(false) onChange({ scale: Number(next) }) }} > <SelectTrigger size={triggerSize} className="min-w-0 flex-1" aria-label={t('panels.exportScale')}> <SelectValue>{formatExportScale(vector ? 1 : value.scale)}</SelectValue> </SelectTrigger> <SelectContent> {EXPORT_SCALE_PRESETS.map((scale) => ( <SelectItem key={scale} value={String(scale)}> {formatExportScale(scale)} </SelectItem> ))} <SelectSeparator /> <SelectItem value={CUSTOM}>{t('panels.exportScaleCustom')}</SelectItem> </SelectContent> </Select> {withFormat && ( <Select value={format} onValueChange={(next) => onChange({ format: next as ExportPickFormat })}> <SelectTrigger size={triggerSize} className="min-w-0 flex-1" aria-label={t('panels.exportFormat')}> <SelectValue /> </SelectTrigger> <SelectContent> {formats.map((option) => ( <SelectItem key={option} value={option}> {FORMAT_LABEL[option]} </SelectItem> ))} </SelectContent> </Select> )} </div> {custom && !vector && ( <Input /* a new committed scale resets what the field shows */ key={value.scale} variant={compact ? 'field' : 'mono'} inputSize={compact ? 'auto' : 'sm'} inputMode="decimal" defaultValue={String(value.scale)} aria-label={t('panels.exportScaleCustomLabel')} placeholder="1.5" onBlur={(e) => commitCustom(e.currentTarget)} onKeyDown={(e) => { if (e.key === 'Enter') commitCustom(e.currentTarget) }} /> )} </div> ) } - src/components/FindBar.tsx (8431 bytes)
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react' import type { Frame } from '../../shared/types' import { readingOrder } from '../../shared/frameOrder' import { useT } from '../lib/i18n' import { usePageCanvas } from '../lib/pages' import { canEditOpenCanvas, useStore } from '../lib/store' import { saveFrameHtml } from '../lib/layerEdits' import { findInHtml, replaceInHtml, type TextMatch } from '../lib/actions/findText' import { saveFramesHtml } from '../lib/actions/edits' import { cn } from '@/lib/utils' import { Button } from './ui/button' import { IconButton } from './ui/icon-button' import { ArrowDownIcon, ArrowUpIcon, ChevronRightIcon, XIcon } from './ui/icons' import { Input } from './ui/input' import { Pressable } from './ui/pressable' import { SearchField } from './ui/search-field' interface Hit { frame: Frame /** the match's place among its frame's matches, which a single replace names */ n: number match: TextMatch } /** * ⌘F: find text across the page's frames, step through the matches (↩ / * ⇧↩), each one picked and flown to; ⌥⌘F opens it with a replace line, * replacing one match or all of them as one undo step. */ export function FindBar({ mode, step, onClose, }: { mode: 'find' | 'replace' /** a step asked for from outside (the Edit menu's Find next/previous) */ step: { dir: 1 | -1; at: number } | null onClose: () => void }) { const t = useT() const page = usePageCanvas() const canEdit = useStore((s) => canEditOpenCanvas(s)) const [query, setQuery] = useState('') const [replacement, setReplacement] = useState('') const [matchCase, setMatchCase] = useState(false) const [showReplace, setShowReplace] = useState(mode === 'replace') const [cursor, setCursor] = useState(0) const inputRef = useRef<HTMLInputElement>(null) /* ⌘F again (or ⌥⌘F) while open puts the keyboard back in the field */ const [seenMode, setSeenMode] = useState(mode) if (seenMode !== mode) { setSeenMode(mode) if (mode === 'replace') setShowReplace(true) } useEffect(() => { inputRef.current?.focus() inputRef.current?.select() }, [mode]) const hits = useMemo<Hit[]>(() => { const frames = readingOrder((page?.frames ?? []).filter((f) => !f.hidden)) return frames.flatMap((frame) => findInHtml(frame.html, query, { matchCase }).map((match, n) => ({ frame, n, match })), ) }, [page?.frames, query, matchCase]) const active = hits.length ? Math.min(cursor, hits.length - 1) : -1 function go(index: number) { const hit = hits[index] if (!hit) return setCursor(index) const s = useStore.getState() s.select(hit.frame.id) s.pickElement({ frameId: hit.frame.id, selector: hit.match.selector }, true) s.requestFlyTo(hit.frame.id) } function move(dir: 1 | -1) { if (!hits.length) return go(active === -1 ? 0 : (active + dir + hits.length) % hits.length) } /* the menus' Find next / previous */ const [seenStep, setSeenStep] = useState(step) if (seenStep !== step) { setSeenStep(step) if (step) move(step.dir) } function replaceOne() { const hit = hits[active] if (!hit || hit.frame.locked || hit.match.locked) return const replaced = replaceInHtml(hit.frame.html, query, replacement, { matchCase, only: hit.n }) if (replaced) saveFrameHtml(hit.frame, replaced.html) } function replaceAll() { const byFrame = new Map<string, Frame>() for (const hit of hits) if (!hit.frame.locked) byFrame.set(hit.frame.id, hit.frame) let count = 0 const changes = [...byFrame.values()].flatMap((frame) => { const replaced = replaceInHtml(frame.html, query, replacement, { matchCase }) if (!replaced) return [] count += replaced.count return [{ frame, html: replaced.html }] }) saveFramesHtml(changes) if (count) useStore.getState().pushNotice(t('actions.replaced', { count })) } function onKeyDown(e: KeyboardEvent<HTMLInputElement>) { if (e.key === 'Escape') { e.preventDefault() onClose() } else if (e.key === 'Enter' && !e.nativeEvent.isComposing) { e.preventDefault() move(e.shiftKey ? -1 : 1) } } const count = !query.trim() ? '' : hits.length ? t('actions.findCount', { current: active + 1, total: hits.length }) : t('actions.findNone') return ( <div role="search" aria-label={t('actions.findLabel')} className="absolute z-40 flex w-[min(360px,calc(100vw-24px))] flex-col gap-1.5 rounded-panel bg-surface p-2 shadow-float" style={{ top: 'calc(var(--chrome-top, 0px) + 10px)', right: 'calc(var(--chrome-right, 0px) + 10px)' }} > <div className="flex items-center gap-1"> {canEdit && ( <IconButton size="sm" aria-label={t('actions.showReplace')} on={showReplace} onClick={() => setShowReplace((v) => !v)} > <ChevronRightIcon width={14} height={14} aria-hidden className={cn('transition-transform', showReplace && 'rotate-90')} /> </IconButton> )} <SearchField ref={inputRef} className="min-w-0 flex-1" value={query} onChange={(e) => { setQuery(e.target.value) setCursor(0) }} onKeyDown={onKeyDown} placeholder={t('actions.findPlaceholder')} aria-label={t('actions.findPlaceholder')} trailing={<span className="flex-none font-mono text-caption text-ink-faint">{count}</span>} /> <IconButton size="sm" aria-label={t('actions.matchCase')} on={matchCase} onClick={() => setMatchCase((v) => !v)} > <span className="font-mono text-caption">Aa</span> </IconButton> <IconButton size="sm" aria-label={t('actions.previousMatch')} disabled={!hits.length} onClick={() => move(-1)}> <ArrowUpIcon width={14} height={14} aria-hidden /> </IconButton> <IconButton size="sm" aria-label={t('actions.nextMatch')} disabled={!hits.length} onClick={() => move(1)}> <ArrowDownIcon width={14} height={14} aria-hidden /> </IconButton> <IconButton size="sm" aria-label={t('actions.closeFind')} onClick={onClose}> <XIcon width={14} height={14} aria-hidden /> </IconButton> </div> {canEdit && showReplace && ( <div className="flex items-center gap-1 pl-7"> <Input inputSize="sm" className="min-w-0 flex-1" value={replacement} onChange={(e) => setReplacement(e.target.value)} onKeyDown={(e) => { if (e.key === 'Escape') onClose() else if (e.key === 'Enter' && !e.nativeEvent.isComposing) { e.preventDefault() replaceOne() } }} placeholder={t('actions.replacePlaceholder')} aria-label={t('actions.replacePlaceholder')} /> <Button size="sm" disabled={active === -1 || !!hits[active]?.match.locked} onClick={replaceOne}> {t('actions.replaceOne')} </Button> <Button size="sm" disabled={!hits.length} onClick={replaceAll}> {t('actions.replaceAll')} </Button> </div> )} {hits.length > 0 && ( <ul className="max-h-56 overflow-y-auto" aria-label={t('actions.findLabel')}> {hits.slice(0, 200).map((hit, i) => ( <li key={`${hit.frame.id}:${i}`}> <Pressable focus="none" onClick={() => go(i)} className={cn( 'flex w-full flex-col items-start rounded-row px-2 py-1 text-left', i === active ? 'bg-paper-deep' : 'hover:bg-sub', )} > <span className="text-caption text-ink-faint">{hit.frame.name}</span> <span className="w-full truncate text-body text-ink-soft"> {hit.match.before} <mark className="rounded-tag bg-brand/20 text-ink">{hit.match.text}</mark> {hit.match.after} </span> </Pressable> </li> ))} </ul> )} </div> ) } - src/components/FlexLayoutControls.tsx (11491 bytes)
import { useId, useState } from 'react' import type { ElementInfo, StylePatch } from '../lib/frameBridge' import { flexAlignmentAt, flexAxes } from '../lib/flexLayout' import { cn } from '../lib/utils' import { useT, type PlainMessageKey } from '../lib/i18n' import { Button } from './ui/button' import { Input } from './ui/input' import { Pressable } from './ui/pressable' import { ArrowDownIcon, ArrowRightIcon, ColumnGapIcon, FlipHorizontal2Icon, HorizontalPaddingIcon, RowGapIcon, SquareDashedIcon, VerticalPaddingIcon, WrapTextIcon, } from './ui/icons' import { NumberField, PropertyRow, PropertySection, SelectField } from './ui/property-field' import { Segmented, SegmentedItem } from './ui/segmented' const control = 'h-[26px] min-h-0 rounded-row bg-sub p-0 text-ink-soft' const caption = 'mb-1 text-caption text-ink-faint' const spacing = [ ['fixed', 'inspector.spacingFixed'], ['space-between', 'inspector.spacingBetween'], ['space-around', 'inspector.spacingAround'], ['space-evenly', 'inspector.spacingEvenly'], ] as const satisfies readonly (readonly [string, PlainMessageKey])[] const crossAlignments: { value: string; label: PlainMessageKey }[] = [ { value: 'flex-start', label: 'inspector.crossStart' }, { value: 'center', label: 'inspector.crossCenter' }, { value: 'flex-end', label: 'inspector.crossEnd' }, { value: 'stretch', label: 'inspector.crossStretch' }, { value: 'baseline', label: 'inspector.crossBaseline' }, ] const PADDING_SIDES = [ ['top', 'inspector.paddingTop'], ['right', 'inspector.paddingRight'], ['bottom', 'inspector.paddingBottom'], ['left', 'inspector.paddingLeft'], ] as const satisfies readonly (readonly [string, PlainMessageKey])[] const VERTICAL: PlainMessageKey[] = ['inspector.vTop', 'inspector.vMiddle', 'inspector.vBottom'] const HORIZONTAL: PlainMessageKey[] = ['inspector.hLeft', 'inspector.hCenter', 'inspector.hRight'] export function PaddingControls({ info, apply }: { info: ElementInfo; apply: (styles: StylePatch) => void }) { const t = useT() const [expanded, setExpanded] = useState(false) const [top, right, bottom, left] = info.padding return ( <div className="mt-2"> <div className="mb-1 flex items-center justify-between"> <span className="text-caption text-ink-faint">{t('inspector.padding')}</span> <Button variant="bare" size="icon-sm" className="size-5 rounded-tag text-ink-faint" aria-label={t('inspector.individualPadding')} title={t('inspector.individualPaddingTitle')} aria-expanded={expanded} aria-pressed={expanded} onClick={() => setExpanded(!expanded)} > <SquareDashedIcon size="rail" /> </Button> </div> <div className="grid grid-cols-2 gap-1.5"> {expanded ? ( PADDING_SIDES.map(([side, label], index) => ( <NumberField key={side} label={t(label)} prefix={side[0]!.toUpperCase()} value={info.padding[index] ?? null} unit="px" onCommit={(value) => apply({ [`padding-${side}`]: `${Math.max(0, value)}px` })} /> )) ) : ( <> <NumberField label={t('inspector.verticalPadding')} prefix={<VerticalPaddingIcon size="rail" />} value={top === bottom ? top : null} placeholder={t('inspector.mixed')} unit="px" onCommit={(value) => apply({ 'padding-top': `${Math.max(0, value)}px`, 'padding-bottom': `${Math.max(0, value)}px` }) } /> <NumberField label={t('inspector.horizontalPadding')} prefix={<HorizontalPaddingIcon size="rail" />} value={left === right ? left : null} placeholder={t('inspector.mixed')} unit="px" onCommit={(value) => apply({ 'padding-left': `${Math.max(0, value)}px`, 'padding-right': `${Math.max(0, value)}px` }) } /> </> )} </div> </div> ) } export function FlexLayoutControls({ info, apply }: { info: ElementInfo; apply: (styles: StylePatch) => void }) { const t = useT() const spacingName = useId() const axes = flexAxes(info) const column = info.flexDirection.startsWith('column') const reverse = info.flexDirection.endsWith('-reverse') const wrapping = info.flexWrap !== 'nowrap' const distributed = info.justifyContent.startsWith('space-') const mode = distributed ? info.justifyContent : 'fixed' const gap = column ? info.rowGap : info.columnGap const crossGap = column ? info.columnGap : info.rowGap const align = info.alignItems === 'normal' ? 'stretch' : info.alignItems const justify = info.justifyContent === 'normal' ? 'flex-start' : info.justifyContent const crossOptions = crossAlignments.map(({ value, label }) => ({ value, label: t(label) })) const keptKey = spacing.find(([value]) => value === info.justifyContent)?.[1] const keptSpacing = keptKey ? t(keptKey).toLowerCase() : info.justifyContent.replace('space-', 'space ') return ( <PropertySection title={t('inspector.flexLayout')} action={ <Button variant="bare" size="icon-sm" className={cn('size-6 rounded-row text-ink-faint', wrapping && 'bg-paper-deep text-ink')} aria-label={t('inspector.wrapChildren')} title={info.flexWrap === 'wrap-reverse' ? t('inspector.wrapReverse') : t('inspector.wrapChildren')} aria-pressed={wrapping} onClick={() => apply({ 'flex-wrap': wrapping ? 'nowrap' : 'wrap' })} > <WrapTextIcon size="rail" /> </Button> } > <div className="flex gap-1.5"> <Segmented className="min-w-0 flex-1 rounded-row bg-sub p-0.5" aria-label={t('inspector.flexDirection')} value={column ? 'column' : 'row'} onValueChange={(value) => apply({ 'flex-direction': `${value}${reverse ? '-reverse' : ''}` })} > {[ { value: 'row', label: t('inspector.rowDirection'), Icon: ArrowRightIcon }, { value: 'column', label: t('inspector.columnDirection'), Icon: ArrowDownIcon }, ].map(({ value, label, Icon }) => ( <SegmentedItem key={value} value={value} aria-label={label} title={label} className="grid h-[22px] min-h-0 flex-1 place-items-center rounded-tag p-0 sm:flex-1" > <Icon size="rail" /> </SegmentedItem> ))} </Segmented> <Button variant="bare" size="icon-sm" className={cn(control, 'w-[30px]', reverse && 'bg-paper-deep text-ink')} aria-label={t('inspector.reverseDirection')} title={t('inspector.reverseDirection')} aria-pressed={reverse} onClick={() => apply({ 'flex-direction': `${column ? 'column' : 'row'}${reverse ? '' : '-reverse'}` })} > <FlipHorizontal2Icon size="rail" /> </Button> </div> <div className="mt-2 grid grid-cols-[84px_minmax(0,1fr)] gap-2"> <div> <div className={caption}>{t('inspector.alignment')}</div> <div role="group" aria-label={t('inspector.flexAlignment')} className="grid size-[84px] grid-cols-3 grid-rows-3 rounded-row bg-sub p-1" > {[0, 1, 2].flatMap((y) => [0, 1, 2].map((x) => { const target = flexAlignmentAt(info, x, y) const active = align === target.align && (distributed || justify === target.justify) const label = t('inspector.alignChildren', { vertical: t(VERTICAL[y]!), horizontal: t(HORIZONTAL[x]!), }) return ( <Pressable key={`${x}-${y}`} type="button" aria-label={label} aria-pressed={active} title={distributed ? t('inspector.alignKeep', { label, spacing: keptSpacing }) : label} className="group grid place-items-center rounded-tag hover:bg-paper-deep focus-visible:outline-2 focus-visible:outline-ink" onClick={() => apply({ 'align-items': target.align, ...(!distributed && { 'justify-content': target.justify }) }) } > <span className={cn( 'size-[3px] rounded-none bg-ink-faint group-hover:size-2', active && 'size-2 rounded-tag bg-brand', )} /> </Pressable> ) }), )} </div> <div className="mt-1.5 flex"> <SelectField label={t('inspector.crossAxisAlignment')} value={align} options={ crossAlignments.some(({ value }) => value === align) ? crossOptions : [...crossOptions, { value: align, label: align }] } onChange={(value) => apply({ 'align-items': value })} /> </div> </div> <div> <div className={caption}>{t('inspector.gap')}</div> <div role="radiogroup" aria-label={t('inspector.flexSpacing')} className="space-y-1"> {spacing.map(([value, label]) => ( <div key={value} className="flex h-[26px] items-center gap-1.5"> <label className="flex min-w-0 cursor-pointer items-center gap-1.5 text-caption text-ink-soft"> <Input variant="bare" inputSize="auto" type="radio" className="size-3 shrink-0 accent-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand" name={spacingName} aria-label={t(label)} checked={mode === value} onChange={() => apply({ 'justify-content': value === 'fixed' ? 'flex-start' : value })} /> {value !== 'fixed' && t(label)} </label> {value === 'fixed' && ( <NumberField label={t('inspector.gap')} prefix={column ? <RowGapIcon size="rail" /> : <ColumnGapIcon size="rail" />} value={gap ?? 0} unit="px" onCommit={(value) => apply({ [axes.gap]: `${Math.max(0, value)}px` })} /> )} </div> ))} </div> </div> </div> {wrapping && ( <PropertyRow label={t('inspector.lineGap')}> <NumberField label={t('inspector.lineGap')} prefix={column ? <ColumnGapIcon size="rail" /> : <RowGapIcon size="rail" />} value={crossGap ?? 0} unit="px" onCommit={(value) => apply({ [axes.crossGap]: `${Math.max(0, value)}px` })} /> </PropertyRow> )} <PaddingControls info={info} apply={apply} /> </PropertySection> ) } - src/components/FlowOverlay.tsx (5460 bytes)
import { useEffect, useMemo, useState } from 'react' import { useStore } from '../lib/store' import { api, type SyncFlow } from '../lib/api' import { isSyncedFrame } from '../lib/sync' /** * The information architecture of a synced app, drawn on the canvas: when a * design-synced frame is selected, every same-app link hotspot on it gets a * connector to the frame it navigates to, weighted with how often real users * took that path. Selection-scoped on purpose — always-on connectors would * turn a synced canvas into spaghetti. Purely presentational overlay in world * coordinates; pointer events pass through. */ interface Connector { /** hotspot outline on the source frame, world coords */ box: { x: number; y: number; w: number; h: number } path: string label: string | null count: number /** label anchor */ mx: number my: number } export function FlowOverlay() { const canvas = useStore((s) => s.canvas) const selectedId = useStore((s) => s.selectedId) const [flow, setFlow] = useState<SyncFlow | null>(null) const selected = canvas?.frames.find((f) => f.id === selectedId) const selectedIsSynced = !!selected && isSyncedFrame(selected.html) /* fetch lazily, on the first selection of a synced frame (and refresh on later selections — sync updates land while the canvas is open) */ useEffect(() => { if (!canvas || !selectedIsSynced) return let stale = false api .syncFlow(canvas.id) .then((f) => !stale && setFlow(f)) .catch(() => !stale && setFlow(null)) return () => { stale = true } /* canvas.frames churn constantly (streams, cursors); refetch only on canvas/selection change */ }, [canvas?.id, selectedId, selectedIsSynced]) // eslint-disable-line react-hooks/exhaustive-deps const connectors = useMemo<Connector[]>(() => { if (!canvas || !selected || !selectedIsSynced || !flow) return [] const frameById = new Map(canvas.frames.map((f) => [f.id, f])) const countFor = new Map(flow.edges.filter((e) => e.fromFrameId === selected.id).map((e) => [e.toFrameId, e.count])) const out: Connector[] = [] for (const link of flow.links) { if (link.fromFrameId !== selected.id) continue const target = frameById.get(link.toFrameId) if (!target || target.id === selected.id) continue /* hotspot coordinates are in the snapshot's own pixels; clamp into the frame so a since-resized frame degrades gracefully */ const bx = selected.x + Math.min(link.x, selected.width - 8) const by = selected.y + Math.min(link.y, selected.height - 8) const bw = Math.min(link.width, selected.width - (bx - selected.x)) const bh = Math.min(link.height, selected.height - (by - selected.y)) const targetLeft = target.x + target.width / 2 >= bx const sx = targetLeft ? bx + bw : bx const sy = by + bh / 2 const tx = targetLeft ? target.x : target.x + target.width const ty = target.y + Math.min(120, target.height / 2) const bend = Math.max(60, Math.abs(tx - sx) / 3) * (targetLeft ? 1 : -1) out.push({ box: { x: bx, y: by, w: bw, h: bh }, path: `M ${sx} ${sy} C ${sx + bend} ${sy}, ${tx - bend} ${ty}, ${tx} ${ty}`, label: link.label, count: countFor.get(target.id) ?? 0, mx: (sx + tx) / 2, my: (sy + ty) / 2 - 10, }) } return out }, [canvas, selected, selectedIsSynced, flow]) if (!connectors.length) return null /* one SVG spanning everything it draws, placed in world space */ const pad = 80 const xs = connectors.flatMap((c) => [c.box.x, c.box.x + c.box.w, c.mx]) const ys = connectors.flatMap((c) => [c.box.y, c.box.y + c.box.h, c.my]) for (const f of canvas!.frames) { xs.push(f.x, f.x + f.width) ys.push(f.y, f.y + f.height) } const minX = Math.min(...xs) - pad const minY = Math.min(...ys) - pad const w = Math.max(...xs) - minX + pad * 2 const h = Math.max(...ys) - minY + pad * 2 return ( <svg /* pointer events pass through: this is a read-only overlay above the frames (z-6) that must never intercept a drag or a right-click */ className="pointer-events-none absolute z-[6] overflow-visible text-accent-ink" style={{ left: minX, top: minY, width: w, height: h }} viewBox={`${minX} ${minY} ${w} ${h}`} > <defs> <marker id="flow-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"> <path d="M 0 1 L 9 5 L 0 9" fill="none" stroke="currentColor" strokeWidth="1.8" /> </marker> </defs> {connectors.map((c, i) => ( <g key={i}> <rect x={c.box.x} y={c.box.y} width={c.box.w} height={c.box.h} rx={4} className="fill-brand/[0.08] stroke-current [stroke-dasharray:4_3] [stroke-width:1.5]" /> <path d={c.path} className="fill-none stroke-current opacity-75 [stroke-width:2]" markerEnd="url(#flow-arrow)" /> {c.count > 0 && ( <text x={c.mx} y={c.my} className="fill-current text-[13px] font-semibold [paint-order:stroke] [stroke-width:4] stroke-surface" textAnchor="middle" > {c.count}× </text> )} </g> ))} </svg> ) } - src/components/FollowFrame.tsx (2318 bytes)
import { useStore } from '../lib/store' import { agentFollowFrame, followedAgent, followedLeader } from '../lib/follow' import { AgentIcon } from './AgentIcon' import { XIcon } from './ui/icons' import { useT } from '../lib/i18n' /** Figma-style "you are following X": a border in the leader's colour around * the stage and a pill naming them (a followed agent while it is idle too). Any pan or zoom of our own lets go, so * the pill's × is for people who want to stop without moving. The pill hangs * below the top bar (--chrome-top, set by the page), where the presence * avatars would otherwise cover it; the 7px plus the 3px border lines it up * with the tool rail. */ export function FollowFrame() { const t = useT() const leader = useStore(followedLeader) /* a followed agent that is idle (out of the roster) or has no frame to show yet */ const waiting = useStore((s) => { const agent = followedAgent(s) return !!agent && (!s.presences[agent.clientId] || !agentFollowFrame(s)) }) const stop = useStore((s) => s.setFollowing) if (!leader) return null return ( <div className="pointer-events-none absolute inset-0 z-[34] animate-[chip-in_0.2s_ease] rounded-[3px] border-[3px]" style={{ borderColor: leader.color }} > <div className="pointer-events-auto absolute left-1/2 top-[calc(var(--chrome-top,0px)+7px)] flex -translate-x-1/2 items-center gap-2 rounded-full py-1.5 pr-2 pl-3.5 text-[12.5px] font-medium text-white shadow-pop" style={{ background: leader.color }} > <span> {t('canvas.following')}{' '} {leader.kind === 'agent' && ( <> <AgentIcon name={leader.name} brand={leader.brand} size={11} color="#fff" />{' '} </> )} {leader.name} {waiting && <span className="font-normal opacity-80"> · {t('canvas.followIdle')}</span>} </span> <button type="button" className="grid size-[18px] place-items-center rounded-full bg-white/25 hover:bg-white/40" aria-label={t('canvas.stopFollowing', { name: leader.name })} title={t('canvas.stopFollowingEsc')} onClick={() => stop(null)} > <XIcon size={11} /> </button> </div> </div> ) } - src/components/FontLibrary.tsx (13617 bytes)
import { useEffect, useRef, useState, type DragEvent } from 'react' import { ApiError, api, errorMessage } from '../lib/api' import { useT } from '../lib/i18n' import { posthog } from '../lib/posthog' import { canAddLocalFonts, pickLocalFonts, readLocalFont, type PickedLocalFont, type SkippedLocalFont, } from '../lib/localFonts' import { MAX_FONT_BYTES, faceLabel, libraryFamilies, type CustomFont } from '../../shared/fonts' import { ConfirmDialog } from './ui/alert-dialog' import { Button } from './ui/button' import { IconButton } from './ui/icon-button' import { Input } from './ui/input' import { Note } from './ui/note' import { EmptyState } from './ui/empty-state' import { cn } from '../lib/utils' import { CardDescription, CardHeader, CardRow, CardTitle, SettingsCard } from './ui/card' import { DesktopIcon, RocketIcon, TrashIcon, UploadIcon } from './ui/icons' import { openUpgrade } from '../lib/upgrade' const ACCEPT = '.ttf,.otf,.woff,.woff2,font/ttf,font/otf,font/woff,font/woff2' /* previews load under an alias of their own: an uploaded "Inter" must never replace the Inter the app itself is set in */ const previewFamily = (font: CustomFont) => `doop-preview-${font.id}` const loadedPreviews = new Set<string>() function loadPreview(font: CustomFont) { if (loadedPreviews.has(font.id)) return loadedPreviews.add(font.id) try { const face = new FontFace(previewFamily(font), `url(${JSON.stringify(font.url)})`, { weight: font.weight, style: font.style, }) document.fonts.add(face) face.load().catch(() => loadedPreviews.delete(font.id)) } catch { loadedPreviews.delete(font.id) } } /** The face a family's preview line is set in: its regular, else the first. */ function previewFace(faces: CustomFont[]): CustomFont | undefined { return faces.find((f) => f.style === 'normal' && (f.weight === '400' || f.weight.includes(' '))) ?? faces[0] } /** * A font library as a settings card: upload font files, see each family set * in itself, remove faces. `workspaceId` picks a workspace's library (used on * its canvases); without it the card manages the person's own, used on their * personal canvases. */ export function FontLibrary({ workspaceId }: { workspaceId?: string }) { const [fonts, setFonts] = useState<CustomFont[] | null>(null) const [uploading, setUploading] = useState(0) const [error, setError] = useState('') /* a Free library is full: the error line gets the way to Pro */ const [limited, setLimited] = useState(false) /* one face, or a whole family (every face it has), awaiting confirmation */ const [removing, setRemoving] = useState<{ family: string; faces: CustomFont[] } | null>(null) const [dragging, setDragging] = useState(false) /* fonts picked from this computer in the desktop shell, awaiting the licence word before they are read and uploaded */ const [localPick, setLocalPick] = useState<PickedLocalFont[] | null>(null) const input = useRef<HTMLInputElement>(null) const t = useT() useEffect(() => { let live = true api.listFonts(workspaceId).then( (list) => live && setFonts(list), (e: unknown) => { if (!live) return setFonts([]) setError(errorMessage(e, t('fonts.loadFailed'))) }, ) return () => { live = false } }, [workspaceId, t]) for (const font of fonts ?? []) loadPreview(font) async function upload(files: File[]) { setError('') setLimited(false) const problems: string[] = [] setUploading((n) => n + files.length) for (const file of files) { try { if (file.size > MAX_FONT_BYTES) throw new Error(t('fonts.tooLarge', { name: file.name })) const font = await api.uploadFont(file, workspaceId) posthog.capture('custom_font_uploaded', { format: font.format, workspace: !!workspaceId }) setFonts((list) => [ ...(list ?? []).filter( (f) => !( f.family.toLowerCase() === font.family.toLowerCase() && f.weight === font.weight && f.style === font.style ), ), font, ]) } catch (e) { if (e instanceof ApiError && e.status === 402) setLimited(true) const failed = t('fonts.uploadFailed') const reason = e instanceof ApiError ? errorMessage(e, failed) : e instanceof Error ? e.message : failed problems.push(reason.startsWith(file.name) ? reason : `${file.name}: ${reason}`) } finally { setUploading((n) => n - 1) } } if (problems.length) setError(problems.join(' · ')) } async function remove(faces: CustomFont[]) { for (const font of faces) { try { await api.deleteFont(font.id) setFonts((list) => list?.filter((f) => f.id !== font.id) ?? null) } catch (e) { setError(errorMessage(e, t('fonts.removeFailed'))) return } } } /** The desktop shell's native panel, opened in the fonts folder; what it * lets through that is not a single font file is named in the error line. */ async function chooseLocal() { setError('') try { const { picked, skipped } = await pickLocalFonts() const names = (reason: SkippedLocalFont['reason']) => skipped.filter((file) => file.reason === reason).map((file) => file.name) const kind = names('kind') const size = names('size') setError( [ kind.length ? t('fonts.localSkipped', { names: kind.join(', '), count: kind.length }) : '', size.length ? t('fonts.localTooLarge', { names: size.join(', '), count: size.length }) : '', ] .filter(Boolean) .join(' · '), ) if (picked.length) setLocalPick(picked) } catch (e) { setError(e instanceof Error ? e.message : t('fonts.uploadFailed')) } } /** Reads each pick through the shell, then uploads like dropped files. */ async function uploadLocal(picked: PickedLocalFont[]) { const files: File[] = [] const problems: string[] = [] for (const font of picked) { try { files.push(await readLocalFont(font)) } catch { problems.push(t('fonts.localReadFailed', { name: font.name })) } } if (files.length) { posthog.capture('custom_font_added_from_computer', { count: files.length, workspace: !!workspaceId }) await upload(files) } if (problems.length) setError((current) => [current, ...problems].filter(Boolean).join(' · ')) } const families = libraryFamilies(fonts ?? []) .sort((a, b) => a.localeCompare(b)) .map((family) => ({ family, faces: (fonts ?? []) .filter((f) => f.family.toLowerCase() === family.toLowerCase()) .sort((a, b) => a.weight.localeCompare(b.weight) || a.style.localeCompare(b.style)), })) const busy = fonts === null || uploading > 0 const uploadButton = ( <div className="flex flex-wrap justify-end gap-2"> {canAddLocalFonts() && ( <Button size="sm" variant="bare" disabled={busy} onClick={() => void chooseLocal()}> <DesktopIcon /> {t('fonts.addLocal')} </Button> )} <Button size="sm" disabled={busy} onClick={() => input.current?.click()}> <UploadIcon /> {uploading > 0 ? t('fonts.uploading') : t('fonts.uploadButton')} </Button> </div> ) const isFontFile = (file: File) => /\.(ttf|otf|woff2?)$/i.test(file.name) const hasFiles = (event: DragEvent) => event.dataTransfer.types.includes('Files') return ( <SettingsCard className={cn(dragging && 'shadow-[0_0_0_2px_var(--brand)]')} /* font files dropped anywhere on the card upload like picked ones */ onDragOver={(event) => { if (busy || !hasFiles(event)) return event.preventDefault() setDragging(true) }} onDragLeave={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false) }} onDrop={(event) => { if (!hasFiles(event)) return event.preventDefault() setDragging(false) const files = [...event.dataTransfer.files] if (busy || !files.length) return const picked = files.filter(isFontFile) if (picked.length) void upload(picked) else setError(t('fonts.dropNotFonts')) }} > <CardHeader> <CardTitle>{t('fonts.title')}</CardTitle> <CardDescription> {workspaceId ? t('fonts.descriptionWorkspace') : t('fonts.descriptionPersonal')} {t('fonts.descriptionRest')} </CardDescription> </CardHeader> <Input ref={input} type="file" multiple accept={ACCEPT} aria-label={t('fonts.chooseFiles')} className="hidden" onChange={(event) => { const files = [...(event.currentTarget.files ?? [])] event.currentTarget.value = '' if (files.length) void upload(files) }} /> {fonts?.length === 0 ? ( <div className="flex flex-col gap-2 px-4 py-5 sm:px-[22px]"> <EmptyState variant="dashed" /* a 1px hairline: the 1.5px default reads heavy inside a card */ className="border" title={t('fonts.emptyTitle')} description={workspaceId ? t('fonts.emptyWorkspace') : t('fonts.emptyPersonal')} action={uploadButton} /> {error && <Note tone="error">{error}</Note>} </div> ) : ( <CardRow label={t('fonts.upload')} action={uploadButton}> {error ? ( <> <Note tone="error">{error}</Note> {limited && ( <Button size="sm" variant="primary" className="mt-2 self-start" onClick={() => openUpgrade({ source: 'font-limit' })} > <RocketIcon size="rail" /> {t('plans.fontLimitAction')} </Button> )} </> ) : ( <Note> {fonts === null ? t('fonts.loading') : `${t('fonts.summary', { families: t('fonts.families', { count: families.length }), files: t('fonts.files', { count: fonts.length }), })} · ${t('fonts.fileRules')}`} </Note> )} </CardRow> )} {families.map(({ family, faces }) => { const preview = previewFace(faces) return ( <CardRow key={family} label={family} action={ <Button size="sm" variant="bare" onClick={() => setRemoving({ family, faces })}> <TrashIcon size="rail" /> {t('fonts.removeFamily')} </Button> } > <div className="flex min-w-0 basis-full flex-col gap-1.5"> <p className="truncate text-heading text-ink" style={ preview ? { fontFamily: `"${previewFamily(preview)}", var(--font-ui)`, fontWeight: preview.weight.split(' ')[0], } : undefined } > {t('fonts.preview')} </p> <div className="flex flex-wrap gap-1.5"> {faces.map((face) => ( <span key={face.id} className="inline-flex items-center gap-1 rounded-pill py-0.5 pl-2.5 pr-0.5 text-caption text-ink-soft shadow-ring" title={face.fileName} > {faceLabel(face)} <IconButton size="sm" shape="round" variant="danger" aria-label={t('fonts.removeFace', { family, face: faceLabel(face) })} onClick={() => setRemoving({ family, faces: [face] })} > <TrashIcon size={12} /> </IconButton> </span> ))} </div> </div> </CardRow> ) })} <ConfirmDialog open={localPick !== null} onOpenChange={(open) => !open && setLocalPick(null)} title={localPick ? t('fonts.addLocalTitle', { count: localPick.length, name: localPick[0]?.name ?? '' }) : ''} description={t('fonts.addLocalDescription')} confirmLabel={t('fonts.addLocalConfirm')} onConfirm={() => { if (localPick) void uploadLocal(localPick) setLocalPick(null) }} /> <ConfirmDialog open={removing !== null} onOpenChange={(open) => !open && setRemoving(null)} title={ !removing ? '' : removing.faces.length === 1 && removing.faces[0] ? t('fonts.removeTitle', { family: removing.family, face: faceLabel(removing.faces[0]) }) : t('fonts.removeFamilyTitle', { family: removing.family, count: removing.faces.length }) } description={ removing && removing.faces.length > 1 ? t('fonts.removeFamilyDescription') : t('fonts.removeDescription') } confirmLabel={t('fonts.remove')} destructive onConfirm={() => { if (removing) void remove(removing.faces) setRemoving(null) }} /> </SettingsCard> ) } - tsconfig.json (637 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "allowImportingTsExtensions": true, "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client", "node"], "jsx": "react-jsx", "strict": true, "noFallthroughCasesInSwitch": true, "noImplicitOverride": true, "noUncheckedIndexedAccess": true, "skipLibCheck": true, "noEmit": true, "resolveJsonModule": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "paths": { "@/*": ["./src/*"] } }, "include": ["src", "server", "shared", "tests"] } - vite.config.ts (3339 bytes)
import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { fileURLToPath } from 'node:url' /* Dev ports. The defaults are the only ones anyone normally needs; the env overrides exist so a second worktree can run its own pair without fighting the first for :4300/:4400. PORT is the same variable the server reads, so the proxy always points at whichever backend this `npm run dev` started. */ const apiPort = Number(process.env.PORT || 4400) const webPort = Number(process.env.VITE_PORT || 4300) const api = `http://localhost:${apiPort}` const clipboardTests = [ 'tests/canvasClipboardBrowser.test.ts', 'tests/elementContextMenuBrowser.test.ts', 'tests/pageCanvasBrowser.test.ts', ] export default defineConfig({ plugins: [react(), tailwindcss()], test: { /* agent worktrees live under .claude/ inside the repo; their copies of the suite must not run as ours */ exclude: ['**/node_modules/**', '**/.claude/**'], setupFiles: ['tests/setup.ts'], globalSetup: ['tests/globalSetup.ts'], projects: [ { test: { name: 'parallel', exclude: clipboardTests } }, // Browser contexts share the system clipboard, so these files must run one at a time. { test: { name: 'clipboard', include: clipboardTests, fileParallelism: false } }, ], /* seven files drive a real Chromium; closing one under a full parallel run can outlast the 10s default */ hookTimeout: 30_000, }, /* Error tracking resolves minified stack frames through the .map next to each bundle. The source is public (AGPL), so the maps are too; browsers only fetch them when devtools open. */ build: { sourcemap: true }, /* mupdf finds its .wasm next to its own module through `import.meta.url`; pre-bundling would move the module and lose the file */ optimizeDeps: { exclude: ['mupdf'] }, resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, server: { port: webPort, /* cargo's build output is huge and, on Windows, its binaries stay locked while the shell runs (EBUSY); nothing under it is ever served by vite */ watch: { ignored: ['**/desktop/src-tauri/target/**'], }, /* the doop-sync snippet posts to /ingest from foreign origins; vite answers CORS preflights itself before the proxy, so its default same-origin policy would block what the express server (prod) allows */ cors: true, proxy: { /* changeOrigin stays OFF so the backend sees the web origin's Host and better-auth builds OAuth discovery/authorize URLs on that origin — the one that serves the login page and that MCP clients connect to */ '/api': { target: api }, '/mcp': { target: api }, '/local-agent': { target: api }, /* frame images only — a bare '/i' prefix would swallow /integrations */ '/i/': { target: api }, '/a/': { target: api }, '/u/': { target: api }, '/ingest': { target: api }, '/relay': { target: api }, '/blog': { target: api }, '/robots.txt': { target: api }, '/sitemap.xml': { target: api }, '/.well-known': { target: api }, '/ws': { target: `ws://localhost:${apiPort}`, ws: true }, }, }, })