diff --git a/.editorconfig b/.editorconfig index 7a5ad7a..79621be 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,7 +6,4 @@ end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true indent_style = space -indent_size = 4 - -[*.{json,yml,yaml,md,html}] indent_size = 2 diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..5c7a90c --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Formatting-only commits, skipped by `git blame` (GitHub reads this file automatically; +# locally: git config blame.ignoreRevsFile .git-blame-ignore-revs). + +# style: reformat with Prettier (2-space indentation) +9d50b8e4a1142ca0d771d83288ab501732602e85 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ee8cede..f0cdca5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,12 @@ jobs: node-version: 24 cache: pnpm - run: pnpm install --frozen-lockfile + # Merging a version bump publishes it (release.yml), with notes from CHANGELOG.md. + - name: CHANGELOG.md has a section for the version + run: | + version="$(node -p "require('./package.json').version")" + grep -Eq "^## ${version//./\\.}( |$)" CHANGELOG.md || { echo "Add a '## $version' section to CHANGELOG.md" >&2; exit 1; } + - run: pnpm format:check - run: pnpm lint - run: pnpm typecheck - run: pnpm test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bc937ff..7c2c183 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,23 +1,33 @@ -name: Publish to npm +name: Release -# Push a tag like v1.0.0 to publish. +# The version in package.json is the switch: merging a pull request that bumps it publishes that +# version. Pushes that leave the version alone (already on npm) do nothing. +# +# On a new version this tests and builds, publishes to npm with provenance (a version with a +# pre-release suffix such as 1.2.0-beta.1 goes to the `next` dist-tag), tags the commit vX.Y.Z and +# creates a GitHub release from the version's section in CHANGELOG.md. # # Authentication, in order of preference: # 1. npm Trusted Publishing (OIDC) — no secret needed. Configure it on npmjs.com under # the package's Settings → Trusted Publisher (repo Inchill/react-whiteboard, workflow release.yml). -# 2. An NPM_TOKEN repository secret — only needed for the very first publish, because npm -# requires the package to exist before Trusted Publishing can be configured. -# Use a short-lived granular token and delete it once Trusted Publishing works. +# 2. An NPM_TOKEN repository secret — use a short-lived granular token and delete it once +# Trusted Publishing works. on: push: - tags: ['v*'] + branches: [main] + workflow_dispatch: permissions: - contents: read - id-token: write # required for Trusted Publishing and provenance + contents: write # push the tag and create the release + id-token: write # Trusted Publishing and provenance + +# Never run two releases at once, and never cancel one halfway through publishing. +concurrency: + group: release + cancel-in-progress: false jobs: - publish: + release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -27,18 +37,68 @@ jobs: node-version: 24 cache: pnpm registry-url: https://registry.npmjs.org - # Trusted Publishing needs npm CLI 11.5.1 or later. - - run: npm install -g npm@11 - - run: pnpm install --frozen-lockfile - - run: pnpm test - - name: Check the tag matches package.json + + - name: Is this version new? + id: version run: | + name="$(node -p "require('./package.json').name")" version="$(node -p "require('./package.json').version")" - if [ "v$version" != "$GITHUB_REF_NAME" ]; then - echo "Tag $GITHUB_REF_NAME does not match package.json version $version" >&2 + echo "version=$version" >> "$GITHUB_OUTPUT" + if npm view "$name@$version" version > /dev/null 2>&1; then + echo "$name@$version is already on npm; nothing to release." + echo "new=false" >> "$GITHUB_OUTPUT" + else + echo "Releasing $name@$version." + echo "new=true" >> "$GITHUB_OUTPUT" + fi + + # Trusted Publishing needs npm CLI 11.5.1 or later. + - if: steps.version.outputs.new == 'true' + run: npm install -g npm@11 + - if: steps.version.outputs.new == 'true' + run: pnpm install --frozen-lockfile + - if: steps.version.outputs.new == 'true' + run: | + pnpm lint + pnpm typecheck + pnpm test + + - name: Release notes from CHANGELOG.md + if: steps.version.outputs.new == 'true' + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + # The lines under "## " up to the next "## " heading. + awk -v v="$VERSION" ' + index($0, "## " v " ") == 1 || $0 == "## " v { found = 1; next } + found && /^## / { exit } + found { print } + ' CHANGELOG.md > release-notes.md + if ! grep -q '[^[:space:]]' release-notes.md; then + echo "CHANGELOG.md has no section for $VERSION" >&2 exit 1 fi - - run: npm publish --provenance --access public + + - name: Publish to npm + if: steps.version.outputs.new == 'true' env: + VERSION: ${{ steps.version.outputs.version }} # Empty once the secret is deleted; npm then uses Trusted Publishing. - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} \ No newline at end of file + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + case "$VERSION" in + *-*) dist_tag=next ;; + *) dist_tag=latest ;; + esac + # prepublishOnly builds the library. + npm publish --provenance --access public --tag "$dist_tag" + + - name: Tag and create the GitHub release + if: steps.version.outputs.new == 'true' + env: + VERSION: ${{ steps.version.outputs.version }} + GH_TOKEN: ${{ github.token }} + run: | + prerelease="" + case "$VERSION" in *-*) prerelease="--prerelease" ;; esac + gh release create "v$VERSION" --target "$GITHUB_SHA" --title "v$VERSION" --notes-file release-notes.md $prerelease diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..0b95780 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,6 @@ +dist +coverage +pnpm-lock.yaml +public +# Prose is wrapped and aligned by hand. +*.md diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..1eb3bec --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/prettierrc", + "tabWidth": 2, + "useTabs": false, + "printWidth": 140, + "singleQuote": true, + "semi": true, + "trailingComma": "all", + "arrowParens": "always", + "endOfLine": "lf" +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index d73b2f0..ef0b29b 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,3 @@ { - "recommendations": ["dbaeumer.vscode-eslint", "editorconfig.editorconfig"] + "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "editorconfig.editorconfig"] } diff --git a/CHANGELOG.md b/CHANGELOG.md index fb24434..c7cea7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.1.0 — 2026-10-13 + +### Added +- Elbow and curved lines and arrows. The style panel's new *Shape* option sets a line or arrow to straight, elbow (right-angled turns, like a flowchart connector) or curve (a smooth curve that follows your drag). It also changes the shape of selected lines. +- `LinearShape` gains optional `via` (points the line passes through) and `curved`. Lines without them are straight, as before, so existing documents are unchanged; older versions of the library draw new elbow and curved lines as straight lines. +- `LineRoute` type export and a `lineRoute` field in `StyleState`. + ## 1.0.0 — 2026-10-08 A rewrite of the original canvas drawing prototype. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f947879..a4d67fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,11 +17,14 @@ Node.js 24+ and pnpm 10+ are required (`.nvmrc` pins 24; installs fail on older ## Before opening a pull request ```bash +pnpm format # Prettier: 2-space indentation, single quotes, semicolons pnpm lint pnpm typecheck pnpm test ``` +Code style is set by `.prettierrc.json` and `.editorconfig`; editors with the Prettier and EditorConfig extensions apply it on save. CI runs `pnpm format:check`. + - Keep the library (`src/whiteboard`) free of runtime dependencies other than React. - Add or update tests in `tests/` for behaviour changes (`tests/.test.ts`). Pure logic lives in `geometry.ts`, `shapes.ts`, `history.ts` and `export.ts`, which are easy to unit test. - New UI strings go into **both** locales in `src/whiteboard/i18n.ts`. @@ -34,6 +37,7 @@ pnpm test | `src/whiteboard/types.ts` | Shape and state types | | `src/whiteboard/geometry.ts` | Bounds, hit-testing, camera math, path smoothing | | `src/whiteboard/shapes.ts` | Creating / updating / styling shapes | +| `src/whiteboard/linear.ts` | Elbow and curved lines: points, curves, simplifying a drawn curve | | `src/whiteboard/render.ts` | Canvas renderer | | `src/whiteboard/export.ts` | SVG / PNG / JSON import & export | | `src/whiteboard/history.ts` | Undo/redo reducer | @@ -47,6 +51,10 @@ pnpm test 2. Handle it in `getBounds`, `hitTest`, `translateShape` (`geometry.ts`), `createShape` / `updateDraft` / `finalizeShape` (`shapes.ts`), `drawShape` (`render.ts`), `shapeToSvg` and `isValidShape` (`export.ts`). 3. Add a tool entry in `constants.ts`, an icon in `icons.tsx` and labels in `i18n.ts`. +## Releasing + +The version in `package.json` is the release switch. To release, bump it in your pull request (semver: `fix` → patch, `feat` → minor, breaking → major) and add a `## X.Y.Z — date` section at the top of `CHANGELOG.md`; CI fails without it. Once the pull request is merged into `main`, the release workflow publishes to npm, tags `vX.Y.Z` and creates a GitHub release from that section. A version with a pre-release suffix (`1.2.0-beta.1`) is published under the `next` dist-tag. + ## Commit messages Conventional Commits are preferred: `feat: …`, `fix: …`, `docs: …`, `chore: …`. diff --git a/README.md b/README.md index 13b2fec..fb6f9a1 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Infinite canvas, shapes, text, selection, undo and PNG / SVG export — about 23 - **Export** — PNG, SVG, copy PNG to clipboard, save/open `.json` (also by drag-and-drop) - **Keyboard first** — single-key tool shortcuts, Shift to constrain angles and squares, arrow keys to nudge, `?` for the cheat sheet - **Feels like a pen** — strokes follow Apple Pencil / tablet pressure (or drawing speed with a mouse or finger) and taper at both ends +- **Elbow and curved arrows** — lines and arrows can be straight, turn at right angles like a flowchart connector, or follow your drag as a smooth curve - **Rub-out eraser** — erase just the part of a stroke you rub over, or switch to removing whole shapes - **Touch & stylus** — Pointer Events with coalesced samples, two-finger pinch zoom - **Autosave** to `localStorage`, **dark mode**, **English / 中文 UI** @@ -201,7 +202,7 @@ src/ tests/ Vitest unit and component tests ``` -The website deploys to GitHub Pages from `main` (see `.github/workflows/deploy.yml`). Pushing a `v*` tag publishes the package to npm (needs an `NPM_TOKEN` secret). +The website deploys to GitHub Pages from `main` (see `.github/workflows/deploy.yml`). Merging a version bump into `main` publishes it to npm: bump `version` in `package.json` and add a matching section to `CHANGELOG.md` in the pull request, and `.github/workflows/release.yml` publishes it, tags `vX.Y.Z` and creates a GitHub release from that section. Changes that keep the version publish nothing. ## Contributing diff --git a/README.zh-CN.md b/README.zh-CN.md index c6db3e7..f9491b2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -25,6 +25,7 @@ - **导出**:PNG、SVG、复制 PNG 到剪贴板,保存 / 打开 `.json`(支持拖拽文件进画布) - **键盘优先**:单键切换工具,Shift 锁定角度 / 正方形,方向键微调,按 `?` 查看全部快捷键 - **像真笔一样**:线条粗细跟随 Apple Pencil / 数位板的压力变化(用鼠标或手指时随书写速度变化),起笔收笔自然变尖 +- **折线和曲线箭头**:直线和箭头可以是直的,可以像流程图连线一样直角拐弯,也可以顺着拖动的轨迹画成平滑曲线 - **局部擦除**:只擦掉划过的那一段笔画,也可以切换成整笔删除 - **触屏与手写笔**:基于 Pointer Events 并读取合并采样点,支持双指缩放 - **自动保存**到 `localStorage`,**深色模式**,**中英文界面** @@ -156,7 +157,7 @@ pnpm build:lib # 组件库 → dist/lib - `src/app/`:`/board/` 全屏白板 - `tests/`:Vitest 单元测试和组件测试 -推送到 `main` 会自动部署官网到 GitHub Pages;推送 `v*` 标签会发布到 npm(需要配置 `NPM_TOKEN` secret)。 +推送到 `main` 会自动部署官网到 GitHub Pages;版本号就是发布开关:在 PR 里把 `package.json` 的 `version` 升级,并在 `CHANGELOG.md` 里加上对应版本的一节,合入 `main` 后 `.github/workflows/release.yml` 会发布到 npm、打上 `vX.Y.Z` 标签,并用这一节创建 GitHub Release;不改版本号的合入不会发布。 ## 参与贡献 diff --git a/board/index.html b/board/index.html index 639b3ec..9ea3a09 100644 --- a/board/index.html +++ b/board/index.html @@ -5,13 +5,23 @@ - + Whiteboard · react-whiteboard diff --git a/docs/screenshot-en-dark.png b/docs/screenshot-en-dark.png index b4281a2..89489dc 100644 Binary files a/docs/screenshot-en-dark.png and b/docs/screenshot-en-dark.png differ diff --git a/docs/screenshot-en-light.png b/docs/screenshot-en-light.png index 829c931..31ad6e2 100644 Binary files a/docs/screenshot-en-light.png and b/docs/screenshot-en-light.png differ diff --git a/docs/screenshot-zh-dark.png b/docs/screenshot-zh-dark.png index 070d4f4..6a218ac 100644 Binary files a/docs/screenshot-zh-dark.png and b/docs/screenshot-zh-dark.png differ diff --git a/docs/screenshot-zh-light.png b/docs/screenshot-zh-light.png index 76d5191..2c9304e 100644 Binary files a/docs/screenshot-zh-light.png and b/docs/screenshot-zh-light.png differ diff --git a/eslint.config.js b/eslint.config.js index 2c498ed..c22ee5d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -5,26 +5,23 @@ import reactRefresh from 'eslint-plugin-react-refresh'; import tseslint from 'typescript-eslint'; export default tseslint.config( - { ignores: ['dist', 'coverage'] }, - { - extends: [js.configs.recommended, ...tseslint.configs.recommended], - files: ['**/*.{ts,tsx}'], - languageOptions: { - ecmaVersion: 2022, - globals: globals.browser, - }, - plugins: { - 'react-hooks': reactHooks, - 'react-refresh': reactRefresh, - }, - rules: { - ...reactHooks.configs.recommended.rules, - 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], - quotes: ['error', 'single', { avoidEscape: true }], - semi: ['error', 'always'], - 'eol-last': ['error', 'always'], - indent: ['error', 4, { SwitchCase: 1 }], - 'no-console': 'warn', - }, + { ignores: ['dist', 'coverage'] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ['**/*.{ts,tsx}'], + languageOptions: { + ecmaVersion: 2022, + globals: globals.browser, }, + plugins: { + 'react-hooks': reactHooks, + 'react-refresh': reactRefresh, + }, + rules: { + ...reactHooks.configs.recommended.rules, + 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], + // Formatting (indentation, quotes, semicolons) is Prettier's job: `pnpm format`. + 'no-console': 'warn', + }, + }, ); diff --git a/index.html b/index.html index 8b8c889..d1e309b 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,10 @@ react-whiteboard — an open-source whiteboard for React - + @@ -23,7 +26,9 @@ - +
diff --git a/package.json b/package.json index 261d177..9594cef 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@inchill/react-whiteboard", - "version": "1.0.0", + "version": "1.1.0", "description": "A lightweight, zero-dependency infinite-canvas whiteboard component for React.", "keywords": [ "react", @@ -48,6 +48,8 @@ "build:lib": "vite build -c vite.lib.config.ts && tsc -p tsconfig.lib.json", "preview": "vite preview", "lint": "eslint .", + "format": "prettier --write .", + "format:check": "prettier --check .", "typecheck": "tsc -b", "test": "vitest run", "test:watch": "vitest", @@ -75,6 +77,7 @@ "eslint-plugin-react-refresh": "^0.5.7", "globals": "^17.13.0", "jsdom": "^26.1.0", + "prettier": "^3.9.10", "react": "^19.3.0", "react-dom": "^19.3.0", "typescript": "~5.9", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a5b4fd4..5095649 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -59,6 +59,9 @@ importers: jsdom: specifier: ^26.1.0 version: 26.1.0 + prettier: + specifier: ^3.9.10 + version: 3.9.10 react: specifier: ^19.3.0 version: 19.3.0 @@ -1244,6 +1247,11 @@ packages: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} + prettier@3.9.10: + resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==} + engines: {node: '>=14'} + hasBin: true + pretty-format@27.5.1: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} @@ -2633,6 +2641,8 @@ snapshots: prelude-ls@1.2.1: {} + prettier@3.9.10: {} + pretty-format@27.5.1: dependencies: ansi-regex: 5.0.1 diff --git a/src/app/main.tsx b/src/app/main.tsx index e0ed2cf..963c622 100644 --- a/src/app/main.tsx +++ b/src/app/main.tsx @@ -4,7 +4,7 @@ import { Whiteboard } from '../whiteboard'; import { REPO_URL } from '../site/links'; createRoot(document.getElementById('root')!).render( - - - , + + + , ); diff --git a/src/site/Landing.tsx b/src/site/Landing.tsx index 8a52c55..733f354 100644 --- a/src/site/Landing.tsx +++ b/src/site/Landing.tsx @@ -10,17 +10,17 @@ import { PACKAGE_NAME, REPO_URL } from './links'; const PREF_KEY = 'react-whiteboard:site'; function readPrefs(): { theme?: Theme; locale?: Locale } { - try { - return JSON.parse(localStorage.getItem(PREF_KEY) || '{}'); - } catch { - return {}; - } + try { + return JSON.parse(localStorage.getItem(PREF_KEY) || '{}'); + } catch { + return {}; + } } const SNIPPETS = [ - `pnpm add ${PACKAGE_NAME}`, - `import '${PACKAGE_NAME}/style.css';`, - `import { Whiteboard } from '${PACKAGE_NAME}'; + `pnpm add ${PACKAGE_NAME}`, + `import '${PACKAGE_NAME}/style.css';`, + `import { Whiteboard } from '${PACKAGE_NAME}'; export default function App() { return ( @@ -37,294 +37,305 @@ const NOTE_COLORS = ['yellow', 'pink', 'blue', 'green']; /** A tiny highlighter for the three snippets above — just enough to read like code. */ function highlight(code: string): ReactNode[] { - const pattern = /('[^']*')|\b(import|from|export|default|function|return)\b|(<\/?[A-Za-z]+|\/?>)|(pnpm|add)\b/g; - const out: ReactNode[] = []; - let last = 0; - let m: RegExpExecArray | null; - while ((m = pattern.exec(code))) { - if (m.index > last) out.push(code.slice(last, m.index)); - const cls = m[1] ? 'tok-str' : m[2] ? 'tok-kw' : m[3] ? 'tok-tag' : 'tok-cmd'; - out.push( - - {m[0]} - , - ); - last = m.index + m[0].length; - } - out.push(code.slice(last)); - return out; + const pattern = /('[^']*')|\b(import|from|export|default|function|return)\b|(<\/?[A-Za-z]+|\/?>)|(pnpm|add)\b/g; + const out: ReactNode[] = []; + let last = 0; + let m: RegExpExecArray | null; + while ((m = pattern.exec(code))) { + if (m.index > last) out.push(code.slice(last, m.index)); + const cls = m[1] ? 'tok-str' : m[2] ? 'tok-kw' : m[3] ? 'tok-tag' : 'tok-cmd'; + out.push( + + {m[0]} + , + ); + last = m.index + m[0].length; + } + out.push(code.slice(last)); + return out; } function CodeBlock({ code, copyLabel, copiedLabel }: { code: string; copyLabel: string; copiedLabel: string }) { - const [copied, setCopied] = useState(false); - useEffect(() => { - if (!copied) return; - const id = setTimeout(() => setCopied(false), 1500); - return () => clearTimeout(id); - }, [copied]); - return ( -
-
-                {highlight(code)}
-            
- -
- ); + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) return; + const id = setTimeout(() => setCopied(false), 1500); + return () => clearTimeout(id); + }, [copied]); + return ( +
+
+        {highlight(code)}
+      
+ +
+ ); } /** Hand-drawn marker arrow used for the annotations around the demo board. */ function ScribbleArrow({ className }: { className?: string }) { - return ( - - ); + return ( + + ); } export function Landing() { - const [prefs] = useState(readPrefs); - const systemDark = typeof matchMedia !== 'undefined' && matchMedia('(prefers-color-scheme: dark)').matches; - const [theme, setTheme] = useState(prefs.theme ?? (systemDark ? 'dark' : 'light')); - const [locale, setLocale] = useState(prefs.locale ?? detectLocale()); - const boardRef = useRef(null); - const dirtyRef = useRef(false); - // setShapes() from the page itself triggers onChange; don't count that as the visitor drawing. - const programmaticRef = useRef(false); - const c = SITE_COPY[locale]; + const [prefs] = useState(readPrefs); + const systemDark = typeof matchMedia !== 'undefined' && matchMedia('(prefers-color-scheme: dark)').matches; + const [theme, setTheme] = useState(prefs.theme ?? (systemDark ? 'dark' : 'light')); + const [locale, setLocale] = useState(prefs.locale ?? detectLocale()); + const boardRef = useRef(null); + const dirtyRef = useRef(false); + // setShapes() from the page itself triggers onChange; don't count that as the visitor drawing. + const programmaticRef = useRef(false); + const c = SITE_COPY[locale]; - useEffect(() => { - document.documentElement.dataset.theme = theme; - document.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en'; - document.title = locale === 'zh' ? 'react-whiteboard —— 开源 React 白板组件' : 'react-whiteboard — an open-source whiteboard for React'; - try { - localStorage.setItem(PREF_KEY, JSON.stringify({ theme, locale })); - } catch { - /* storage unavailable */ - } - }, [theme, locale]); + useEffect(() => { + document.documentElement.dataset.theme = theme; + document.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en'; + document.title = locale === 'zh' ? 'react-whiteboard —— 开源 React 白板组件' : 'react-whiteboard — an open-source whiteboard for React'; + try { + localStorage.setItem(PREF_KEY, JSON.stringify({ theme, locale })); + } catch { + /* storage unavailable */ + } + }, [theme, locale]); - // Re-label the demo sketch when the language changes, unless the visitor has drawn on it. - const firstLocale = useRef(locale); - useEffect(() => { - if (locale === firstLocale.current || dirtyRef.current) return; - programmaticRef.current = true; - boardRef.current?.setShapes(demoShapes(locale), { history: false }); - }, [locale]); + // Re-label the demo sketch when the language changes, unless the visitor has drawn on it. + const firstLocale = useRef(locale); + useEffect(() => { + if (locale === firstLocale.current || dirtyRef.current) return; + programmaticRef.current = true; + boardRef.current?.setShapes(demoShapes(locale), { history: false }); + }, [locale]); - const resetDemo = () => { - programmaticRef.current = true; - dirtyRef.current = false; - boardRef.current?.setShapes(demoShapes(locale), { history: false }); - requestAnimationFrame(() => boardRef.current?.zoomToFit()); - }; + const resetDemo = () => { + programmaticRef.current = true; + dirtyRef.current = false; + boardRef.current?.setShapes(demoShapes(locale), { history: false }); + requestAnimationFrame(() => boardRef.current?.zoomToFit()); + }; - return ( -
- - Skip to content + return ( +
+ + Skip to content + +
+
+ + + react-whiteboard + + +
+ + + + -
-
- - - react-whiteboard - - -
- - - - - -
-
-
+
+
+
-
-
-
-

- {c.title.split('\n').map((line) => ( - {line} - ))} -

-
-

{c.lede}

- -
    - {c.badges.map((b) => ( -
  • {b}
  • - ))} -
-
-
+
+
+
+

+ {c.title.split('\n').map((line) => ( + {line} + ))} +

+
+

{c.lede}

+ +
    + {c.badges.map((b) => ( +
  • {b}
  • + ))} +
+
+
-
- - -
- { - if (programmaticRef.current) programmaticRef.current = false; - else dirtyRef.current = true; - }} - /> -
- -
- {c.caption} - -
-
-
+
+ + +
+ { + if (programmaticRef.current) programmaticRef.current = false; + else dirtyRef.current = true; + }} + /> +
+ +
+ {c.caption} + +
+
+
-
-

{c.useTitle}

-

{c.useLede}

-
    - {c.steps.map((step, i) => ( -
  1. -
    -

    {step.title}

    -

    {step.body}

    -
    - -
  2. - ))} -
-
+
+

{c.useTitle}

+

{c.useLede}

+
    + {c.steps.map((step, i) => ( +
  1. +
    +

    {step.title}

    +

    {step.body}

    +
    + +
  2. + ))} +
+
-
-

{c.featuresTitle}

-
    - {c.features.map((f, i) => { - const Icon = FEATURE_ICONS[i] ?? Icons.pen; - return ( -
  • - -

    {f.title}

    -

    {f.body}

    -
  • - ); - })} -
-
+
+

{c.featuresTitle}

+
    + {c.features.map((f, i) => { + const Icon = FEATURE_ICONS[i] ?? Icons.pen; + return ( +
  • + +

    {f.title}

    +

    {f.body}

    +
  • + ); + })} +
+
-
-

{c.apiTitle}

-

{c.apiLede}

-

{c.propsHeading}

-
- - - - - - - - - - {c.props.map(([name, type, desc]) => ( - - - - - - ))} - -
{c.col.name}{c.col.type}{c.col.desc}
- {name} - - {type} - {desc}
-
-

{c.handleHeading}

-
- - - {c.handle.map(([name, desc]) => ( - - - - - ))} - -
- {name} - {desc}
-
-
+
+

{c.apiTitle}

+

{c.apiLede}

+

{c.propsHeading}

+
+ + + + + + + + + + {c.props.map(([name, type, desc]) => ( + + + + + + ))} + +
{c.col.name}{c.col.type}{c.col.desc}
+ {name} + + {type} + {desc}
+
+

{c.handleHeading}

+
+ + + {c.handle.map(([name, desc]) => ( + + + + + ))} + +
+ {name} + {desc}
+
+
-
-
-

{c.endTitle}

-

{c.endBody}

- - - {c.openBoard} - - -
-
-
+
+
+

{c.endTitle}

+

{c.endBody}

+ + + {c.openBoard} + + +
+
+ - -
- ); + +
+ ); } diff --git a/src/site/copy.ts b/src/site/copy.ts index f3a2e96..7ce7153 100644 --- a/src/site/copy.ts +++ b/src/site/copy.ts @@ -1,163 +1,172 @@ import type { Locale } from '../whiteboard/types'; export type SiteCopy = { - nav: { use: string; features: string; api: string }; - title: string; - lede: string; - openBoard: string; - github: string; - caption: string; - reset: string; - useTitle: string; - useLede: string; - steps: { title: string; body: string }[]; - copy: string; - copied: string; - featuresTitle: string; - features: { title: string; body: string }[]; - apiTitle: string; - apiLede: string; - propsHeading: string; - handleHeading: string; - col: { name: string; type: string; desc: string }; - props: [string, string, string][]; - handle: [string, string][]; - footer: string; - badges: string[]; - noteTools: string; - noteDraw: string; - endTitle: string; - endBody: string; - themeToggle: string; - langToggle: string; + nav: { use: string; features: string; api: string }; + title: string; + lede: string; + openBoard: string; + github: string; + caption: string; + reset: string; + useTitle: string; + useLede: string; + steps: { title: string; body: string }[]; + copy: string; + copied: string; + featuresTitle: string; + features: { title: string; body: string }[]; + apiTitle: string; + apiLede: string; + propsHeading: string; + handleHeading: string; + col: { name: string; type: string; desc: string }; + props: [string, string, string][]; + handle: [string, string][]; + footer: string; + badges: string[]; + noteTools: string; + noteDraw: string; + endTitle: string; + endBody: string; + themeToggle: string; + langToggle: string; }; const en: SiteCopy = { - nav: { use: 'Get started', features: 'Features', api: 'API' }, - title: 'A whiteboard you can drop into any React app.', - lede: 'Infinite canvas, shapes, text, selection, undo and export to PNG or SVG. One component, about 23 kB gzipped, with no dependencies beyond React.', - openBoard: 'Open the full board', - github: 'View on GitHub', - caption: 'That is the real component, not a screenshot. Draw on it.', - reset: 'Reset demo', - useTitle: 'Get started', - useLede: 'Give the board a parent with a height and you are done. Drawings autosave to localStorage by default.', - steps: [ - { title: 'Install', body: 'Add the package with pnpm (npm and yarn work too).' }, - { title: 'Import the styles', body: 'Load the stylesheet once, anywhere in your app.' }, - { title: 'Render it', body: 'The board fills its parent, so give the parent a size.' }, - ], - copy: 'Copy', - copied: 'Copied', - featuresTitle: 'What it does', - features: [ - { title: 'Eleven tools', body: 'Select, pan, pen, highlighter, eraser, line, arrow, rectangle, ellipse, triangle and text.' }, - { title: 'Vector, not pixels', body: 'Every stroke is a shape you can select, move, restyle, reorder or delete. Resizing the window never loses work.' }, - { title: 'Infinite canvas', body: 'Pan with the hand tool, Space or the trackpad; zoom with Ctrl + wheel or a two-finger pinch.' }, - { title: 'Rub-out eraser', body: 'Erase just the part of a stroke you rub over, or switch to removing whole shapes. Every swipe is one undo step.' }, - { title: 'Export anywhere', body: 'PNG, SVG and a JSON file you can open again later. Copy a PNG straight to the clipboard.' }, - { title: 'Keyboard first', body: 'Single-key tool shortcuts, Shift to constrain angles and squares, arrow keys to nudge.' }, - { title: 'Feels like a pen', body: 'Strokes follow Apple Pencil and tablet pressure, or drawing speed with a mouse, and taper at both ends.' }, - { title: 'Light, dark, 中文', body: 'Built-in dark theme and English / Chinese UI, both controllable from props.' }, - ], - apiTitle: 'API', - apiLede: 'Everything is optional. Use a ref when you need to read or replace the drawing from outside.', - propsHeading: 'Props', - handleHeading: 'Ref methods', - col: { name: 'Name', type: 'Type', desc: 'Description' }, - props: [ - ['storageKey', 'string | null', 'localStorage key for autosave. Default "react-whiteboard"; null turns it off.'], - ['initialShapes', 'Shape[]', 'Shapes to start with when nothing is saved.'], - ['theme', '"light" | "dark"', 'Controls the theme. Leave unset to let users toggle it.'], - ['locale', '"en" | "zh"', 'Controls the UI language. Detected from the browser when unset.'], - ['initialTool', 'Tool', 'Tool selected on mount. Default "pen".'], - ['tools', 'Tool[]', 'Tools shown in the toolbar, in order. For example ["pen", "highlighter", "eraser"] for a doodle pad.'], - ['onChange', '(shapes) => void', 'Called after each committed change.'], - ['globalShortcuts', 'boolean', 'Listen for shortcuts on window. Default true; set false when embedding.'], - ['captureWheel', 'boolean', 'Plain wheel pans the canvas. Set false inside scrolling pages.'], - ['showMenu', 'boolean', 'Show the main menu with file, export and settings. Default true.'], - ], - handle: [ - ['getShapes()', 'Current shapes.'], - ['setShapes(shapes, { history })', 'Replace the drawing, as an undo step unless history is false.'], - ['undo() / redo() / clear()', 'Same as the toolbar buttons.'], - ['exportPng(options)', 'Resolves to a PNG Blob.'], - ['exportSvg(options)', 'Returns an SVG string.'], - ['exportJson()', 'Returns the JSON that the Open menu item reads back.'], - ['zoomToFit()', 'Fit all content in view.'], - ], - footer: 'MIT licensed. Made by Inchill and contributors.', - badges: ['MIT licensed', '~23 kB gzipped', 'React 18 & 19', 'TypeScript'], - noteTools: 'pick a tool', - noteDraw: 'scribble anywhere!', - endTitle: 'Your turn.', - endBody: 'Open a blank board in your browser. Nothing to install, and your drawing stays on your device.', - themeToggle: 'Toggle dark mode', - langToggle: '中文', + nav: { use: 'Get started', features: 'Features', api: 'API' }, + title: 'A whiteboard you can drop into any React app.', + lede: 'Infinite canvas, shapes, text, selection, undo and export to PNG or SVG. One component, about 23 kB gzipped, with no dependencies beyond React.', + openBoard: 'Open the full board', + github: 'View on GitHub', + caption: 'That is the real component, not a screenshot. Draw on it.', + reset: 'Reset demo', + useTitle: 'Get started', + useLede: 'Give the board a parent with a height and you are done. Drawings autosave to localStorage by default.', + steps: [ + { title: 'Install', body: 'Add the package with pnpm (npm and yarn work too).' }, + { title: 'Import the styles', body: 'Load the stylesheet once, anywhere in your app.' }, + { title: 'Render it', body: 'The board fills its parent, so give the parent a size.' }, + ], + copy: 'Copy', + copied: 'Copied', + featuresTitle: 'What it does', + features: [ + { title: 'Eleven tools', body: 'Select, pan, pen, highlighter, eraser, line, arrow, rectangle, ellipse, triangle and text.' }, + { + title: 'Vector, not pixels', + body: 'Every stroke is a shape you can select, move, restyle, reorder or delete. Resizing the window never loses work.', + }, + { title: 'Infinite canvas', body: 'Pan with the hand tool, Space or the trackpad; zoom with Ctrl + wheel or a two-finger pinch.' }, + { + title: 'Rub-out eraser', + body: 'Erase just the part of a stroke you rub over, or switch to removing whole shapes. Every swipe is one undo step.', + }, + { title: 'Export anywhere', body: 'PNG, SVG and a JSON file you can open again later. Copy a PNG straight to the clipboard.' }, + { title: 'Keyboard first', body: 'Single-key tool shortcuts, Shift to constrain angles and squares, arrow keys to nudge.' }, + { + title: 'Feels like a pen', + body: 'Strokes follow Apple Pencil and tablet pressure, or drawing speed with a mouse, and taper at both ends.', + }, + { title: 'Light, dark, 中文', body: 'Built-in dark theme and English / Chinese UI, both controllable from props.' }, + ], + apiTitle: 'API', + apiLede: 'Everything is optional. Use a ref when you need to read or replace the drawing from outside.', + propsHeading: 'Props', + handleHeading: 'Ref methods', + col: { name: 'Name', type: 'Type', desc: 'Description' }, + props: [ + ['storageKey', 'string | null', 'localStorage key for autosave. Default "react-whiteboard"; null turns it off.'], + ['initialShapes', 'Shape[]', 'Shapes to start with when nothing is saved.'], + ['theme', '"light" | "dark"', 'Controls the theme. Leave unset to let users toggle it.'], + ['locale', '"en" | "zh"', 'Controls the UI language. Detected from the browser when unset.'], + ['initialTool', 'Tool', 'Tool selected on mount. Default "pen".'], + ['tools', 'Tool[]', 'Tools shown in the toolbar, in order. For example ["pen", "highlighter", "eraser"] for a doodle pad.'], + ['onChange', '(shapes) => void', 'Called after each committed change.'], + ['globalShortcuts', 'boolean', 'Listen for shortcuts on window. Default true; set false when embedding.'], + ['captureWheel', 'boolean', 'Plain wheel pans the canvas. Set false inside scrolling pages.'], + ['showMenu', 'boolean', 'Show the main menu with file, export and settings. Default true.'], + ], + handle: [ + ['getShapes()', 'Current shapes.'], + ['setShapes(shapes, { history })', 'Replace the drawing, as an undo step unless history is false.'], + ['undo() / redo() / clear()', 'Same as the toolbar buttons.'], + ['exportPng(options)', 'Resolves to a PNG Blob.'], + ['exportSvg(options)', 'Returns an SVG string.'], + ['exportJson()', 'Returns the JSON that the Open menu item reads back.'], + ['zoomToFit()', 'Fit all content in view.'], + ], + footer: 'MIT licensed. Made by Inchill and contributors.', + badges: ['MIT licensed', '~23 kB gzipped', 'React 18 & 19', 'TypeScript'], + noteTools: 'pick a tool', + noteDraw: 'scribble anywhere!', + endTitle: 'Your turn.', + endBody: 'Open a blank board in your browser. Nothing to install, and your drawing stays on your device.', + themeToggle: 'Toggle dark mode', + langToggle: '中文', }; const zh: SiteCopy = { - nav: { use: '快速开始', features: '功能', api: 'API' }, - title: '一块白板,\n放进任何 React 应用。', - lede: '无限画布、图形、文字、选择移动、撤销重做,还能导出 PNG 和 SVG。只有一个组件,gzip 后约 23 kB,除了 React 没有其他依赖。', - openBoard: '打开完整白板', - github: '在 GitHub 查看', - caption: '上面就是组件本身,不是截图,可以直接画。', - reset: '重置示例', - useTitle: '快速开始', - useLede: '给白板一个有高度的父元素就能用。画的内容默认自动保存在 localStorage。', - steps: [ - { title: '安装', body: '用 pnpm 安装(npm、yarn 也可以)。' }, - { title: '引入样式', body: '在应用里任意位置引入一次样式表。' }, - { title: '渲染组件', body: '白板会撑满父元素,所以父元素要有尺寸。' }, - ], - copy: '复制', - copied: '已复制', - featuresTitle: '能做什么', - features: [ - { title: '11 种工具', body: '选择、抓手、画笔、荧光笔、橡皮擦、直线、箭头、矩形、椭圆、三角形和文字。' }, - { title: '矢量,而非像素', body: '每一笔都是可以选中、移动、改样式、调层级、删除的图形,调整窗口大小也不会丢内容。' }, - { title: '无限画布', body: '用抓手、空格或触控板平移;Ctrl + 滚轮或双指捏合缩放。' }, - { title: '局部擦除', body: '只擦掉划过的那一段笔画,也能切换成整笔删除。每擦一下都能单独撤销。' }, - { title: '多种导出', body: '导出 PNG、SVG,或保存成 JSON 以后再打开,也能一键复制 PNG 到剪贴板。' }, - { title: '键盘优先', body: '单键切换工具,按住 Shift 锁定角度和正方形,方向键微调位置。' }, - { title: '像真笔一样', body: '线条粗细跟随 Apple Pencil、数位板的压力,用鼠标时随书写速度变化,起笔收笔自然变尖。' }, - { title: '深色模式与中英文', body: '内置深色主题和中英文界面,也可以通过 props 控制。' }, - ], - apiTitle: 'API', - apiLede: '所有参数都是可选的。需要从外部读取或替换画板内容时,用 ref。', - propsHeading: 'Props', - handleHeading: 'Ref 方法', - col: { name: '名称', type: '类型', desc: '说明' }, - props: [ - ['storageKey', 'string | null', '自动保存用的 localStorage key,默认 "react-whiteboard",传 null 关闭。'], - ['initialShapes', 'Shape[]', '没有已保存内容时的初始图形。'], - ['theme', '"light" | "dark"', '受控主题。不传则由用户在菜单中切换。'], - ['locale', '"en" | "zh"', '受控界面语言。不传则根据浏览器自动判断。'], - ['initialTool', 'Tool', '初始工具,默认 "pen"。'], - ['tools', 'Tool[]', '工具栏显示的工具及顺序,例如 ["pen", "highlighter", "eraser"] 就是一个涂鸦板。'], - ['onChange', '(shapes) => void', '每次提交修改后调用。'], - ['globalShortcuts', 'boolean', '在 window 上监听快捷键,默认 true;嵌入页面时建议 false。'], - ['captureWheel', 'boolean', '普通滚轮用于平移画布。放在可滚动页面里时设为 false。'], - ['showMenu', 'boolean', '是否显示主菜单(文件、导出、设置),默认 true。'], - ], - handle: [ - ['getShapes()', '获取当前所有图形。'], - ['setShapes(shapes, { history })', '替换画板内容;除非 history 为 false,否则可撤销。'], - ['undo() / redo() / clear()', '与工具栏按钮相同。'], - ['exportPng(options)', '返回 PNG Blob 的 Promise。'], - ['exportSvg(options)', '返回 SVG 字符串。'], - ['exportJson()', '返回 JSON,可通过菜单里的“打开”重新载入。'], - ['zoomToFit()', '缩放到能看到全部内容。'], - ], - footer: '基于 MIT 协议开源。由 Inchill 和贡献者维护。', - badges: ['MIT 开源', 'gzip 约 23 kB', '支持 React 18 / 19', 'TypeScript'], - noteTools: '选个工具', - noteDraw: '随便画画!', - endTitle: '轮到你了。', - endBody: '在浏览器里打开一块空白画板。不用安装,画的内容只保存在你自己的设备上。', - themeToggle: '切换深色模式', - langToggle: 'English', + nav: { use: '快速开始', features: '功能', api: 'API' }, + title: '一块白板,\n放进任何 React 应用。', + lede: '无限画布、图形、文字、选择移动、撤销重做,还能导出 PNG 和 SVG。只有一个组件,gzip 后约 23 kB,除了 React 没有其他依赖。', + openBoard: '打开完整白板', + github: '在 GitHub 查看', + caption: '上面就是组件本身,不是截图,可以直接画。', + reset: '重置示例', + useTitle: '快速开始', + useLede: '给白板一个有高度的父元素就能用。画的内容默认自动保存在 localStorage。', + steps: [ + { title: '安装', body: '用 pnpm 安装(npm、yarn 也可以)。' }, + { title: '引入样式', body: '在应用里任意位置引入一次样式表。' }, + { title: '渲染组件', body: '白板会撑满父元素,所以父元素要有尺寸。' }, + ], + copy: '复制', + copied: '已复制', + featuresTitle: '能做什么', + features: [ + { title: '11 种工具', body: '选择、抓手、画笔、荧光笔、橡皮擦、直线、箭头、矩形、椭圆、三角形和文字。' }, + { title: '矢量,而非像素', body: '每一笔都是可以选中、移动、改样式、调层级、删除的图形,调整窗口大小也不会丢内容。' }, + { title: '无限画布', body: '用抓手、空格或触控板平移;Ctrl + 滚轮或双指捏合缩放。' }, + { title: '局部擦除', body: '只擦掉划过的那一段笔画,也能切换成整笔删除。每擦一下都能单独撤销。' }, + { title: '多种导出', body: '导出 PNG、SVG,或保存成 JSON 以后再打开,也能一键复制 PNG 到剪贴板。' }, + { title: '键盘优先', body: '单键切换工具,按住 Shift 锁定角度和正方形,方向键微调位置。' }, + { title: '像真笔一样', body: '线条粗细跟随 Apple Pencil、数位板的压力,用鼠标时随书写速度变化,起笔收笔自然变尖。' }, + { title: '深色模式与中英文', body: '内置深色主题和中英文界面,也可以通过 props 控制。' }, + ], + apiTitle: 'API', + apiLede: '所有参数都是可选的。需要从外部读取或替换画板内容时,用 ref。', + propsHeading: 'Props', + handleHeading: 'Ref 方法', + col: { name: '名称', type: '类型', desc: '说明' }, + props: [ + ['storageKey', 'string | null', '自动保存用的 localStorage key,默认 "react-whiteboard",传 null 关闭。'], + ['initialShapes', 'Shape[]', '没有已保存内容时的初始图形。'], + ['theme', '"light" | "dark"', '受控主题。不传则由用户在菜单中切换。'], + ['locale', '"en" | "zh"', '受控界面语言。不传则根据浏览器自动判断。'], + ['initialTool', 'Tool', '初始工具,默认 "pen"。'], + ['tools', 'Tool[]', '工具栏显示的工具及顺序,例如 ["pen", "highlighter", "eraser"] 就是一个涂鸦板。'], + ['onChange', '(shapes) => void', '每次提交修改后调用。'], + ['globalShortcuts', 'boolean', '在 window 上监听快捷键,默认 true;嵌入页面时建议 false。'], + ['captureWheel', 'boolean', '普通滚轮用于平移画布。放在可滚动页面里时设为 false。'], + ['showMenu', 'boolean', '是否显示主菜单(文件、导出、设置),默认 true。'], + ], + handle: [ + ['getShapes()', '获取当前所有图形。'], + ['setShapes(shapes, { history })', '替换画板内容;除非 history 为 false,否则可撤销。'], + ['undo() / redo() / clear()', '与工具栏按钮相同。'], + ['exportPng(options)', '返回 PNG Blob 的 Promise。'], + ['exportSvg(options)', '返回 SVG 字符串。'], + ['exportJson()', '返回 JSON,可通过菜单里的“打开”重新载入。'], + ['zoomToFit()', '缩放到能看到全部内容。'], + ], + footer: '基于 MIT 协议开源。由 Inchill 和贡献者维护。', + badges: ['MIT 开源', 'gzip 约 23 kB', '支持 React 18 / 19', 'TypeScript'], + noteTools: '选个工具', + noteDraw: '随便画画!', + endTitle: '轮到你了。', + endBody: '在浏览器里打开一块空白画板。不用安装,画的内容只保存在你自己的设备上。', + themeToggle: '切换深色模式', + langToggle: 'English', }; export const SITE_COPY: Record = { en, zh }; diff --git a/src/site/demo.ts b/src/site/demo.ts index 20b705e..11c1944 100644 --- a/src/site/demo.ts +++ b/src/site/demo.ts @@ -5,42 +5,95 @@ import type { Locale } from '../whiteboard/types'; const base = { strokeStyle: 'solid' as const }; function text(id: string, x: number, y: number, value: string, fontSize: number, color = INK): Shape { - return { ...base, id, type: 'text', x, y, text: value, fontSize, color, strokeWidth: 1, ...measureText(value, fontSize) }; + return { ...base, id, type: 'text', x, y, text: value, fontSize, color, strokeWidth: 1, ...measureText(value, fontSize) }; } /** The sketch shown in the landing-page hero. Real shapes, fully editable. */ export function demoShapes(locale: Locale): Shape[] { - const zh = locale === 'zh'; - const title = zh ? '在这里画画看' : 'Go on, draw here'; - const sub = zh ? '拖动、擦除、写字都行 —— 按 ? 查看快捷键' : 'Move things, erase them, add text. Press ? for shortcuts.'; - const titleSize = measureText(title, 56); - const squiggle: [number, number, number][] = []; - for (let i = 0; i <= 48; i++) { - const a = (i / 48) * Math.PI * 4; - // Pressure swells along the stroke, like a real pen. - squiggle.push([760 + i * 4.2, 300 + Math.sin(a) * 14 + i * 0.4, 0.35 + 0.5 * Math.sin((i / 48) * Math.PI)]); - } - return [ - { - ...base, - id: 'demo-hl', - type: 'highlighter', - color: '#fab005', - strokeWidth: 22, - points: [ - [-6, 58], - [titleSize.w * 0.5, 56], - [titleSize.w + 8, 54], - ], - }, - text('demo-title', 0, 0, title, 56), - text('demo-sub', 2, 92, sub, 22, '#5d6573'), - { ...base, id: 'demo-box', type: 'rect', x: 0, y: 190, w: 220, h: 120, fill: 'semi', color: '#1971c2', strokeWidth: 3 }, - text('demo-box-label', 34, 232, zh ? '想法' : 'Idea', 32, '#1971c2'), - { ...base, id: 'demo-arrow', type: 'arrow', x1: 240, y1: 250, x2: 410, y2: 250, color: INK, strokeWidth: 3 }, - { ...base, id: 'demo-oval', type: 'ellipse', x: 430, y: 190, w: 250, h: 120, fill: 'semi', color: '#2f9e44', strokeWidth: 3 }, - text('demo-oval-label', 480, 232, zh ? '上线!' : 'Ship it', 32, '#2f9e44'), - { ...base, id: 'demo-squiggle', type: 'pen', pressure: true, color: '#e03131', strokeWidth: 5, points: squiggle }, - { ...base, id: 'demo-tri', type: 'triangle', x: 800, y: 170, w: 120, h: 100, fill: 'none', color: '#7048e8', strokeWidth: 3, strokeStyle: 'dashed' }, - ]; + const zh = locale === 'zh'; + const title = zh ? '在这里画画看' : 'Go on, draw here'; + const sub = zh ? '拖动、擦除、写字都行 —— 按 ? 查看快捷键' : 'Move things, erase them, add text. Press ? for shortcuts.'; + const titleSize = measureText(title, 56); + const learn = zh ? '复盘' : 'Learn'; + const learnSize = measureText(learn, 28); + const squiggle: [number, number, number][] = []; + for (let i = 0; i <= 48; i++) { + const a = (i / 48) * Math.PI * 4; + // Pressure swells along the stroke, like a real pen. + squiggle.push([760 + i * 4.2, 300 + Math.sin(a) * 14 + i * 0.4, 0.35 + 0.5 * Math.sin((i / 48) * Math.PI)]); + } + return [ + { + ...base, + id: 'demo-hl', + type: 'highlighter', + color: '#fab005', + strokeWidth: 22, + points: [ + [-6, 58], + [titleSize.w * 0.5, 56], + [titleSize.w + 8, 54], + ], + }, + text('demo-title', 0, 0, title, 56), + text('demo-sub', 2, 92, sub, 22, '#5d6573'), + { ...base, id: 'demo-box', type: 'rect', x: 0, y: 190, w: 220, h: 120, fill: 'semi', color: '#1971c2', strokeWidth: 3 }, + text('demo-box-label', 34, 232, zh ? '想法' : 'Idea', 32, '#1971c2'), + // A curved arrow over the top, and elbow arrows around the loop below. + { + ...base, + id: 'demo-arrow', + type: 'arrow', + x1: 190, + y1: 182, + via: [[330, 128]], + curved: true, + x2: 462, + y2: 198, + color: INK, + strokeWidth: 3, + }, + { ...base, id: 'demo-oval', type: 'ellipse', x: 430, y: 190, w: 250, h: 120, fill: 'semi', color: '#2f9e44', strokeWidth: 3 }, + text('demo-oval-label', 480, 232, zh ? '上线!' : 'Ship it', 32, '#2f9e44'), + { + ...base, + id: 'demo-elbow-down', + type: 'arrow', + x1: 555, + y1: 322, + via: [[555, 420]], + x2: 452, + y2: 420, + color: INK, + strokeWidth: 3, + }, + { ...base, id: 'demo-learn', type: 'rect', x: 240, y: 380, w: 200, h: 80, fill: 'semi', color: '#f08c00', strokeWidth: 3 }, + text('demo-learn-label', 240 + (200 - learnSize.w) / 2, 380 + (80 - learnSize.h) / 2, learn, 28, '#f08c00'), + { + ...base, + id: 'demo-elbow-up', + type: 'arrow', + x1: 228, + y1: 420, + via: [[110, 420]], + x2: 110, + y2: 322, + color: INK, + strokeWidth: 3, + }, + { ...base, id: 'demo-squiggle', type: 'pen', pressure: true, color: '#e03131', strokeWidth: 5, points: squiggle }, + { + ...base, + id: 'demo-tri', + type: 'triangle', + x: 800, + y: 170, + w: 120, + h: 100, + fill: 'none', + color: '#7048e8', + strokeWidth: 3, + strokeStyle: 'dashed', + }, + ]; } diff --git a/src/site/main.tsx b/src/site/main.tsx index 0050793..57851c0 100644 --- a/src/site/main.tsx +++ b/src/site/main.tsx @@ -7,7 +7,7 @@ import { Landing } from './Landing'; import './site.css'; createRoot(document.getElementById('root')!).render( - - - , + + + , ); diff --git a/src/site/site.css b/src/site/site.css index a1bede2..0c23521 100644 --- a/src/site/site.css +++ b/src/site/site.css @@ -1,904 +1,909 @@ /* Layout: a clean whiteboard page — dotted canvas background, the live board as hero, marker-colored accents, handwritten annotations and sticky notes. */ :root { - --bg: #ffffff; - --dot: rgba(47, 91, 255, 0.16); - --ink: #14161b; - --muted: #5b6170; - --line: rgba(20, 22, 27, 0.1); - --surface: #ffffff; - --header: rgba(255, 255, 255, 0.78); - --blue: #2f5bff; - --blue-ink: #ffffff; - --red: #f03e3e; - --green: #0ca678; - --yellow: #fcc419; - --rim-hi: #f6f8fb; - --rim-lo: #d9dee7; - --tray: #e2e6ed; - --board-shadow: rgba(47, 91, 255, 0.28); - --code-bg: #16181f; - --code-fg: #e7e9f0; - --note-ink: #23262d; - --note-yellow: #fff1a1; - --note-pink: #ffd9e4; - --note-blue: #d6e6ff; - --note-green: #d3f4e0; - --font: 'Bricolage Grotesque Variable', 'Bricolage Grotesque', ui-sans-serif, system-ui, -apple-system, 'PingFang SC', 'Microsoft YaHei', sans-serif; - --hand: 'Caveat', 'Kaiti SC', 'STKaiti', 'KaiTi', cursive; - --mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; - color-scheme: light; + --bg: #ffffff; + --dot: rgba(47, 91, 255, 0.16); + --ink: #14161b; + --muted: #5b6170; + --line: rgba(20, 22, 27, 0.1); + --surface: #ffffff; + --header: rgba(255, 255, 255, 0.78); + --blue: #2f5bff; + --blue-ink: #ffffff; + --red: #f03e3e; + --green: #0ca678; + --yellow: #fcc419; + --rim-hi: #f6f8fb; + --rim-lo: #d9dee7; + --tray: #e2e6ed; + --board-shadow: rgba(47, 91, 255, 0.28); + --code-bg: #16181f; + --code-fg: #e7e9f0; + --note-ink: #23262d; + --note-yellow: #fff1a1; + --note-pink: #ffd9e4; + --note-blue: #d6e6ff; + --note-green: #d3f4e0; + --font: + 'Bricolage Grotesque Variable', 'Bricolage Grotesque', ui-sans-serif, system-ui, -apple-system, 'PingFang SC', 'Microsoft YaHei', + sans-serif; + --hand: 'Caveat', 'Kaiti SC', 'STKaiti', 'KaiTi', cursive; + --mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + color-scheme: light; } :root[data-theme='dark'] { - --bg: #0f1116; - --dot: rgba(125, 151, 255, 0.14); - --ink: #eceef3; - --muted: #9aa1b0; - --line: rgba(236, 238, 243, 0.1); - --surface: #171a21; - --header: rgba(15, 17, 22, 0.78); - --blue: #7d97ff; - --blue-ink: #0f1116; - --red: #ff6b6b; - --green: #38d9a9; - --yellow: #ffd43b; - --rim-hi: #353a45; - --rim-lo: #1d2028; - --tray: #262a33; - --board-shadow: rgba(0, 0, 0, 0.6); - --code-bg: #0a0b0f; - color-scheme: dark; + --bg: #0f1116; + --dot: rgba(125, 151, 255, 0.14); + --ink: #eceef3; + --muted: #9aa1b0; + --line: rgba(236, 238, 243, 0.1); + --surface: #171a21; + --header: rgba(15, 17, 22, 0.78); + --blue: #7d97ff; + --blue-ink: #0f1116; + --red: #ff6b6b; + --green: #38d9a9; + --yellow: #ffd43b; + --rim-hi: #353a45; + --rim-lo: #1d2028; + --tray: #262a33; + --board-shadow: rgba(0, 0, 0, 0.6); + --code-bg: #0a0b0f; + color-scheme: dark; } *, *::before, *::after { - box-sizing: border-box; + box-sizing: border-box; } html { - scroll-behavior: smooth; - scroll-padding-top: 80px; + scroll-behavior: smooth; + scroll-padding-top: 80px; } body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--font); - font-size: 17px; - line-height: 1.6; - -webkit-font-smoothing: antialiased; + margin: 0; + background: var(--bg); + color: var(--ink); + font-family: var(--font); + font-size: 17px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; } a { - color: inherit; + color: inherit; } :focus-visible { - outline: 2px solid var(--blue); - outline-offset: 2px; + outline: 2px solid var(--blue); + outline-offset: 2px; } .skip { - position: absolute; - left: -999px; - top: 8px; - padding: 8px 12px; - background: var(--ink); - color: var(--bg); - border-radius: 6px; - z-index: 100; + position: absolute; + left: -999px; + top: 8px; + padding: 8px 12px; + background: var(--ink); + color: var(--bg); + border-radius: 6px; + z-index: 100; } .skip:focus { - left: 8px; + left: 8px; } .page { - position: relative; - isolation: isolate; - overflow-x: clip; + position: relative; + isolation: isolate; + overflow-x: clip; } /* Dotted canvas behind the top of the page, fading out as you scroll. */ .page::before { - content: ''; - position: absolute; - inset: 0 0 auto; - height: 1500px; - background-image: radial-gradient(var(--dot) 1.3px, transparent 1.4px); - background-size: 24px 24px; - mask-image: linear-gradient(#000 40%, transparent); - -webkit-mask-image: linear-gradient(#000 40%, transparent); - pointer-events: none; - z-index: -1; + content: ''; + position: absolute; + inset: 0 0 auto; + height: 1500px; + background-image: radial-gradient(var(--dot) 1.3px, transparent 1.4px); + background-size: 24px 24px; + mask-image: linear-gradient(#000 40%, transparent); + -webkit-mask-image: linear-gradient(#000 40%, transparent); + pointer-events: none; + z-index: -1; } .wrap { - max-width: 1200px; - margin-inline: auto; - padding-inline: 24px; + max-width: 1200px; + margin-inline: auto; + padding-inline: 24px; } /* ---- header ---- */ .site-header { - position: sticky; - top: env(safe-area-inset-top, 0px); - z-index: 20; - background: var(--header); - backdrop-filter: saturate(1.4) blur(12px); - -webkit-backdrop-filter: saturate(1.4) blur(12px); - border-bottom: 1px solid var(--line); + position: sticky; + top: env(safe-area-inset-top, 0px); + z-index: 20; + background: var(--header); + backdrop-filter: saturate(1.4) blur(12px); + -webkit-backdrop-filter: saturate(1.4) blur(12px); + border-bottom: 1px solid var(--line); } .header-inner { - display: flex; - align-items: center; - gap: 32px; - height: 64px; + display: flex; + align-items: center; + gap: 32px; + height: 64px; } .brand { - display: inline-flex; - align-items: center; - gap: 10px; - font-weight: 700; - font-size: 18px; - letter-spacing: -0.01em; - text-decoration: none; + display: inline-flex; + align-items: center; + gap: 10px; + font-weight: 700; + font-size: 18px; + letter-spacing: -0.01em; + text-decoration: none; } .site-header nav { - display: flex; - gap: 24px; - font-size: 15px; + display: flex; + gap: 24px; + font-size: 15px; } .site-header nav a { - color: var(--muted); - text-decoration: none; + color: var(--muted); + text-decoration: none; } .site-header nav a:hover { - color: var(--ink); + color: var(--ink); } .header-actions { - margin-left: auto; - display: flex; - align-items: center; - gap: 4px; + margin-left: auto; + display: flex; + align-items: center; + gap: 4px; } .text-btn { - border: 0; - background: none; - padding: 6px 10px; - border-radius: 8px; - color: var(--muted); - font: inherit; - font-size: 15px; - cursor: pointer; + border: 0; + background: none; + padding: 6px 10px; + border-radius: 8px; + color: var(--muted); + font: inherit; + font-size: 15px; + cursor: pointer; } .text-btn:hover { - color: var(--ink); - background: var(--line); + color: var(--ink); + background: var(--line); } .icon-only { - display: inline-flex; - align-items: center; - justify-content: center; - width: 38px; - height: 38px; - border: 0; - border-radius: 8px; - background: none; - color: var(--ink); - cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + width: 38px; + height: 38px; + border: 0; + border-radius: 8px; + background: none; + color: var(--ink); + cursor: pointer; } .icon-only:hover { - background: var(--line); + background: var(--line); } /* ---- hero ---- */ .hero { - padding-block: 64px 24px; + padding-block: 64px 24px; } .hero-text { - display: grid; - grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); - gap: 24px 64px; - align-items: end; - margin-bottom: 96px; + display: grid; + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + gap: 24px 64px; + align-items: end; + margin-bottom: 96px; } .hero h1 { - margin: 0; - font-size: clamp(2.6rem, 5.8vw, 4.9rem); - line-height: 0.98; - font-weight: 800; - letter-spacing: -0.04em; - text-wrap: balance; + margin: 0; + font-size: clamp(2.6rem, 5.8vw, 4.9rem); + line-height: 0.98; + font-weight: 800; + letter-spacing: -0.04em; + text-wrap: balance; } .hero h1 span { - display: block; + display: block; } :root[lang='zh-CN'] .hero h1 span { - white-space: nowrap; + white-space: nowrap; } :root[lang='zh-CN'] .hero h1 { - font-size: clamp(1.9rem, 4.2vw, 3.5rem); - letter-spacing: 0; - line-height: 1.15; + font-size: clamp(1.9rem, 4.2vw, 3.5rem); + letter-spacing: 0; + line-height: 1.15; } .hero-side { - display: grid; - gap: 22px; - min-width: 0; + display: grid; + gap: 22px; + min-width: 0; } .lede { - margin: 0; - max-width: 46ch; - color: var(--muted); - font-size: 1.12rem; + margin: 0; + max-width: 46ch; + color: var(--muted); + font-size: 1.12rem; } .cta { - display: flex; - flex-wrap: wrap; - gap: 10px; + display: flex; + flex-wrap: wrap; + gap: 10px; } .btn { - display: inline-flex; - align-items: center; - gap: 8px; - height: 48px; - padding: 0 22px; - border-radius: 999px; - font-weight: 600; - font-size: 16px; - text-decoration: none; - transition: transform 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease; + display: inline-flex; + align-items: center; + gap: 8px; + height: 48px; + padding: 0 22px; + border-radius: 999px; + font-weight: 600; + font-size: 16px; + text-decoration: none; + transition: + transform 0.15s ease, + box-shadow 0.15s ease, + background-color 0.15s ease; } .btn:hover { - transform: translateY(-1px); + transform: translateY(-1px); } .btn:active { - transform: translateY(1px); + transform: translateY(1px); } .btn-primary { - background: var(--blue); - color: var(--blue-ink); - box-shadow: 0 8px 20px -8px var(--blue); + background: var(--blue); + color: var(--blue-ink); + box-shadow: 0 8px 20px -8px var(--blue); } .btn-ghost { - background: var(--surface); - border: 1.5px solid var(--line); + background: var(--surface); + border: 1.5px solid var(--line); } .btn-ghost:hover { - border-color: var(--ink); + border-color: var(--ink); } .badges { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-wrap: wrap; - gap: 8px 18px; - color: var(--muted); - font-size: 14px; + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 8px 18px; + color: var(--muted); + font-size: 14px; } .badges li { - display: inline-flex; - align-items: center; - gap: 7px; + display: inline-flex; + align-items: center; + gap: 7px; } .badges li::before { - content: ''; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--blue); + content: ''; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--blue); } .badges li:nth-child(2)::before { - background: var(--red); + background: var(--red); } .badges li:nth-child(3)::before { - background: var(--green); + background: var(--green); } .badges li:nth-child(4)::before { - background: var(--yellow); + background: var(--yellow); } /* The board is the hero: a physical whiteboard with a rim and a marker tray. */ .board-frame { - position: relative; - margin: 0; - padding: 12px; - border-radius: 22px; - background: linear-gradient(165deg, var(--rim-hi), var(--rim-lo)); - box-shadow: - 0 1px 0 rgba(255, 255, 255, 0.7) inset, - 0 40px 80px -40px var(--board-shadow), - 0 14px 28px -16px rgba(15, 23, 42, 0.25); + position: relative; + margin: 0; + padding: 12px; + border-radius: 22px; + background: linear-gradient(165deg, var(--rim-hi), var(--rim-lo)); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.7) inset, + 0 40px 80px -40px var(--board-shadow), + 0 14px 28px -16px rgba(15, 23, 42, 0.25); } .board-surface { - height: clamp(440px, 68vh, 700px); - border-radius: 12px; - overflow: hidden; - box-shadow: 0 0 0 1px var(--line) inset; + height: clamp(440px, 68vh, 700px); + border-radius: 12px; + overflow: hidden; + box-shadow: 0 0 0 1px var(--line) inset; } .board-tray { - position: absolute; - left: 8%; - right: 8%; - bottom: -14px; - height: 16px; - border-radius: 0 0 12px 12px; - background: var(--tray); - box-shadow: 0 8px 14px -8px rgba(15, 23, 42, 0.35); - display: flex; - align-items: flex-start; - gap: 14px; - padding: 0 28px; + position: absolute; + left: 8%; + right: 8%; + bottom: -14px; + height: 16px; + border-radius: 0 0 12px 12px; + background: var(--tray); + box-shadow: 0 8px 14px -8px rgba(15, 23, 42, 0.35); + display: flex; + align-items: flex-start; + gap: 14px; + padding: 0 28px; } .marker { - width: 78px; - height: 11px; - margin-top: -4px; - border-radius: 3px 7px 7px 3px; - background: linear-gradient(90deg, var(--c) 0 18%, #f4f5f7 18% 100%); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); + width: 78px; + height: 11px; + margin-top: -4px; + border-radius: 3px 7px 7px 3px; + background: linear-gradient(90deg, var(--c) 0 18%, #f4f5f7 18% 100%); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); } .marker-blue { - --c: #2f5bff; + --c: #2f5bff; } .marker-red { - --c: #f03e3e; + --c: #f03e3e; } .marker-green { - --c: #0ca678; + --c: #0ca678; } .eraser-block { - margin-left: auto; - width: 58px; - height: 14px; - margin-top: -6px; - border-radius: 4px; - background: linear-gradient(#3a3f4a 0 45%, #ececec 45%); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); + margin-left: auto; + width: 58px; + height: 14px; + margin-top: -6px; + border-radius: 4px; + background: linear-gradient(#3a3f4a 0 45%, #ececec 45%); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); } .board-frame figcaption { - position: absolute; - left: 0; - right: 0; - top: calc(100% + 28px); - display: flex; - justify-content: space-between; - align-items: center; - gap: 12px; - color: var(--muted); - font-size: 15px; + position: absolute; + left: 0; + right: 0; + top: calc(100% + 28px); + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + color: var(--muted); + font-size: 15px; } /* Handwritten marker annotations around the board. */ .note { - position: absolute; - margin: 0; - font-family: var(--hand); - font-weight: 700; - font-size: 30px; - line-height: 1; - pointer-events: none; - white-space: nowrap; + position: absolute; + margin: 0; + font-family: var(--hand); + font-weight: 700; + font-size: 30px; + line-height: 1; + pointer-events: none; + white-space: nowrap; } :root[lang='zh-CN'] .note { - font-size: 26px; + font-size: 26px; } .note-tools { - top: -62px; - left: calc(50% - 400px); - color: var(--red); - transform: rotate(-5deg); + top: -62px; + left: calc(50% - 400px); + color: var(--red); + transform: rotate(-5deg); } .note-arrow { - position: absolute; - left: calc(100% + 6px); - top: 6px; - width: 92px; - height: 70px; + position: absolute; + left: calc(100% + 6px); + top: 6px; + width: 92px; + height: 70px; } .note-draw { - top: -54px; - right: 4%; - color: var(--blue); - transform: rotate(4deg); + top: -54px; + right: 4%; + color: var(--blue); + transform: rotate(4deg); } /* ---- sections ---- */ .section { - padding-block: 120px 0; + padding-block: 120px 0; } .hero + .section { - padding-top: 148px; + padding-top: 148px; } .section h2 { - margin: 0 0 12px; - font-size: clamp(2rem, 3.6vw, 2.8rem); - line-height: 1.1; - letter-spacing: -0.03em; - font-weight: 800; - text-wrap: balance; + margin: 0 0 12px; + font-size: clamp(2rem, 3.6vw, 2.8rem); + line-height: 1.1; + letter-spacing: -0.03em; + font-weight: 800; + text-wrap: balance; } .section-lede { - margin: 0 0 40px; - max-width: 60ch; - color: var(--muted); + margin: 0 0 40px; + max-width: 60ch; + color: var(--muted); } /* ---- get started ---- */ .steps { - list-style: none; - margin: 0; - padding: 0; - counter-reset: step; - display: grid; - gap: 28px; - max-width: 1040px; + list-style: none; + margin: 0; + padding: 0; + counter-reset: step; + display: grid; + gap: 28px; + max-width: 1040px; } .steps > li { - --step: var(--blue); - counter-increment: step; - display: grid; - grid-template-columns: 260px minmax(0, 1fr); - gap: 28px; - align-items: start; + --step: var(--blue); + counter-increment: step; + display: grid; + grid-template-columns: 260px minmax(0, 1fr); + gap: 28px; + align-items: start; } .steps > li:nth-child(2) { - --step: var(--red); + --step: var(--red); } .steps > li:nth-child(3) { - --step: var(--green); + --step: var(--green); } .step-text { - position: relative; - padding-left: 50px; - min-width: 0; + position: relative; + padding-left: 50px; + min-width: 0; } .step-text::before { - content: counter(step); - position: absolute; - left: 0; - top: -2px; - width: 34px; - height: 34px; - border-radius: 50%; - background: var(--step); - color: #fff; - display: grid; - place-items: center; - font-weight: 700; - font-size: 16px; + content: counter(step); + position: absolute; + left: 0; + top: -2px; + width: 34px; + height: 34px; + border-radius: 50%; + background: var(--step); + color: #fff; + display: grid; + place-items: center; + font-weight: 700; + font-size: 16px; } .step-text h3 { - margin: 0 0 4px; - font-size: 20px; - letter-spacing: -0.01em; + margin: 0 0 4px; + font-size: 20px; + letter-spacing: -0.01em; } .step-text p { - margin: 0; - color: var(--muted); - font-size: 15px; + margin: 0; + color: var(--muted); + font-size: 15px; } .code { - position: relative; - min-width: 0; - border-radius: 14px; - background: var(--code-bg); - color: var(--code-fg); - box-shadow: 0 12px 30px -18px rgba(15, 23, 42, 0.6); + position: relative; + min-width: 0; + border-radius: 14px; + background: var(--code-bg); + color: var(--code-fg); + box-shadow: 0 12px 30px -18px rgba(15, 23, 42, 0.6); } .code pre { - margin: 0; - padding: 18px 88px 18px 20px; - overflow-x: auto; - font: 14px/1.7 var(--mono); + margin: 0; + padding: 18px 88px 18px 20px; + overflow-x: auto; + font: 14px/1.7 var(--mono); } .tok-kw { - color: #c9a8ff; + color: #c9a8ff; } .tok-str { - color: #9ae6b4; + color: #9ae6b4; } .tok-tag { - color: #7cc7ff; + color: #7cc7ff; } .tok-cmd { - color: #ffd666; + color: #ffd666; } .code-copy { - position: absolute; - top: 12px; - right: 12px; - padding: 4px 12px; - border-radius: 7px; - border: 1px solid rgba(255, 255, 255, 0.14); - background: rgba(255, 255, 255, 0.06); - color: #c4c8d4; - font: 13px var(--font); - cursor: pointer; + position: absolute; + top: 12px; + right: 12px; + padding: 4px 12px; + border-radius: 7px; + border: 1px solid rgba(255, 255, 255, 0.14); + background: rgba(255, 255, 255, 0.06); + color: #c4c8d4; + font: 13px var(--font); + cursor: pointer; } .code-copy:hover { - color: #fff; - background: rgba(255, 255, 255, 0.12); + color: #fff; + background: rgba(255, 255, 255, 0.12); } /* ---- features as sticky notes ---- */ .notes { - list-style: none; - margin: 48px 0 0; - padding: 0; - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 36px 28px; + list-style: none; + margin: 48px 0 0; + padding: 0; + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 36px 28px; } .sticky { - --tilt: -1.6deg; - position: relative; - min-height: 210px; - padding: 30px 22px 22px; - border-radius: 3px 3px 14px 3px; - color: var(--note-ink); - transform: rotate(var(--tilt)); - box-shadow: - 0 1px 1px rgba(0, 0, 0, 0.06), - 0 14px 22px -14px rgba(0, 0, 0, 0.35); - transition: transform 0.2s ease; + --tilt: -1.6deg; + position: relative; + min-height: 210px; + padding: 30px 22px 22px; + border-radius: 3px 3px 14px 3px; + color: var(--note-ink); + transform: rotate(var(--tilt)); + box-shadow: + 0 1px 1px rgba(0, 0, 0, 0.06), + 0 14px 22px -14px rgba(0, 0, 0, 0.35); + transition: transform 0.2s ease; } .sticky:nth-child(4n + 2) { - --tilt: 1.2deg; + --tilt: 1.2deg; } .sticky:nth-child(4n + 3) { - --tilt: -0.7deg; + --tilt: -0.7deg; } .sticky:nth-child(4n) { - --tilt: 1.8deg; + --tilt: 1.8deg; } .sticky:hover { - transform: rotate(0deg) translateY(-4px); + transform: rotate(0deg) translateY(-4px); } /* A strip of tape holding each note to the board. */ .sticky::before { - content: ''; - position: absolute; - top: -11px; - left: 50%; - width: 72px; - height: 22px; - transform: translateX(-50%) rotate(-3deg); - background: rgba(255, 255, 255, 0.55); - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); + content: ''; + position: absolute; + top: -11px; + left: 50%; + width: 72px; + height: 22px; + transform: translateX(-50%) rotate(-3deg); + background: rgba(255, 255, 255, 0.55); + border: 1px solid rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); } .sticky-yellow { - background: var(--note-yellow); + background: var(--note-yellow); } .sticky-pink { - background: var(--note-pink); + background: var(--note-pink); } .sticky-blue { - background: var(--note-blue); + background: var(--note-blue); } .sticky-green { - background: var(--note-green); + background: var(--note-green); } .sticky svg { - opacity: 0.75; + opacity: 0.75; } .sticky h3 { - margin: 10px 0 6px; - font-size: 19px; - line-height: 1.25; - letter-spacing: -0.01em; + margin: 10px 0 6px; + font-size: 19px; + line-height: 1.25; + letter-spacing: -0.01em; } .sticky p { - margin: 0; - font-size: 15px; - line-height: 1.55; - color: rgba(35, 38, 45, 0.78); + margin: 0; + font-size: 15px; + line-height: 1.55; + color: rgba(35, 38, 45, 0.78); } /* ---- API ---- */ .table-title { - margin: 36px 0 12px; - font-size: 20px; + margin: 36px 0 12px; + font-size: 20px; } .table-wrap { - overflow-x: auto; - border: 1px solid var(--line); - border-radius: 14px; - background: var(--surface); + overflow-x: auto; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--surface); } table { - width: 100%; - border-collapse: collapse; - font-size: 15px; + width: 100%; + border-collapse: collapse; + font-size: 15px; } th, td { - text-align: left; - vertical-align: top; - padding: 13px 18px; - border-bottom: 1px solid var(--line); + text-align: left; + vertical-align: top; + padding: 13px 18px; + border-bottom: 1px solid var(--line); } tr:last-child td { - border-bottom: 0; + border-bottom: 0; } th { - font-weight: 600; - color: var(--muted); - font-size: 14px; - background: color-mix(in srgb, var(--blue) 5%, transparent); + font-weight: 600; + color: var(--muted); + font-size: 14px; + background: color-mix(in srgb, var(--blue) 5%, transparent); } td code { - font: 13.5px var(--mono); - white-space: nowrap; - color: var(--blue); + font: 13.5px var(--mono); + white-space: nowrap; + color: var(--blue); } td code.type { - color: var(--muted); + color: var(--muted); } /* ---- closing ---- */ .closing { - position: relative; - overflow: hidden; - margin-top: 140px; - padding: 72px 64px; - border-radius: 28px; - background: var(--blue); - color: var(--blue-ink); - display: grid; - justify-items: start; - gap: 18px; + position: relative; + overflow: hidden; + margin-top: 140px; + padding: 72px 64px; + border-radius: 28px; + background: var(--blue); + color: var(--blue-ink); + display: grid; + justify-items: start; + gap: 18px; } .closing h2 { - margin: 0; - font-family: var(--hand); - font-size: clamp(3rem, 7vw, 5rem); - line-height: 1; - font-weight: 700; + margin: 0; + font-family: var(--hand); + font-size: clamp(3rem, 7vw, 5rem); + line-height: 1; + font-weight: 700; } .closing p { - margin: 0 0 10px; - max-width: 44ch; - font-size: 1.1rem; - opacity: 0.88; + margin: 0 0 10px; + max-width: 44ch; + font-size: 1.1rem; + opacity: 0.88; } .btn-light { - background: var(--blue-ink); - color: var(--blue); + background: var(--blue-ink); + color: var(--blue); } .closing-doodle { - position: absolute; - right: -10px; - bottom: 16px; - width: min(420px, 50%); - opacity: 0.25; - pointer-events: none; + position: absolute; + right: -10px; + bottom: 16px; + width: min(420px, 50%); + opacity: 0.25; + pointer-events: none; } .site-footer { - display: flex; - justify-content: space-between; - gap: 16px; - padding-block: 36px 48px; - color: var(--muted); - font-size: 15px; + display: flex; + justify-content: space-between; + gap: 16px; + padding-block: 36px 48px; + color: var(--muted); + font-size: 15px; } /* ---- responsive ---- */ @media (max-width: 1080px) { - .notes { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } + .notes { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } - .note-tools { - left: 8%; - } + .note-tools { + left: 8%; + } } @media (max-width: 860px) { - .hero-text { - grid-template-columns: 1fr; - } + .hero-text { + grid-template-columns: 1fr; + } - .steps > li { - grid-template-columns: 1fr; - gap: 14px; - } + .steps > li { + grid-template-columns: 1fr; + gap: 14px; + } - .note-draw { - display: none; - } + .note-draw { + display: none; + } } @media (max-width: 640px) { - .wrap { - padding-inline: 16px; - } - - .header-inner { - gap: 12px; - } - - .site-header nav { - display: none; - } - - .brand span { - font-size: 16px; - } - - .hero { - padding-top: 36px; - } - - .hero-text { - margin-bottom: 72px; - } - - .note-tools { - top: -50px; - left: 4px; - font-size: 24px; - } - - .note-arrow { - width: 64px; - height: 50px; - } - - .board-frame { - padding: 6px; - border-radius: 16px; - } - - .board-surface { - /* Leave room above/below so touch users can still scroll the page past the board. */ - height: 58vh; - } - - .board-tray { - left: 4%; - right: 4%; - padding: 0 14px; - } - - .marker { - width: 48px; - } - - .board-frame figcaption { - flex-direction: column; - align-items: flex-start; - gap: 4px; - } - - .board-frame figcaption .text-btn { - margin-left: -10px; - } - - .hero + .section { - padding-top: 150px; - } - - .section { - padding-top: 88px; - } - - .notes { - grid-template-columns: 1fr; - } - - .sticky { - min-height: 0; - } - - td code { - white-space: normal; - } - - .closing { - padding: 48px 24px; - margin-top: 100px; - } + .wrap { + padding-inline: 16px; + } + + .header-inner { + gap: 12px; + } + + .site-header nav { + display: none; + } + + .brand span { + font-size: 16px; + } + + .hero { + padding-top: 36px; + } + + .hero-text { + margin-bottom: 72px; + } + + .note-tools { + top: -50px; + left: 4px; + font-size: 24px; + } + + .note-arrow { + width: 64px; + height: 50px; + } + + .board-frame { + padding: 6px; + border-radius: 16px; + } + + .board-surface { + /* Leave room above/below so touch users can still scroll the page past the board. */ + height: 58vh; + } + + .board-tray { + left: 4%; + right: 4%; + padding: 0 14px; + } + + .marker { + width: 48px; + } + + .board-frame figcaption { + flex-direction: column; + align-items: flex-start; + gap: 4px; + } + + .board-frame figcaption .text-btn { + margin-left: -10px; + } + + .hero + .section { + padding-top: 150px; + } + + .section { + padding-top: 88px; + } + + .notes { + grid-template-columns: 1fr; + } + + .sticky { + min-height: 0; + } + + td code { + white-space: normal; + } + + .closing { + padding: 48px 24px; + margin-top: 100px; + } } @media (prefers-reduced-motion: reduce) { - html { - scroll-behavior: auto; - } - - .btn, - .sticky { - transition: none; - } + html { + scroll-behavior: auto; + } + + .btn, + .sticky { + transition: none; + } } diff --git a/src/whiteboard/Whiteboard.tsx b/src/whiteboard/Whiteboard.tsx index 603a813..8aba441 100644 --- a/src/whiteboard/Whiteboard.tsx +++ b/src/whiteboard/Whiteboard.tsx @@ -1,40 +1,41 @@ import { - forwardRef, - useCallback, - useEffect, - useImperativeHandle, - useLayoutEffect, - useMemo, - useReducer, - useRef, - useState, - type CSSProperties, - type KeyboardEvent as ReactKeyboardEvent, - type MouseEvent as ReactMouseEvent, - type PointerEvent as ReactPointerEvent, + forwardRef, + useCallback, + useEffect, + useImperativeHandle, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + type CSSProperties, + type KeyboardEvent as ReactKeyboardEvent, + type MouseEvent as ReactMouseEvent, + type PointerEvent as ReactPointerEvent, } from 'react'; import { DEFAULT_STYLE, DRAWING_TOOLS, FONT_FAMILY, LINE_HEIGHT, MAX_ZOOM, MIN_ZOOM, MOD, TOOLS, type ToolDef } from './constants'; import { deserialize, downloadBlob, exportToPngBlob, exportToSvg, serialize, timestampName, type ExportOptions } from './export'; import { - boundsFromPoints, - boundsIntersect, - distance, - fitCamera, - type Insets, - getBounds, - measureText, - screenToWorld, - shapeAt, - shapesBounds, - translateShape, - worldToScreen, - zoomAt, + boundsFromPoints, + boundsIntersect, + distance, + fitCamera, + type Insets, + getBounds, + measureText, + screenToWorld, + shapeAt, + shapesBounds, + translateShape, + worldToScreen, + zoomAt, } from './geometry'; import { historyReducer, initHistory } from './history'; import { detectLocale, MESSAGES } from './i18n'; import { Icons } from './icons'; import { drawScene, resolveColor } from './render'; import { eraseAt } from './erase'; +import { routeOf } from './linear'; import { samplePressure } from './stroke'; import { applyStyle, createId, createShape, finalizeShape, isDrawableTool, updateDraft } from './shapes'; import { loadState, saveState } from './storage'; @@ -43,56 +44,56 @@ import { HelpDialog, IconButton, Menu, StylePanel, Toolbar, Tooltip, type MenuIt import './whiteboard.css'; export type WhiteboardProps = { - /** Shapes to start with when nothing is stored under `storageKey`. */ - initialShapes?: Shape[]; - /** localStorage key used for autosave. Pass `null` to disable persistence. */ - storageKey?: string | null; - /** Controlled theme. When omitted the board manages its own theme (with a toggle in the menu). */ - theme?: Theme; - /** Controlled locale. When omitted it is detected from the browser and switchable from the menu. */ - locale?: Locale; - initialTool?: Tool; - /** - * Tools shown in the toolbar (and reachable by shortcut), in this order. - * Defaults to every tool. Example: `['pen', 'highlighter', 'eraser']` for a simple doodle pad. - */ - tools?: Tool[]; - /** Called after every committed change (not on every pointer move). */ - onChange?: (shapes: Shape[]) => void; - onThemeChange?: (theme: Theme) => void; - /** Listen for shortcuts on `window` (full-page apps). When false, only while the board has focus. */ - globalShortcuts?: boolean; - /** Use plain wheel/trackpad scroll to pan. Set false when embedding inside a scrolling page. */ - captureWheel?: boolean; - /** Show the main menu (file, export, settings). */ - showMenu?: boolean; - githubUrl?: string; - className?: string; - style?: CSSProperties; + /** Shapes to start with when nothing is stored under `storageKey`. */ + initialShapes?: Shape[]; + /** localStorage key used for autosave. Pass `null` to disable persistence. */ + storageKey?: string | null; + /** Controlled theme. When omitted the board manages its own theme (with a toggle in the menu). */ + theme?: Theme; + /** Controlled locale. When omitted it is detected from the browser and switchable from the menu. */ + locale?: Locale; + initialTool?: Tool; + /** + * Tools shown in the toolbar (and reachable by shortcut), in this order. + * Defaults to every tool. Example: `['pen', 'highlighter', 'eraser']` for a simple doodle pad. + */ + tools?: Tool[]; + /** Called after every committed change (not on every pointer move). */ + onChange?: (shapes: Shape[]) => void; + onThemeChange?: (theme: Theme) => void; + /** Listen for shortcuts on `window` (full-page apps). When false, only while the board has focus. */ + globalShortcuts?: boolean; + /** Use plain wheel/trackpad scroll to pan. Set false when embedding inside a scrolling page. */ + captureWheel?: boolean; + /** Show the main menu (file, export, settings). */ + showMenu?: boolean; + githubUrl?: string; + className?: string; + style?: CSSProperties; }; export type WhiteboardHandle = { - getShapes: () => Shape[]; - /** Replace the document. Recorded in undo history unless `{ history: false }`. */ - setShapes: (shapes: Shape[], options?: { history?: boolean }) => void; - clear: () => void; - undo: () => void; - redo: () => void; - zoomToFit: () => void; - exportPng: (options?: ExportOptions & { scale?: number }) => Promise; - exportSvg: (options?: ExportOptions) => string; - exportJson: () => string; + getShapes: () => Shape[]; + /** Replace the document. Recorded in undo history unless `{ history: false }`. */ + setShapes: (shapes: Shape[], options?: { history?: boolean }) => void; + clear: () => void; + undo: () => void; + redo: () => void; + zoomToFit: () => void; + exportPng: (options?: ExportOptions & { scale?: number }) => Promise; + exportSvg: (options?: ExportOptions) => string; + exportJson: () => string; }; type Interaction = - | { kind: 'none' } - | { kind: 'draw'; start: Point } - | { kind: 'pan'; startScreen: Point; startCamera: Camera } - | { kind: 'move'; start: Point; originals: Shape[]; moved: boolean; clickedId: string } - | { kind: 'marquee'; start: Point; base: string[] } - | { kind: 'erase'; last: Point; hits: Set } - | { kind: 'erasePartial'; last: Point; working: Shape[] } - | { kind: 'pinch'; startDist: number; startMid: Point; startCamera: Camera }; + | { kind: 'none' } + | { kind: 'draw'; start: Point } + | { kind: 'pan'; startScreen: Point; startCamera: Camera } + | { kind: 'move'; start: Point; originals: Shape[]; moved: boolean; clickedId: string } + | { kind: 'marquee'; start: Point; base: string[] } + | { kind: 'erase'; last: Point; hits: Set } + | { kind: 'erasePartial'; last: Point; working: Shape[] } + | { kind: 'pinch'; startDist: number; startMid: Point; startCamera: Camera }; type TextEditing = { id: string | null; x: number; y: number; text: string; fontSize: number; color: string }; @@ -102,976 +103,1017 @@ const clampZoom = (z: number) => Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, z)); /** Leave room for the floating toolbar and style panel when fitting content. */ const fitInsets = (width: number): Insets => - width > 720 ? { top: 76, right: 32, bottom: 72, left: 248 } : { top: 72, right: 20, bottom: 76, left: 20 }; + width > 720 ? { top: 76, right: 32, bottom: 72, left: 248 } : { top: 72, right: 20, bottom: 76, left: 20 }; const systemTheme = (): Theme => - typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; + typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; function styleFromShape(shape: Shape, fallback: StyleState): StyleState { - return { - ...fallback, - color: shape.color, - strokeWidth: shape.type === 'highlighter' ? Math.max(1, Math.round(shape.strokeWidth / 3)) : shape.type === 'text' ? fallback.strokeWidth : shape.strokeWidth, - strokeStyle: shape.strokeStyle, - fill: 'fill' in shape ? shape.fill : fallback.fill, - fontSize: shape.type === 'text' ? shape.fontSize : fallback.fontSize, - }; + return { + ...fallback, + color: shape.color, + strokeWidth: + shape.type === 'highlighter' + ? Math.max(1, Math.round(shape.strokeWidth / 3)) + : shape.type === 'text' + ? fallback.strokeWidth + : shape.strokeWidth, + strokeStyle: shape.strokeStyle, + fill: 'fill' in shape ? shape.fill : fallback.fill, + fontSize: shape.type === 'text' ? shape.fontSize : fallback.fontSize, + lineRoute: shape.type === 'line' || shape.type === 'arrow' ? routeOf(shape) : fallback.lineRoute, + }; } const isEditableTarget = (t: EventTarget | null) => - t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName)); + t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName)); export const Whiteboard = forwardRef(function Whiteboard(props, ref) { - const { - initialShapes, - storageKey = 'react-whiteboard', - theme: themeProp, - locale: localeProp, - initialTool = 'pen', - tools: toolsProp, - onChange, - onThemeChange, - globalShortcuts = true, - captureWheel = true, - showMenu = true, - githubUrl, - className, - style: styleProp, - } = props; - - // ---- persisted & document state ------------------------------------------------- - const [saved] = useState(() => (storageKey ? loadState(storageKey) : null)); - const [history, dispatch] = useReducer(historyReducer, undefined, () => initHistory(saved?.shapes ?? initialShapes ?? [])); - const shapes = history.present; - - const toolDefs = useMemo(() => { - if (!toolsProp) return TOOLS; - // Custom subsets get sequential number keys (1–9, then 0) in the order given. - const picked = toolsProp.map((id) => TOOLS.find((d) => d.id === id)).filter((d): d is ToolDef => !!d); - return picked.map((d, i) => ({ ...d, num: i < 9 ? String(i + 1) : i === 9 ? '0' : undefined })); - }, [toolsProp]); - const hasTool = useCallback((id: Tool) => toolDefs.some((d) => d.id === id), [toolDefs]); - const [tool, setToolState] = useState(() => - !toolsProp || toolsProp.includes(initialTool) ? initialTool : (toolsProp[0] ?? 'pen'), - ); - const [style, setStyle] = useState(() => ({ ...DEFAULT_STYLE, ...saved?.app.style })); - const [camera, setCamera] = useState(() => saved?.app.camera ?? { x: 0, y: 0, zoom: 1 }); - const [ownTheme, setOwnTheme] = useState(() => saved?.app.theme ?? systemTheme()); - const [ownLocale, setOwnLocale] = useState(() => saved?.app.locale ?? detectLocale()); - const [grid, setGrid] = useState(() => saved?.app.grid ?? true); - const [selection, setSelection] = useState([]); - const [editing, setEditing] = useState(null); - const [menuOpen, setMenuOpen] = useState(false); - const [helpOpen, setHelpOpen] = useState(false); - const [panelOpen, setPanelOpen] = useState(false); - const [toast, setToast] = useState<{ id: number; message: string } | null>(null); - const [panning, setPanning] = useState(false); - const [spaceDown, setSpaceDown] = useState(false); - const [drawing, setDrawing] = useState(false); - - const theme = themeProp ?? ownTheme; - const locale = localeProp ?? ownLocale; - const t = MESSAGES[locale]; - - // ---- refs used by the imperative render loop ------------------------------------- - const containerRef = useRef(null); - const canvasRef = useRef(null); - const fileInputRef = useRef(null); - const sizeRef = useRef({ width: 0, height: 0, dpr: 1 }); - const interactionRef = useRef({ kind: 'none' }); - const draftRef = useRef(null); - const transientRef = useRef>(new Map()); - /** Whole-document preview while the partial eraser is dragging. */ - const erasePreviewRef = useRef(null); - /** Last pen sample, for pressure / speed estimation. */ - const sampleRef = useRef<{ x: number; y: number; t: number; p: number } | null>(null); - const fadedRef = useRef>(new Set()); - const marqueeRef = useRef<{ a: Point; b: Point } | null>(null); - const cursorRef = useRef(null); - const pointersRef = useRef>(new Map()); - const clipboardRef = useRef([]); - const editingRef = useRef(null); - const needsFitRef = useRef(!saved?.app.camera && (initialShapes?.length ?? 0) > 0); - const rafRef = useRef(0); - - const selectedSet = useMemo(() => new Set(selection), [selection]); - const live = useRef({ shapes, camera, selectedSet, theme, grid, tool, editing, style }); - live.current = { shapes, camera, selectedSet, theme, grid, tool, editing, style }; - editingRef.current = editing; - - // ---- rendering -------------------------------------------------------------------- - const draw = useCallback(() => { - rafRef.current = 0; - const canvas = canvasRef.current; - const ctx = canvas?.getContext('2d'); - const { width, height, dpr } = sizeRef.current; - if (!ctx || width === 0) return; - const s = live.current; - let list = erasePreviewRef.current ?? s.shapes; - const transient = transientRef.current; - if (transient.size) list = list.map((sh) => transient.get(sh.id) ?? sh); - if (draftRef.current) list = [...list, draftRef.current]; - const marquee = marqueeRef.current; - const cursor = cursorRef.current; - drawScene(ctx, { - shapes: list, - camera: s.camera, - width, - height, - dpr, - theme: s.theme, - grid: s.grid, - selectedIds: s.selectedSet, - fadedIds: fadedRef.current, - hiddenIds: s.editing?.id ? new Set([s.editing.id]) : undefined, - marquee: marquee ? boundsFromPoints(marquee.a, marquee.b) : null, - draftId: draftRef.current?.id, - eraserCursor: s.tool === 'eraser' && cursor ? { ...cursor, r: s.style.eraserSize } : null, - }); - }, []); - - const scheduleRender = useCallback(() => { - if (!rafRef.current) rafRef.current = requestAnimationFrame(draw); - }, [draw]); - - useEffect(() => scheduleRender(), [shapes, camera, selectedSet, theme, grid, tool, editing, style.eraserSize, scheduleRender]); - useEffect(() => () => cancelAnimationFrame(rafRef.current), []); - - // Keep the canvas backing store in sync with its CSS size and devicePixelRatio. - useLayoutEffect(() => { - const container = containerRef.current; - const canvas = canvasRef.current; - if (!container || !canvas) return; - const resize = () => { - const rect = container.getBoundingClientRect(); - const dpr = window.devicePixelRatio || 1; - sizeRef.current = { width: rect.width, height: rect.height, dpr }; - canvas.width = Math.max(1, Math.round(rect.width * dpr)); - canvas.height = Math.max(1, Math.round(rect.height * dpr)); - if (needsFitRef.current && rect.width > 0) { - needsFitRef.current = false; - const b = shapesBounds(live.current.shapes); - if (b) setCamera(fitCamera(b, rect.width, rect.height, fitInsets(rect.width))); - } - draw(); + const { + initialShapes, + storageKey = 'react-whiteboard', + theme: themeProp, + locale: localeProp, + initialTool = 'pen', + tools: toolsProp, + onChange, + onThemeChange, + globalShortcuts = true, + captureWheel = true, + showMenu = true, + githubUrl, + className, + style: styleProp, + } = props; + + // ---- persisted & document state ------------------------------------------------- + const [saved] = useState(() => (storageKey ? loadState(storageKey) : null)); + const [history, dispatch] = useReducer(historyReducer, undefined, () => initHistory(saved?.shapes ?? initialShapes ?? [])); + const shapes = history.present; + + const toolDefs = useMemo(() => { + if (!toolsProp) return TOOLS; + // Custom subsets get sequential number keys (1–9, then 0) in the order given. + const picked = toolsProp.map((id) => TOOLS.find((d) => d.id === id)).filter((d): d is ToolDef => !!d); + return picked.map((d, i) => ({ ...d, num: i < 9 ? String(i + 1) : i === 9 ? '0' : undefined })); + }, [toolsProp]); + const hasTool = useCallback((id: Tool) => toolDefs.some((d) => d.id === id), [toolDefs]); + const [tool, setToolState] = useState(() => + !toolsProp || toolsProp.includes(initialTool) ? initialTool : (toolsProp[0] ?? 'pen'), + ); + const [style, setStyle] = useState(() => ({ ...DEFAULT_STYLE, ...saved?.app.style })); + const [camera, setCamera] = useState(() => saved?.app.camera ?? { x: 0, y: 0, zoom: 1 }); + const [ownTheme, setOwnTheme] = useState(() => saved?.app.theme ?? systemTheme()); + const [ownLocale, setOwnLocale] = useState(() => saved?.app.locale ?? detectLocale()); + const [grid, setGrid] = useState(() => saved?.app.grid ?? true); + const [selection, setSelection] = useState([]); + const [editing, setEditing] = useState(null); + const [menuOpen, setMenuOpen] = useState(false); + const [helpOpen, setHelpOpen] = useState(false); + const [panelOpen, setPanelOpen] = useState(false); + const [toast, setToast] = useState<{ id: number; message: string } | null>(null); + const [panning, setPanning] = useState(false); + const [spaceDown, setSpaceDown] = useState(false); + const [drawing, setDrawing] = useState(false); + + const theme = themeProp ?? ownTheme; + const locale = localeProp ?? ownLocale; + const t = MESSAGES[locale]; + + // ---- refs used by the imperative render loop ------------------------------------- + const containerRef = useRef(null); + const canvasRef = useRef(null); + const fileInputRef = useRef(null); + const sizeRef = useRef({ width: 0, height: 0, dpr: 1 }); + const interactionRef = useRef({ kind: 'none' }); + const draftRef = useRef(null); + const transientRef = useRef>(new Map()); + /** Whole-document preview while the partial eraser is dragging. */ + const erasePreviewRef = useRef(null); + /** Last pen sample, for pressure / speed estimation. */ + const sampleRef = useRef<{ x: number; y: number; t: number; p: number } | null>(null); + const fadedRef = useRef>(new Set()); + const marqueeRef = useRef<{ a: Point; b: Point } | null>(null); + const cursorRef = useRef(null); + const pointersRef = useRef>(new Map()); + const clipboardRef = useRef([]); + const editingRef = useRef(null); + const needsFitRef = useRef(!saved?.app.camera && (initialShapes?.length ?? 0) > 0); + const rafRef = useRef(0); + + const selectedSet = useMemo(() => new Set(selection), [selection]); + const live = useRef({ shapes, camera, selectedSet, theme, grid, tool, editing, style }); + live.current = { shapes, camera, selectedSet, theme, grid, tool, editing, style }; + editingRef.current = editing; + + // ---- rendering -------------------------------------------------------------------- + const draw = useCallback(() => { + rafRef.current = 0; + const canvas = canvasRef.current; + const ctx = canvas?.getContext('2d'); + const { width, height, dpr } = sizeRef.current; + if (!ctx || width === 0) return; + const s = live.current; + let list = erasePreviewRef.current ?? s.shapes; + const transient = transientRef.current; + if (transient.size) list = list.map((sh) => transient.get(sh.id) ?? sh); + if (draftRef.current) list = [...list, draftRef.current]; + const marquee = marqueeRef.current; + const cursor = cursorRef.current; + drawScene(ctx, { + shapes: list, + camera: s.camera, + width, + height, + dpr, + theme: s.theme, + grid: s.grid, + selectedIds: s.selectedSet, + fadedIds: fadedRef.current, + hiddenIds: s.editing?.id ? new Set([s.editing.id]) : undefined, + marquee: marquee ? boundsFromPoints(marquee.a, marquee.b) : null, + draftId: draftRef.current?.id, + eraserCursor: s.tool === 'eraser' && cursor ? { ...cursor, r: s.style.eraserSize } : null, + }); + }, []); + + const scheduleRender = useCallback(() => { + if (!rafRef.current) rafRef.current = requestAnimationFrame(draw); + }, [draw]); + + useEffect(() => scheduleRender(), [shapes, camera, selectedSet, theme, grid, tool, editing, style.eraserSize, scheduleRender]); + useEffect(() => () => cancelAnimationFrame(rafRef.current), []); + + // Keep the canvas backing store in sync with its CSS size and devicePixelRatio. + useLayoutEffect(() => { + const container = containerRef.current; + const canvas = canvasRef.current; + if (!container || !canvas) return; + const resize = () => { + const rect = container.getBoundingClientRect(); + const dpr = window.devicePixelRatio || 1; + sizeRef.current = { width: rect.width, height: rect.height, dpr }; + canvas.width = Math.max(1, Math.round(rect.width * dpr)); + canvas.height = Math.max(1, Math.round(rect.height * dpr)); + if (needsFitRef.current && rect.width > 0) { + needsFitRef.current = false; + const b = shapesBounds(live.current.shapes); + if (b) setCamera(fitCamera(b, rect.width, rect.height, fitInsets(rect.width))); + } + draw(); + }; + resize(); + const ro = new ResizeObserver(resize); + ro.observe(container); + return () => ro.disconnect(); + }, [draw]); + + // ---- persistence & change notification ------------------------------------------- + useEffect(() => { + if (!storageKey) return; + const id = window.setTimeout(() => { + saveState(storageKey, shapes, { + camera, + style, + grid, + theme: themeProp ? undefined : ownTheme, + locale: localeProp ? undefined : ownLocale, + }); + }, 300); + return () => window.clearTimeout(id); + }, [storageKey, shapes, camera, style, grid, ownTheme, ownLocale, themeProp, localeProp]); + + const onChangeRef = useRef(onChange); + onChangeRef.current = onChange; + const firstShapes = useRef(shapes); + useEffect(() => { + if (shapes !== firstShapes.current) onChangeRef.current?.(shapes); + }, [shapes]); + + // Drop selected ids that no longer exist (after undo, erase, etc.). + useEffect(() => { + setSelection((sel) => { + if (sel.length === 0) return sel; + const ids = new Set(shapes.map((s) => s.id)); + const next = sel.filter((id) => ids.has(id)); + return next.length === sel.length ? sel : next; + }); + }, [shapes]); + + useEffect(() => { + if (!toast) return; + const id = window.setTimeout(() => setToast(null), 2600); + return () => window.clearTimeout(id); + }, [toast]); + + const notify = useCallback((message: string) => setToast({ id: Date.now(), message }), []); + + // ---- document helpers ------------------------------------------------------------- + const commit = useCallback((next: Shape[] | ((prev: Shape[]) => Shape[])) => dispatch({ type: 'commit', shapes: next }), []); + + const zoomTo = useCallback((zoom: number, anchor?: Point) => { + setCamera((c) => zoomAt(c, clampZoom(zoom), anchor ?? { x: sizeRef.current.width / 2, y: sizeRef.current.height / 2 })); + }, []); + + const zoomToFit = useCallback(() => { + const b = shapesBounds(live.current.shapes); + const { width, height } = sizeRef.current; + if (!b || !width) { + setCamera({ x: 0, y: 0, zoom: 1 }); + return; + } + setCamera(fitCamera(b, width, height, fitInsets(width))); + }, []); + + const setTool = useCallback((next: Tool) => { + setToolState(next); + if (next !== 'select') setSelection([]); + cursorRef.current = null; + }, []); + + const cancelInteraction = useCallback(() => { + interactionRef.current = { kind: 'none' }; + draftRef.current = null; + transientRef.current = new Map(); + fadedRef.current = new Set(); + erasePreviewRef.current = null; + marqueeRef.current = null; + setDrawing(false); + setPanning(false); + scheduleRender(); + }, [scheduleRender]); + + const selectedShapes = useMemo(() => shapes.filter((s) => selectedSet.has(s.id)), [shapes, selectedSet]); + + const deleteSelection = useCallback(() => { + if (!selectedSet.size) return; + commit((prev) => prev.filter((s) => !selectedSet.has(s.id))); + setSelection([]); + }, [commit, selectedSet]); + + const pasteShapes = useCallback( + (source: Shape[], offset: number) => { + if (!source.length) return; + const copies = source.map((s) => ({ ...translateShape(s, offset, offset), id: createId() })); + commit((prev) => [...prev, ...copies]); + if (hasTool('select')) { + setToolState('select'); + setSelection(copies.map((c) => c.id)); + } + return copies; + }, + [commit, hasTool], + ); + + const duplicateSelection = useCallback(() => pasteShapes(selectedShapes, 16), [pasteShapes, selectedShapes]); + + const reorderSelection = useCallback( + (toFront: boolean) => { + if (!selectedSet.size) return; + const picked = shapes.filter((s) => selectedSet.has(s.id)); + const rest = shapes.filter((s) => !selectedSet.has(s.id)); + commit(toFront ? [...rest, ...picked] : [...picked, ...rest]); + }, + [commit, shapes, selectedSet], + ); + + const clearCanvas = useCallback(() => { + if (!live.current.shapes.length) return; + commit([]); + setSelection([]); + notify(t.cleared.replace('Ctrl', MOD)); + }, [commit, notify, t]); + + const updateStyle = useCallback( + (patch: Partial) => { + setStyle((s) => ({ ...s, ...patch })); + if (selectedSet.size) commit((prev) => prev.map((s) => (selectedSet.has(s.id) ? applyStyle(s, patch) : s))); + if (editingRef.current) { + setEditing((e) => (e ? { ...e, color: patch.color ?? e.color, fontSize: patch.fontSize ?? e.fontSize } : e)); + } + }, + [commit, selectedSet], + ); + + // ---- text editing ------------------------------------------------------------------- + const startTextEdit = useCallback( + (at: Point, existing?: TextShape) => { + setSelection([]); + setEditing( + existing + ? { id: existing.id, x: existing.x, y: existing.y, text: existing.text, fontSize: existing.fontSize, color: existing.color } + : { id: null, x: at.x, y: at.y - (style.fontSize * LINE_HEIGHT) / 2, text: '', fontSize: style.fontSize, color: style.color }, + ); + }, + [style.color, style.fontSize], + ); + + const commitText = useCallback(() => { + const e = editingRef.current; + if (!e) return; + editingRef.current = null; + setEditing(null); + const text = e.text.replace(/\s+$/, ''); + if (!text.trim()) { + if (e.id) commit((prev) => prev.filter((s) => s.id !== e.id)); + return; + } + const size = measureText(text, e.fontSize); + if (e.id) { + commit((prev) => + prev.map((s) => (s.id === e.id && s.type === 'text' ? { ...s, text, fontSize: e.fontSize, color: e.color, ...size } : s)), + ); + } else { + const shape: TextShape = { + id: createId(), + type: 'text', + x: e.x, + y: e.y, + text, + fontSize: e.fontSize, + color: e.color, + strokeWidth: 1, + strokeStyle: 'solid', + ...size, + }; + commit((prev) => [...prev, shape]); + } + }, [commit]); + + // ---- import / export ---------------------------------------------------------------- + const exportPng = useCallback( + (opts?: ExportOptions & { scale?: number }) => exportToPngBlob(live.current.shapes, { theme: live.current.theme, ...opts }), + [], + ); + + const handleExportPng = useCallback(async () => { + if (!shapes.length) return notify(t.nothingToExport); + const blob = await exportPng(); + if (blob) downloadBlob(blob, timestampName('png')); + }, [exportPng, notify, shapes.length, t]); + + const handleExportSvg = useCallback(() => { + if (!shapes.length) return notify(t.nothingToExport); + downloadBlob(new Blob([exportToSvg(shapes, { theme })], { type: 'image/svg+xml' }), timestampName('svg')); + }, [notify, shapes, t, theme]); + + const handleSaveFile = useCallback(() => { + downloadBlob(new Blob([serialize(shapes)], { type: 'application/json' }), timestampName('json')); + }, [shapes]); + + const handleCopyPng = useCallback(async () => { + if (!shapes.length) return notify(t.nothingToExport); + try { + const blob = await exportPng(); + if (!blob) throw new Error('no blob'); + await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); + notify(t.copied); + } catch { + notify(t.copyFailed); + } + }, [exportPng, notify, shapes.length, t]); + + const loadFile = useCallback( + async (file: File) => { + try { + const next = deserialize(await file.text()); + commit(next); + setSelection([]); + needsFitRef.current = false; + const b = shapesBounds(next); + if (b && sizeRef.current.width) + setCamera(fitCamera(b, sizeRef.current.width, sizeRef.current.height, fitInsets(sizeRef.current.width))); + notify(t.loaded); + } catch { + notify(t.openFailed); + } + }, + [commit, notify, t], + ); + + useImperativeHandle( + ref, + () => ({ + getShapes: () => live.current.shapes, + setShapes: (next, options) => + dispatch(options?.history === false ? { type: 'reset', shapes: next } : { type: 'commit', shapes: next }), + clear: () => dispatch({ type: 'commit', shapes: [] }), + undo: () => dispatch({ type: 'undo' }), + redo: () => dispatch({ type: 'redo' }), + zoomToFit, + exportPng, + exportSvg: (opts) => exportToSvg(live.current.shapes, { theme: live.current.theme, ...opts }), + exportJson: () => serialize(live.current.shapes), + }), + [exportPng, zoomToFit], + ); + + // ---- pointer interaction ------------------------------------------------------------ + const localPoint = (e: { clientX: number; clientY: number }): Point => { + const rect = canvasRef.current!.getBoundingClientRect(); + return { x: e.clientX - rect.left, y: e.clientY - rect.top }; + }; + + /** Sample points along a drag so fast eraser moves don't skip anything. */ + const eraserSteps = (from: Point, to: Point, r: number) => { + const steps = Math.max(1, Math.ceil(distance(from, to) / (r / 2))); + return Array.from({ length: steps + 1 }, (_, i) => ({ + x: from.x + ((to.x - from.x) * i) / steps, + y: from.y + ((to.y - from.y) * i) / steps, + })); + }; + + const erasePartialAlong = (from: Point, to: Point, working: Shape[]): Shape[] => { + const { camera: cam, style: st } = live.current; + const r = st.eraserSize / cam.zoom; + let out = working; + for (const p of eraserSteps(from, to, r)) out = eraseAt(out, p, r, 0); + return out; + }; + + /** Pressure for a pen sample, from the stylus or simulated from speed. */ + const nextPressure = (ev: PointerEvent, screen: Point) => { + const prev = sampleRef.current; + const p = samplePressure({ + pointerType: ev.pointerType, + pressure: ev.pressure, + prev: prev?.p, + distance: prev ? Math.hypot(screen.x - prev.x, screen.y - prev.y) : 0, + dt: prev ? ev.timeStamp - prev.t : 16, + }); + sampleRef.current = { x: screen.x, y: screen.y, t: ev.timeStamp, p }; + return p; + }; + + const eraseAlong = (from: Point, to: Point, hits: Set) => { + const { shapes: list, camera: cam, style: st } = live.current; + const r = st.eraserSize / cam.zoom; + const steps = Math.max(1, Math.ceil(distance(from, to) / (r / 2))); + for (let i = 0; i <= steps; i++) { + const p = { x: from.x + ((to.x - from.x) * i) / steps, y: from.y + ((to.y - from.y) * i) / steps }; + for (const s of list) { + if (!hits.has(s.id) && shapeAt([s], p, r)) hits.add(s.id); + } + } + fadedRef.current = new Set(hits); + }; + + const onPointerDown = (e: ReactPointerEvent) => { + e.preventDefault(); + // Check before focusing: moving focus blurs the text editor, which commits it. + const wasEditing = !!editingRef.current; + if (wasEditing) commitText(); + containerRef.current?.focus({ preventScroll: true }); + setMenuOpen(false); + if (wasEditing) return; + const screen = localPoint(e); + pointersRef.current.set(e.pointerId, screen); + e.currentTarget.setPointerCapture?.(e.pointerId); + const cam = live.current.camera; + + if (pointersRef.current.size === 2) { + // Second finger: switch to pinch-zoom and discard whatever the first finger started. + cancelInteraction(); + const [a, b] = [...pointersRef.current.values()]; + interactionRef.current = { + kind: 'pinch', + startDist: Math.max(distance(a, b), 1), + startMid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, + startCamera: cam, + }; + return; + } + if (pointersRef.current.size > 2) return; + + if (e.button === 1 || tool === 'hand' || spaceDown) { + interactionRef.current = { kind: 'pan', startScreen: screen, startCamera: cam }; + setPanning(true); + return; + } + if (e.button !== 0) return; + + const world = screenToWorld(screen, cam); + const tol = HIT_TOLERANCE / cam.zoom; + + if (tool === 'select') { + const hit = shapeAt(shapes, world, tol); + if (hit) { + let nextSel = selection; + if (e.shiftKey) { + nextSel = selectedSet.has(hit.id) ? selection.filter((id) => id !== hit.id) : [...selection, hit.id]; + setSelection(nextSel); + if (!nextSel.includes(hit.id)) return; + } else if (!selectedSet.has(hit.id)) { + nextSel = [hit.id]; + setSelection(nextSel); + setStyle((s) => styleFromShape(hit, s)); + } + const ids = new Set(nextSel); + interactionRef.current = { + kind: 'move', + start: world, + originals: shapes.filter((s) => ids.has(s.id)), + moved: false, + clickedId: hit.id, }; - resize(); - const ro = new ResizeObserver(resize); - ro.observe(container); - return () => ro.disconnect(); - }, [draw]); - - // ---- persistence & change notification ------------------------------------------- - useEffect(() => { - if (!storageKey) return; - const id = window.setTimeout(() => { - saveState(storageKey, shapes, { - camera, - style, - grid, - theme: themeProp ? undefined : ownTheme, - locale: localeProp ? undefined : ownLocale, - }); - }, 300); - return () => window.clearTimeout(id); - }, [storageKey, shapes, camera, style, grid, ownTheme, ownLocale, themeProp, localeProp]); - - const onChangeRef = useRef(onChange); - onChangeRef.current = onChange; - const firstShapes = useRef(shapes); - useEffect(() => { - if (shapes !== firstShapes.current) onChangeRef.current?.(shapes); - }, [shapes]); - - // Drop selected ids that no longer exist (after undo, erase, etc.). - useEffect(() => { - setSelection((sel) => { - if (sel.length === 0) return sel; - const ids = new Set(shapes.map((s) => s.id)); - const next = sel.filter((id) => ids.has(id)); - return next.length === sel.length ? sel : next; + } else { + const base = e.shiftKey ? selection : []; + if (!e.shiftKey) setSelection([]); + interactionRef.current = { kind: 'marquee', start: world, base }; + marqueeRef.current = { a: world, b: world }; + } + return; + } + + if (tool === 'eraser' && style.eraserMode === 'partial') { + const working = erasePartialAlong(world, world, shapes); + erasePreviewRef.current = working; + interactionRef.current = { kind: 'erasePartial', last: world, working }; + cursorRef.current = screen; + scheduleRender(); + return; + } + + if (tool === 'eraser') { + const hits = new Set(); + eraseAlong(world, world, hits); + interactionRef.current = { kind: 'erase', last: world, hits }; + cursorRef.current = screen; + scheduleRender(); + return; + } + + if (tool === 'text') { + const hit = shapeAt(shapes, world, tol); + startTextEdit(world, hit?.type === 'text' ? hit : undefined); + return; + } + + if (isDrawableTool(tool)) { + sampleRef.current = null; + draftRef.current = createShape(tool, world, style, nextPressure(e.nativeEvent, screen)); + interactionRef.current = { kind: 'draw', start: world }; + setDrawing(true); + scheduleRender(); + } + }; + + const onPointerMove = (e: ReactPointerEvent) => { + const screen = localPoint(e); + if (pointersRef.current.has(e.pointerId)) pointersRef.current.set(e.pointerId, screen); + if (live.current.tool === 'eraser' && e.pointerType !== 'touch') { + cursorRef.current = screen; + scheduleRender(); + } + const it = interactionRef.current; + const cam = live.current.camera; + + switch (it.kind) { + case 'pinch': { + const pts = [...pointersRef.current.values()]; + if (pts.length < 2) return; + const [a, b] = pts; + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + const zoom = clampZoom(it.startCamera.zoom * (distance(a, b) / it.startDist)); + const k = zoom / it.startCamera.zoom; + setCamera({ zoom, x: mid.x - (it.startMid.x - it.startCamera.x) * k, y: mid.y - (it.startMid.y - it.startCamera.y) * k }); + return; + } + case 'pan': + setCamera({ + ...it.startCamera, + x: it.startCamera.x + screen.x - it.startScreen.x, + y: it.startCamera.y + screen.y - it.startScreen.y, }); - }, [shapes]); - - useEffect(() => { - if (!toast) return; - const id = window.setTimeout(() => setToast(null), 2600); - return () => window.clearTimeout(id); - }, [toast]); - - const notify = useCallback((message: string) => setToast({ id: Date.now(), message }), []); - - // ---- document helpers ------------------------------------------------------------- - const commit = useCallback((next: Shape[] | ((prev: Shape[]) => Shape[])) => dispatch({ type: 'commit', shapes: next }), []); - - const zoomTo = useCallback((zoom: number, anchor?: Point) => { - setCamera((c) => zoomAt(c, clampZoom(zoom), anchor ?? { x: sizeRef.current.width / 2, y: sizeRef.current.height / 2 })); - }, []); - - const zoomToFit = useCallback(() => { - const b = shapesBounds(live.current.shapes); - const { width, height } = sizeRef.current; - if (!b || !width) { - setCamera({ x: 0, y: 0, zoom: 1 }); - return; + return; + case 'draw': { + let draft = draftRef.current; + if (!draft) return; + const events = e.nativeEvent.getCoalescedEvents?.() ?? []; + const samples = draft.type === 'pen' || draft.type === 'highlighter' ? (events.length ? events : [e.nativeEvent]) : [e.nativeEvent]; + for (const ev of samples) { + const pt = localPoint(ev); + const pressure = draft.type === 'pen' && draft.pressure ? nextPressure(ev, pt) : undefined; + draft = updateDraft(draft, it.start, screenToWorld(pt, cam), e.shiftKey, cam.zoom, pressure); } - setCamera(fitCamera(b, width, height, fitInsets(width))); - }, []); - - const setTool = useCallback((next: Tool) => { - setToolState(next); - if (next !== 'select') setSelection([]); - cursorRef.current = null; - }, []); - - const cancelInteraction = useCallback(() => { - interactionRef.current = { kind: 'none' }; + draftRef.current = draft; + scheduleRender(); + return; + } + case 'move': { + const world = screenToWorld(screen, cam); + const dx = world.x - it.start.x; + const dy = world.y - it.start.y; + if (!it.moved && Math.hypot(dx, dy) * cam.zoom < 2) return; + it.moved = true; + transientRef.current = new Map(it.originals.map((s) => [s.id, translateShape(s, dx, dy)])); + scheduleRender(); + return; + } + case 'marquee': { + const world = screenToWorld(screen, cam); + marqueeRef.current = { a: it.start, b: world }; + const box = boundsFromPoints(it.start, world); + const inside = live.current.shapes.filter((s) => boundsIntersect(getBounds(s), box)).map((s) => s.id); + setSelection([...new Set([...it.base, ...inside])]); + scheduleRender(); + return; + } + case 'erasePartial': { + const world = screenToWorld(screen, cam); + it.working = erasePartialAlong(it.last, world, it.working); + erasePreviewRef.current = it.working; + it.last = world; + cursorRef.current = screen; + scheduleRender(); + return; + } + case 'erase': { + const world = screenToWorld(screen, cam); + eraseAlong(it.last, world, it.hits); + it.last = world; + cursorRef.current = screen; + scheduleRender(); + return; + } + } + }; + + const onPointerUp = (e: ReactPointerEvent) => { + pointersRef.current.delete(e.pointerId); + if (e.pointerType === 'touch') cursorRef.current = null; + const it = interactionRef.current; + if (it.kind === 'pinch') { + if (pointersRef.current.size === 0) interactionRef.current = { kind: 'none' }; + return; + } + interactionRef.current = { kind: 'none' }; + + switch (it.kind) { + case 'draw': { + const final = draftRef.current && finalizeShape(draftRef.current, live.current.camera.zoom); draftRef.current = null; + setDrawing(false); + if (final) commit((prev) => [...prev, final]); + else scheduleRender(); + break; + } + case 'move': { + const moved = transientRef.current; transientRef.current = new Map(); - fadedRef.current = new Set(); - erasePreviewRef.current = null; + if (it.moved && moved.size) commit((prev) => prev.map((s) => moved.get(s.id) ?? s)); + else if (!it.moved && !e.shiftKey && selection.length > 1) setSelection([it.clickedId]); + scheduleRender(); + break; + } + case 'marquee': marqueeRef.current = null; - setDrawing(false); - setPanning(false); scheduleRender(); - }, [scheduleRender]); - - const selectedShapes = useMemo(() => shapes.filter((s) => selectedSet.has(s.id)), [shapes, selectedSet]); - - const deleteSelection = useCallback(() => { - if (!selectedSet.size) return; - commit((prev) => prev.filter((s) => !selectedSet.has(s.id))); - setSelection([]); - }, [commit, selectedSet]); - - const pasteShapes = useCallback( - (source: Shape[], offset: number) => { - if (!source.length) return; - const copies = source.map((s) => ({ ...translateShape(s, offset, offset), id: createId() })); - commit((prev) => [...prev, ...copies]); - if (hasTool('select')) { - setToolState('select'); - setSelection(copies.map((c) => c.id)); - } - return copies; - }, - [commit, hasTool], - ); - - const duplicateSelection = useCallback(() => pasteShapes(selectedShapes, 16), [pasteShapes, selectedShapes]); - - const reorderSelection = useCallback( - (toFront: boolean) => { - if (!selectedSet.size) return; - const picked = shapes.filter((s) => selectedSet.has(s.id)); - const rest = shapes.filter((s) => !selectedSet.has(s.id)); - commit(toFront ? [...rest, ...picked] : [...picked, ...rest]); - }, - [commit, shapes, selectedSet], - ); - - const clearCanvas = useCallback(() => { - if (!live.current.shapes.length) return; - commit([]); - setSelection([]); - notify(t.cleared.replace('Ctrl', MOD)); - }, [commit, notify, t]); - - const updateStyle = useCallback( - (patch: Partial) => { - setStyle((s) => ({ ...s, ...patch })); - if (selectedSet.size) commit((prev) => prev.map((s) => (selectedSet.has(s.id) ? applyStyle(s, patch) : s))); - if (editingRef.current) { - setEditing((e) => - e ? { ...e, color: patch.color ?? e.color, fontSize: patch.fontSize ?? e.fontSize } : e, - ); - } - }, - [commit, selectedSet], - ); - - // ---- text editing ------------------------------------------------------------------- - const startTextEdit = useCallback( - (at: Point, existing?: TextShape) => { - setSelection([]); - setEditing( - existing - ? { id: existing.id, x: existing.x, y: existing.y, text: existing.text, fontSize: existing.fontSize, color: existing.color } - : { id: null, x: at.x, y: at.y - (style.fontSize * LINE_HEIGHT) / 2, text: '', fontSize: style.fontSize, color: style.color }, - ); - }, - [style.color, style.fontSize], - ); - - const commitText = useCallback(() => { - const e = editingRef.current; - if (!e) return; - editingRef.current = null; - setEditing(null); - const text = e.text.replace(/\s+$/, ''); - if (!text.trim()) { - if (e.id) commit((prev) => prev.filter((s) => s.id !== e.id)); - return; - } - const size = measureText(text, e.fontSize); - if (e.id) { - commit((prev) => prev.map((s) => (s.id === e.id && s.type === 'text' ? { ...s, text, fontSize: e.fontSize, color: e.color, ...size } : s))); - } else { - const shape: TextShape = { - id: createId(), - type: 'text', - x: e.x, - y: e.y, - text, - fontSize: e.fontSize, - color: e.color, - strokeWidth: 1, - strokeStyle: 'solid', - ...size, - }; - commit((prev) => [...prev, shape]); - } - }, [commit]); - - // ---- import / export ---------------------------------------------------------------- - const exportPng = useCallback( - (opts?: ExportOptions & { scale?: number }) => exportToPngBlob(live.current.shapes, { theme: live.current.theme, ...opts }), - [], - ); - - const handleExportPng = useCallback(async () => { - if (!shapes.length) return notify(t.nothingToExport); - const blob = await exportPng(); - if (blob) downloadBlob(blob, timestampName('png')); - }, [exportPng, notify, shapes.length, t]); - - const handleExportSvg = useCallback(() => { - if (!shapes.length) return notify(t.nothingToExport); - downloadBlob(new Blob([exportToSvg(shapes, { theme })], { type: 'image/svg+xml' }), timestampName('svg')); - }, [notify, shapes, t, theme]); - - const handleSaveFile = useCallback(() => { - downloadBlob(new Blob([serialize(shapes)], { type: 'application/json' }), timestampName('json')); - }, [shapes]); - - const handleCopyPng = useCallback(async () => { - if (!shapes.length) return notify(t.nothingToExport); - try { - const blob = await exportPng(); - if (!blob) throw new Error('no blob'); - await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); - notify(t.copied); - } catch { - notify(t.copyFailed); - } - }, [exportPng, notify, shapes.length, t]); - - const loadFile = useCallback( - async (file: File) => { - try { - const next = deserialize(await file.text()); - commit(next); - setSelection([]); - needsFitRef.current = false; - const b = shapesBounds(next); - if (b && sizeRef.current.width) setCamera(fitCamera(b, sizeRef.current.width, sizeRef.current.height, fitInsets(sizeRef.current.width))); - notify(t.loaded); - } catch { - notify(t.openFailed); - } - }, - [commit, notify, t], - ); - - useImperativeHandle( - ref, - () => ({ - getShapes: () => live.current.shapes, - setShapes: (next, options) => dispatch(options?.history === false ? { type: 'reset', shapes: next } : { type: 'commit', shapes: next }), - clear: () => dispatch({ type: 'commit', shapes: [] }), - undo: () => dispatch({ type: 'undo' }), - redo: () => dispatch({ type: 'redo' }), - zoomToFit, - exportPng, - exportSvg: (opts) => exportToSvg(live.current.shapes, { theme: live.current.theme, ...opts }), - exportJson: () => serialize(live.current.shapes), - }), - [exportPng, zoomToFit], - ); - - // ---- pointer interaction ------------------------------------------------------------ - const localPoint = (e: { clientX: number; clientY: number }): Point => { - const rect = canvasRef.current!.getBoundingClientRect(); - return { x: e.clientX - rect.left, y: e.clientY - rect.top }; - }; - - /** Sample points along a drag so fast eraser moves don't skip anything. */ - const eraserSteps = (from: Point, to: Point, r: number) => { - const steps = Math.max(1, Math.ceil(distance(from, to) / (r / 2))); - return Array.from({ length: steps + 1 }, (_, i) => ({ x: from.x + ((to.x - from.x) * i) / steps, y: from.y + ((to.y - from.y) * i) / steps })); - }; - - const erasePartialAlong = (from: Point, to: Point, working: Shape[]): Shape[] => { - const { camera: cam, style: st } = live.current; - const r = st.eraserSize / cam.zoom; - let out = working; - for (const p of eraserSteps(from, to, r)) out = eraseAt(out, p, r, 0); - return out; - }; - - /** Pressure for a pen sample, from the stylus or simulated from speed. */ - const nextPressure = (ev: PointerEvent, screen: Point) => { - const prev = sampleRef.current; - const p = samplePressure({ - pointerType: ev.pointerType, - pressure: ev.pressure, - prev: prev?.p, - distance: prev ? Math.hypot(screen.x - prev.x, screen.y - prev.y) : 0, - dt: prev ? ev.timeStamp - prev.t : 16, - }); - sampleRef.current = { x: screen.x, y: screen.y, t: ev.timeStamp, p }; - return p; - }; - - const eraseAlong = (from: Point, to: Point, hits: Set) => { - const { shapes: list, camera: cam, style: st } = live.current; - const r = st.eraserSize / cam.zoom; - const steps = Math.max(1, Math.ceil(distance(from, to) / (r / 2))); - for (let i = 0; i <= steps; i++) { - const p = { x: from.x + ((to.x - from.x) * i) / steps, y: from.y + ((to.y - from.y) * i) / steps }; - for (const s of list) { - if (!hits.has(s.id) && shapeAt([s], p, r)) hits.add(s.id); - } - } - fadedRef.current = new Set(hits); - }; - - const onPointerDown = (e: ReactPointerEvent) => { + break; + case 'erasePartial': { + erasePreviewRef.current = null; + const before = live.current.shapes; + if (it.working !== before) { + const result = it.working; + commit(() => result); + } else scheduleRender(); + break; + } + case 'erase': + fadedRef.current = new Set(); + if (it.hits.size) commit((prev) => prev.filter((s) => !it.hits.has(s.id))); + else scheduleRender(); + break; + case 'pan': + setPanning(false); + break; + } + }; + + const onPointerLeave = () => { + if (cursorRef.current) { + cursorRef.current = null; + scheduleRender(); + } + }; + + const onDoubleClick = (e: ReactMouseEvent) => { + if (tool !== 'select') return; + const cam = live.current.camera; + const world = screenToWorld(localPoint(e), cam); + const hit = shapeAt(shapes, world, HIT_TOLERANCE / cam.zoom); + if (!hit && hasTool('text')) startTextEdit(world); + else if (hit?.type === 'text') startTextEdit(world, hit); + }; + + // Wheel needs a non-passive listener so we can preventDefault. + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + const onWheel = (e: WheelEvent) => { + const scale = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1; + const dx = e.deltaX * scale; + const dy = e.deltaY * scale; + const rect = canvas.getBoundingClientRect(); + const anchor = { x: e.clientX - rect.left, y: e.clientY - rect.top }; + if (e.ctrlKey || e.metaKey) { e.preventDefault(); - // Check before focusing: moving focus blurs the text editor, which commits it. - const wasEditing = !!editingRef.current; - if (wasEditing) commitText(); - containerRef.current?.focus({ preventScroll: true }); - setMenuOpen(false); - if (wasEditing) return; - const screen = localPoint(e); - pointersRef.current.set(e.pointerId, screen); - e.currentTarget.setPointerCapture?.(e.pointerId); - const cam = live.current.camera; - - if (pointersRef.current.size === 2) { - // Second finger: switch to pinch-zoom and discard whatever the first finger started. - cancelInteraction(); - const [a, b] = [...pointersRef.current.values()]; - interactionRef.current = { - kind: 'pinch', - startDist: Math.max(distance(a, b), 1), - startMid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, - startCamera: cam, - }; - return; - } - if (pointersRef.current.size > 2) return; - - if (e.button === 1 || tool === 'hand' || spaceDown) { - interactionRef.current = { kind: 'pan', startScreen: screen, startCamera: cam }; - setPanning(true); - return; - } - if (e.button !== 0) return; - - const world = screenToWorld(screen, cam); - const tol = HIT_TOLERANCE / cam.zoom; - - if (tool === 'select') { - const hit = shapeAt(shapes, world, tol); - if (hit) { - let nextSel = selection; - if (e.shiftKey) { - nextSel = selectedSet.has(hit.id) ? selection.filter((id) => id !== hit.id) : [...selection, hit.id]; - setSelection(nextSel); - if (!nextSel.includes(hit.id)) return; - } else if (!selectedSet.has(hit.id)) { - nextSel = [hit.id]; - setSelection(nextSel); - setStyle((s) => styleFromShape(hit, s)); - } - const ids = new Set(nextSel); - interactionRef.current = { kind: 'move', start: world, originals: shapes.filter((s) => ids.has(s.id)), moved: false, clickedId: hit.id }; - } else { - const base = e.shiftKey ? selection : []; - if (!e.shiftKey) setSelection([]); - interactionRef.current = { kind: 'marquee', start: world, base }; - marqueeRef.current = { a: world, b: world }; - } - return; - } - - if (tool === 'eraser' && style.eraserMode === 'partial') { - const working = erasePartialAlong(world, world, shapes); - erasePreviewRef.current = working; - interactionRef.current = { kind: 'erasePartial', last: world, working }; - cursorRef.current = screen; - scheduleRender(); - return; - } - - if (tool === 'eraser') { - const hits = new Set(); - eraseAlong(world, world, hits); - interactionRef.current = { kind: 'erase', last: world, hits }; - cursorRef.current = screen; - scheduleRender(); - return; - } - - if (tool === 'text') { - const hit = shapeAt(shapes, world, tol); - startTextEdit(world, hit?.type === 'text' ? hit : undefined); - return; - } - - if (isDrawableTool(tool)) { - sampleRef.current = null; - draftRef.current = createShape(tool, world, style, nextPressure(e.nativeEvent, screen)); - interactionRef.current = { kind: 'draw', start: world }; - setDrawing(true); - scheduleRender(); - } - }; - - const onPointerMove = (e: ReactPointerEvent) => { - const screen = localPoint(e); - if (pointersRef.current.has(e.pointerId)) pointersRef.current.set(e.pointerId, screen); - if (live.current.tool === 'eraser' && e.pointerType !== 'touch') { - cursorRef.current = screen; - scheduleRender(); - } - const it = interactionRef.current; - const cam = live.current.camera; - - switch (it.kind) { - case 'pinch': { - const pts = [...pointersRef.current.values()]; - if (pts.length < 2) return; - const [a, b] = pts; - const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - const zoom = clampZoom(it.startCamera.zoom * (distance(a, b) / it.startDist)); - const k = zoom / it.startCamera.zoom; - setCamera({ zoom, x: mid.x - (it.startMid.x - it.startCamera.x) * k, y: mid.y - (it.startMid.y - it.startCamera.y) * k }); - return; - } - case 'pan': - setCamera({ ...it.startCamera, x: it.startCamera.x + screen.x - it.startScreen.x, y: it.startCamera.y + screen.y - it.startScreen.y }); - return; - case 'draw': { - let draft = draftRef.current; - if (!draft) return; - const events = e.nativeEvent.getCoalescedEvents?.() ?? []; - const samples = draft.type === 'pen' || draft.type === 'highlighter' ? (events.length ? events : [e.nativeEvent]) : [e.nativeEvent]; - for (const ev of samples) { - const pt = localPoint(ev); - const pressure = draft.type === 'pen' && draft.pressure ? nextPressure(ev, pt) : undefined; - draft = updateDraft(draft, it.start, screenToWorld(pt, cam), e.shiftKey, cam.zoom, pressure); - } - draftRef.current = draft; - scheduleRender(); - return; - } - case 'move': { - const world = screenToWorld(screen, cam); - const dx = world.x - it.start.x; - const dy = world.y - it.start.y; - if (!it.moved && Math.hypot(dx, dy) * cam.zoom < 2) return; - it.moved = true; - transientRef.current = new Map(it.originals.map((s) => [s.id, translateShape(s, dx, dy)])); - scheduleRender(); - return; - } - case 'marquee': { - const world = screenToWorld(screen, cam); - marqueeRef.current = { a: it.start, b: world }; - const box = boundsFromPoints(it.start, world); - const inside = live.current.shapes.filter((s) => boundsIntersect(getBounds(s), box)).map((s) => s.id); - setSelection([...new Set([...it.base, ...inside])]); - scheduleRender(); - return; - } - case 'erasePartial': { - const world = screenToWorld(screen, cam); - it.working = erasePartialAlong(it.last, world, it.working); - erasePreviewRef.current = it.working; - it.last = world; - cursorRef.current = screen; - scheduleRender(); - return; - } - case 'erase': { - const world = screenToWorld(screen, cam); - eraseAlong(it.last, world, it.hits); - it.last = world; - cursorRef.current = screen; - scheduleRender(); - return; - } - } - }; - - const onPointerUp = (e: ReactPointerEvent) => { - pointersRef.current.delete(e.pointerId); - if (e.pointerType === 'touch') cursorRef.current = null; - const it = interactionRef.current; - if (it.kind === 'pinch') { - if (pointersRef.current.size === 0) interactionRef.current = { kind: 'none' }; - return; - } - interactionRef.current = { kind: 'none' }; - - switch (it.kind) { - case 'draw': { - const final = draftRef.current && finalizeShape(draftRef.current); - draftRef.current = null; - setDrawing(false); - if (final) commit((prev) => [...prev, final]); - else scheduleRender(); - break; - } - case 'move': { - const moved = transientRef.current; - transientRef.current = new Map(); - if (it.moved && moved.size) commit((prev) => prev.map((s) => moved.get(s.id) ?? s)); - else if (!it.moved && !e.shiftKey && selection.length > 1) setSelection([it.clickedId]); - scheduleRender(); - break; - } - case 'marquee': - marqueeRef.current = null; - scheduleRender(); - break; - case 'erasePartial': { - erasePreviewRef.current = null; - const before = live.current.shapes; - if (it.working !== before) { - const result = it.working; - commit(() => result); - } else scheduleRender(); - break; - } - case 'erase': - fadedRef.current = new Set(); - if (it.hits.size) commit((prev) => prev.filter((s) => !it.hits.has(s.id))); - else scheduleRender(); - break; - case 'pan': - setPanning(false); - break; - } + const factor = Math.exp(-Math.max(-50, Math.min(50, dy)) * 0.01); + setCamera((c) => zoomAt(c, clampZoom(c.zoom * factor), anchor)); + } else if (captureWheel) { + e.preventDefault(); + const [px, py] = e.shiftKey && !dx ? [dy, 0] : [dx, dy]; + setCamera((c) => ({ ...c, x: c.x - px, y: c.y - py })); + } }; - - const onPointerLeave = () => { - if (cursorRef.current) { - cursorRef.current = null; - scheduleRender(); - } + canvas.addEventListener('wheel', onWheel, { passive: false }); + return () => canvas.removeEventListener('wheel', onWheel); + }, [captureWheel]); + + // ---- keyboard ----------------------------------------------------------------------- + const handleKeyDown = (e: KeyboardEvent | ReactKeyboardEvent) => { + if (isEditableTarget(e.target) || editingRef.current || helpOpen) return; + // Let Space/Enter activate focused buttons and links (keyboard accessibility). + if ((e.key === ' ' || e.key === 'Enter') && e.target instanceof HTMLElement && e.target.closest('button, a')) return; + const mod = e.ctrlKey || e.metaKey; + const key = e.key.toLowerCase(); + let handled = true; + + if (mod && key === 'z') dispatch({ type: e.shiftKey ? 'redo' : 'undo' }); + else if (mod && key === 'y') dispatch({ type: 'redo' }); + else if (mod && key === 'a' && hasTool('select')) { + setToolState('select'); + setSelection(shapes.map((s) => s.id)); + } else if (mod && key === 'd') duplicateSelection(); + else if (mod && key === 'c') clipboardRef.current = selectedShapes; + else if (mod && key === 'x') { + clipboardRef.current = selectedShapes; + deleteSelection(); + } else if (mod && key === 'v') pasteShapes(clipboardRef.current, 24); + else if (mod && (key === '=' || key === '+')) zoomTo(camera.zoom * 1.2); + else if (mod && key === '-') zoomTo(camera.zoom / 1.2); + else if (mod && key === '0') zoomTo(1); + else if (mod) handled = false; + else if (e.shiftKey && e.code === 'Digit1') zoomToFit(); + else if (key === 'delete' || key === 'backspace') deleteSelection(); + else if (key === 'escape') { + cancelInteraction(); + setSelection([]); + setMenuOpen(false); + } else if (key.startsWith('arrow') && selectedSet.size) { + const step = (e.shiftKey ? 10 : 1) / camera.zoom; + const dx = key === 'arrowleft' ? -step : key === 'arrowright' ? step : 0; + const dy = key === 'arrowup' ? -step : key === 'arrowdown' ? step : 0; + commit((prev) => prev.map((s) => (selectedSet.has(s.id) ? translateShape(s, dx, dy) : s))); + } else if (key === '[' || key === ']') reorderSelection(key === ']'); + else if (e.key === '?') setHelpOpen(true); + else if (key === ' ') { + if (!e.repeat) setSpaceDown(true); + } else { + const def = toolDefs.find((d) => (d.key === key || d.num === key) && !e.altKey); + if (def && !e.shiftKey) setTool(def.id); + else handled = false; + } + if (handled) e.preventDefault(); + }; + + const handleKeyUp = (e: KeyboardEvent | ReactKeyboardEvent) => { + if (e.key === ' ') setSpaceDown(false); + }; + + const keyHandlers = useRef({ down: handleKeyDown, up: handleKeyUp }); + keyHandlers.current = { down: handleKeyDown, up: handleKeyUp }; + + useEffect(() => { + if (!globalShortcuts) return; + const down = (e: KeyboardEvent) => keyHandlers.current.down(e); + const up = (e: KeyboardEvent) => keyHandlers.current.up(e); + const blur = () => setSpaceDown(false); + window.addEventListener('keydown', down); + window.addEventListener('keyup', up); + window.addEventListener('blur', blur); + return () => { + window.removeEventListener('keydown', down); + window.removeEventListener('keyup', up); + window.removeEventListener('blur', blur); }; - - const onDoubleClick = (e: ReactMouseEvent) => { - if (tool !== 'select') return; - const cam = live.current.camera; - const world = screenToWorld(localPoint(e), cam); - const hit = shapeAt(shapes, world, HIT_TOLERANCE / cam.zoom); - if (!hit && hasTool('text')) startTextEdit(world); - else if (hit?.type === 'text') startTextEdit(world, hit); - }; - - // Wheel needs a non-passive listener so we can preventDefault. - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - const onWheel = (e: WheelEvent) => { - const scale = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1; - const dx = e.deltaX * scale; - const dy = e.deltaY * scale; - const rect = canvas.getBoundingClientRect(); - const anchor = { x: e.clientX - rect.left, y: e.clientY - rect.top }; - if (e.ctrlKey || e.metaKey) { - e.preventDefault(); - const factor = Math.exp(-Math.max(-50, Math.min(50, dy)) * 0.01); - setCamera((c) => zoomAt(c, clampZoom(c.zoom * factor), anchor)); - } else if (captureWheel) { - e.preventDefault(); - const [px, py] = e.shiftKey && !dx ? [dy, 0] : [dx, dy]; - setCamera((c) => ({ ...c, x: c.x - px, y: c.y - py })); + }, [globalShortcuts]); + + // ---- derived UI state --------------------------------------------------------------- + const panelStyle = selectedShapes.length ? styleFromShape(selectedShapes[0], style) : style; + const showPanel = selectedShapes.length > 0 || DRAWING_TOOLS.includes(tool) || tool === 'eraser' || !!editing; + const cursor = panning + ? 'grabbing' + : spaceDown || tool === 'hand' + ? 'grab' + : tool === 'select' + ? 'default' + : tool === 'text' + ? 'text' + : tool === 'eraser' + ? 'none' + : 'crosshair'; + + const menuItems: MenuItem[] = [ + { kind: 'action', label: t.open, icon: , onClick: () => fileInputRef.current?.click() }, + { kind: 'action', label: t.saveFile, icon: , onClick: handleSaveFile }, + { kind: 'action', label: t.exportPng, icon: , onClick: handleExportPng }, + { kind: 'action', label: t.exportSvg, icon: , onClick: handleExportSvg }, + { kind: 'action', label: t.copyPng, icon: , onClick: handleCopyPng }, + { kind: 'separator' }, + { kind: 'toggle', label: t.grid, icon: , checked: grid, onClick: () => setGrid((g) => !g) }, + ...(themeProp + ? [] + : [ + { + kind: 'toggle' as const, + label: t.darkMode, + icon: , + checked: theme === 'dark', + onClick: () => { + const next = theme === 'dark' ? 'light' : 'dark'; + setOwnTheme(next); + onThemeChange?.(next); + }, + }, + ]), + ...(localeProp + ? [] + : [ + { kind: 'action' as const, label: t.language, icon: , onClick: () => setOwnLocale(locale === 'en' ? 'zh' : 'en') }, + ]), + { kind: 'action', label: t.shortcuts, icon: , onClick: () => setHelpOpen(true), shortcut: '?' }, + ...(githubUrl ? [{ kind: 'link' as const, label: t.github, icon: , href: githubUrl }] : []), + { kind: 'separator' }, + { kind: 'action', label: t.clear, icon: , onClick: clearCanvas, danger: true }, + ]; + + const editorScreen = editing ? worldToScreen({ x: editing.x, y: editing.y }, camera) : null; + const editorSize = editing ? measureText(editing.text || t.textPlaceholder, editing.fontSize) : null; + + return ( +
{ + if (e.dataTransfer.types.includes('Files')) e.preventDefault(); + }} + onDrop={(e) => { + const file = e.dataTransfer.files[0]; + if (!file) return; + e.preventDefault(); + loadFile(file); + }} + > + e.preventDefault()} + /> + + {shapes.length === 0 && !drawing && !editing &&
{t.emptyHint}
} + + {editing && editorScreen && editorSize && ( +