Skip to content

Realistic watercolor drawings

TypeScript paintwatercolor

preact

Maksim1091bffbedae
diff --git a/README.md b/README.md
index f070762..3f3e2c6 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# Watercolor
-A watercolour painting app in plain TypeScript and WebGL2, with almost no runtime dependencies.
+A watercolour painting app in TypeScript and WebGL2, with a Preact UI and few runtime dependencies.
It combines ideas from two projects:
- **[inkwash](https://github.com/johnowhitaker/inkwash)**: the GPU fluid simulation (velocity /
@@ -15,8 +15,23 @@ npm run dev # http://localhost:5173
npm run build # static site in dist/
```
-Small runtime dependencies: vpype-js for SVG import, q-floodfill for the bucket fill, and heic-to for iPhone HEIC photos. heic-to is about 3 MB, so it is a separate chunk and only downloads when a browser can't decode HEIC itself. Vite and TypeScript are only used at build time; the UI is plain DOM,
-and the simulation, colour science and rendering are TypeScript + GLSL.
+Small runtime dependencies: vpype-js for SVG import, q-floodfill for the bucket fill, and heic-to for iPhone HEIC photos. heic-to is about 3 MB, so it is a separate chunk and only downloads when a browser can't decode HEIC itself. Vite and TypeScript are only used at build time. The UI is Preact with `@preact/signals`; the
+simulation, colour science and rendering are TypeScript + GLSL and know nothing about the UI.
+
+## Code layout
+
+- `src/engine/` the WebGL2 simulation and renderer (`WatercolorEngine`), brushes, spectral colour, undo history.
+- `src/app/` the UI's state and wiring: `store.ts` holds every signal and action (`AppStore`), `registry.ts`
+ lists the tools, `keyboard.ts` the shortcuts, `persisted.ts` localStorage-backed signals.
+- `src/ui/` shared primitives: `Panel`, `PanelHead`, `ToolPanel`, `Seg` (radio group), `Slider` / `SliderRows`
+ (a list of sliders from a spec), `Icon`.
+- `src/components/` the chrome: toolbar, brush library, action bar, settings, palette, paper, overlays.
+- `src/text/`, `src/shapes/`, `src/fill/` panel tools. Each is a store class implementing `PanelTool`
+ (`active`, `busy`, `activate`, `deactivate`, `stop` and an optional `gesture` that `<Paper/>` forwards pointer
+ events to) plus a `*Panel.tsx` component. To add a tool, add a folder like these and one entry in `registry.ts`.
+- `src/reference/`, `src/export/` the reference image and save popovers, same store + panel split.
+
+In development `window.app` (the `AppStore`) and `window.engine` are exposed for scripting.
## Text and shapes
diff --git a/index.html b/index.html
index cf1f192..c95f92b 100644
--- a/index.html
+++ b/index.html
@@ -12,6 +12,6 @@
</head>
<body>
<div id="root"></div>
- <script type="module" src="/src/main.ts"></script>
+ <script type="module" src="/src/main.tsx"></script>
</body>
</html>
diff --git a/package-lock.json b/package-lock.json
index ff28321..4ac43b4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -8,15 +8,383 @@
"name": "watercolor",
"version": "0.1.0",
"dependencies": {
+ "@preact/signals": "^2.11.3",
"heic-to": "^1.6.5",
+ "preact": "^11.0.0",
"q-floodfill": "^1.3.1",
"vpype-js": "^0.1.0"
},
"devDependencies": {
+ "@preact/preset-vite": "^2.10.6",
"typescript": "^7.0.2",
"vite": "^8.3.2"
}
},
+ "node_modules/@babel/code-frame": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "js-tokens": "^4.0.0",
+ "picocolors": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "@jridgewell/remapping": "^2.3.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/babel"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
+ "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.8",
+ "@babel/types": "^7.29.8",
+ "@jridgewell/gen-mapping": "^0.3.12",
+ "@jridgewell/trace-mapping": "^0.3.28",
+ "jsesc": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-annotate-as-pure": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz",
+ "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
+ "browserslist": "^4.24.0",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-globals": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+ "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.9",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
+ "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-syntax-jsx": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz",
+ "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.29.7.tgz",
+ "integrity": "sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.29.7",
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-plugin-utils": "^7.29.7",
+ "@babel/plugin-syntax-jsx": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-development": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.29.7.tgz",
+ "integrity": "sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/plugin-transform-react-jsx": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
+ "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.8",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.8",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.8",
+ "debug": "^4.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.152.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",
@@ -27,6 +395,127 @@
"url": "https://github.com/sponsors/oxc-project"
}
},
+ "node_modules/@preact/preset-vite": {
+ "version": "2.10.6",
+ "resolved": "https://registry.npmjs.org/@preact/preset-vite/-/preset-vite-2.10.6.tgz",
+ "integrity": "sha512-ZZ5RIT2ZVXg8UxRA8VZpoT8CdpDG7RFIqOT4bELqNBp85+HKvQBbgmh3gsoW1UOQXx26TLe+ZRNKI7q281Kckw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/plugin-transform-react-jsx": "^7.27.1",
+ "@babel/plugin-transform-react-jsx-development": "^7.27.1",
+ "@prefresh/vite": "^2.4.11",
+ "@rollup/pluginutils": "^5.0.0",
+ "babel-plugin-transform-hook-names": "^1.0.2",
+ "debug": "^4.4.3",
+ "magic-string": "^0.30.21",
+ "picocolors": "^1.1.1",
+ "vite-prerender-plugin": "^0.5.8",
+ "zimmerframe": "^1.1.4"
+ },
+ "peerDependencies": {
+ "@babel/core": "7.x",
+ "vite": "2.x || 3.x || 4.x || 5.x || 6.x || 7.x || 8.x"
+ }
+ },
+ "node_modules/@preact/signals": {
+ "version": "2.11.3",
+ "resolved": "https://registry.npmjs.org/@preact/signals/-/signals-2.11.3.tgz",
+ "integrity": "sha512-mttwFM98G/JiriTgMwU+UWygL6sfVmYEiNcPSKkUnv4PxPpZhmP2ugGC4qi360+ZIHyQ8NY05bfJT3b4RUIGlw==",
+ "license": "MIT",
+ "dependencies": {
+ "@preact/signals-core": "^1.14.4"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ },
+ "peerDependencies": {
+ "preact": ">= 10.25.0 || >=11.0.0-0"
+ }
+ },
+ "node_modules/@preact/signals-core": {
+ "version": "1.14.4",
+ "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz",
+ "integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ }
+ },
+ "node_modules/@prefresh/babel-plugin": {
+ "version": "0.5.4",
+ "resolved": "https://registry.npmjs.org/@prefresh/babel-plugin/-/babel-plugin-0.5.4.tgz",
+ "integrity": "sha512-GSwqHGVem7AjnOKAkmLNbAExqZZFddf9S3ySOwowGEsJR8vwNKJ7Z/262fov5wra8LkDVSmFw3CjMGRdLoCmRA==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@babel/core": "^7.0.0 || ^8.0.0"
+ }
+ },
+ "node_modules/@prefresh/core": {
+ "version": "1.5.11",
+ "resolved": "https://registry.npmjs.org/@prefresh/core/-/core-1.5.11.tgz",
+ "integrity": "sha512-Ml00PP8jeHaADxfQqxUs4+M5JS+T5J26UnvPVfsrmlpGw2I3e9XtM0DMeuzkmvg+Tn7VdHSMpLBrDPG0iHoDqQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "preact": "^10.0.0 || ^11.0.0-0"
+ }
+ },
+ "node_modules/@prefresh/utils": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@prefresh/utils/-/utils-1.2.1.tgz",
+ "integrity": "sha512-vq/sIuN5nYfYzvyayXI4C2QkprfNaHUQ9ZX+3xLD8nL3rWyzpxOm1+K7RtMbhd+66QcaISViK7amjnheQ/4WZw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@prefresh/vite": {
+ "version": "2.4.12",
+ "resolved": "https://registry.npmjs.org/@prefresh/vite/-/vite-2.4.12.tgz",
+ "integrity": "sha512-FY1fzXpUjiuosznMV0YM7XAOPZjB5FIdWS0W24+XnlxYkt9hNAwwsiKYn+cuTEoMtD/ZVazS5QVssBr9YhpCQA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/core": "^7.22.1",
+ "@prefresh/babel-plugin": "^0.5.2",
+ "@prefresh/core": "^1.5.0",
+ "@prefresh/utils": "^1.2.0",
+ "@rollup/pluginutils": "^4.2.1"
+ },
+ "peerDependencies": {
+ "preact": "^10.4.0 || ^11.0.0-0",
+ "vite": ">=2.0.0"
+ }
+ },
+ "node_modules/@prefresh/vite/node_modules/@rollup/pluginutils": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz",
+ "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "estree-walker": "^2.0.1",
+ "picomatch": "^2.2.2"
+ },
+ "engines": {
+ "node": ">= 8.0.0"
+ }
+ },
+ "node_modules/@prefresh/vite/node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/@rgrove/parse-xml": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/@rgrove/parse-xml/-/parse-xml-4.2.3.tgz",
@@ -316,6 +805,36 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@rollup/pluginutils": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz",
+ "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "estree-walker": "^2.0.2",
+ "picomatch": "^4.0.2"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
@@ -656,6 +1175,146 @@
"node": ">=16.20.0"
}
},
+ "node_modules/babel-plugin-transform-hook-names": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/babel-plugin-transform-hook-names/-/babel-plugin-transform-hook-names-1.0.2.tgz",
+ "integrity": "sha512-5gafyjyyBTTdX/tQQ0hRgu4AhNHG/hqWi0ZZmg2xvs2FgRkJXzDNKBZCyoYqgFkovfDrgM8OoKg8karoUvWeCw==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@babel/core": "^7.12.10"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.11.27",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
+ "integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/browserslist": {
+ "version": "4.29.3",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
+ "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.11.26",
+ "caniuse-lite": "^1.0.30001813",
+ "electron-to-chromium": "^1.5.439",
+ "node-releases": "^2.0.57",
+ "update-browserslist-db": "^1.3.3"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001814",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
+ "integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/css-select": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz",
+ "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-what": "^6.1.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "nth-check": "^2.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/css-what": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz",
+ "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">= 6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -666,6 +1325,102 @@
"node": ">=8"
}
},
+ "node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.444",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz",
+ "integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -699,12 +1454,72 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/he": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
+ "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "he": "bin/he"
+ }
+ },
"node_modules/heic-to": {
"version": "1.6.5",
"resolved": "https://registry.npmjs.org/heic-to/-/heic-to-1.6.5.tgz",
"integrity": "sha512-xPH6gvrzSRIFo/GyzYbr+DZX1JoQliw1oJBT1PCduR0ruDVs1DjlAdU1m5Thed2ZXBoLqYMCd5UXiJteRl3BNQ==",
"license": "LGPL-3.0"
},
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jsesc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/kolorist": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz",
+ "integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
@@ -978,6 +1793,33 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/nanoid": {
"version": "3.3.19",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
@@ -997,6 +1839,40 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/node-html-parser": {
+ "version": "6.1.13",
+ "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-6.1.13.tgz",
+ "integrity": "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "css-select": "^5.1.0",
+ "he": "1.2.0"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.57",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
+ "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/nth-check": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
+ "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -1046,6 +1922,24 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/preact": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/preact/-/preact-11.0.0.tgz",
+ "integrity": "sha512-LRTLKuSe6VYPhvBDjwFaX+nuZnpsw6IN2GSboisAvhGsncylBmrbDCERhgKDn6yP2mAwbGvsB5OVyTe33M8gBg==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ },
+ "peerDependencies": {
+ "preact-render-to-string": ">=6.7.0"
+ },
+ "peerDependenciesMeta": {
+ "preact-render-to-string": {
+ "optional": true
+ }
+ }
+ },
"node_modules/q-floodfill": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/q-floodfill/-/q-floodfill-1.3.1.tgz",
@@ -1086,6 +1980,26 @@
"@rolldown/binding-win32-x64-msvc": "1.2.12"
}
},
+ "node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/simple-code-frame": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/simple-code-frame/-/simple-code-frame-1.3.0.tgz",
+ "integrity": "sha512-MB4pQmETUBlNs62BBeRjIFGeuy/x6gGKh7+eRUemn1rCFhqo7K+4slPqsyizCbcbYLnaYqaoZ2FWsZ/jN06D8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "kolorist": "^1.6.0"
+ }
+ },
"node_modules/smol-toml": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz",
@@ -1098,6 +2012,16 @@
"url": "https://github.com/sponsors/cyyynthia"
}
},
+ "node_modules/source-map": {
+ "version": "0.7.6",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
@@ -1108,6 +2032,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/stack-trace": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-1.0.0.tgz",
+ "integrity": "sha512-H6D7134xi6qONvh7ZHKgviXf+rd3vhGBSvebPZCaUkd8zvQ+7PtDw6CljPTe4cXWNf2IKZGNqw6VJXSb9IgBpA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/svgpath": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/svgpath/-/svgpath-2.6.0.tgz",
@@ -1169,6 +2103,37 @@
"@typescript/typescript-win32-x64": "7.0.2"
}
},
+ "node_modules/update-browserslist-db": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
+ "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
"node_modules/vite": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.2.tgz",
@@ -1247,6 +2212,24 @@
}
}
},
+ "node_modules/vite-prerender-plugin": {
+ "version": "0.5.14",
+ "resolved": "https://registry.npmjs.org/vite-prerender-plugin/-/vite-prerender-plugin-0.5.14.tgz",
+ "integrity": "sha512-X2w9AS1OhwEUec9HSryGAmEnEQJGhW6eFoiCVJv8BfOTVpM8SOjk75cEw/IC28APDHZudeIRbP8Sp7wfABq+Aw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "kolorist": "^1.8.0",
+ "magic-string": "0.x >= 0.26.0",
+ "node-html-parser": "^6.1.12",
+ "simple-code-frame": "^1.3.0",
+ "source-map": "^0.7.4",
+ "stack-trace": "^1.0.0-pre2"
+ },
+ "peerDependencies": {
+ "vite": "5.x || 6.x || 7.x || 8.x"
+ }
+ },
"node_modules/vpype-js": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/vpype-js/-/vpype-js-0.1.0.tgz",
@@ -1263,6 +2246,20 @@
"engines": {
"node": ">=18"
}
+ },
+ "node_modules/yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/zimmerframe": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz",
+ "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==",
+ "dev": true,
+ "license": "MIT"
}
}
}
diff --git a/package.json b/package.json
index 0e86b89..d5a5e81 100644
--- a/package.json
+++ b/package.json
@@ -10,11 +10,14 @@
"typecheck": "tsc -b"
},
"devDependencies": {
+ "@preact/preset-vite": "^2.10.6",
"typescript": "^7.0.2",
"vite": "^8.3.2"
},
"dependencies": {
+ "@preact/signals": "^2.11.3",
"heic-to": "^1.6.5",
+ "preact": "^11.0.0",
"q-floodfill": "^1.3.1",
"vpype-js": "^0.1.0"
}
diff --git a/src/app/App.tsx b/src/app/App.tsx
new file mode 100644
index 0000000..992c259
--- /dev/null
+++ b/src/app/App.tsx
@@ -0,0 +1,67 @@
+import { useEffect, useState } from 'preact/hooks';
+import { ActionBar } from '../components/ActionBar';
+import { BrushLibrary } from '../components/BrushLibrary';
+import { DropChoice, Ghost, Toast } from '../components/Overlays';
+import { Palette } from '../components/Palette';
+import { Paper } from '../components/Paper';
+import { SettingsPanel } from '../components/SettingsPanel';
+import { Toolbar } from '../components/Toolbar';
+import { ExportPanel } from '../export/ExportPanel';
+import { ReferencePanel } from '../reference/ReferencePanel';
+import { RefFrame } from '../reference/RefFrame';
+import { AppContext, useApp } from './context';
+import { useKeyboard } from './keyboard';
+import { bumpResize } from './resize';
+import type { AppStore } from './store';
+
+/** Everything but the paper: toolbars, panels and overlays. Rendered once the engine exists. */
+function Chrome() {
+ const app = useApp();
+ useKeyboard(app);
+ useEffect(() => {
+ const onResize = () => { app.resize(); bumpResize(); };
+ window.addEventListener('resize', onResize);
+ return () => window.removeEventListener('resize', onResize);
+ }, [app]);
+ return <>
+ <Toolbar />
+ <BrushLibrary />
+ <ActionBar />
+ <SettingsPanel />
+ <ReferencePanel />
+ <ExportPanel />
+ <Palette />
+ {[...app.panelTools.values()].map(({ def, tool }) => <def.Panel key={def.id} tool={tool} />)}
+ <RefFrame />
+ <Ghost />
+ <DropChoice />
+ </>;
+}
+
+export function App() {
+ const [app, setApp] = useState<AppStore | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (app && import.meta.env.DEV) (window as unknown as { app: AppStore; engine: unknown }).app = app, (window as unknown as { engine: unknown }).engine = app.engine;
+ }, [app]);
+
+ if (error) return <div class="error"><p>{error}</p><p class="sub">A browser with WebGL2 is required.</p></div>;
+
+ // drop an image anywhere to use it as the reference or make a brush from it
+ const onDragOver = (e: DragEvent) => { if (e.dataTransfer?.types.includes('Files')) e.preventDefault(); };
+ const onDrop = (e: DragEvent) => {
+ const f = e.dataTransfer?.files?.[0];
+ if (f && app?.dropFile(f, e.clientX, e.clientY)) e.preventDefault();
+ };
+
+ return (
+ <AppContext.Provider value={app}>
+ <div class="app" onDragOver={onDragOver} onDrop={onDrop}>
+ <Paper app={app} onReady={setApp} onError={e => setError(e instanceof Error ? e.message : String(e))} />
+ {app && <Chrome />}
+ <Toast />
+ </div>
+ </AppContext.Provider>
+ );
+}
diff --git a/src/app/context.ts b/src/app/context.ts
new file mode 100644
index 0000000..02dd654
--- /dev/null
+++ b/src/app/context.ts
@@ -0,0 +1,12 @@
+import { createContext } from 'preact';
+import { useContext } from 'preact/hooks';
+import type { AppStore } from './store';
+
+export const AppContext = createContext<AppStore | null>(null);
+
+/** The app store; components are always rendered inside <AppContext.Provider>. */
+export function useApp(): AppStore {
+ const app = useContext(AppContext);
+ if (!app) throw new Error('useApp outside <AppContext.Provider>');
+ return app;
+}
diff --git a/src/app/keyboard.ts b/src/app/keyboard.ts
new file mode 100644
index 0000000..24ba1e1
--- /dev/null
+++ b/src/app/keyboard.ts
@@ -0,0 +1,33 @@
+import { useEffect } from 'preact/hooks';
+import { PALETTE } from '../palette';
+import { ENGINE_TOOLS, PANEL_TOOLS } from './registry';
+import type { AppStore } from './store';
+
+/** Global shortcuts. Text fields keep their keys; range sliders do not. */
+export function useKeyboard(app: AppStore) {
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.target instanceof HTMLInputElement && e.target.type !== 'range') return;
+ const k = e.key.toLowerCase();
+ if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); if (e.shiftKey) app.redo(); else app.undo(); return; }
+ if ((e.metaKey || e.ctrlKey) && k === 'y') { e.preventDefault(); app.redo(); return; }
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (k === 'escape') { app.escape(); return; }
+ const tool = [...ENGINE_TOOLS, ...PANEL_TOOLS].find(t => t.key.toLowerCase() === k);
+ if (tool) app.setTool(tool.id);
+ else if (k === '[' || k === ']') app.setParams({ size: Math.min(1, Math.max(0, app.params.peek().size + (k === ']' ? 0.05 : -0.05))) });
+ else if (k === ',' || k === '<') app.cycleBrush(-1);
+ else if (k === '.' || k === '>') app.cycleBrush(1);
+ else if (k === 'd') app.dry();
+ else if (k === 's') void app.exporter.save();
+ else if (k === 'r') app.reference.toggleVisible();
+ else if (k === 'f') {
+ if (document.fullscreenElement) void document.exitFullscreen();
+ else void document.documentElement.requestFullscreen?.();
+ } else if (/^[1-9]$/.test(k)) app.choose(PALETTE[Number(k) - 1]);
+ else if (k === '0') app.choose(PALETTE[PALETTE.length - 1]);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [app]);
+}
diff --git a/src/app/persisted.ts b/src/app/persisted.ts
new file mode 100644
index 0000000..395481c
--- /dev/null
+++ b/src/app/persisted.ts
@@ -0,0 +1,28 @@
+import { effect, signal, type Signal } from '@preact/signals';
+
+/**
+ * A signal backed by localStorage. Reads once (merged over `defaults`, then passed through
+ * `sanitize`) and writes on every change. Storage that is full or blocked fails quietly.
+ */
+export function persisted<T extends object>(key: string, defaults: T, sanitize: (v: T) => T = v => v): Signal<T> {
+ let value: T = { ...defaults };
+ try {
+ const raw = localStorage.getItem(key);
+ const parsed = raw ? (JSON.parse(raw) as unknown) : null;
+ if (parsed && typeof parsed === 'object') value = { ...value, ...(parsed as Partial<T>) };
+ } catch { /* storage blocked or corrupt */ }
+ const s = signal(sanitize(value));
+ let first = true;
+ effect(() => {
+ const v = s.value;
+ if (first) { first = false; return; }
+ try { localStorage.setItem(key, JSON.stringify(v)); } catch { /* storage blocked */ }
+ });
+ return s;
+}
+
+/** A single string remembered in localStorage (no JSON). */
+export const storedString = {
+ get(key: string): string | null { try { return localStorage.getItem(key); } catch { return null; } },
+ set(key: string, v: string) { try { localStorage.setItem(key, v); } catch { /* storage blocked */ } },
+};
diff --git a/src/app/registry.ts b/src/app/registry.ts
new file mode 100644
index 0000000..6620da1
--- /dev/null
+++ b/src/app/registry.ts
@@ -0,0 +1,35 @@
+import type { Tool } from '../engine/Engine';
+import { FillPanel } from '../fill/FillPanel';
+import { FillStore } from '../fill/FillStore';
+import { ShapePanel } from '../shapes/ShapePanel';
+import { ShapeStore } from '../shapes/ShapeStore';
+import { TextPanel } from '../text/TextPanel';
+import { TextStore } from '../text/TextStore';
+import { defineTool, type PanelToolDef } from './tools';
+
+/** The engine's own tools, in toolbar order. */
+export const ENGINE_TOOLS: { id: Tool; label: string; key: string; hint: string }[] = [
+ { id: 'brush', label: 'Brush', key: 'B', hint: 'Wet paint: pigment and water' },
+ { id: 'water', label: 'Water', key: 'W', hint: 'Clear water: wets paper, moves paint' },
+ { id: 'pen', label: 'Pen', key: 'P', hint: 'Ink line in the current colour' },
+ { id: 'lift', label: 'Lift', key: 'L', hint: 'Blot with a tissue: lifts wet paint' },
+];
+
+/** Tools with their own panel that drive the engine themselves. To add one, append it here. */
+export const PANEL_TOOLS: PanelToolDef[] = [
+ defineTool<TextStore>({
+ id: 'text', label: 'Text', key: 'T', icon: 'text',
+ hint: 'Write a line of text, drawn slowly with the current brush',
+ create: ({ engine }) => new TextStore(engine), Panel: TextPanel,
+ }),
+ defineTool<ShapeStore>({
+ id: 'shape', label: 'Shape', key: 'G', icon: 'shape',
+ hint: 'Drag a line, arrow, rectangle, ellipse, polygon or star, drawn slowly with the current brush',
+ create: ({ engine }) => new ShapeStore(engine), Panel: ShapePanel,
+ }),
+ defineTool<FillStore>({
+ id: 'fill', label: 'Fill', key: 'K', icon: 'fill',
+ hint: 'Tap an area to flood it with a wash of the current pigment',
+ create: ({ engine }) => new FillStore(engine), Panel: FillPanel,
+ }),
+];
diff --git a/src/app/resize.ts b/src/app/resize.ts
new file mode 100644
index 0000000..4885125
--- /dev/null
+++ b/src/app/resize.ts
@@ -0,0 +1,5 @@
+import { signal } from '@preact/signals';
+
+/** Bumped on every window resize so layout-dependent effects (ghosts, frames, thumbnails) re-run. */
+export const resizeTick = signal(0);
+export const bumpResize = () => { resizeTick.value++; };
diff --git a/src/app/store.ts b/src/app/store.ts
new file mode 100644
index 0000000..62f12e8
--- /dev/null
+++ b/src/app/store.ts
@@ -0,0 +1,215 @@
+import { computed, effect, signal } from '@preact/signals';
+import { BRUSH_PRESETS, buildBrush, type Brush } from '../engine/brushes';
+import { DEFAULT_PARAMS, WatercolorEngine, type Params, type Tool } from '../engine/Engine';
+import { ExportStore } from '../export/ExportStore';
+import { PALETTE, type PaletteEntry } from '../palette';
+import { isRasterFile } from '../reference/decode';
+import { ReferenceStore } from '../reference/ReferenceStore';
+import type { ShapeStore } from '../shapes/ShapeStore';
+import { isSvgFile } from '../shapes/svgImport';
+import { loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } from '../ui/customBrushes';
+import { forgetTipImages } from '../ui/preview';
+import { storedString } from './persisted';
+import { ENGINE_TOOLS, PANEL_TOOLS } from './registry';
+import { showToast } from './toast';
+import type { PanelTool, PanelToolDef } from './tools';
+
+/** An engine tool or the id of a panel tool from the registry. */
+export type UiTool = Tool | string;
+export type PopoverId = 'settings' | 'reference' | 'save';
+
+const BRUSH_KEY = 'watercolor.brush';
+const isEngineTool = (t: UiTool): t is Tool => ENGINE_TOOLS.some(e => e.id === t);
+
+/**
+ * All UI state as signals, plus the actions that change it. Owns the engine and the
+ * tool stores. Components read signals and call actions; effects mirror state into
+ * the engine so no component talks to it for state it also displays.
+ */
+export class AppStore {
+ readonly engine: WatercolorEngine;
+
+ readonly tool = signal<UiTool>('brush');
+ /** A tool temporarily chosen by the stylus (barrel button, eraser) for the current stroke. */
+ readonly strokeTool = signal<Tool | null>(null);
+ /** The tool to highlight in the toolbar. */
+ readonly shownTool = computed(() => this.strokeTool.value ?? this.tool.value);
+ readonly params = signal<Params>({ ...DEFAULT_PARAMS });
+ readonly current = signal<PaletteEntry>(PALETTE[5]);
+ readonly previous = signal<PaletteEntry>(PALETTE[0]);
+ readonly builtIn: Brush[] = BRUSH_PRESETS.map(p => buildBrush(p));
+ readonly customs = signal<Brush[]>([]);
+ readonly allBrushes = computed(() => [...this.builtIn, ...this.customs.value]);
+ readonly brush = signal<Brush>(this.builtIn[0]);
+ /** Colour used for brush previews: the current pigment, or ink for white gouache. */
+ readonly previewHex = computed(() => (this.current.value.pigment.white ? '#3b4552' : this.current.value.hex));
+ readonly canUndo = signal(false);
+ readonly canRedo = signal(false);
+ /** Small panels that drop down under the action bar, one at a time. */
+ readonly popover = signal<PopoverId | null>(null);
+ readonly libraryOpen = signal(false);
+ readonly confirmClear = signal(false);
+ readonly hintGone = signal(false);
+ /** A dropped image waiting for the user to say what it is for. */
+ readonly dropped = signal<{ file: File; x: number; y: number } | null>(null);
+
+ readonly panelTools = new Map<string, { def: PanelToolDef; tool: PanelTool }>();
+ readonly reference: ReferenceStore;
+ readonly exporter: ExportStore;
+ /** The active panel tool, if the current tool is one. */
+ readonly activePanelTool = computed(() => this.panelTools.get(this.tool.value)?.tool ?? null);
+
+ private confirmTimer = 0;
+
+ constructor(canvas: HTMLCanvasElement, cursor: HTMLElement) {
+ this.engine = new WatercolorEngine(canvas, cursor, {
+ onHistoryChange: (u, r) => { this.canUndo.value = u; this.canRedo.value = r; },
+ onStrokeTool: t => { this.strokeTool.value = t; },
+ });
+ const ctx = { engine: this.engine };
+ for (const def of PANEL_TOOLS) this.panelTools.set(def.id, { def, tool: def.create(ctx) });
+ this.reference = new ReferenceStore(this.engine);
+ this.exporter = new ExportStore(this.engine);
+
+ // mirror state into the engine
+ effect(() => this.engine.setParams(this.params.value));
+ effect(() => this.engine.setPigment(this.current.value.pigment));
+ effect(() => this.engine.setBrush(this.brush.value));
+ effect(() => { const t = this.tool.value; if (isEngineTool(t)) this.engine.setTool(t); });
+ effect(() => { this.engine.interactive = isEngineTool(this.tool.value) && !this.reference.adjusting.value; });
+ effect(() => storedString.set(BRUSH_KEY, this.brush.value.id));
+
+ void loadCustomBrushes().then(list => {
+ this.customs.value = list;
+ const wanted = storedString.get(BRUSH_KEY);
+ const b = wanted && this.allBrushes.peek().find(x => x.id === wanted);
+ if (b) this.brush.value = b;
+ });
+ }
+
+ /** A panel tool's store by id, typed by the caller. */
+ panelTool<T extends PanelTool>(id: string): T { return this.panelTools.get(id)!.tool as T; }
+ isPanelTool(t: UiTool) { return this.panelTools.has(t); }
+
+ /* -------------------------------------------------------------- actions */
+
+ setTool(t: UiTool) {
+ const prev = this.tool.peek();
+ if (this.isPanelTool(t) && t !== prev) this.toggleLibrary(false);
+ this.reference.stopAdjust();
+ for (const [id, p] of this.panelTools) if (p.tool.active.peek() && id !== t) p.tool.deactivate();
+ this.tool.value = t;
+ if (this.isPanelTool(t)) this.panelTools.get(t)!.tool.activate();
+ }
+
+ setParams(p: Partial<Params>) { this.params.value = { ...this.params.value, ...p }; }
+
+ choose(e: PaletteEntry) {
+ const cur = this.current.peek();
+ if (cur.hex !== e.hex) this.previous.value = cur;
+ this.current.value = e;
+ const t = this.tool.peek();
+ if (t === 'water' || t === 'lift') this.setTool('brush');
+ }
+
+ chooseBrush(b: Brush) {
+ this.brush.value = b;
+ const t = this.tool.peek();
+ if (t === 'pen' || t === 'lift') this.setTool('brush');
+ }
+
+ cycleBrush(dir: 1 | -1) {
+ const list = this.allBrushes.peek();
+ const i = list.findIndex(b => b.id === this.brush.peek().id);
+ this.chooseBrush(list[(i + dir + list.length) % list.length]);
+ showToast(this.brush.peek().name);
+ }
+
+ async importTexture(file: File) {
+ try {
+ const tip = await tipFromImage(file);
+ const name = file.name.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').trim().slice(0, 22) || 'Imported';
+ const b = makeCustomBrush(`custom-${Date.now().toString(36)}`, name, tip);
+ this.customs.value = [...this.customs.value, b];
+ if (!saveCustomBrushes(this.customs.value)) showToast('Brush added, but could not be saved for next time');
+ this.chooseBrush(b);
+ } catch (e) {
+ showToast(e instanceof Error ? e.message : 'Could not read that image');
+ }
+ }
+
+ removeBrush(id: string) {
+ if (!this.customs.peek().some(c => c.id === id)) return;
+ this.customs.value = this.customs.value.filter(c => c.id !== id);
+ saveCustomBrushes(this.customs.value);
+ this.engine.forgetBrush(id);
+ forgetTipImages(id);
+ if (this.brush.peek().id === id) this.chooseBrush(this.builtIn[0]);
+ }
+
+ /** A file picked or dropped: SVGs become a shape to trace, rasters a brush tip. */
+ importFile(file: File) {
+ if (isSvgFile(file)) void this.panelTool<ShapeStore>('shape').loadSvg(file).then(ok => { if (ok) this.setTool('shape'); });
+ else void this.importTexture(file);
+ }
+
+ /** A file dropped on the page: SVGs are traced, rasters ask whether they are a reference or a brush. */
+ dropFile(file: File, x: number, y: number): boolean {
+ if (isSvgFile(file)) { this.importFile(file); return true; }
+ if (isRasterFile(file)) { this.dropped.value = { file, x, y }; return true; }
+ return false;
+ }
+
+ resolveDrop(as: 'reference' | 'brush') {
+ const d = this.dropped.peek();
+ this.dropped.value = null;
+ if (!d) return;
+ if (as === 'reference') void this.reference.load(d.file);
+ else void this.importTexture(d.file);
+ }
+
+ closeDrop() { this.dropped.value = null; }
+
+ undo() { this.engine.undo(); }
+ redo() { this.engine.redo(); }
+ dry() { this.engine.fix(); }
+
+ /** First press arms the button ("Sure?"), a second press within 2.5 s clears. */
+ clear() {
+ clearTimeout(this.confirmTimer);
+ if (!this.confirmClear.peek()) {
+ this.confirmClear.value = true;
+ this.confirmTimer = window.setTimeout(() => { this.confirmClear.value = false; }, 2500);
+ return;
+ }
+ this.engine.clear();
+ this.reference.syncRect();
+ this.confirmClear.value = false;
+ }
+
+ /** Open or close one popover (toggling when `force` is omitted); opening one closes the rest. */
+ togglePopover(name: PopoverId, force?: boolean) {
+ const open = force ?? this.popover.peek() !== name;
+ this.popover.value = open ? name : null;
+ }
+
+ closePopovers() { this.popover.value = null; }
+
+ toggleLibrary(force?: boolean) { this.libraryOpen.value = force ?? !this.libraryOpen.peek(); }
+
+ /** Escape: the most transient thing goes first. */
+ escape() {
+ if (this.dropped.peek()) { this.closeDrop(); return; }
+ if (this.reference.stopAdjust()) return;
+ for (const p of this.panelTools.values()) if (p.tool.stop()) return;
+ this.toggleLibrary(false);
+ this.closePopovers();
+ }
+
+ resize() {
+ this.engine.resize();
+ this.reference.syncRect();
+ }
+
+ destroy() { this.engine.destroy(); }
+}
diff --git a/src/app/toast.ts b/src/app/toast.ts
new file mode 100644
index 0000000..c3542dd
--- /dev/null
+++ b/src/app/toast.ts
@@ -0,0 +1,11 @@
+import { signal } from '@preact/signals';
+
+/** The short confirmation shown at the top of the screen, or null. */
+export const toast = signal<string | null>(null);
+let timer = 0;
+
+export function showToast(text: string) {
+ clearTimeout(timer);
+ toast.value = text;
+ timer = window.setTimeout(() => { toast.value = null; }, 1200);
+}
diff --git a/src/app/tools.ts b/src/app/tools.ts
new file mode 100644
index 0000000..55724ba
--- /dev/null
+++ b/src/app/tools.ts
@@ -0,0 +1,49 @@
+import type { ReadonlySignal } from '@preact/signals';
+import type { JSX } from 'preact';
+import type { WatercolorEngine } from '../engine/Engine';
+
+// Panel tools (text, shape, fill, ...) have their own panel and drive the engine
+// themselves while active. Each is a store class implementing PanelTool, plus a
+// panel component; `app/registry.ts` lists them. Adding a tool is one folder and
+// one registry entry.
+
+/** Pointer events on the paper, forwarded to the active panel tool by <Paper/>. `uv` is document space. */
+export interface PaperGesture {
+ down?(e: PointerEvent, uv: [number, number]): void;
+ move?(e: PointerEvent, uv: [number, number]): void;
+ up?(e: PointerEvent, uv: [number, number]): void;
+ cancel?(e: PointerEvent): void;
+ /** The pointer left the paper (moved onto a panel or off the window). */
+ leave?(): void;
+}
+
+export interface PanelTool {
+ readonly id: string;
+ readonly active: ReadonlySignal<boolean>;
+ /** Drawing / filling in progress. */
+ readonly busy: ReadonlySignal<boolean>;
+ activate(): void;
+ deactivate(): void;
+ /** Stop whatever is in progress. Returns whether anything was stopped. */
+ stop(): boolean;
+ readonly gesture?: PaperGesture;
+}
+
+export interface ToolContext {
+ engine: WatercolorEngine;
+}
+
+export interface PanelToolDef<T extends PanelTool = PanelTool> {
+ id: string;
+ label: string;
+ /** Keyboard shortcut (single letter). */
+ key: string;
+ hint: string;
+ /** Icon name (see ui/Icon.tsx). */
+ icon: string;
+ create(ctx: ToolContext): T;
+ Panel: (props: { tool: T }) => JSX.Element;
+}
+
+/** Erases the store type so differently typed tools fit one registry array. */
+export const defineTool = <T extends PanelTool>(d: PanelToolDef<T>) => d as unknown as PanelToolDef;
diff --git a/src/components/ActionBar.tsx b/src/components/ActionBar.tsx
new file mode 100644
index 0000000..4bfe27c
--- /dev/null
+++ b/src/components/ActionBar.tsx
@@ -0,0 +1,33 @@
+import { useApp } from '../app/context';
+import type { PopoverId } from '../app/store';
+import { Icon } from '../ui/Icon';
+import { Panel } from '../ui/Panel';
+
+function Action({ icon, label, title, onClick, disabled, danger, popover }: {
+ icon: string; label: string; title: string; onClick(): void; disabled?: boolean; danger?: boolean; popover?: PopoverId;
+}) {
+ const app = useApp();
+ const on = popover !== undefined && app.popover.value === popover;
+ return (
+ <button class={`${on ? 'on' : ''}${danger ? ' danger' : ''}`} title={title} disabled={disabled} onClick={onClick}
+ aria-expanded={popover !== undefined ? on : undefined}>
+ <Icon name={icon} /><span>{label}</span>
+ </button>
+ );
+}
+
+export function ActionBar() {
+ const app = useApp();
+ const sure = app.confirmClear.value;
+ return (
+ <Panel class="actions">
+ <Action icon="undo" label="Undo" title="Undo (⌘Z)" disabled={!app.canUndo.value} onClick={() => app.undo()} />
+ <Action icon="redo" label="Redo" title="Redo (⇧⌘Z)" disabled={!app.canRedo.value} onClick={() => app.redo()} />
+ <Action icon="dry" label="Dry" title="Dry and fix the painting into the paper (D)" onClick={() => app.dry()} />
+ <Action icon="clear" label={sure ? 'Sure?' : 'Clear'} title="Clear the paper" danger={sure} onClick={() => app.clear()} />
+ <Action icon="image" label="Ref" title="Reference image under the paint (R to show / hide)" popover="reference" onClick={() => app.togglePopover('reference')} />
+ <Action icon="save" label="Save" title="Save image (S saves with the last settings)" popover="save" onClick={() => app.togglePopover('save')} />
+ <Action icon="sliders" label="Settings" title="Brush & water settings" popover="settings" onClick={() => app.togglePopover('settings')} />
+ </Panel>
+ );
+}
diff --git a/src/components/BrushLibrary.tsx b/src/components/BrushLibrary.tsx
new file mode 100644
index 0000000..49e5517
--- /dev/null
+++ b/src/components/BrushLibrary.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import { resizeTick } from '../app/resize';
+import type { Brush } from '../engine/brushes';
+import { Icon } from '../ui/Icon';
+import { Panel, PanelHead } from '../ui/Panel';
+import { drawStroke } from '../ui/preview';
+
+function BrushCard({ brush, hex, selected, visible, onPick, onRemove }: {
+ brush: Brush; hex: string; selected: boolean; visible: boolean; onPick(): void; onRemove(): void;
+}) {
+ const el = useRef<HTMLDivElement>(null);
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const tick = resizeTick.value;
+ useEffect(() => { drawStroke(canvas.current!, brush, hex); }, [brush, hex, tick]);
+ useEffect(() => { if (selected && visible) el.current?.scrollIntoView({ block: 'nearest' }); }, [selected, visible]);
+ return (
+ <div ref={el} class={`brush${brush.custom ? ' custom' : ''}${selected ? ' on' : ''}`} role="option" aria-selected={selected} tabIndex={0}
+ title={brush.hint} onClick={onPick}
+ onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPick(); } }}>
+ <canvas ref={canvas} class="stroke" width={150} height={44} />
+ <span class="label">{brush.name}</span>
+ {brush.custom && <button class="icon remove" title="Remove this brush" onClick={e => { e.stopPropagation(); onRemove(); }}><Icon name="close" size={14} /></button>}
+ </div>
+ );
+}
+
+export function BrushLibrary() {
+ const app = useApp();
+ const open = app.libraryOpen.value;
+ const hex = app.previewHex.value;
+ const selected = app.brush.value.id;
+ const file = useRef<HTMLInputElement>(null);
+ return (
+ <Panel class="library" open={open} role="dialog" label="Brushes">
+ <PanelHead title="Brushes" sub="Shape follows the stroke, pen tilt or a set angle. Dry brushes skip the paper tooth." onClose={() => app.toggleLibrary(false)} />
+ <div class="brushes" role="listbox" aria-label="Brush library">
+ {app.allBrushes.value.map(b => (
+ <BrushCard key={b.id} brush={b} hex={hex} selected={b.id === selected} visible={open}
+ onPick={() => app.chooseBrush(b)} onRemove={() => app.removeBrush(b.id)} />
+ ))}
+ </div>
+ <div class="library-foot">
+ <button class="import" title="Use an image as a brush tip: dark marks on white, or white on transparent" onClick={() => file.current?.click()}>
+ <Icon name="plus" size={16} /><span>Import texture…</span>
+ </button>
+ <span class="note">PNG or JPG. Light background is inverted automatically.</span>
+ </div>
+ <input ref={file} type="file" accept="image/*,.heic,.heif" hidden onChange={e => {
+ const el = e.currentTarget as HTMLInputElement, f = el.files?.[0];
+ el.value = '';
+ if (f) app.importFile(f);
+ }} />
+ </Panel>
+ );
+}
diff --git a/src/components/Overlays.tsx b/src/components/Overlays.tsx
new file mode 100644
index 0000000..c99b6f8
--- /dev/null
+++ b/src/components/Overlays.tsx
@@ -0,0 +1,42 @@
+import { useEffect, useLayoutEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import { toast } from '../app/toast';
+import { ghostPath } from '../draw/ghost';
+import { Icon } from '../ui/Icon';
+
+export function Toast() {
+ const text = toast.value;
+ return <div class="toast" hidden={text === null}>{text}</div>;
+}
+
+/** Dashed outline of where a scripted drawing (text, shape) will land. */
+export function Ghost() {
+ const d = ghostPath.value;
+ return <svg class="ghost" style={{ display: d === null ? 'none' : '' }}><path d={d ?? ''} /></svg>;
+}
+
+/** Asks what a dropped image is for, next to where it was dropped. */
+export function DropChoice() {
+ const app = useApp();
+ const drop = app.dropped.value;
+ const el = useRef<HTMLDivElement>(null);
+ useLayoutEffect(() => {
+ const node = el.current;
+ if (!drop || !node) return;
+ const r = node.getBoundingClientRect();
+ node.style.left = `${Math.max(8, Math.min(innerWidth - r.width - 8, drop.x - r.width / 2))}px`;
+ node.style.top = `${Math.max(8, Math.min(innerHeight - r.height - 8, drop.y - r.height / 2))}px`;
+ }, [drop]);
+ useEffect(() => {
+ if (!drop) return;
+ const away = (e: PointerEvent) => { if (!el.current?.contains(e.target as Node)) app.closeDrop(); };
+ window.addEventListener('pointerdown', away);
+ return () => window.removeEventListener('pointerdown', away);
+ }, [drop, app]);
+ return (
+ <div ref={el} class="panel drop-choice" hidden={!drop} role="dialog" aria-label="Use the dropped image">
+ <button onClick={() => app.resolveDrop('reference')}><Icon name="image" size={16} /><span>Use as reference</span></button>
+ <button onClick={() => app.resolveDrop('brush')}><Icon name="brush" size={16} /><span>Make a brush</span></button>
+ </div>
+ );
+}
diff --git a/src/components/Palette.tsx b/src/components/Palette.tsx
new file mode 100644
index 0000000..dba583d
--- /dev/null
+++ b/src/components/Palette.tsx
@@ -0,0 +1,40 @@
+import { useApp } from '../app/context';
+import { mixToHex } from '../engine/spectral';
+import { customEntry, PALETTE, type PaletteEntry } from '../palette';
+import { Panel } from '../ui/Panel';
+
+/** Dab-like swatch: masstone at the centre, diluted towards the rim. */
+function swatchBackground(e: PaletteEntry): string {
+ if (e.pigment.white) return `radial-gradient(circle at 40% 38%, #fff, ${e.hex} 70%)`;
+ const at = (c: number) => mixToHex([{ pigment: e.pigment, amount: c }]);
+ return `radial-gradient(circle at 42% 40%, ${at(0.55)}, ${at(1)} 55%, ${at(1.25)} 72%, ${at(0.7)} 100%)`;
+}
+
+const BACKGROUNDS = PALETTE.map(swatchBackground);
+const shortcut = (i: number) => (i < 9 ? ` (${i + 1})` : i === PALETTE.length - 1 ? ' (0)' : '');
+
+export function Palette() {
+ const app = useApp();
+ const current = app.current.value, previous = app.previous.value;
+ const custom = current.name === 'Custom';
+ const mixable = !current.pigment.white && !previous.pigment.white;
+ const wet = mixable ? mixToHex([{ pigment: previous.pigment, amount: 0.5 }, { pigment: current.pigment, amount: 0.5 }]) : '';
+ return (
+ <Panel class="palette">
+ <div class="swatches" role="listbox" aria-label="Pigments">
+ {PALETTE.map((e, i) => {
+ const on = e.name === current.name;
+ return <button key={e.name} class={`swatch${on ? ' on' : ''}`} role="option" aria-selected={on} title={e.name + shortcut(i)}
+ style={{ background: BACKGROUNDS[i] }} onClick={() => app.choose(e)} />;
+ })}
+ <label class={`swatch custom${custom ? ' on' : ''}`} title="Custom pigment" style={custom ? { background: swatchBackground(current) } : undefined}>
+ <input type="color" value={custom ? current.hex : '#7a3b8f'} onInput={e => app.choose(customEntry((e.currentTarget as HTMLInputElement).value))} />
+ </label>
+ </div>
+ <div class="well" title="Spectral mix of your last two pigments">
+ <span class="name">{current.name}</span>
+ <span class="mix">{mixable && <><i style={{ background: previous.hex }} />+<i style={{ background: current.hex }} />=<i style={{ background: wet }} /></>}</span>
+ </div>
+ </Panel>
+ );
+}
diff --git a/src/components/Paper.tsx b/src/components/Paper.tsx
new file mode 100644
index 0000000..9d4b4c8
--- /dev/null
+++ b/src/components/Paper.tsx
@@ -0,0 +1,44 @@
+import { useLayoutEffect, useRef } from 'preact/hooks';
+import { AppStore } from '../app/store';
+
+/**
+ * The canvas the engine paints on, its hover cursor and the first-run hint. Creates the
+ * engine (via the AppStore) once mounted, and forwards pointer events on the paper to
+ * the active panel tool. The engine listens to the same canvas itself for hand strokes.
+ */
+export function Paper({ app, onReady, onError }: { app: AppStore | null; onReady(app: AppStore): void; onError(e: unknown): void }) {
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const cursor = useRef<HTMLDivElement>(null);
+ const store = useRef<AppStore | null>(null);
+
+ useLayoutEffect(() => {
+ try {
+ store.current = new AppStore(canvas.current!, cursor.current!);
+ onReady(store.current);
+ } catch (e) { onError(e); }
+ return () => { store.current?.destroy(); store.current = null; };
+ }, []);
+
+ const gesture = () => store.current?.activePanelTool.peek()?.gesture;
+ const uv = (e: PointerEvent) => store.current!.engine.clientToDoc(e.clientX, e.clientY);
+ const placing = !!app?.activePanelTool.value;
+
+ return <>
+ <canvas ref={canvas} class={`paper${placing ? ' placing' : ''}`}
+ onPointerDown={e => {
+ const a = store.current;
+ if (!a) return;
+ a.hintGone.value = true;
+ // painting dismisses the library so it never covers the work for long
+ a.toggleLibrary(false);
+ gesture()?.down?.(e, uv(e));
+ }}
+ onPointerMove={e => gesture()?.move?.(e, uv(e))}
+ onPointerUp={e => gesture()?.up?.(e, uv(e))}
+ onPointerCancel={e => gesture()?.cancel?.(e)}
+ onPointerLeave={() => gesture()?.leave?.()} />
+ <div ref={cursor} class="cursor" />
+ <div class={`hint${app?.hintGone.value ? ' gone' : ''}`}>Pick a brush and a pigment, then paint.<br />Water moves paint only where the paper is wet.</div>
+ </>;
+}
+
diff --git a/src/components/SettingsPanel.tsx b/src/components/SettingsPanel.tsx
new file mode 100644
index 0000000..65466cf
--- /dev/null
+++ b/src/components/SettingsPanel.tsx
@@ -0,0 +1,25 @@
+import { useApp } from '../app/context';
+import { DEFAULT_PARAMS, type Params } from '../engine/Engine';
+import { Panel } from '../ui/Panel';
+import { SliderRows, type SliderSpec } from '../ui/Slider';
+
+const SLIDERS: SliderSpec<Params>[] = [
+ { key: 'size', label: 'Size' },
+ { key: 'water', label: 'Water' },
+ { key: 'load', label: 'Pigment' },
+ { key: 'flow', label: 'Flow' },
+ { key: 'bleed', label: 'Bleed' },
+ { key: 'edge', label: 'Edges' },
+ { key: 'granulation', label: 'Grain' },
+ { key: 'dry', label: 'Dry speed' },
+];
+
+export function SettingsPanel() {
+ const app = useApp();
+ return (
+ <Panel class="settings" open={app.popover.value === 'settings'}>
+ <SliderRows spec={SLIDERS} settings={app.params.value} onChange={p => app.setParams(p)} />
+ <button class="reset" onClick={() => app.setParams(DEFAULT_PARAMS)}>Reset</button>
+ </Panel>
+ );
+}
diff --git a/src/components/Toolbar.tsx b/src/components/Toolbar.tsx
new file mode 100644
index 0000000..22a13ab
--- /dev/null
+++ b/src/components/Toolbar.tsx
@@ -0,0 +1,34 @@
+import { useEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import { ENGINE_TOOLS, PANEL_TOOLS } from '../app/registry';
+import { resizeTick } from '../app/resize';
+import { Icon } from '../ui/Icon';
+import { Panel } from '../ui/Panel';
+import { drawThumb } from '../ui/preview';
+
+const TOOLS = [...ENGINE_TOOLS.map(t => ({ ...t, icon: t.id as string })), ...PANEL_TOOLS];
+
+export function Toolbar() {
+ const app = useApp();
+ const brush = app.brush.value, hex = app.previewHex.value, tick = resizeTick.value;
+ const shown = app.shownTool.value, tool = app.tool.value;
+ const open = app.libraryOpen.value;
+ const thumb = useRef<HTMLCanvasElement>(null);
+ useEffect(() => { drawThumb(thumb.current!, brush, hex); }, [brush, hex, tick]);
+
+ return (
+ <Panel class="tools" role="navigation" label="Tools">
+ <button class={`tool pick${open ? ' open' : ''}`} aria-haspopup="listbox" aria-expanded={open}
+ title={`${brush.name}: ${brush.hint}. Open the brush library (, and . to cycle)`} onClick={() => app.toggleLibrary()}>
+ <canvas ref={thumb} class="thumb" width={28} height={28} /><span class="brushname">{brush.name}</span>
+ </button>
+ <hr />
+ {TOOLS.map(t => (
+ <button key={t.id} class={`tool${shown === t.id ? ' on' : ''}`} aria-pressed={tool === t.id}
+ title={`${t.label} (${t.key}): ${t.hint}`} onClick={() => app.setTool(t.id)}>
+ <Icon name={t.icon} /><span>{t.label}</span>
+ </button>
+ ))}
+ </Panel>
+ );
+}
diff --git a/src/draw/ghost.ts b/src/draw/ghost.ts
index 6e7bc5a..39cab6a 100644
--- a/src/draw/ghost.ts
+++ b/src/draw/ghost.ts
@@ -1,20 +1,8 @@
-// A dashed outline over the paper showing where a scripted drawing will land.
+import { signal } from '@preact/signals';
-export interface Ghost {
- /** Show the given SVG path (client-space coordinates). */
- set(d: string): void;
- hide(): void;
-}
+// A dashed outline over the paper showing where a scripted drawing will land.
+// Tools write an SVG path (client-space coordinates); <Ghost/> draws it.
-export function createGhost(root: HTMLElement): Ghost {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('class', 'ghost');
- svg.innerHTML = '<path/>';
- svg.style.display = 'none';
- root.appendChild(svg);
- const path = svg.querySelector('path')!;
- return {
- set(d) { path.setAttribute('d', d); svg.style.display = ''; },
- hide() { svg.style.display = 'none'; },
- };
-}
+export const ghostPath = signal<string | null>(null);
+export const setGhost = (d: string) => { ghostPath.value = d; };
+export const hideGhost = () => { if (ghostPath.peek() !== null) ghostPath.value = null; };
diff --git a/src/export/ExportPanel.tsx b/src/export/ExportPanel.tsx
new file mode 100644
index 0000000..0220ebc
--- /dev/null
+++ b/src/export/ExportPanel.tsx
@@ -0,0 +1,23 @@
+import { useApp } from '../app/context';
+import { Panel, PanelHead } from '../ui/Panel';
+import { Seg } from '../ui/Seg';
+import { Slider } from '../ui/Slider';
+import { BACKGROUNDS, FORMATS } from './ExportStore';
+
+export function ExportPanel() {
+ const app = useApp();
+ const ex = app.exporter;
+ const s = ex.settings.value;
+ return (
+ <Panel class="popover export" open={app.popover.value === 'save'} role="dialog" label="Save image">
+ <PanelHead title="Save image" sub="The reference image is never included." />
+ <div class="field"><span>Background</span>
+ <Seg value={s.background} onChange={background => ex.set({ background })}
+ options={BACKGROUNDS.map(b => ({ ...b, disabled: b.id === 'transparent' && s.format === 'jpeg' }))} />
+ </div>
+ <div class="field"><span>Format</span><Seg options={FORMATS} value={s.format} onChange={format => ex.set({ format })} /></div>
+ <Slider label="Quality" min={0.5} max={1} value={s.quality} hidden={s.format === 'png'} onInput={quality => ex.set({ quality })} />
+ <button class="primary" onClick={() => void ex.save()}>Download</button>
+ </Panel>
+ );
+}
diff --git a/src/export/ExportStore.ts b/src/export/ExportStore.ts
new file mode 100644
index 0000000..6f82355
--- /dev/null
+++ b/src/export/ExportStore.ts
@@ -0,0 +1,51 @@
+import type { ExportBackground, ExportFormat, WatercolorEngine } from '../engine/Engine';
+import { persisted } from '../app/persisted';
+import { showToast } from '../app/toast';
+
+const KEY = 'watercolor.export';
+
+export interface ExportSettings { format: ExportFormat; background: ExportBackground; quality: number }
+
+const DEFAULTS: ExportSettings = { format: 'png', background: 'transparent', quality: 0.92 };
+export const FORMATS: { id: ExportFormat; label: string; ext: string }[] = [
+ { id: 'png', label: 'PNG', ext: 'png' },
+ { id: 'jpeg', label: 'JPEG', ext: 'jpg' },
+ { id: 'webp', label: 'WebP', ext: 'webp' },
+];
+export const BACKGROUNDS: { id: ExportBackground; label: string; title: string }[] = [
+ { id: 'transparent', label: 'Transparent', title: 'Transparent: only the paint, no paper' },
+ { id: 'paper', label: 'Paper', title: 'On the textured watercolour paper' },
+ { id: 'white', label: 'White', title: 'On plain white' },
+];
+
+/** Save options (format, background, quality), remembered between visits. */
+export class ExportStore {
+ readonly settings = persisted<ExportSettings>(KEY, DEFAULTS);
+
+ constructor(private engine: WatercolorEngine) {}
+
+ set(p: Partial<ExportSettings>) {
+ const s = { ...this.settings.value, ...p };
+ // JPEG has no alpha channel
+ if (s.format === 'jpeg' && s.background === 'transparent') s.background = 'paper';
+ this.settings.value = s;
+ }
+
+ /** Save straight away with the current settings. */
+ async save() {
+ const { format, background, quality } = this.settings.peek();
+ try {
+ const blob = await this.engine.exportImage({ format, background, quality: format === 'png' ? undefined : quality });
+ const ext = FORMATS.find(f => f.id === format)!.ext;
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = `watercolor-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.${ext}`;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
+ const bg = background === 'transparent' ? 'transparent' : `on ${background}`;
+ showToast(`Saved ${FORMATS.find(f => f.id === format)!.label} · ${bg}`);
+ } catch (e) {
+ showToast(e instanceof Error ? e.message : 'Could not save the image');
+ }
+ }
+}
diff --git a/src/export/exportPanel.ts b/src/export/exportPanel.ts
deleted file mode 100644
index f1a5070..0000000
--- a/src/export/exportPanel.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { ExportBackground, ExportFormat, WatercolorEngine } from '../engine/Engine';
-
-const KEY = 'watercolor.export';
-
-interface Settings { format: ExportFormat; background: ExportBackground; quality: number }
-
-const DEFAULTS: Settings = { format: 'png', background: 'transparent', quality: 0.92 };
-const FORMATS: { id: ExportFormat; label: string; ext: string }[] = [
- { id: 'png', label: 'PNG', ext: 'png' },
- { id: 'jpeg', label: 'JPEG', ext: 'jpg' },
- { id: 'webp', label: 'WebP', ext: 'webp' },
-];
-const BACKGROUNDS: { id: ExportBackground; label: string; title: string }[] = [
- { id: 'transparent', label: 'Transparent', title: 'Transparent: only the paint, no paper' },
- { id: 'paper', label: 'Paper', title: 'On the textured watercolour paper' },
- { id: 'white', label: 'White', title: 'On plain white' },
-];
-
-export interface ExportPanel {
- panel: HTMLElement;
- /** Save straight away with the last used settings. */
- save(): Promise<void>;
-}
-
-/** Save dialog: format, background and quality, remembered between visits. */
-export function createExportPanel(engine: WatercolorEngine, root: HTMLElement, showToast: (s: string) => void): ExportPanel {
- let settings: Settings = { ...DEFAULTS };
- try { settings = { ...settings, ...JSON.parse(localStorage.getItem(KEY) ?? '{}') }; } catch { /* storage blocked */ }
-
- const panel = document.createElement('div');
- panel.className = 'panel popover export';
- panel.hidden = true;
- panel.setAttribute('role', 'dialog');
- panel.setAttribute('aria-label', 'Save image');
- panel.innerHTML = `
- <div class="pop-head"><span>Save image</span><span class="sub">The reference image is never included.</span></div>
- <div class="field"><span>Background</span><div class="seg">${BACKGROUNDS.map(b => `<button data-bg="${b.id}" title="${b.title}">${b.label}</button>`).join('')}</div></div>
- <div class="field"><span>Format</span><div class="seg">${FORMATS.map(f => `<button data-format="${f.id}">${f.label}</button>`).join('')}</div></div>
- <label class="slider" data-quality><span>Quality</span><input type="range" min="0.5" max="1" step="0.01"></label>
- <button class="primary" data-export="download">Download</button>`;
- root.appendChild(panel);
-
- const quality = panel.querySelector<HTMLInputElement>('[data-quality] input')!;
-
- function render() {
- for (const b of panel.querySelectorAll<HTMLButtonElement>('[data-bg]')) {
- b.classList.toggle('on', b.dataset.bg === settings.background);
- // JPEG has no alpha channel
- b.disabled = b.dataset.bg === 'transparent' && settings.format === 'jpeg';
- }
- for (const b of panel.querySelectorAll<HTMLElement>('[data-format]')) b.classList.toggle('on', b.dataset.format === settings.format);
- panel.querySelector<HTMLElement>('[data-quality]')!.hidden = settings.format === 'png';
- quality.value = String(settings.quality);
- }
-
- function update(p: Partial<Settings>) {
- settings = { ...settings, ...p };
- if (settings.format === 'jpeg' && settings.background === 'transparent') settings.background = 'paper';
- try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
- render();
- }
-
- async function save() {
- const { format, background, quality: q } = settings;
- try {
- const blob = await engine.exportImage({ format, background, quality: format === 'png' ? undefined : q });
- const ext = FORMATS.find(f => f.id === format)!.ext;
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = `watercolor-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.${ext}`;
- a.click();
- setTimeout(() => URL.revokeObjectURL(a.href), 4000);
- const bg = background === 'transparent' ? 'transparent' : `on ${background}`;
- showToast(`Saved ${FORMATS.find(f => f.id === format)!.label} · ${bg}`);
- } catch (e) {
- showToast(e instanceof Error ? e.message : 'Could not save the image');
- }
- }
-
- panel.addEventListener('click', e => {
- const el = (e.target as Element).closest<HTMLElement>('[data-bg], [data-format], [data-export]');
- if (!el) return;
- if (el.dataset.bg) update({ background: el.dataset.bg as ExportBackground });
- else if (el.dataset.format) update({ format: el.dataset.format as ExportFormat });
- else void save();
- });
- quality.addEventListener('input', () => update({ quality: Number(quality.value) }));
-
- render();
- return { panel, save };
-}
diff --git a/src/fill/FillPanel.tsx b/src/fill/FillPanel.tsx
new file mode 100644
index 0000000..d257e8c
--- /dev/null
+++ b/src/fill/FillPanel.tsx
@@ -0,0 +1,30 @@
+import { useApp } from '../app/context';
+import { Seg } from '../ui/Seg';
+import { Row, SliderRows, type SliderSpec } from '../ui/Slider';
+import { ToolPanel } from '../ui/ToolPanel';
+import type { FillSettings, FillStore } from './FillStore';
+
+const SLIDERS: SliderSpec<FillSettings>[] = [
+ { key: 'tolerance', label: 'Tolerance', hint: 'How different a colour may be and still count as the same area' },
+ { key: 'speed', label: 'Speed', hint: 'How fast the wash spreads' },
+ { key: 'water', label: 'Water', hint: 'How wet the wash is' },
+ { key: 'strength', label: 'Amount', max: 1.5, hint: 'Pigment laid down (on top of the Pigment setting)', show: s => s.mode === 'paint' },
+ { key: 'soft', label: 'Soft edge', hint: 'Feather the wash at the edge of the area' },
+];
+
+const MODES: { id: FillSettings['mode']; label: string }[] = [{ id: 'paint', label: 'Paint' }, { id: 'water', label: 'Water' }];
+
+export function FillPanel({ tool }: { tool: FillStore }) {
+ const app = useApp();
+ const s = tool.settings.value;
+ return (
+ <ToolPanel title="Fill" class="fill" open={tool.active.value} status={tool.status.value} busy={tool.progress.value !== null}
+ sub="Tap an area of the paper; a wash of the current pigment spreads out from the tap until it meets a different colour."
+ onStop={() => tool.stop()} onClose={() => app.setTool('brush')}>
+ <div class="tool-rows">
+ <Row label="Fill with"><Seg options={MODES} value={s.mode} onChange={mode => tool.set({ mode })} /></Row>
+ <SliderRows spec={SLIDERS} settings={s} onChange={p => tool.set(p)} />
+ </div>
+ </ToolPanel>
+ );
+}
diff --git a/src/fill/FillStore.ts b/src/fill/FillStore.ts
new file mode 100644
index 0000000..f258cb0
--- /dev/null
+++ b/src/fill/FillStore.ts
@@ -0,0 +1,135 @@
+import { computed, signal, type ReadonlySignal } from '@preact/signals';
+import type { WatercolorEngine } from '../engine/Engine';
+import type { PanelTool, PaperGesture } from '../app/tools';
+import { persisted } from '../app/persisted';
+import { showToast } from '../app/toast';
+import { distanceField, pickRegion } from './region';
+
+// The Fill tool (paint bucket): tap an area of the paper and a wash of the current
+// pigment spreads out from the tap across every connected pixel of similar colour.
+// q-floodfill picks the region on a flat readback of the paper; the engine then
+// deposits pigment and water band by band along a distance field, so the fill is
+// animated and the live wet simulation bleeds it like any other wash.
+
+export interface FillSettings {
+ mode: 'paint' | 'water';
+ tolerance: number; // 0..1 -> colour difference
+ water: number; // 0..1 wetness of the wash
+ strength: number; // 0..1.5 pigment amount
+ speed: number; // 0..1 -> px / s
+ soft: number; // 0..1 -> feathered edge width
+}
+
+const KEY = 'watercolor.fill';
+const DEFAULTS: FillSettings = { mode: 'paint', tolerance: 0.25, water: 0.6, strength: 1, speed: 0.5, soft: 0.3 };
+
+/** Slider 0..1 -> px/s of front travel (about 120 .. 3000). */
+const fillSpeed = (v: number) => 120 * Math.pow(25, v);
+const EDGE_CAP = 48;
+
+interface Run { raf: number; from: number; maxDist: number; last: number }
+
+export class FillStore implements PanelTool {
+ readonly id = 'fill';
+ readonly settings = persisted<FillSettings>(KEY, DEFAULTS, s => (s.mode === 'paint' || s.mode === 'water' ? s : { ...s, mode: DEFAULTS.mode }));
+ readonly active = signal(false);
+ /** 0..1 while a fill is spreading, else null. */
+ readonly progress = signal<number | null>(null);
+ readonly picking = signal(false);
+ readonly busy: ReadonlySignal<boolean> = computed(() => this.progress.value !== null || this.picking.value);
+ readonly status = computed(() => {
+ const p = this.progress.value;
+ if (p !== null) return `Filling… ${Math.round(p * 100)}%`;
+ if (this.picking.value) return 'Finding the area…';
+ if (!this.active.value) return '';
+ return this.settings.value.mode === 'water' ? 'Tap an area to wet it' : 'Tap an area to fill it';
+ });
+
+ private press: { id: number; x: number; y: number } | null = null;
+ private run: Run | null = null;
+
+ constructor(private engine: WatercolorEngine) {}
+
+ set(p: Partial<FillSettings>) { this.settings.value = { ...this.settings.value, ...p }; }
+
+ private fillAt(clientX: number, clientY: number) {
+ const engine = this.engine;
+ const [u, v] = engine.clientToDoc(clientX, clientY);
+ if (u < 0 || v < 0 || u > 1 || v > 1) return;
+ const [dw, dh] = engine.docSize;
+ const px = Math.min(dw - 1, Math.floor(u * dw)), py = Math.min(dh - 1, Math.floor(v * dh));
+ this.picking.value = true;
+ // let the status paint before the synchronous region search
+ requestAnimationFrame(() => {
+ this.picking.value = false;
+ if (!this.active.peek()) return;
+ const s = this.settings.peek();
+ const flat = engine.readFlat();
+ const tol = Math.round(s.tolerance * s.tolerance * 255); // 0.25 -> 16 of 255 per channel
+ const mask = pickRegion({ width: dw, height: dh, data: new Uint8ClampedArray(flat.buffer) }, px, py, tol);
+ if (!mask) { showToast('Nothing to fill here'); return; }
+ const region = distanceField(mask, dw, dh, px, py, EDGE_CAP);
+ if (region.count < 4) { showToast('That area is too small to fill'); return; }
+ if (!engine.fillBegin(region.field, region.bbox)) { showToast('Wait for the stroke to finish'); return; }
+ this.run = { raf: 0, from: -0.5, maxDist: region.maxDist + engine.fillMargin, last: performance.now() };
+ this.run.raf = requestAnimationFrame(this.frame);
+ this.progress.value = 0;
+ });
+ }
+
+ private frame = (now: number) => {
+ const run = this.run;
+ if (!run) return;
+ const s = this.settings.peek();
+ const dt = Math.min(0.1, Math.max(0, (now - run.last) / 1000));
+ run.last = now;
+ const to = Math.min(run.maxDist, run.from + fillSpeed(s.speed) * dt);
+ const ok = this.engine.fillStep(run.from, to, { strength: s.strength, water: s.water, soft: s.soft * 40, paint: s.mode === 'paint' });
+ if (!ok) { this.finish(); return; } // undone, cleared or interrupted by another action
+ run.from = to;
+ if (to >= run.maxDist) { this.engine.fillEnd(); this.finish(); return; }
+ run.raf = requestAnimationFrame(this.frame);
+ this.progress.value = Math.min(1, Math.max(0, run.from) / Math.max(run.maxDist, 1e-6));
+ };
+
+ private finish() {
+ if (this.run) cancelAnimationFrame(this.run.raf);
+ this.run = null;
+ this.progress.value = null;
+ }
+
+ private cancel(): boolean {
+ if (!this.run) return false;
+ this.engine.fillEnd();
+ this.finish();
+ return true;
+ }
+
+ readonly gesture: PaperGesture = {
+ down: e => {
+ if (this.press) return;
+ if (this.busy.peek()) { showToast('Still filling… press Stop or Esc'); return; }
+ try { (e.currentTarget as Element).setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
+ this.press = { id: e.pointerId, x: e.clientX, y: e.clientY };
+ },
+ up: e => {
+ const p = this.press;
+ if (!p || e.pointerId !== p.id) return;
+ this.press = null;
+ try { (e.currentTarget as Element).releasePointerCapture(p.id); } catch { /* already released */ }
+ if (Math.hypot(e.clientX - p.x, e.clientY - p.y) > 6) { showToast('Tap, rather than drag, to fill an area'); return; }
+ this.fillAt(e.clientX, e.clientY);
+ },
+ cancel: e => { if (this.press && e.pointerId === this.press.id) this.press = null; },
+ };
+
+ activate() { this.active.value = true; }
+
+ deactivate() {
+ this.active.value = false;
+ this.press = null;
+ this.cancel();
+ }
+
+ stop() { return this.cancel(); }
+}
diff --git a/src/fill/fillTool.ts b/src/fill/fillTool.ts
deleted file mode 100644
index fdf2b49..0000000
--- a/src/fill/fillTool.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-import type { WatercolorEngine } from '../engine/Engine';
-import { icon } from '../ui/icons';
-import { distanceField, pickRegion } from './region';
-
-// The Fill tool (paint bucket): tap an area of the paper and a wash of the current
-// pigment spreads out from the tap across every connected pixel of similar colour.
-// q-floodfill picks the region on a flat readback of the paper; the engine then
-// deposits pigment and water band by band along a distance field, so the fill is
-// animated and the live wet simulation bleeds it like any other wash.
-
-export interface FillSettings {
- mode: 'paint' | 'water';
- tolerance: number; // 0..1 -> colour difference
- water: number; // 0..1 wetness of the wash
- strength: number; // 0..1.5 pigment amount
- speed: number; // 0..1 -> px / s
- soft: number; // 0..1 -> feathered edge width
-}
-
-const KEY = 'watercolor.fill';
-const DEFAULTS: FillSettings = { mode: 'paint', tolerance: 0.25, water: 0.6, strength: 1, speed: 0.5, soft: 0.3 };
-
-const SLIDERS: { key: keyof FillSettings; label: string; min: number; max: number; step: number; hint: string }[] = [
- { key: 'tolerance', label: 'Tolerance', min: 0, max: 1, step: 0.01, hint: 'How different a colour may be and still count as the same area' },
- { key: 'speed', label: 'Speed', min: 0, max: 1, step: 0.01, hint: 'How fast the wash spreads' },
- { key: 'water', label: 'Water', min: 0, max: 1, step: 0.01, hint: 'How wet the wash is' },
- { key: 'strength', label: 'Amount', min: 0, max: 1.5, step: 0.01, hint: 'Pigment laid down (on top of the Pigment setting)' },
- { key: 'soft', label: 'Soft edge', min: 0, max: 1, step: 0.01, hint: 'Feather the wash at the edge of the area' },
-];
-
-const MODES: { id: FillSettings['mode']; label: string }[] = [{ id: 'paint', label: 'Paint' }, { id: 'water', label: 'Water' }];
-
-/** Slider 0..1 -> px/s of front travel (about 120 .. 3000). */
-const fillSpeed = (v: number) => 120 * Math.pow(25, v);
-const EDGE_CAP = 48;
-
-export interface FillToolHandle {
- panel: HTMLElement;
- activate(): void;
- deactivate(): void;
- /** Stop a running fill (the paint laid so far stays). Returns whether anything was stopped. */
- stop(): boolean;
- readonly active: boolean;
- readonly busy: boolean;
-}
-
-export function createFillTool(engine: WatercolorEngine, root: HTMLElement, canvas: HTMLCanvasElement, toast: (s: string) => void): FillToolHandle {
- let settings: FillSettings = { ...DEFAULTS, ...load() };
- if (!MODES.some(m => m.id === settings.mode)) settings.mode = DEFAULTS.mode;
- let active = false;
- let press: { id: number; x: number; y: number } | null = null;
- let run: { raf: number; from: number; maxDist: number; last: number } | null = null;
- let picking = false;
-
- /* ---------------------------------------------------------------- markup */
-
- const panel = document.createElement('div');
- panel.className = 'panel text fill';
- panel.hidden = true;
- panel.setAttribute('role', 'dialog');
- panel.setAttribute('aria-label', 'Fill');
- panel.innerHTML = `
- <div class="library-head">
- <span>Fill</span>
- <span class="sub">Tap an area of the paper; a wash of the current pigment spreads out from the tap until it meets a different colour.</span>
- <button class="icon" data-action="fill-close" title="Close">${icon('close', 16)}</button>
- </div>
- <div class="text-body">
- <div class="text-rows">
- <label class="slider"><span>Fill with</span><div class="seg" data-opt="mode" role="radiogroup">${MODES.map(m => `<button role="radio" data-value="${m.id}">${m.label}</button>`).join('')}</div></label>
- ${SLIDERS.map(s => `<label class="slider" data-slider="${s.key}" title="${s.hint}"><span>${s.label}</span><input type="range" min="${s.min}" max="${s.max}" step="${s.step}" data-opt="${s.key}"></label>`).join('')}
- </div>
- <div class="text-foot">
- <span class="status"></span>
- <button class="stop" data-action="fill-stop" hidden>${icon('close', 14)}<span>Stop</span></button>
- </div>
- </div>`;
- root.appendChild(panel);
-
- const status = panel.querySelector<HTMLElement>('.status')!;
- const stopBtn = panel.querySelector<HTMLButtonElement>('.stop')!;
- const sliders = [...panel.querySelectorAll<HTMLInputElement>('input[type="range"][data-opt]')];
-
- /* ------------------------------------------------------------- rendering */
-
- function render() {
- for (const s of sliders) s.value = String(settings[s.dataset.opt as keyof FillSettings]);
- panel.querySelector<HTMLElement>('[data-slider="strength"]')!.hidden = settings.mode === 'water';
- for (const b of panel.querySelectorAll<HTMLElement>('.seg button')) {
- const on = b.dataset.value === settings.mode;
- b.classList.toggle('on', on);
- b.setAttribute('aria-checked', String(on));
- }
- renderStatus();
- }
-
- function renderStatus() {
- stopBtn.hidden = !run;
- if (run) status.textContent = `Filling… ${Math.round(Math.min(1, Math.max(0, run.from) / Math.max(run.maxDist, 1e-6)) * 100)}%`;
- else if (picking) status.textContent = 'Finding the area…';
- else if (!active) status.textContent = '';
- else status.textContent = settings.mode === 'water' ? 'Tap an area to wet it' : 'Tap an area to fill it';
- }
-
- /* --------------------------------------------------------------- actions */
-
- function save() {
- try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
- }
-
- function set(p: Partial<FillSettings>) {
- settings = { ...settings, ...p };
- save();
- render();
- }
-
- const busy = () => !!run || picking;
-
- function fillAt(clientX: number, clientY: number) {
- const [u, v] = engine.clientToDoc(clientX, clientY);
- if (u < 0 || v < 0 || u > 1 || v > 1) return;
- const [dw, dh] = engine.docSize;
- const px = Math.min(dw - 1, Math.floor(u * dw)), py = Math.min(dh - 1, Math.floor(v * dh));
- picking = true;
- renderStatus();
- // let the status paint before the synchronous region search
- requestAnimationFrame(() => {
- picking = false;
- if (!active) { renderStatus(); return; }
- const flat = engine.readFlat();
- const tol = Math.round(settings.tolerance * settings.tolerance * 255); // 0.25 -> 16 of 255 per channel
- const mask = pickRegion({ width: dw, height: dh, data: new Uint8ClampedArray(flat.buffer) }, px, py, tol);
- if (!mask) { toast('Nothing to fill here'); renderStatus(); return; }
- const region = distanceField(mask, dw, dh, px, py, EDGE_CAP);
- if (region.count < 4) { toast('That area is too small to fill'); renderStatus(); return; }
- if (!engine.fillBegin(region.field, region.bbox)) { toast('Wait for the stroke to finish'); renderStatus(); return; }
- run = { raf: 0, from: -0.5, maxDist: region.maxDist + engine.fillMargin, last: performance.now() };
- run.raf = requestAnimationFrame(frame);
- renderStatus();
- });
- }
-
- function frame(now: number) {
- if (!run) return;
- const dt = Math.min(0.1, Math.max(0, (now - run.last) / 1000));
- run.last = now;
- const to = Math.min(run.maxDist, run.from + fillSpeed(settings.speed) * dt);
- const ok = engine.fillStep(run.from, to, {
- strength: settings.strength, water: settings.water, soft: settings.soft * 40, paint: settings.mode === 'paint',
- });
- if (!ok) { finish(); return; } // undone, cleared or interrupted by another action
- run.from = to;
- if (to >= run.maxDist) { engine.fillEnd(); finish(); return; }
- run.raf = requestAnimationFrame(frame);
- renderStatus();
- }
-
- function finish() {
- if (run) cancelAnimationFrame(run.raf);
- run = null;
- renderStatus();
- }
-
- function cancel(): boolean {
- if (!run) return false;
- engine.fillEnd();
- finish();
- return true;
- }
-
- /* ---------------------------------------------------------------- wiring */
-
- panel.addEventListener('input', e => {
- const s = e.target as HTMLInputElement;
- if (s.type === 'range' && s.dataset.opt) set({ [s.dataset.opt]: Number(s.value) } as Partial<FillSettings>);
- });
-
- panel.addEventListener('click', e => {
- const el = (e.target as Element).closest<HTMLElement>('.seg button, [data-action]');
- if (!el) return;
- if (el.dataset.value !== undefined) set({ mode: el.dataset.value as FillSettings['mode'] });
- else if (el.dataset.action === 'fill-stop') cancel();
- });
-
- canvas.addEventListener('pointerdown', e => {
- if (!active || press) return;
- if (busy()) { toast('Still filling… press Stop or Esc'); return; }
- try { canvas.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
- press = { id: e.pointerId, x: e.clientX, y: e.clientY };
- });
- const up = (e: PointerEvent) => {
- if (!active || !press || e.pointerId !== press.id) return;
- const p = press;
- press = null;
- try { canvas.releasePointerCapture(p.id); } catch { /* already released */ }
- if (e.type === 'pointercancel') return;
- if (Math.hypot(e.clientX - p.x, e.clientY - p.y) > 6) { toast('Tap, rather than drag, to fill an area'); return; }
- fillAt(e.clientX, e.clientY);
- };
- canvas.addEventListener('pointerup', up);
- canvas.addEventListener('pointercancel', up);
-
- render();
-
- return {
- panel,
- get active() { return active; },
- get busy() { return busy(); },
- activate() {
- active = true;
- panel.hidden = false;
- canvas.classList.add('placing');
- renderStatus();
- },
- deactivate() {
- active = false;
- press = null;
- cancel();
- panel.hidden = true;
- canvas.classList.remove('placing');
- },
- stop: () => cancel(),
- };
-}
-
-function load(): Partial<FillSettings> {
- try {
- const raw = localStorage.getItem(KEY);
- return raw ? (JSON.parse(raw) as Partial<FillSettings>) : {};
- } catch {
- return {};
- }
-}
diff --git a/src/main.ts b/src/main.ts
deleted file mode 100644
index 884bff3..0000000
--- a/src/main.ts
+++ /dev/null
@@ -1,479 +0,0 @@
-import { BRUSH_PRESETS, buildBrush, type Brush } from './engine/brushes';
-import { DEFAULT_PARAMS, WatercolorEngine, type Params, type Tool } from './engine/Engine';
-import { mixToHex } from './engine/spectral';
-import { PALETTE, customEntry, type PaletteEntry } from './palette';
-import { loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } from './ui/customBrushes';
-import { icon } from './ui/icons';
-import { drawStroke, drawThumb, forgetTipImages } from './ui/preview';
-import { createTextTool } from './text/textTool';
-import { createShapeTool } from './shapes/shapeTool';
-import { createFillTool } from './fill/fillTool';
-import { isSvgFile } from './shapes/svgImport';
-import { createReference } from './reference/referenceTool';
-import { isRasterFile } from './reference/decode';
-import { createExportPanel } from './export/exportPanel';
-import './styles.css';
-
-/** Engine tools plus the text, shape and fill tools, which drive the engine themselves. */
-type UiTool = Tool | 'text' | 'shape' | 'fill';
-type PanelTool = Exclude<UiTool, Tool>;
-
-const TOOLS: { id: UiTool; label: string; key: string; hint: string }[] = [
- { id: 'brush', label: 'Brush', key: 'B', hint: 'Wet paint: pigment and water' },
- { id: 'water', label: 'Water', key: 'W', hint: 'Clear water: wets paper, moves paint' },
- { id: 'pen', label: 'Pen', key: 'P', hint: 'Ink line in the current colour' },
- { id: 'lift', label: 'Lift', key: 'L', hint: 'Blot with a tissue: lifts wet paint' },
- { id: 'text', label: 'Text', key: 'T', hint: 'Write a line of text, drawn slowly with the current brush' },
- { id: 'shape', label: 'Shape', key: 'G', hint: 'Drag a line, arrow, rectangle, ellipse, polygon or star, drawn slowly with the current brush' },
- { id: 'fill', label: 'Fill', key: 'K', hint: 'Tap an area to flood it with a wash of the current pigment' },
-];
-
-const SLIDERS: { key: keyof Params; label: string }[] = [
- { key: 'size', label: 'Size' },
- { key: 'water', label: 'Water' },
- { key: 'load', label: 'Pigment' },
- { key: 'flow', label: 'Flow' },
- { key: 'bleed', label: 'Bleed' },
- { key: 'edge', label: 'Edges' },
- { key: 'granulation', label: 'Grain' },
- { key: 'dry', label: 'Dry speed' },
-];
-
-const BRUSH_KEY = 'watercolor.brush';
-
-/** Dab-like swatch: masstone at the centre, diluted towards the rim. */
-function swatchBackground(e: PaletteEntry): string {
- if (e.pigment.white) return `radial-gradient(circle at 40% 38%, #fff, ${e.hex} 70%)`;
- const at = (c: number) => mixToHex([{ pigment: e.pigment, amount: c }]);
- return `radial-gradient(circle at 42% 40%, ${at(0.55)}, ${at(1)} 55%, ${at(1.25)} 72%, ${at(0.7)} 100%)`;
-}
-
-const button = (action: string, iconName: string, label: string, title: string) =>
- `<button data-action="${action}" title="${title}">${icon(iconName)}<span>${label}</span></button>`;
-
-const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
-
-const root = document.getElementById('root')!;
-root.innerHTML = `
- <canvas class="paper"></canvas>
- <div class="cursor"></div>
- <div class="hint">Pick a brush and a pigment, then paint.<br>Water moves paint only where the paper is wet.</div>
- <nav class="panel tools" aria-label="Tools">
- <button class="tool pick" data-action="library" title="Brushes (, and . to cycle)" aria-haspopup="listbox">
- <canvas class="thumb" width="28" height="28"></canvas><span class="brushname"></span>
- </button>
- <hr>
- ${TOOLS.map(t => `<button class="tool" data-tool="${t.id}" title="${t.label} (${t.key}): ${t.hint}">${icon(t.id)}<span>${t.label}</span></button>`).join('')}
- </nav>
- <div class="panel library" hidden role="dialog" aria-label="Brushes">
- <div class="library-head">
- <span>Brushes</span>
- <span class="sub">Shape follows the stroke, pen tilt or a set angle. Dry brushes skip the paper tooth.</span>
- <button class="icon" data-action="library" title="Close">${icon('close', 16)}</button>
- </div>
- <div class="brushes" role="listbox" aria-label="Brush library"></div>
- <div class="library-foot">
- <button class="import" data-action="import" title="Use an image as a brush tip: dark marks on white, or white on transparent">${icon('plus', 16)}<span>Import texture…</span></button>
- <span class="note">PNG or JPG. Light background is inverted automatically.</span>
- </div>
- <input type="file" accept="image/*,.heic,.heif" hidden>
- </div>
- <div class="panel actions">
- ${button('undo', 'undo', 'Undo', 'Undo (⌘Z)')}
- ${button('redo', 'redo', 'Redo', 'Redo (⇧⌘Z)')}
- ${button('dry', 'dry', 'Dry', 'Dry and fix the painting into the paper (D)')}
- ${button('clear', 'clear', 'Clear', 'Clear the paper')}
- ${button('reference', 'image', 'Ref', 'Reference image under the paint (R to show / hide)')}
- ${button('save', 'save', 'Save', 'Save image (S saves with the last settings)')}
- ${button('settings', 'sliders', 'Settings', 'Brush &amp; water settings')}
- </div>
- <div class="panel settings" hidden>
- ${SLIDERS.map(s => `<label class="slider"><span>${s.label}</span><input type="range" min="0" max="1" step="0.01" data-param="${s.key}"></label>`).join('')}
- <button class="reset" data-action="reset">Reset</button>
- </div>
- <div class="panel palette">
- <div class="swatches" role="listbox" aria-label="Pigments">
- ${PALETTE.map((e, i) => `<button class="swatch" role="option" data-index="${i}" title="${e.name}${i < 9 ? ` (${i + 1})` : i === PALETTE.length - 1 ? ' (0)' : ''}"></button>`).join('')}
- <label class="swatch custom" title="Custom pigment"><input type="color" value="#7a3b8f"></label>
- </div>
- <div class="well" title="Spectral mix of your last two pigments"><span class="name"></span><span class="mix"></span></div>
- </div>
- <div class="panel drop-choice" hidden role="dialog" aria-label="Use the dropped image">
- <button data-drop="reference">${icon('image', 16)}<span>Use as reference</span></button>
- <button data-drop="brush">${icon('brush', 16)}<span>Make a brush</span></button>
- </div>
- <div class="toast" hidden></div>`;
-
-const $ = <T extends HTMLElement = HTMLElement>(sel: string) => root.querySelector<T>(sel)!;
-const $$ = <T extends HTMLElement = HTMLElement>(sel: string) => [...root.querySelectorAll<T>(sel)];
-
-const canvas = $<HTMLCanvasElement>('canvas.paper');
-const settings = $('.settings');
-const library = $('.library');
-const brushList = $('.brushes');
-const pickBtn = $('.tool.pick');
-const pickThumb = $<HTMLCanvasElement>('.tool.pick .thumb');
-const fileInput = $<HTMLInputElement>('.library input[type="file"]');
-const undoBtn = $<HTMLButtonElement>('[data-action="undo"]');
-const redoBtn = $<HTMLButtonElement>('[data-action="redo"]');
-const clearBtn = $('[data-action="clear"]');
-const dropChoice = $('.drop-choice');
-const customSwatch = $('.swatch.custom');
-const customInput = $<HTMLInputElement>('.swatch.custom input');
-const toast = $('.toast');
-const sliders = $$<HTMLInputElement>('[data-param]');
-const swatchButtons = $$('.swatch[data-index]');
-swatchButtons.forEach((b, i) => { b.style.background = swatchBackground(PALETTE[i]); });
-
-/* ---------------------------------------------------------------- state */
-
-let engine: WatercolorEngine;
-let tool: UiTool = 'brush';
-let strokeTool: Tool | null = null;
-let params: Params = { ...DEFAULT_PARAMS };
-let current: PaletteEntry = PALETTE[5];
-let previous: PaletteEntry = PALETTE[0];
-let confirmTimer = 0;
-let toastTimer = 0;
-
-const builtIn: Brush[] = BRUSH_PRESETS.map(p => buildBrush(p));
-let customs: Brush[] = [];
-const allBrushes = () => [...builtIn, ...customs];
-let brush: Brush = builtIn[0];
-
-try {
- engine = new WatercolorEngine(canvas, $('.cursor'), {
- onHistoryChange: (canUndo, canRedo) => { undoBtn.disabled = !canUndo; redoBtn.disabled = !canRedo; },
- onStrokeTool: t => { strokeTool = t; renderTools(); },
- });
-} catch (e) {
- root.innerHTML = `<div class="error"><p>${e instanceof Error ? e.message : String(e)}</p><p class="sub">A browser with WebGL2 is required.</p></div>`;
- throw e;
-}
-if (import.meta.env.DEV) (window as unknown as { engine: WatercolorEngine }).engine = engine;
-
-const textTool = createTextTool(engine, root, canvas, showToast);
-const shapeTool = createShapeTool(engine, root, canvas, showToast);
-const fillTool = createFillTool(engine, root, canvas, showToast);
-const reference = createReference(engine, root, showToast, on => { engine.interactive = !on && !isPanelTool(tool); });
-const exporter = createExportPanel(engine, root, showToast);
-/** Small panels that drop down under the action bar, one at a time, keyed by their button's action. */
-const popovers: Record<string, HTMLElement> = { settings, reference: reference.panel, save: exporter.panel };
-/** Tools with their own panel that drive the engine themselves. */
-const panelTools: Record<PanelTool, { active: boolean; activate(): void; deactivate(): void; stop(): boolean }> = { text: textTool, shape: shapeTool, fill: fillTool };
-const isPanelTool = (t: UiTool): t is PanelTool => t in panelTools;
-
-/* ------------------------------------------------------------ rendering */
-
-function renderTools() {
- const shown = strokeTool ?? tool;
- for (const b of $$('[data-tool]')) {
- b.classList.toggle('on', b.dataset.tool === shown);
- b.setAttribute('aria-pressed', String(b.dataset.tool === tool));
- }
-}
-
-function renderParams() {
- for (const s of sliders) s.value = String(params[s.dataset.param as keyof Params]);
-}
-
-function renderPalette() {
- swatchButtons.forEach((b, i) => {
- const on = PALETTE[i].name === current.name;
- b.classList.toggle('on', on);
- b.setAttribute('aria-selected', String(on));
- });
- const custom = current.name === 'Custom';
- customSwatch.classList.toggle('on', custom);
- customSwatch.style.background = custom ? swatchBackground(current) : '';
- $('.well .name').textContent = current.name;
- const mix = $('.well .mix');
- if (current.pigment.white || previous.pigment.white) { mix.innerHTML = ''; return; }
- const wet = mixToHex([{ pigment: previous.pigment, amount: 0.5 }, { pigment: current.pigment, amount: 0.5 }]);
- mix.innerHTML = `<i style="background:${previous.hex}"></i>+<i style="background:${current.hex}"></i>=<i style="background:${wet}"></i>`;
-}
-
-/** Colour used for brush previews: the current pigment, or ink for white gouache. */
-const previewHex = () => (current.pigment.white ? '#3b4552' : current.hex);
-
-/** Rebuild the library's cards (on load, and when custom brushes change). */
-function buildLibrary() {
- brushList.innerHTML = allBrushes().map(b => `
- <div class="brush${b.custom ? ' custom' : ''}" role="option" data-brush="${esc(b.id)}" aria-selected="false" tabindex="0" title="${esc(b.hint)}">
- <canvas class="stroke" width="150" height="44"></canvas>
- <span class="label">${esc(b.name)}</span>
- ${b.custom ? `<button class="icon remove" data-remove="${esc(b.id)}" title="Remove this brush">${icon('close', 14)}</button>` : ''}
- </div>`).join('');
- renderPreviews();
- renderBrush();
-}
-
-function renderPreviews() {
- const hex = previewHex();
- const byId = new Map(allBrushes().map(b => [b.id, b]));
- for (const el of $$('.brush[data-brush]')) {
- const b = byId.get(el.dataset.brush!);
- if (b) drawStroke(el.querySelector('canvas')!, b, hex);
- }
- drawThumb(pickThumb, brush, hex);
-}
-
-function renderBrush() {
- for (const el of $$('.brush[data-brush]')) {
- const on = el.dataset.brush === brush.id;
- el.classList.toggle('on', on);
- el.setAttribute('aria-selected', String(on));
- }
- $('.tool.pick .brushname').textContent = brush.name;
- pickBtn.title = `${brush.name}: ${brush.hint}. Open the brush library (, and . to cycle)`;
- drawThumb(pickThumb, brush, previewHex());
-}
-
-/* -------------------------------------------------------------- actions */
-
-function setTool(t: UiTool) {
- if (isPanelTool(t) && t !== tool) toggleLibrary(false);
- reference.stopAdjust();
- tool = t;
- for (const [id, p] of Object.entries(panelTools)) if (p.active && id !== t) p.deactivate();
- if (isPanelTool(t)) {
- engine.interactive = false;
- panelTools[t].activate();
- } else {
- engine.interactive = true;
- engine.setTool(t);
- }
- renderTools();
-}
-
-function setParams(p: Partial<Params>) {
- params = { ...params, ...p };
- engine.setParams(params);
- renderParams();
-}
-
-function choose(e: PaletteEntry) {
- if (current.hex !== e.hex) previous = current;
- current = e;
- engine.setPigment(e.pigment);
- if (tool === 'water' || tool === 'lift') setTool('brush');
- renderPalette();
- renderPreviews();
-}
-
-function chooseBrush(b: Brush, scroll = false) {
- brush = b;
- engine.setBrush(b);
- if (tool === 'pen' || tool === 'lift') setTool('brush');
- renderBrush();
- try { localStorage.setItem(BRUSH_KEY, b.id); } catch { /* storage blocked */ }
- if (scroll) brushList.querySelector(`[data-brush="${CSS.escape(b.id)}"]`)?.scrollIntoView({ block: 'nearest' });
-}
-
-function cycleBrush(dir: 1 | -1) {
- const list = allBrushes();
- const i = list.findIndex(b => b.id === brush.id);
- chooseBrush(list[(i + dir + list.length) % list.length], true);
- showToast(brush.name);
-}
-
-function showToast(text: string) {
- clearTimeout(toastTimer);
- toast.textContent = text;
- toast.hidden = false;
- toastTimer = window.setTimeout(() => { toast.hidden = true; }, 1200);
-}
-
-async function importTexture(file: File) {
- try {
- const tip = await tipFromImage(file);
- const name = file.name.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').trim().slice(0, 22) || 'Imported';
- const b = makeCustomBrush(`custom-${Date.now().toString(36)}`, name, tip);
- customs.push(b);
- if (!saveCustomBrushes(customs)) showToast('Brush added, but could not be saved for next time');
- buildLibrary();
- chooseBrush(b, true);
- } catch (e) {
- showToast(e instanceof Error ? e.message : 'Could not read that image');
- }
-}
-
-function removeBrush(id: string) {
- const b = customs.find(c => c.id === id);
- if (!b) return;
- customs = customs.filter(c => c.id !== id);
- saveCustomBrushes(customs);
- engine.forgetBrush(id);
- forgetTipImages(id);
- if (brush.id === id) chooseBrush(builtIn[0]);
- buildLibrary();
-}
-
-function setConfirmClear(on: boolean) {
- clearTimeout(confirmTimer);
- clearBtn.classList.toggle('danger', on);
- clearBtn.querySelector('span')!.textContent = on ? 'Sure?' : 'Clear';
- if (on) confirmTimer = window.setTimeout(() => setConfirmClear(false), 2500);
-}
-
-function clear() {
- if (!clearBtn.classList.contains('danger')) { setConfirmClear(true); return; }
- engine.clear();
- reference.layout();
- setConfirmClear(false);
-}
-
-/** Open or close one popover (toggling when `force` is omitted); opening one closes the rest. */
-function togglePopover(name: string, force?: boolean) {
- const open = force ?? popovers[name].hidden;
- for (const [n, el] of Object.entries(popovers)) {
- el.hidden = !(open && n === name);
- const b = $(`.actions [data-action="${n}"]`);
- b.classList.toggle('on', !el.hidden);
- b.setAttribute('aria-expanded', String(!el.hidden));
- }
-}
-
-const closePopovers = () => { for (const n of Object.keys(popovers)) togglePopover(n, false); };
-
-/* ------------------------------------------------- dropping an image file */
-
-let dropped: File | null = null;
-
-function offerDrop(f: File, x: number, y: number) {
- dropped = f;
- dropChoice.hidden = false;
- const r = dropChoice.getBoundingClientRect();
- dropChoice.style.left = `${Math.max(8, Math.min(innerWidth - r.width - 8, x - r.width / 2))}px`;
- dropChoice.style.top = `${Math.max(8, Math.min(innerHeight - r.height - 8, y - r.height / 2))}px`;
-}
-
-function closeDrop() { dropped = null; dropChoice.hidden = true; }
-
-function toggleLibrary(force?: boolean) {
- library.hidden = force === undefined ? !library.hidden : !force;
- pickBtn.classList.toggle('open', !library.hidden);
- pickBtn.setAttribute('aria-expanded', String(!library.hidden));
- if (!library.hidden) brushList.querySelector<HTMLElement>('.brush.on')?.scrollIntoView({ block: 'nearest' });
-}
-
-/* --------------------------------------------------------------- wiring */
-
-root.addEventListener('click', e => {
- const el = (e.target as Element).closest<HTMLElement>('[data-tool], [data-action], [data-index], [data-brush], [data-remove]');
- if (!el) return;
- if (el.dataset.remove) { removeBrush(el.dataset.remove); return; }
- if (el.dataset.tool) setTool(el.dataset.tool as UiTool);
- else if (el.dataset.brush) { const b = allBrushes().find(x => x.id === el.dataset.brush); if (b) chooseBrush(b); }
- else if (el.dataset.index) choose(PALETTE[Number(el.dataset.index)]);
- else switch (el.dataset.action) {
- case 'undo': engine.undo(); break;
- case 'redo': engine.redo(); break;
- case 'dry': engine.fix(); break;
- case 'clear': clear(); break;
- case 'save': togglePopover('save'); break;
- case 'reference': togglePopover('reference'); break;
- case 'settings': togglePopover('settings'); break;
- case 'library': toggleLibrary(); break;
- case 'import': fileInput.click(); break;
- case 'reset': setParams(DEFAULT_PARAMS); break;
- case 'text-close': case 'shape-close': case 'fill-close': setTool('brush'); break;
- }
-});
-
-brushList.addEventListener('keydown', e => {
- if (e.key !== 'Enter' && e.key !== ' ') return;
- const el = (e.target as Element).closest<HTMLElement>('[data-brush]');
- const b = el && allBrushes().find(x => x.id === el.dataset.brush);
- if (b) { e.preventDefault(); chooseBrush(b); }
-});
-
-dropChoice.addEventListener('click', e => {
- const k = (e.target as Element).closest<HTMLElement>('[data-drop]')?.dataset.drop;
- const f = dropped;
- if (!k || !f) return;
- closeDrop();
- if (k === 'reference') void reference.load(f);
- else void importTexture(f);
-});
-window.addEventListener('pointerdown', e => { if (!dropChoice.hidden && !dropChoice.contains(e.target as Node)) closeDrop(); });
-
-fileInput.addEventListener('change', () => {
- const f = fileInput.files?.[0];
- fileInput.value = '';
- if (!f) return;
- if (isSvgFile(f)) void shapeTool.loadSvg(f).then(ok => { if (ok) setTool('shape'); });
- else void importTexture(f);
-});
-
-// drop an image anywhere to use it as the reference or make a brush from it
-root.addEventListener('dragover', e => { if (e.dataTransfer?.types.includes('Files')) e.preventDefault(); });
-root.addEventListener('drop', e => {
- const f = e.dataTransfer?.files?.[0];
- if (!f) return;
- if (isSvgFile(f)) {
- // an SVG's paths become a shape to trace, not a brush tip
- e.preventDefault();
- void shapeTool.loadSvg(f).then(ok => { if (ok) setTool('shape'); });
- } else if (isRasterFile(f)) { e.preventDefault(); offerDrop(f, e.clientX, e.clientY); }
-});
-
-settings.addEventListener('input', e => {
- const s = e.target as HTMLInputElement;
- if (s.dataset.param) setParams({ [s.dataset.param]: Number(s.value) });
-});
-
-customInput.addEventListener('input', () => choose(customEntry(customInput.value)));
-
-canvas.addEventListener('pointerdown', () => $('.hint').classList.add('gone'), { once: true });
-// painting dismisses the library so it never covers the work for long
-canvas.addEventListener('pointerdown', () => { if (!library.hidden) toggleLibrary(false); });
-
-window.addEventListener('resize', () => { engine.resize(); reference.layout(); renderPreviews(); });
-
-window.addEventListener('keydown', e => {
- if (e.target instanceof HTMLInputElement && e.target.type !== 'range') return;
- const k = e.key.toLowerCase();
- if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); if (e.shiftKey) engine.redo(); else engine.undo(); return; }
- if ((e.metaKey || e.ctrlKey) && k === 'y') { e.preventDefault(); engine.redo(); return; }
- if (e.metaKey || e.ctrlKey || e.altKey) return;
- if (k === 'escape') {
- if (!dropChoice.hidden) closeDrop();
- else if (reference.stopAdjust()) { /* done moving the reference */ }
- else if (!Object.values(panelTools).some(p => p.stop())) { toggleLibrary(false); closePopovers(); }
- return;
- }
- const t = TOOLS.find(x => x.key.toLowerCase() === k);
- if (t) setTool(t.id);
- else if (k === '[' || k === ']') setParams({ size: Math.min(1, Math.max(0, params.size + (k === ']' ? 0.05 : -0.05))) });
- else if (k === ',' || k === '<') cycleBrush(-1);
- else if (k === '.' || k === '>') cycleBrush(1);
- else if (k === 'd') engine.fix();
- else if (k === 's') void exporter.save();
- else if (k === 'r') reference.toggleVisible();
- else if (k === 'f') {
- if (document.fullscreenElement) void document.exitFullscreen();
- else void document.documentElement.requestFullscreen?.();
- } else if (/^[1-9]$/.test(k)) choose(PALETTE[Number(k) - 1]);
- else if (k === '0') choose(PALETTE[PALETTE.length - 1]);
-});
-
-/* ----------------------------------------------------------------- init */
-
-engine.setPigment(current.pigment);
-engine.setBrush(brush);
-undoBtn.disabled = true;
-redoBtn.disabled = true;
-renderTools();
-renderParams();
-renderPalette();
-buildLibrary();
-
-void loadCustomBrushes().then(list => {
- customs = list;
- let wanted: string | null = null;
- try { wanted = localStorage.getItem(BRUSH_KEY); } catch { /* storage blocked */ }
- buildLibrary();
- const b = wanted && allBrushes().find(x => x.id === wanted);
- if (b) chooseBrush(b);
-});
diff --git a/src/main.tsx b/src/main.tsx
new file mode 100644
index 0000000..21f31bd
--- /dev/null
+++ b/src/main.tsx
@@ -0,0 +1,5 @@
+import { render } from 'preact';
+import { App } from './app/App';
+import './styles.css';
+
+render(<App />, document.getElementById('root')!);
diff --git a/src/reference/RefFrame.tsx b/src/reference/RefFrame.tsx
new file mode 100644
index 0000000..f52dc4e
--- /dev/null
+++ b/src/reference/RefFrame.tsx
@@ -0,0 +1,111 @@
+import { useEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import { resizeTick } from '../app/resize';
+
+const MIN_PX = 24; // smallest the reference can be scaled to, in CSS px
+
+/** A rectangle in client (CSS) px. */
+interface Box { l: number; t: number; w: number; h: number }
+
+type Gesture =
+ | { kind: 'move'; start: Box; x: number; y: number }
+ | { kind: 'corner'; start: Box; ax: number; ay: number; sx: number; sy: number }
+ | { kind: 'pinch'; start: Box; mx: number; my: number; dist: number };
+
+/** Scale the box by `s` about the client point (cx, cy), keeping a sensible minimum. */
+function scaleAbout(b: Box, s: number, cx: number, cy: number): Box {
+ s = Math.max(s, MIN_PX / Math.min(b.w, b.h));
+ return { l: cx + (b.l - cx) * s, t: cy + (b.t - cy) * s, w: b.w * s, h: b.h * s };
+}
+
+/** The reference image's move / scale frame: drag to move, corners / wheel / pinch to scale. */
+export function RefFrame() {
+ const app = useApp();
+ const ref = app.reference;
+ const { engine } = app;
+ const el = useRef<HTMLDivElement>(null);
+ const pointers = useRef(new Map<number, { x: number; y: number }>());
+ const gesture = useRef<Gesture | null>(null);
+
+ const show = ref.adjusting.value && ref.has.value;
+ resizeTick.value; // re-place the frame after a resize
+ const r = ref.rect.value;
+ const [l, t] = engine.docToClient(r.x, r.y + r.h);
+ const [rr, b] = engine.docToClient(r.x + r.w, r.y);
+ const box = (): Box => ({ l, t, w: rr - l, h: b - t });
+
+ function setBox(bx: Box) {
+ const [x0, y0] = engine.clientToDoc(bx.l, bx.t + bx.h);
+ const [x1, y1] = engine.clientToDoc(bx.l + bx.w, bx.t);
+ ref.rect.value = { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
+ }
+
+ function beginGesture(corner?: string) {
+ const start = box();
+ const pts = [...pointers.current.values()];
+ if (pts.length >= 2) {
+ const [a, c] = pts;
+ gesture.current = { kind: 'pinch', start, mx: (a.x + c.x) / 2, my: (a.y + c.y) / 2, dist: Math.max(1, Math.hypot(a.x - c.x, a.y - c.y)) };
+ } else if (corner) {
+ // the opposite corner stays put; sx / sy say which way the box grows from it
+ const sx = corner.includes('e') ? 1 : -1, sy = corner.includes('s') ? 1 : -1;
+ gesture.current = { kind: 'corner', start, ax: sx > 0 ? start.l : start.l + start.w, ay: sy > 0 ? start.t : start.t + start.h, sx, sy };
+ } else {
+ gesture.current = { kind: 'move', start, x: pts[0].x, y: pts[0].y };
+ }
+ }
+
+ const onDown = (e: PointerEvent) => {
+ e.preventDefault();
+ try { el.current!.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ beginGesture((e.target as HTMLElement).dataset.corner);
+ };
+ const onMove = (e: PointerEvent) => {
+ const g = gesture.current;
+ if (!pointers.current.has(e.pointerId) || !g) return;
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ if (g.kind === 'move') {
+ setBox({ ...g.start, l: g.start.l + e.clientX - g.x, t: g.start.t + e.clientY - g.y });
+ } else if (g.kind === 'corner') {
+ const s = Math.max((g.sx * (e.clientX - g.ax)) / g.start.w, (g.sy * (e.clientY - g.ay)) / g.start.h, MIN_PX / Math.min(g.start.w, g.start.h));
+ const w = g.start.w * s, h = g.start.h * s;
+ setBox({ l: g.sx > 0 ? g.ax : g.ax - w, t: g.sy > 0 ? g.ay : g.ay - h, w, h });
+ } else {
+ const [a, c] = [...pointers.current.values()];
+ const mx = (a.x + c.x) / 2, my = (a.y + c.y) / 2;
+ const s = Math.hypot(a.x - c.x, a.y - c.y) / g.dist;
+ const scaled = scaleAbout(g.start, s, g.mx, g.my);
+ setBox({ ...scaled, l: scaled.l + mx - g.mx, t: scaled.t + my - g.my });
+ }
+ };
+ const release = (e: PointerEvent) => {
+ if (!pointers.current.delete(e.pointerId)) return;
+ // a pinch that loses a finger carries on as a move with the one left
+ if (pointers.current.size) beginGesture(); else gesture.current = null;
+ };
+
+ // wheel must be non-passive to stop the page zooming; attach it by hand
+ useEffect(() => {
+ const node = el.current;
+ if (!node) return;
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ // trackpad pinches arrive as ctrl+wheel with small deltas
+ const s = Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015));
+ setBox(scaleAbout(box(), s, e.clientX, e.clientY));
+ };
+ node.addEventListener('wheel', onWheel, { passive: false });
+ return () => node.removeEventListener('wheel', onWheel);
+ });
+
+ // leaving adjust mode drops any half-finished gesture
+ useEffect(() => { if (!show) { pointers.current.clear(); gesture.current = null; } }, [show]);
+
+ return (
+ <div ref={el} class="ref-frame" hidden={!show} style={{ left: `${l}px`, top: `${t}px`, width: `${rr - l}px`, height: `${b - t}px` }}
+ onPointerDown={onDown} onPointerMove={onMove} onPointerUp={release} onPointerCancel={release}>
+ {['nw', 'ne', 'sw', 'se'].map(c => <i key={c} data-corner={c} />)}
+ </div>
+ );
+}
diff --git a/src/reference/ReferencePanel.tsx b/src/reference/ReferencePanel.tsx
new file mode 100644
index 0000000..b59a64f
--- /dev/null
+++ b/src/reference/ReferencePanel.tsx
@@ -0,0 +1,33 @@
+import { useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import { Icon } from '../ui/Icon';
+import { Panel, PanelHead } from '../ui/Panel';
+import { Slider } from '../ui/Slider';
+import { IMAGE_ACCEPT } from './decode';
+
+export function ReferencePanel() {
+ const app = useApp();
+ const ref = app.reference;
+ const has = ref.has.value;
+ const file = useRef<HTMLInputElement>(null);
+ const seg = (label: string, title: string, on: boolean, click: () => void) =>
+ <button class={on ? 'on' : ''} title={title} disabled={!has} onClick={click}>{label}</button>;
+ return (
+ <Panel class="popover reference" open={app.popover.value === 'reference'} role="dialog" label="Reference image">
+ <PanelHead title="Reference" sub="Shown under the paint to work from. Never exported." />
+ <button class="import" onClick={() => file.current?.click()}><Icon name="plus" size={16} /><span>{has ? 'Replace image…' : 'Import image…'}</span></button>
+ <Slider label="Opacity" value={ref.opacity} disabled={!has} onInput={v => ref.setOpacity(v)} />
+ <div class="seg">
+ {seg('Show', 'Show or hide the reference (R)', has && ref.visible, () => ref.setVisible(!ref.visible))}
+ {seg('Move', 'Drag to move, drag a corner or pinch to scale', ref.adjusting.value, () => ref.setAdjust(!ref.adjusting.value))}
+ {seg('Fit', 'Fit to the paper', false, () => ref.fit())}
+ {seg('Remove', 'Remove the reference', false, () => ref.remove())}
+ </div>
+ <input ref={file} type="file" accept={IMAGE_ACCEPT} hidden onChange={e => {
+ const el = e.currentTarget as HTMLInputElement, f = el.files?.[0];
+ el.value = '';
+ if (f) void ref.load(f);
+ }} />
+ </Panel>
+ );
+}
diff --git a/src/reference/ReferenceStore.ts b/src/reference/ReferenceStore.ts
new file mode 100644
index 0000000..b6439a2
--- /dev/null
+++ b/src/reference/ReferenceStore.ts
@@ -0,0 +1,79 @@
+import { effect, signal } from '@preact/signals';
+import type { RefRect, WatercolorEngine } from '../engine/Engine';
+import { persisted } from '../app/persisted';
+import { showToast } from '../app/toast';
+import { decodeImage } from './decode';
+
+// A photo or sketch shown under the paint to work from. It lives only on screen: the
+// engine never draws it into an export. While adjusting, a frame over it moves (drag),
+// scales (corners, wheel, pinch) and painting is paused.
+
+const KEY = 'watercolor.reference';
+
+interface Stored { opacity: number; visible: boolean }
+
+export class ReferenceStore {
+ readonly stored = persisted<Stored>(KEY, { opacity: 0.5, visible: true });
+ readonly has = signal(false);
+ /** Is the move / scale frame up? */
+ readonly adjusting = signal(false);
+ /** Mirror of the engine's placement (document uv), so the frame can follow it. */
+ readonly rect = signal<RefRect>({ x: 0, y: 0, w: 1, h: 1 });
+
+ constructor(readonly engine: WatercolorEngine) {
+ effect(() => {
+ const { opacity, visible } = this.stored.value;
+ engine.referenceOpacity = opacity;
+ engine.referenceVisible = visible;
+ });
+ effect(() => { engine.referenceRect = this.rect.value; });
+ }
+
+ get visible() { return this.stored.value.visible; }
+ get opacity() { return this.stored.value.opacity; }
+
+ setOpacity(v: number) { this.stored.value = { opacity: v, visible: true }; }
+ setVisible(v: boolean) {
+ this.stored.value = { ...this.stored.value, visible: v };
+ if (!v) this.setAdjust(false);
+ }
+
+ setAdjust(on: boolean) {
+ on &&= this.has.peek();
+ if (on === this.adjusting.peek()) return;
+ if (on && !this.visible) this.setVisible(true);
+ this.adjusting.value = on;
+ }
+
+ /** Leave move / scale mode; true if it was on. */
+ stopAdjust(): boolean { const was = this.adjusting.peek(); this.setAdjust(false); return was; }
+
+ toggleVisible() {
+ if (!this.has.peek()) return;
+ this.setVisible(!this.visible);
+ showToast(this.visible ? 'Reference shown' : 'Reference hidden');
+ }
+
+ fit() { this.engine.fitReference(); this.syncRect(); }
+
+ remove() { this.setAdjust(false); this.engine.setReference(null); this.has.value = false; }
+
+ /** Pull the placement back from the engine (after it fitted or re-created the document). */
+ syncRect() { this.rect.value = this.engine.referenceRect; }
+
+ async load(file: File): Promise<boolean> {
+ try {
+ const bmp = await decodeImage(file);
+ this.engine.setReference(bmp);
+ bmp.close();
+ this.has.value = true;
+ this.syncRect();
+ if (!this.visible) this.setVisible(true);
+ showToast('Reference added');
+ return true;
+ } catch (e) {
+ showToast(e instanceof Error ? e.message : 'Could not read that image');
+ return false;
+ }
+ }
+}
diff --git a/src/reference/referenceTool.ts b/src/reference/referenceTool.ts
deleted file mode 100644
index 2599382..0000000
--- a/src/reference/referenceTool.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import type { WatercolorEngine } from '../engine/Engine';
-import { icon } from '../ui/icons';
-import { decodeImage, IMAGE_ACCEPT } from './decode';
-
-const KEY = 'watercolor.reference';
-const MIN_PX = 24; // smallest the reference can be scaled to, in CSS px
-
-interface Stored { opacity: number; visible: boolean }
-
-/** A rectangle in client (CSS) px. */
-interface Box { l: number; t: number; w: number; h: number }
-
-export interface ReferenceController {
- panel: HTMLElement;
- /** Is the move / scale frame up? */
- readonly adjusting: boolean;
- load(file: File): Promise<boolean>;
- toggleVisible(): void;
- /** Leave move / scale mode; true if it was on. */
- stopAdjust(): boolean;
- /** Re-place the frame after the window or document changed. */
- layout(): void;
-}
-
-/**
- * A photo or sketch shown under the paint to work from. It lives only on screen: the
- * engine never draws it into an export. While adjusting, a frame over it moves (drag),
- * scales (corners, wheel, pinch) and painting is paused.
- */
-export function createReference(
- engine: WatercolorEngine, root: HTMLElement, showToast: (s: string) => void,
- onAdjust: (on: boolean) => void,
-): ReferenceController {
- let stored: Stored = { opacity: 0.5, visible: true };
- try { stored = { ...stored, ...JSON.parse(localStorage.getItem(KEY) ?? '{}') }; } catch { /* storage blocked */ }
- engine.referenceOpacity = stored.opacity;
- engine.referenceVisible = stored.visible;
- const persist = () => {
- try { localStorage.setItem(KEY, JSON.stringify({ opacity: engine.referenceOpacity, visible: engine.referenceVisible })); } catch { /* storage blocked */ }
- };
-
- const panel = document.createElement('div');
- panel.className = 'panel popover reference';
- panel.hidden = true;
- panel.setAttribute('role', 'dialog');
- panel.setAttribute('aria-label', 'Reference image');
- panel.innerHTML = `
- <div class="pop-head"><span>Reference</span><span class="sub">Shown under the paint to work from. Never exported.</span></div>
- <button class="import" data-ref="import">${icon('plus', 16)}<span>Import image…</span></button>
- <label class="slider"><span>Opacity</span><input type="range" min="0" max="1" step="0.01" data-ref="opacity"></label>
- <div class="seg">
- <button data-ref="show" title="Show or hide the reference (R)">Show</button>
- <button data-ref="adjust" title="Drag to move, drag a corner or pinch to scale">Move</button>
- <button data-ref="fit" title="Fit to the paper">Fit</button>
- <button data-ref="remove" title="Remove the reference">Remove</button>
- </div>
- <input type="file" accept="${IMAGE_ACCEPT}" hidden>`;
- root.appendChild(panel);
-
- const fileInput = panel.querySelector<HTMLInputElement>('input[type="file"]')!;
- const opacity = panel.querySelector<HTMLInputElement>('[data-ref="opacity"]')!;
- const btn = (k: string) => panel.querySelector<HTMLButtonElement>(`[data-ref="${k}"]`)!;
-
- const frame = document.createElement('div');
- frame.className = 'ref-frame';
- frame.hidden = true;
- frame.innerHTML = ['nw', 'ne', 'sw', 'se'].map(c => `<i data-corner="${c}"></i>`).join('');
- root.appendChild(frame);
-
- let adjusting = false;
-
- function render() {
- const has = engine.hasReference;
- opacity.value = String(engine.referenceOpacity);
- opacity.disabled = !has;
- for (const k of ['show', 'adjust', 'fit', 'remove']) btn(k).disabled = !has;
- btn('show').classList.toggle('on', has && engine.referenceVisible);
- btn('adjust').classList.toggle('on', adjusting);
- btn('import').querySelector('span')!.textContent = has ? 'Replace image…' : 'Import image…';
- layout();
- }
-
- /* ------------------------------------------------- doc uv <-> client box */
-
- function box(): Box {
- const r = engine.referenceRect;
- const [l, t] = engine.docToClient(r.x, r.y + r.h);
- const [rr, b] = engine.docToClient(r.x + r.w, r.y);
- return { l, t, w: rr - l, h: b - t };
- }
-
- function setBox(b: Box) {
- const [x0, y0] = engine.clientToDoc(b.l, b.t + b.h);
- const [x1, y1] = engine.clientToDoc(b.l + b.w, b.t);
- engine.referenceRect = { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
- layout();
- }
-
- function layout() {
- frame.hidden = !adjusting || !engine.hasReference;
- if (frame.hidden) return;
- const b = box();
- Object.assign(frame.style, { left: `${b.l}px`, top: `${b.t}px`, width: `${b.w}px`, height: `${b.h}px` });
- }
-
- /** Scale the box by `s` about the client point (cx, cy), keeping a sensible minimum. */
- function scaleAbout(b: Box, s: number, cx: number, cy: number): Box {
- s = Math.max(s, MIN_PX / Math.min(b.w, b.h));
- return { l: cx + (b.l - cx) * s, t: cy + (b.t - cy) * s, w: b.w * s, h: b.h * s };
- }
-
- /* ------------------------------------------------------------- gestures */
-
- const pointers = new Map<number, { x: number; y: number }>();
- let gesture:
- | { kind: 'move'; start: Box; x: number; y: number }
- | { kind: 'corner'; start: Box; ax: number; ay: number; sx: number; sy: number }
- | { kind: 'pinch'; start: Box; mx: number; my: number; dist: number }
- | null = null;
-
- function beginGesture(corner?: string) {
- const start = box();
- const pts = [...pointers.values()];
- if (pts.length >= 2) {
- const [a, b] = pts;
- gesture = { kind: 'pinch', start, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2, dist: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)) };
- } else if (corner) {
- // the opposite corner stays put; sx / sy say which way the box grows from it
- const sx = corner.includes('e') ? 1 : -1, sy = corner.includes('s') ? 1 : -1;
- gesture = { kind: 'corner', start, ax: sx > 0 ? start.l : start.l + start.w, ay: sy > 0 ? start.t : start.t + start.h, sx, sy };
- } else {
- gesture = { kind: 'move', start, x: pts[0].x, y: pts[0].y };
- }
- }
-
- frame.addEventListener('pointerdown', e => {
- e.preventDefault();
- frame.setPointerCapture(e.pointerId);
- pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
- beginGesture((e.target as HTMLElement).dataset.corner);
- });
-
- frame.addEventListener('pointermove', e => {
- if (!pointers.has(e.pointerId) || !gesture) return;
- pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
- const g = gesture;
- if (g.kind === 'move') {
- setBox({ ...g.start, l: g.start.l + e.clientX - g.x, t: g.start.t + e.clientY - g.y });
- } else if (g.kind === 'corner') {
- const s = Math.max((g.sx * (e.clientX - g.ax)) / g.start.w, (g.sy * (e.clientY - g.ay)) / g.start.h, MIN_PX / Math.min(g.start.w, g.start.h));
- const w = g.start.w * s, h = g.start.h * s;
- setBox({ l: g.sx > 0 ? g.ax : g.ax - w, t: g.sy > 0 ? g.ay : g.ay - h, w, h });
- } else {
- const [a, b] = [...pointers.values()];
- const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
- const s = Math.hypot(a.x - b.x, a.y - b.y) / g.dist;
- const scaled = scaleAbout(g.start, s, g.mx, g.my);
- setBox({ ...scaled, l: scaled.l + mx - g.mx, t: scaled.t + my - g.my });
- }
- });
-
- const release = (e: PointerEvent) => {
- if (!pointers.delete(e.pointerId)) return;
- // a pinch that loses a finger carries on as a move with the one left
- if (pointers.size) beginGesture(); else gesture = null;
- };
- frame.addEventListener('pointerup', release);
- frame.addEventListener('pointercancel', release);
-
- frame.addEventListener('wheel', e => {
- e.preventDefault();
- // trackpad pinches arrive as ctrl+wheel with small deltas
- const s = Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015));
- setBox(scaleAbout(box(), s, e.clientX, e.clientY));
- }, { passive: false });
-
- /* ------------------------------------------------------------ actions */
-
- function setAdjust(on: boolean) {
- on &&= engine.hasReference;
- if (on === adjusting) return;
- adjusting = on;
- pointers.clear();
- gesture = null;
- if (on && !engine.referenceVisible) { engine.referenceVisible = true; persist(); }
- onAdjust(on);
- render();
- }
-
- async function load(file: File): Promise<boolean> {
- try {
- const bmp = await decodeImage(file);
- engine.setReference(bmp);
- bmp.close();
- if (!engine.referenceVisible) { engine.referenceVisible = true; persist(); }
- render();
- showToast('Reference added');
- return true;
- } catch (e) {
- showToast(e instanceof Error ? e.message : 'Could not read that image');
- return false;
- }
- }
-
- panel.addEventListener('click', e => {
- const k = (e.target as Element).closest<HTMLElement>('[data-ref]')?.dataset.ref;
- switch (k) {
- case 'import': fileInput.click(); break;
- case 'show': engine.referenceVisible = !engine.referenceVisible; persist(); render(); break;
- case 'adjust': setAdjust(!adjusting); break;
- case 'fit': engine.fitReference(); render(); break;
- case 'remove': setAdjust(false); engine.setReference(null); render(); break;
- }
- });
-
- opacity.addEventListener('input', () => {
- engine.referenceOpacity = Number(opacity.value);
- if (!engine.referenceVisible) engine.referenceVisible = true;
- persist();
- render();
- });
-
- fileInput.addEventListener('change', () => {
- const f = fileInput.files?.[0];
- fileInput.value = '';
- if (f) void load(f);
- });
-
- render();
-
- return {
- panel,
- get adjusting() { return adjusting; },
- load,
- toggleVisible() {
- if (!engine.hasReference) return;
- engine.referenceVisible = !engine.referenceVisible;
- if (!engine.referenceVisible) setAdjust(false);
- persist();
- render();
- showToast(engine.referenceVisible ? 'Reference shown' : 'Reference hidden');
- },
- stopAdjust() { const was = adjusting; setAdjust(false); return was; },
- layout,
- };
-}
diff --git a/src/shapes/ShapePanel.tsx b/src/shapes/ShapePanel.tsx
new file mode 100644
index 0000000..de37d50
--- /dev/null
+++ b/src/shapes/ShapePanel.tsx
@@ -0,0 +1,83 @@
+import { useEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import type { Tool } from '../engine/Engine';
+import { Icon } from '../ui/Icon';
+import { Seg } from '../ui/Seg';
+import { Row, SliderRows, type SliderSpec } from '../ui/Slider';
+import { ToolPanel } from '../ui/ToolPanel';
+import { hasRotation, hasSides, SHAPES, type ShapeKind } from './shapes';
+import type { ShapeSettings, ShapeStore } from './ShapeStore';
+
+const SLIDERS: SliderSpec<ShapeSettings>[] = [
+ { key: 'speed', label: 'Speed', hint: 'How fast the brush travels' },
+ { key: 'pressure', label: 'Pressure', min: 0.05, hint: 'How hard the brush presses' },
+ { key: 'taper', label: 'Taper', hint: 'Lighter touch at the ends of each stroke' },
+ { key: 'wobble', label: 'Wobble', hint: 'Hand tremor' },
+ { key: 'sides', label: 'Sides', min: 3, max: 12, step: 1, hint: 'Polygon sides / star points', show: s => hasSides(s.kind) },
+ { key: 'inner', label: 'Inner', min: 0.2, max: 0.9, hint: 'Star inner radius', show: s => s.kind === 'star' },
+ { key: 'rotation', label: 'Rotate', min: 0, max: 360, step: 1, hint: 'Rotation in degrees', show: s => hasRotation(s.kind) },
+];
+
+const TOOLS: { id: Tool; label: string }[] = [{ id: 'brush', label: 'Brush' }, { id: 'pen', label: 'Pen' }, { id: 'water', label: 'Water' }];
+const LOCKS = [{ id: false, label: 'Free' }, { id: true, label: '1 : 1' }];
+
+/** Small outline glyphs for the shape grid (24×24 viewBox). */
+const GLYPHS: Record<ShapeKind, string> = {
+ line: 'M5 19 19 5',
+ arrow: 'M5 19 19 5 M11 5h8v8',
+ rect: 'M4.5 6.5h15v11h-15Z',
+ ellipse: 'M12 5.5c4.4 0 8 2.9 8 6.5s-3.6 6.5-8 6.5-8-2.9-8-6.5 3.6-6.5 8-6.5Z',
+ triangle: 'M12 5 20 19H4Z',
+ polygon: 'M12 4.5 19.5 10l-2.9 9H7.4L4.5 10Z',
+ star: 'M12 4.5l2.2 5 5.3.5-4 3.6 1.2 5.3L12 16.1l-4.7 2.8 1.2-5.3-4-3.6 5.3-.5Z',
+ svg: 'M7 3.5h7l4 4V20.5H7Z M14 3.5v4h4 M9.5 16.5c1.5-4 3.5-4 5 0',
+};
+
+export function ShapePanel({ tool }: { tool: ShapeStore }) {
+ const app = useApp();
+ const s = tool.settings.value;
+ const svg = tool.svg.value;
+ const file = useRef<HTMLInputElement>(null);
+
+ const pickRequest = tool.pickRequest.value;
+ useEffect(() => { if (pickRequest) file.current?.click(); }, [pickRequest]);
+
+ const pick = (kind: ShapeKind) => {
+ tool.set({ kind });
+ if (kind === 'svg' && !svg) file.current?.click();
+ };
+
+ return (
+ <ToolPanel title="Shapes" class="shape" open={tool.active.value} status={tool.status.value} busy={tool.drawing.value}
+ sub="Drag a box on the paper; when you let go the outline is drawn stroke by stroke with the current brush and pigment."
+ onStop={() => tool.stop()} onClose={() => app.setTool('brush')}>
+ <div class="shapes" role="radiogroup" aria-label="Shape">
+ {SHAPES.map(k => (
+ <button key={k.id} role="radio" class={k.id === s.kind ? 'on' : ''} aria-checked={k.id === s.kind} title={k.hint} onClick={() => pick(k.id)}>
+ <Icon d={GLYPHS[k.id]} size={22} /><span>{k.short ?? k.label}</span>
+ </button>
+ ))}
+ </div>
+ <div class="tool-rows">
+ {s.kind === 'svg' && (
+ <div class="slider"><span>File</span>
+ <div class="svg-file">
+ <span class="svg-name" title={svg?.name ?? ''}>{svg ? `${svg.name} · ${svg.count} ${svg.count === 1 ? 'stroke' : 'strokes'}` : 'No file yet'}</span>
+ <button class="svg-pick" onClick={() => file.current?.click()}>{svg ? 'Replace…' : 'Choose…'}</button>
+ </div>
+ </div>
+ )}
+ <Row label="Draw with"><Seg options={TOOLS} value={s.tool} onChange={t => tool.set({ tool: t })} /></Row>
+ <Row label="Lock" title="Keep squares square, circles round, lines on 45° steps and SVGs in their own proportions (or hold Shift)">
+ <Seg options={LOCKS} value={s.lock} onChange={lock => tool.set({ lock })} />
+ </Row>
+ <SliderRows spec={SLIDERS} settings={s} onChange={p => tool.set(p)} />
+ </div>
+ <input ref={file} type="file" accept=".svg,image/svg+xml" hidden onChange={e => {
+ const el = e.currentTarget as HTMLInputElement, f = el.files?.[0];
+ el.value = '';
+ if (f) void tool.loadSvg(f);
+ }} />
+ </ToolPanel>
+ );
+}
diff --git a/src/shapes/ShapeStore.ts b/src/shapes/ShapeStore.ts
new file mode 100644
index 0000000..2c0aa25
--- /dev/null
+++ b/src/shapes/ShapeStore.ts
@@ -0,0 +1,178 @@
+import { computed, effect, signal, type ReadonlySignal } from '@preact/signals';
+import type { Tool, WatercolorEngine } from '../engine/Engine';
+import type { PanelTool, PaperGesture } from '../app/tools';
+import { persisted } from '../app/persisted';
+import { resizeTick } from '../app/resize';
+import { showToast } from '../app/toast';
+import { hideGhost, setGhost } from '../draw/ghost';
+import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
+import { constrain, fitSvg, SHAPES, shapeStrokes, type ShapeKind } from './shapes';
+import { importSvg, type ImportedSvg } from './svgImport';
+
+// The Shape tool: pick a shape, drag a box on the paper (a dashed ghost follows),
+// and on release the StrokeWriter draws the outline slowly with the current brush.
+
+export interface ShapeSettings {
+ kind: ShapeKind;
+ tool: Tool;
+ lock: boolean; // keep squares square / circles round / lines on 45° steps
+ speed: number; // 0..1 slider
+ pressure: number; // 0.05..1
+ taper: number; // 0..1
+ wobble: number; // 0..1
+ sides: number; // 3..12
+ inner: number; // 0.2..0.9
+ rotation: number; // 0..360
+}
+
+const KEY = 'watercolor.shape';
+const DEFAULTS: ShapeSettings = {
+ kind: 'rect', tool: 'brush', lock: false,
+ speed: 0.5, pressure: 0.6, taper: 0.4, wobble: 0.2, sides: 5, inner: 0.45, rotation: 0,
+};
+
+type Pt = [number, number];
+interface Drag { id: number; a: Pt; b: Pt; shift: boolean }
+
+export class ShapeStore implements PanelTool {
+ readonly id = 'shape';
+ // the imported file lives for the session only, so a saved `svg` kind starts as the default
+ readonly settings = persisted<ShapeSettings>(KEY, DEFAULTS,
+ s => (SHAPES.some(k => k.id === s.kind) && s.kind !== 'svg' ? s : { ...s, kind: DEFAULTS.kind }));
+ readonly active = signal(false);
+ readonly svg = signal<ImportedSvg | null>(null);
+ readonly drawing = signal(false);
+ readonly progress = signal<[number, number] | null>(null);
+ readonly drag = signal<Drag | null>(null);
+ /** Bumped when the panel should open its SVG file picker. */
+ readonly pickRequest = signal(0);
+ readonly busy: ReadonlySignal<boolean> = this.drawing;
+ readonly status = computed(() => {
+ const s = this.settings.value, svg = this.svg.value;
+ if (this.drawing.value) { const p = this.progress.value; return p && p[1] > 1 ? `Drawing… ${p[0]} / ${p[1]} strokes` : 'Drawing…'; }
+ if (this.drag.value) return 'Let go to draw';
+ if (!this.active.value) return '';
+ if (s.kind === 'svg') return svg ? `Drag on the paper to place ${svg.name}` : 'Choose an SVG file, or drop one on the paper';
+ return `Drag on the paper to draw a ${SHAPES.find(k => k.id === s.kind)!.label.toLowerCase()}`;
+ });
+
+ private writer: StrokeWriter;
+
+ constructor(private engine: WatercolorEngine) {
+ this.writer = new StrokeWriter(engine);
+ effect(() => this.renderGhost());
+ }
+
+ set(p: Partial<ShapeSettings>) { this.settings.value = { ...this.settings.value, ...p }; }
+
+ /** Shape parameters including the imported file. */
+ private params() { return { ...this.settings.peek(), svg: this.svg.peek() }; }
+
+ /** The drag end, constrained if the lock (or Shift) is on. */
+ private endPoint(d: Drag): Pt {
+ const s = this.settings.peek(), svg = this.svg.peek();
+ const boxAspect = s.kind === 'svg' && svg ? svg.aspect : 1;
+ return s.lock !== d.shift ? constrain(s.kind, d.a, d.b, this.engine.aspect, boxAspect) : d.b;
+ }
+
+ /** Strokes for the ghost: the thinned copy for SVGs, the real thing otherwise. */
+ private ghostStrokes(a: Pt, b: Pt, aspect: number) {
+ const s = this.settings.value, svg = this.svg.value;
+ if (s.kind !== 'svg') return shapeStrokes(s.kind, a, b, this.params(), aspect);
+ return svg ? fitSvg(svg.ghost, (b[0] - a[0]) * aspect, b[1] - a[1], s.rotation) : [];
+ }
+
+ private renderGhost() {
+ resizeTick.value;
+ const drag = this.drag.value;
+ if (!this.active.value || !drag || this.drawing.value) { hideGhost(); return; }
+ const a = this.engine.aspect;
+ const [ax, ay] = drag.a;
+ let d = '';
+ for (const pl of this.ghostStrokes(drag.a, this.endPoint(drag), a)) {
+ pl.forEach(([x, y], i) => {
+ const [cx, cy] = this.engine.docToClient(ax + x / a, ay + y);
+ d += `${i ? 'L' : 'M'}${cx.toFixed(1)} ${cy.toFixed(1)}`;
+ });
+ }
+ setGhost(d);
+ }
+
+ private draw(d: Drag) {
+ const s = this.settings.peek();
+ const b = this.endPoint(d);
+ const aspect = this.engine.aspect;
+ const w = Math.abs(b[0] - d.a[0]) * aspect, h = Math.abs(b[1] - d.a[1]);
+ const strokes = shapeStrokes(s.kind, d.a, b, this.params(), aspect);
+ if (!strokes.length) return;
+ const ref = s.kind === 'line' || s.kind === 'arrow' ? Math.hypot(w, h) * 0.5 : Math.max(0.01, Math.min(w, h));
+ this.drawing.value = true;
+ this.progress.value = [0, strokes.length];
+ this.writer.write(strokes, d.a, {
+ tool: s.tool, ref, speed: penSpeed(s.speed), pressure: s.pressure, taper: s.taper, wobble: s.wobble,
+ }, {
+ onProgress: (done, total) => { this.progress.value = [done, total]; },
+ onDone: () => { this.drawing.value = false; this.progress.value = null; },
+ });
+ }
+
+ /** Load an SVG file as the `svg` shape. Resolves false (after a toast) if it could not be read. */
+ async loadSvg(file: File): Promise<boolean> {
+ try {
+ this.svg.value = await importSvg(file);
+ } catch (e) {
+ showToast(e instanceof Error ? e.message : 'Could not read that SVG');
+ return false;
+ }
+ this.set({ kind: 'svg' });
+ return true;
+ }
+
+ private cancelDrag(canvas?: Element) {
+ const d = this.drag.peek();
+ if (!d) return false;
+ try { canvas?.releasePointerCapture(d.id); } catch { /* already released */ }
+ this.drag.value = null;
+ return true;
+ }
+
+ readonly gesture: PaperGesture = {
+ down: (e, uv) => {
+ if (this.drag.peek()) return;
+ if (this.drawing.peek()) { showToast('Still drawing… press Stop or Esc'); return; }
+ try { (e.currentTarget as Element).setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
+ this.drag.value = { id: e.pointerId, a: uv, b: uv, shift: e.shiftKey };
+ },
+ move: (e, uv) => {
+ const d = this.drag.peek();
+ if (!d || e.pointerId !== d.id) return;
+ this.drag.value = { ...d, b: uv, shift: e.shiftKey };
+ },
+ up: (e, uv) => {
+ const d = this.drag.peek();
+ if (!d || e.pointerId !== d.id) return;
+ const done = { ...d, b: uv, shift: e.shiftKey };
+ this.cancelDrag(e.currentTarget as Element);
+ const [x0, y0] = this.engine.docToClient(...done.a), [x1, y1] = this.engine.docToClient(...done.b);
+ if (this.settings.peek().kind === 'svg' && !this.svg.peek()) { this.pickRequest.value++; return; }
+ if (Math.hypot(x1 - x0, y1 - y0) < 6) { showToast('Drag to size the shape'); return; }
+ this.draw(done);
+ },
+ cancel: e => { const d = this.drag.peek(); if (d && e.pointerId === d.id) this.cancelDrag(e.currentTarget as Element); },
+ };
+
+ activate() { this.active.value = true; }
+
+ deactivate() {
+ this.active.value = false;
+ this.cancelDrag();
+ this.writer.cancel();
+ }
+
+ stop() {
+ if (this.cancelDrag()) return true;
+ if (!this.drawing.peek()) return false;
+ this.writer.cancel();
+ return true;
+ }
+}
diff --git a/src/shapes/shapeTool.ts b/src/shapes/shapeTool.ts
deleted file mode 100644
index 3f2f11f..0000000
--- a/src/shapes/shapeTool.ts
+++ /dev/null
@@ -1,323 +0,0 @@
-import type { Tool, WatercolorEngine } from '../engine/Engine';
-import { icon } from '../ui/icons';
-import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
-import { createGhost } from '../draw/ghost';
-import { constrain, fitSvg, hasRotation, hasSides, SHAPES, shapeStrokes, type ShapeKind } from './shapes';
-import { importSvg, type ImportedSvg } from './svgImport';
-
-// The Shape tool: pick a shape, drag a box on the paper (a dashed ghost follows),
-// and on release the StrokeWriter draws the outline slowly with the current brush.
-
-export interface ShapeSettings {
- kind: ShapeKind;
- tool: Tool;
- lock: boolean; // keep squares square / circles round / lines on 45° steps
- speed: number; // 0..1 slider
- pressure: number; // 0.05..1
- taper: number; // 0..1
- wobble: number; // 0..1
- sides: number; // 3..12
- inner: number; // 0.2..0.9
- rotation: number; // 0..360
-}
-
-const KEY = 'watercolor.shape';
-const DEFAULTS: ShapeSettings = {
- kind: 'rect', tool: 'brush', lock: false,
- speed: 0.5, pressure: 0.6, taper: 0.4, wobble: 0.2, sides: 5, inner: 0.45, rotation: 0,
-};
-
-const SLIDERS: { key: keyof ShapeSettings; label: string; min: number; max: number; step: number; hint: string; show?: (k: ShapeKind) => boolean }[] = [
- { key: 'speed', label: 'Speed', min: 0, max: 1, step: 0.01, hint: 'How fast the brush travels' },
- { key: 'pressure', label: 'Pressure', min: 0.05, max: 1, step: 0.01, hint: 'How hard the brush presses' },
- { key: 'taper', label: 'Taper', min: 0, max: 1, step: 0.01, hint: 'Lighter touch at the ends of each stroke' },
- { key: 'wobble', label: 'Wobble', min: 0, max: 1, step: 0.01, hint: 'Hand tremor' },
- { key: 'sides', label: 'Sides', min: 3, max: 12, step: 1, hint: 'Polygon sides / star points', show: hasSides },
- { key: 'inner', label: 'Inner', min: 0.2, max: 0.9, step: 0.01, hint: 'Star inner radius', show: k => k === 'star' },
- { key: 'rotation', label: 'Rotate', min: 0, max: 360, step: 1, hint: 'Rotation in degrees', show: hasRotation },
-];
-
-const TOOLS: { id: Tool; label: string }[] = [{ id: 'brush', label: 'Brush' }, { id: 'pen', label: 'Pen' }, { id: 'water', label: 'Water' }];
-
-/** Small outline glyphs for the shape grid (24×24 viewBox). */
-const GLYPHS: Record<ShapeKind, string> = {
- line: 'M5 19 19 5',
- arrow: 'M5 19 19 5 M11 5h8v8',
- rect: 'M4.5 6.5h15v11h-15Z',
- ellipse: 'M12 5.5c4.4 0 8 2.9 8 6.5s-3.6 6.5-8 6.5-8-2.9-8-6.5 3.6-6.5 8-6.5Z',
- triangle: 'M12 5 20 19H4Z',
- polygon: 'M12 4.5 19.5 10l-2.9 9H7.4L4.5 10Z',
- star: 'M12 4.5l2.2 5 5.3.5-4 3.6 1.2 5.3L12 16.1l-4.7 2.8 1.2-5.3-4-3.6 5.3-.5Z',
- svg: 'M7 3.5h7l4 4V20.5H7Z M14 3.5v4h4 M9.5 16.5c1.5-4 3.5-4 5 0',
-};
-
-const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
-type Pt = [number, number];
-
-export interface ShapeToolHandle {
- panel: HTMLElement;
- activate(): void;
- deactivate(): void;
- /** Cancel a drag or stop drawing. Returns whether anything was stopped. */
- stop(): boolean;
- /** Load an SVG file as the `svg` shape. Resolves false (after a toast) if it could not be read. */
- loadSvg(file: File): Promise<boolean>;
- readonly active: boolean;
-}
-
-export function createShapeTool(engine: WatercolorEngine, root: HTMLElement, canvas: HTMLCanvasElement, toast: (s: string) => void): ShapeToolHandle {
- let settings: ShapeSettings = { ...DEFAULTS, ...load() };
- // the imported file lives for the session only, so a saved `svg` kind starts empty
- if (!SHAPES.some(s => s.id === settings.kind) || settings.kind === 'svg') settings.kind = DEFAULTS.kind;
- let svg: ImportedSvg | null = null;
- let active = false;
- let drag: { id: number; a: Pt; b: Pt; shift: boolean } | null = null;
- const writer = new StrokeWriter(engine);
- const ghost = createGhost(root);
-
- /* ---------------------------------------------------------------- markup */
-
- const panel = document.createElement('div');
- panel.className = 'panel text shape';
- panel.hidden = true;
- panel.setAttribute('role', 'dialog');
- panel.setAttribute('aria-label', 'Shapes');
- panel.innerHTML = `
- <div class="library-head">
- <span>Shapes</span>
- <span class="sub">Drag a box on the paper; when you let go the outline is drawn stroke by stroke with the current brush and pigment.</span>
- <button class="icon" data-action="shape-close" title="Close">${icon('close', 16)}</button>
- </div>
- <div class="text-body">
- <div class="shapes" role="radiogroup" aria-label="Shape">
- ${SHAPES.map(s => `<button role="radio" data-kind="${s.id}" title="${esc(s.hint)}"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${GLYPHS[s.id]}"/></svg><span>${s.short ?? s.label}</span></button>`).join('')}
- </div>
- <div class="text-rows">
- <div class="slider svg-row" hidden><span>File</span><div class="svg-file"><span class="svg-name"></span><button class="svg-pick" data-action="svg-pick">Choose…</button></div></div>
- <label class="slider"><span>Draw with</span><div class="seg" data-opt="tool" role="radiogroup">${TOOLS.map(t => `<button role="radio" data-value="${t.id}">${t.label}</button>`).join('')}</div></label>
- <label class="slider"><span>Lock</span><div class="seg" data-opt="lock" role="radiogroup" title="Keep squares square, circles round, lines on 45° steps and SVGs in their own proportions (or hold Shift)"><button role="radio" data-value="false">Free</button><button role="radio" data-value="true">1 : 1</button></div></label>
- ${SLIDERS.map(s => `<label class="slider" data-slider="${s.key}" title="${s.hint}"><span>${s.label}</span><input type="range" min="${s.min}" max="${s.max}" step="${s.step}" data-opt="${s.key}"></label>`).join('')}
- </div>
- <div class="text-foot">
- <span class="status"></span>
- <button class="stop" data-action="shape-stop" hidden>${icon('close', 14)}<span>Stop</span></button>
- </div>
- </div>
- <input type="file" accept=".svg,image/svg+xml" hidden>`;
- root.appendChild(panel);
-
- const status = panel.querySelector<HTMLElement>('.status')!;
- const stopBtn = panel.querySelector<HTMLButtonElement>('.stop')!;
- const sliders = [...panel.querySelectorAll<HTMLInputElement>('input[type="range"][data-opt]')];
- const svgRow = panel.querySelector<HTMLElement>('.svg-row')!;
- const svgName = panel.querySelector<HTMLElement>('.svg-name')!;
- const svgPick = panel.querySelector<HTMLButtonElement>('.svg-pick')!;
- const fileInput = panel.querySelector<HTMLInputElement>('input[type="file"]')!;
- /** Shape parameters including the imported file. */
- const params = () => ({ ...settings, svg });
-
- /* ------------------------------------------------------------- rendering */
-
- function render() {
- for (const s of sliders) s.value = String(settings[s.dataset.opt as keyof ShapeSettings]);
- for (const s of SLIDERS) panel.querySelector<HTMLElement>(`[data-slider="${s.key}"]`)!.hidden = s.show ? !s.show(settings.kind) : false;
- svgRow.hidden = settings.kind !== 'svg';
- svgName.textContent = svg ? `${svg.name} · ${svg.count} ${svg.count === 1 ? 'stroke' : 'strokes'}` : 'No file yet';
- svgName.title = svg ? svg.name : '';
- svgPick.textContent = svg ? 'Replace…' : 'Choose…';
- for (const b of panel.querySelectorAll<HTMLElement>('.shapes button')) {
- const on = b.dataset.kind === settings.kind;
- b.classList.toggle('on', on);
- b.setAttribute('aria-checked', String(on));
- }
- for (const el of panel.querySelectorAll<HTMLElement>('.seg')) {
- const v = String(settings[el.dataset.opt as 'tool' | 'lock']);
- for (const b of el.querySelectorAll<HTMLElement>('button')) {
- b.classList.toggle('on', b.dataset.value === v);
- b.setAttribute('aria-checked', String(b.dataset.value === v));
- }
- }
- renderStatus();
- }
-
- function renderStatus(progress?: [number, number]) {
- stopBtn.hidden = !writer.busy;
- const name = SHAPES.find(s => s.id === settings.kind)!.label.toLowerCase();
- if (writer.busy) status.textContent = progress && progress[1] > 1 ? `Drawing… ${progress[0]} / ${progress[1]} strokes` : 'Drawing…';
- else if (drag) status.textContent = 'Let go to draw';
- else if (!active) status.textContent = '';
- else if (settings.kind === 'svg') status.textContent = svg ? `Drag on the paper to place ${svg.name}` : 'Choose an SVG file, or drop one on the paper';
- else status.textContent = `Drag on the paper to draw a ${name}`;
- }
-
- /** The drag end, constrained if the lock (or Shift) is on. */
- function endPoint(d: { a: Pt; b: Pt; shift: boolean }): Pt {
- const boxAspect = settings.kind === 'svg' && svg ? svg.aspect : 1;
- return settings.lock !== d.shift ? constrain(settings.kind, d.a, d.b, engine.aspect, boxAspect) : d.b;
- }
-
- /** Strokes for the ghost: the thinned copy for SVGs, the real thing otherwise. */
- function ghostStrokes(a: Pt, b: Pt, aspect: number) {
- if (settings.kind !== 'svg') return shapeStrokes(settings.kind, a, b, params(), aspect);
- return svg ? fitSvg(svg.ghost, (b[0] - a[0]) * aspect, b[1] - a[1], settings.rotation) : [];
- }
-
- function renderGhost() {
- if (!active || !drag || writer.busy) { ghost.hide(); return; }
- const a = engine.aspect;
- const [ax, ay] = drag.a;
- let d = '';
- for (const pl of ghostStrokes(drag.a, endPoint(drag), a)) {
- pl.forEach(([x, y], i) => {
- const [cx, cy] = engine.docToClient(ax + x / a, ay + y);
- d += `${i ? 'L' : 'M'}${cx.toFixed(1)} ${cy.toFixed(1)}`;
- });
- }
- ghost.set(d);
- }
-
- /* --------------------------------------------------------------- actions */
-
- function save() {
- try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
- }
-
- function set(p: Partial<ShapeSettings>) {
- settings = { ...settings, ...p };
- save();
- render();
- renderGhost();
- }
-
- function draw(d: { a: Pt; b: Pt; shift: boolean }) {
- const b = endPoint(d);
- const aspect = engine.aspect;
- const w = Math.abs(b[0] - d.a[0]) * aspect, h = Math.abs(b[1] - d.a[1]);
- const strokes = shapeStrokes(settings.kind, d.a, b, params(), aspect);
- if (!strokes.length) return;
- const ref = settings.kind === 'line' || settings.kind === 'arrow' ? Math.hypot(w, h) * 0.5 : Math.max(0.01, Math.min(w, h));
- writer.write(strokes, d.a, {
- tool: settings.tool, ref, speed: penSpeed(settings.speed),
- pressure: settings.pressure, taper: settings.taper, wobble: settings.wobble,
- }, {
- onProgress: (done, total) => renderStatus([done, total]),
- onDone: () => { renderStatus(); renderGhost(); },
- });
- renderStatus([0, strokes.length]);
- renderGhost();
- }
-
- async function loadSvg(file: File): Promise<boolean> {
- try {
- svg = await importSvg(file);
- } catch (e) {
- toast(e instanceof Error ? e.message : 'Could not read that SVG');
- return false;
- }
- set({ kind: 'svg' });
- return true;
- }
-
- function cancelDrag() {
- if (!drag) return false;
- try { canvas.releasePointerCapture(drag.id); } catch { /* already released */ }
- drag = null;
- renderGhost();
- renderStatus();
- return true;
- }
-
- /* ---------------------------------------------------------------- wiring */
-
- panel.addEventListener('input', e => {
- const s = e.target as HTMLInputElement;
- if (s.type === 'range' && s.dataset.opt) set({ [s.dataset.opt]: Number(s.value) } as Partial<ShapeSettings>);
- });
-
- panel.addEventListener('click', e => {
- const el = (e.target as Element).closest<HTMLElement>('[data-kind], .seg button, [data-action]');
- if (!el) return;
- if (el.dataset.kind) {
- const kind = el.dataset.kind as ShapeKind;
- set({ kind });
- if (kind === 'svg' && !svg) fileInput.click();
- } else if (el.dataset.value !== undefined) {
- const opt = el.parentElement!.dataset.opt!;
- set({ [opt]: opt === 'lock' ? el.dataset.value === 'true' : el.dataset.value } as Partial<ShapeSettings>);
- } else if (el.dataset.action === 'shape-stop') writer.cancel();
- else if (el.dataset.action === 'svg-pick') fileInput.click();
- });
-
- fileInput.addEventListener('change', () => {
- const f = fileInput.files?.[0];
- fileInput.value = '';
- if (f) void loadSvg(f);
- });
-
- canvas.addEventListener('pointerdown', e => {
- if (!active || drag) return;
- if (writer.busy) { toast('Still drawing… press Stop or Esc'); return; }
- try { canvas.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
- const a = engine.clientToDoc(e.clientX, e.clientY);
- drag = { id: e.pointerId, a, b: a, shift: e.shiftKey };
- renderStatus();
- });
- canvas.addEventListener('pointermove', e => {
- if (!active || !drag || e.pointerId !== drag.id) return;
- drag.b = engine.clientToDoc(e.clientX, e.clientY);
- drag.shift = e.shiftKey;
- renderGhost();
- });
- const up = (e: PointerEvent) => {
- if (!active || !drag || e.pointerId !== drag.id) return;
- const d = drag;
- d.b = engine.clientToDoc(e.clientX, e.clientY);
- d.shift = e.shiftKey;
- cancelDrag();
- if (e.type === 'pointercancel') return;
- const [x0, y0] = engine.docToClient(...d.a), [x1, y1] = engine.docToClient(...d.b);
- if (settings.kind === 'svg' && !svg) { fileInput.click(); return; }
- if (Math.hypot(x1 - x0, y1 - y0) < 6) { toast('Drag to size the shape'); return; }
- draw(d);
- };
- canvas.addEventListener('pointerup', up);
- canvas.addEventListener('pointercancel', up);
- window.addEventListener('resize', renderGhost);
-
- render();
-
- return {
- panel,
- get active() { return active; },
- activate() {
- active = true;
- panel.hidden = false;
- canvas.classList.add('placing');
- renderStatus();
- },
- deactivate() {
- active = false;
- cancelDrag();
- writer.cancel();
- panel.hidden = true;
- canvas.classList.remove('placing');
- ghost.hide();
- },
- stop() {
- if (cancelDrag()) return true;
- if (!writer.busy) return false;
- writer.cancel();
- return true;
- },
- loadSvg,
- };
-}
-
-function load(): Partial<ShapeSettings> {
- try {
- const raw = localStorage.getItem(KEY);
- if (!raw) return {};
- const v = JSON.parse(raw) as Partial<ShapeSettings>;
- return typeof v === 'object' && v ? v : {};
- } catch { return {}; }
-}
diff --git a/src/styles.css b/src/styles.css
index 47587f1..32adf0a 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -13,7 +13,7 @@
[hidden] { display: none !important; }
-html, body, #root { margin: 0; height: 100%; overflow: hidden; background: #dbd7cf; }
+html, body, #root, .app { margin: 0; height: 100%; overflow: hidden; background: #dbd7cf; }
body {
font: 12px/1.3 "Avenir Next", "Helvetica Neue", system-ui, sans-serif;
@@ -90,13 +90,13 @@ button { font: inherit; color: inherit; }
display: flex; flex-direction: column;
z-index: 6; /* above the text panel, which shares its spot */
}
-.library-head {
+.panel-head {
display: grid; grid-template-columns: 1fr auto; align-items: start; column-gap: 8px;
padding: 12px 10px 8px 14px; border-bottom: 1px solid var(--line);
}
-.library-head > span:first-child { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink); }
-.library-head .sub { grid-column: 1; font-size: 10px; color: var(--ink-faint); line-height: 1.4; margin-top: 3px; }
-.library-head .icon { grid-column: 2; grid-row: 1 / span 2; }
+.panel-head > span:first-child { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink); }
+.panel-head .sub { grid-column: 1; font-size: 10px; color: var(--ink-faint); line-height: 1.4; margin-top: 3px; }
+.panel-head .icon { grid-column: 2; grid-row: 1 / span 2; }
.panel button.icon { padding: 4px; border-radius: 8px; flex-direction: row; }
.brushes {
@@ -151,9 +151,7 @@ button { font: inherit; color: inherit; }
width: 268px; padding: 12px 14px 12px;
display: flex; flex-direction: column; gap: 10px;
}
-.pop-head { display: flex; flex-direction: column; gap: 3px; }
-.pop-head > span:first-child { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink); }
-.pop-head .sub { font-size: 10px; color: var(--ink-faint); line-height: 1.4; }
+.popover .panel-head { padding: 0; border-bottom: 0; }
.popover .import { align-self: flex-start; }
.popover .field { display: flex; flex-direction: column; gap: 5px; }
.popover .field > span { font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft); }
@@ -245,7 +243,7 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius
left: 10px; right: 10px; top: auto; transform: none; width: auto;
bottom: calc(150px + env(safe-area-inset-bottom)); max-height: 46vh;
}
- .library-head .sub, .library-foot .note { display: none; }
+ .panel-head .sub, .library-foot .note { display: none; }
.brush .stroke { width: 100%; height: 40px; }
.panel .import span { display: inline; }
.toast { top: calc(60px + env(safe-area-inset-top)); }
@@ -262,12 +260,12 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius
}
.ghost path { fill: none; stroke: rgba(42, 42, 51, 0.45); stroke-width: 1.2; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 3 3; }
-.text {
+.tool-panel {
left: calc(84px + env(safe-area-inset-left)); top: 50%; transform: translateY(-50%);
width: 316px; max-height: calc(100vh - 28px);
display: flex; flex-direction: column;
}
-.text-body { display: flex; flex-direction: column; gap: 10px; padding: 10px 12px 10px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; }
+.tool-body { display: flex; flex-direction: column; gap: 10px; padding: 10px 12px 10px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; }
.text-input {
width: 100%; font: 15px/1.3 "Avenir Next", "Helvetica Neue", system-ui, sans-serif; color: var(--ink);
padding: 8px 10px; border-radius: 10px; border: 1px solid var(--line);
@@ -285,7 +283,7 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius
.fontrow:hover { background: rgba(255, 255, 255, 0.7); }
.fontrow:focus-visible { outline: 2px solid rgba(42, 42, 51, 0.5); outline-offset: -2px; }
.fontrow.on { background: rgba(255, 255, 255, 0.85); border-color: rgba(42, 42, 51, 0.5); }
-.fontrow i { display: block; width: 260px; height: 32px; max-width: 100%; background-repeat: no-repeat; background-size: 260px auto; opacity: 0.85; }
+.fontrow i { background-image: var(--atlas); display: block; width: 260px; height: 32px; max-width: 100%; background-repeat: no-repeat; background-size: 260px auto; opacity: 0.85; }
.fontrow span { display: block; font-size: 12px; line-height: 32px; }
.shapes { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 2px; }
@@ -296,23 +294,23 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius
.panel .shapes button span { font-size: 8px; letter-spacing: 0.06em; white-space: nowrap; }
.panel .shapes button.on { color: var(--ink); background: rgba(255, 255, 255, 0.85); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }
-.text-rows { display: flex; flex-direction: column; gap: 7px; }
-.text-rows .slider { grid-template-columns: 58px 1fr; }
+.tool-rows { display: flex; flex-direction: column; gap: 7px; }
+.tool-rows .slider { grid-template-columns: 58px 1fr; }
.seg { display: flex; gap: 2px; padding: 2px; border-radius: 9px; background: rgba(42, 42, 51, 0.06); }
.panel .seg button { flex: 1; padding: 5px 4px; border-radius: 7px; font-size: 9px; letter-spacing: 0.12em; text-transform: uppercase; }
.panel .seg button.on { background: rgba(255, 255, 255, 0.85); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }
-.text-foot { display: flex; align-items: center; gap: 8px; min-height: 22px; font-size: 10px; color: var(--ink-soft); }
-.text-foot .status { flex: 1; }
+.tool-foot { display: flex; align-items: center; gap: 8px; min-height: 22px; font-size: 10px; color: var(--ink-soft); }
+.tool-foot .status { flex: 1; }
.panel .stop { flex-direction: row; gap: 5px; padding: 4px 8px; border: 1px solid var(--line); color: #a0281c; }
-.text-foot .credit { font-size: 10px; color: var(--ink-faint); text-decoration: none; white-space: nowrap; }
-.text-foot .credit:hover { color: var(--ink); }
+.tool-foot .credit { font-size: 10px; color: var(--ink-faint); text-decoration: none; white-space: nowrap; }
+.tool-foot .credit:hover { color: var(--ink); }
@media (max-width: 640px) {
- .text {
+ .tool-panel {
left: 10px; right: 10px; top: auto; transform: none; width: auto;
bottom: calc(150px + env(safe-area-inset-bottom)); max-height: 52vh;
}
.fontlist { max-height: 120px; }
- .text-foot .credit { display: none; }
+ .tool-foot .credit { display: none; }
}
diff --git a/src/text/TextPanel.tsx b/src/text/TextPanel.tsx
new file mode 100644
index 0000000..95ea8e5
--- /dev/null
+++ b/src/text/TextPanel.tsx
@@ -0,0 +1,71 @@
+import { useEffect, useRef } from 'preact/hooks';
+import { useApp } from '../app/context';
+import type { Tool } from '../engine/Engine';
+import { Seg } from '../ui/Seg';
+import { Row, SliderRows, type SliderSpec } from '../ui/Slider';
+import { ToolPanel } from '../ui/ToolPanel';
+import { ATLAS, FONTS, fontGroups, fontLabel } from './fonts';
+import type { Align } from './layout';
+import type { TextSettings, TextStore } from './TextStore';
+
+const SLIDERS: SliderSpec<TextSettings>[] = [
+ { key: 'size', label: 'Size', hint: 'Letter height' },
+ { key: 'speed', label: 'Speed', hint: 'How fast the brush travels' },
+ { key: 'pressure', label: 'Pressure', min: 0.05, hint: 'How hard the brush presses' },
+ { key: 'taper', label: 'Taper', hint: 'Lighter touch at the ends of each stroke' },
+ { key: 'spacing', label: 'Spacing', min: -0.1, max: 0.4, hint: 'Extra space between letters' },
+ { key: 'wobble', label: 'Wobble', hint: 'Hand tremor' },
+];
+
+const TOOLS: { id: Tool; label: string }[] = [{ id: 'brush', label: 'Brush' }, { id: 'pen', label: 'Pen' }, { id: 'water', label: 'Water' }];
+const ALIGNS: { id: Align; label: string }[] = [{ id: 'left', label: 'Left' }, { id: 'center', label: 'Centre' }, { id: 'right', label: 'Right' }];
+const GROUPS = fontGroups();
+
+export function TextPanel({ tool }: { tool: TextStore }) {
+ const app = useApp();
+ const s = tool.settings.value;
+ const open = tool.active.value;
+ const input = useRef<HTMLInputElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+
+ // focus the field when the tool asks (opened with nothing to write, or tapped with no text)
+ const focusRequest = tool.focusRequest.value;
+ useEffect(() => { if (focusRequest) input.current?.focus(); }, [focusRequest]);
+ // keep the chosen font in view
+ useEffect(() => {
+ if (open) list.current?.querySelector('.fontrow.on')?.scrollIntoView({ block: open ? 'center' : 'nearest' });
+ }, [open, s.font]);
+
+ const stopKeys = (e: KeyboardEvent) => { if (e.key === 'Enter') input.current?.blur(); e.stopPropagation(); };
+
+ return (
+ <ToolPanel title="Text" open={open} status={tool.status.value} busy={tool.writing.value}
+ sub="Tap the paper to write there. Each letter is drawn stroke by stroke with the current brush and pigment."
+ onStop={() => tool.stop()} onClose={() => app.setTool('brush')}
+ foot={<a class="credit" target="_blank" rel="noopener" href={FONTS[s.font].source} title="Font source">{fontLabel(s.font)} ↗</a>}>
+ <input ref={input} class="text-input" type="text" placeholder="Write something…" maxLength={160} spellcheck={false}
+ autocomplete="off" aria-label="Text to write" value={s.text}
+ onInput={e => tool.set({ text: (e.currentTarget as HTMLInputElement).value })} onKeyDown={stopKeys} />
+ <div ref={list} class="fontlist" role="listbox" aria-label="Font" style={{ '--atlas': `url("${ATLAS.url}")` }}>
+ {GROUPS.map(g => <>
+ <div class="fontgroup">{g.label}</div>
+ {g.keys.map(k => {
+ const row = ATLAS.row(k), on = k === s.font;
+ return (
+ <div key={k} class={`fontrow${on ? ' on' : ''}`} role="option" aria-selected={on} tabIndex={0} title={fontLabel(k)}
+ onClick={() => tool.set({ font: k })}
+ onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); tool.set({ font: k }); } }}>
+ {row >= 0 ? <i style={{ backgroundPosition: `0 ${-row * ATLAS.rowHeight}px` }} /> : <span>{fontLabel(k)}</span>}
+ </div>
+ );
+ })}
+ </>)}
+ </div>
+ <div class="tool-rows">
+ <Row label="Draw with"><Seg options={TOOLS} value={s.tool} onChange={t => tool.set({ tool: t })} /></Row>
+ <Row label="Anchor"><Seg options={ALIGNS} value={s.align} onChange={align => tool.set({ align })} /></Row>
+ <SliderRows spec={SLIDERS} settings={s} onChange={p => tool.set(p)} />
+ </div>
+ </ToolPanel>
+ );
+}
diff --git a/src/text/TextStore.ts b/src/text/TextStore.ts
new file mode 100644
index 0000000..87a3db8
--- /dev/null
+++ b/src/text/TextStore.ts
@@ -0,0 +1,148 @@
+import { computed, effect, signal, type ReadonlySignal } from '@preact/signals';
+import type { Tool, WatercolorEngine } from '../engine/Engine';
+import type { PanelTool, PaperGesture } from '../app/tools';
+import { persisted } from '../app/persisted';
+import { resizeTick } from '../app/resize';
+import { showToast } from '../app/toast';
+import { hideGhost, setGhost } from '../draw/ghost';
+import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
+import { DEFAULT_FONT, FONTS, fontUrl } from './fonts';
+import { loadFont, type Font } from './fontLoader';
+import { layoutText, type Align, type TextLayout } from './layout';
+
+// The Text tool: compose one line of text in a single-stroke font, see a ghost of it
+// under the pointer, and on tap the StrokeWriter draws it on the paper, slowly, with
+// the current brush and pigment.
+
+export interface TextSettings {
+ text: string;
+ font: string;
+ tool: Tool;
+ align: Align;
+ size: number; // 0..1 slider
+ speed: number; // 0..1 slider
+ pressure: number; // 0.05..1
+ taper: number; // 0..1
+ spacing: number; // em, -0.1..0.4
+ wobble: number; // 0..1
+}
+
+const KEY = 'watercolor.text';
+const DEFAULTS: TextSettings = {
+ text: 'hello', font: DEFAULT_FONT, tool: 'brush', align: 'left',
+ size: 0.4, speed: 0.5, pressure: 0.6, taper: 0.5, spacing: 0, wobble: 0.2,
+};
+
+/** Em height in document heights. */
+export const emSize = (v: number) => 0.03 * Math.pow(12, v);
+
+export class TextStore implements PanelTool {
+ readonly id = 'text';
+ readonly settings = persisted<TextSettings>(KEY, DEFAULTS, s => (FONTS[s.font] ? s : { ...s, font: DEFAULT_FONT }));
+ readonly active = signal(false);
+ readonly font = signal<Font | null>(null);
+ readonly layout = signal<TextLayout | null>(null);
+ readonly writing = signal(false);
+ readonly progress = signal<[number, number] | null>(null);
+ /** Bumped when the panel should focus the text field. */
+ readonly focusRequest = signal(0);
+ readonly busy: ReadonlySignal<boolean> = this.writing;
+ readonly status = computed(() => {
+ if (this.writing.value) { const p = this.progress.value; return p ? `Writing… ${p[0]} / ${p[1]} strokes` : 'Writing…'; }
+ if (!this.font.value) return 'Loading font…';
+ if (!this.settings.value.text.trim()) return 'Type something to write';
+ if (!this.layout.value?.strokes.length) return 'This font has none of those characters';
+ return this.active.value ? 'Tap the paper to write' : '';
+ });
+
+ private hover = signal<[number, number] | null>(null); // document uv under the pointer
+ private writer: StrokeWriter;
+ private fontGen = 0;
+
+ constructor(private engine: WatercolorEngine) {
+ this.writer = new StrokeWriter(engine);
+ const fontKey = computed(() => this.settings.value.font);
+ effect(() => this.useFont(fontKey.value));
+ effect(() => {
+ const { text, spacing, align } = this.settings.value;
+ const f = this.font.value;
+ this.layout.value = f ? layoutText(text, f, spacing, align) : null;
+ });
+ effect(() => this.renderGhost());
+ }
+
+ set(p: Partial<TextSettings>) { this.settings.value = { ...this.settings.value, ...p }; }
+
+ private useFont(key: string) {
+ const gen = ++this.fontGen;
+ this.font.value = null;
+ loadFont(key, fontUrl(key)).then(f => { if (gen === this.fontGen) this.font.value = f; })
+ .catch(e => { if (gen === this.fontGen) showToast(e instanceof Error ? e.message : 'Could not load that font'); });
+ }
+
+ /** Client-space path of the ghost at the hovered anchor. */
+ private renderGhost() {
+ resizeTick.value; // re-run after a resize
+ const layout = this.layout.value, hover = this.hover.value;
+ if (!this.active.value || !layout || !hover || this.writing.value) { hideGhost(); return; }
+ const em = emSize(this.settings.value.size), a = this.engine.aspect;
+ const [ax, ay] = hover;
+ let d = '';
+ for (const pl of layout.strokes) {
+ pl.forEach(([x, y], i) => {
+ const [cx, cy] = this.engine.docToClient(ax + (x * em) / a, ay - y * em);
+ d += `${i ? 'L' : 'M'}${cx.toFixed(1)} ${cy.toFixed(1)}`;
+ });
+ }
+ // baseline tick at the anchor
+ const [bx, by] = this.engine.docToClient(ax, ay);
+ d += `M${(bx - 6).toFixed(1)} ${by.toFixed(1)}h12M${bx.toFixed(1)} ${(by - 6).toFixed(1)}v12`;
+ setGhost(d);
+ }
+
+ private writeAt(anchor: [number, number]) {
+ const layout = this.layout.value;
+ if (!layout?.strokes.length || this.writing.value) return;
+ const s = this.settings.value;
+ const em = emSize(s.size);
+ // em units (y down) -> document heights relative to the anchor (y up)
+ const strokes = layout.strokes.map(pl => pl.map(([x, y]) => [x * em, -y * em] as [number, number]));
+ this.writing.value = true;
+ this.progress.value = [0, strokes.length];
+ this.writer.write(strokes, anchor, {
+ tool: s.tool, ref: em, speed: penSpeed(s.speed), pressure: s.pressure, taper: s.taper, wobble: s.wobble,
+ }, {
+ onProgress: (done, total) => { this.progress.value = [done, total]; },
+ onDone: () => { this.writing.value = false; this.progress.value = null; },
+ });
+ }
+
+ readonly gesture: PaperGesture = {
+ move: (_e, uv) => { this.hover.value = uv; },
+ leave: () => { this.hover.value = null; },
+ down: (_e, uv) => {
+ if (this.writing.value) { showToast('Still writing… press Stop or Esc'); return; }
+ if (!this.font.value) { showToast('Loading font…'); return; }
+ if (!this.layout.value?.strokes.length) { this.focusRequest.value++; showToast('Type something first'); return; }
+ this.hover.value = uv;
+ this.writeAt(uv);
+ },
+ };
+
+ activate() {
+ this.active.value = true;
+ if (!this.settings.value.text.trim()) this.focusRequest.value++;
+ }
+
+ deactivate() {
+ this.active.value = false;
+ this.writer.cancel();
+ this.hover.value = null;
+ }
+
+ stop() {
+ if (!this.writing.value) return false;
+ this.writer.cancel();
+ return true;
+ }
+}
diff --git a/src/text/textTool.ts b/src/text/textTool.ts
deleted file mode 100644
index 2cc3842..0000000
--- a/src/text/textTool.ts
+++ /dev/null
@@ -1,301 +0,0 @@
-import type { Tool, WatercolorEngine } from '../engine/Engine';
-import { icon } from '../ui/icons';
-import { ATLAS, DEFAULT_FONT, FONTS, fontGroups, fontLabel, fontUrl } from './fonts';
-import { loadFont, type Font } from './fontLoader';
-import { layoutText, type Align, type TextLayout } from './layout';
-import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
-import { createGhost } from '../draw/ghost';
-
-// The Text tool: a panel to compose one line of text in a single-stroke font,
-// a ghost of it under the pointer, and on tap the TextWriter draws it on the
-// paper, slowly, with the current brush and pigment.
-
-export interface TextSettings {
- text: string;
- font: string;
- tool: Tool;
- align: Align;
- size: number; // 0..1 slider
- speed: number; // 0..1 slider
- pressure: number; // 0.05..1
- taper: number; // 0..1
- spacing: number; // em, -0.1..0.4
- wobble: number; // 0..1
-}
-
-const KEY = 'watercolor.text';
-const DEFAULTS: TextSettings = {
- text: 'hello', font: DEFAULT_FONT, tool: 'brush', align: 'left',
- size: 0.4, speed: 0.5, pressure: 0.6, taper: 0.5, spacing: 0, wobble: 0.2,
-};
-
-const SLIDERS: { key: keyof TextSettings; label: string; min: number; max: number; hint: string }[] = [
- { key: 'size', label: 'Size', min: 0, max: 1, hint: 'Letter height' },
- { key: 'speed', label: 'Speed', min: 0, max: 1, hint: 'How fast the brush travels' },
- { key: 'pressure', label: 'Pressure', min: 0.05, max: 1, hint: 'How hard the brush presses' },
- { key: 'taper', label: 'Taper', min: 0, max: 1, hint: 'Lighter touch at the ends of each stroke' },
- { key: 'spacing', label: 'Spacing', min: -0.1, max: 0.4, hint: 'Extra space between letters' },
- { key: 'wobble', label: 'Wobble', min: 0, max: 1, hint: 'Hand tremor' },
-];
-
-const TOOLS: { id: Tool; label: string }[] = [{ id: 'brush', label: 'Brush' }, { id: 'pen', label: 'Pen' }, { id: 'water', label: 'Water' }];
-const ALIGNS: { id: Align; label: string }[] = [{ id: 'left', label: 'Left' }, { id: 'center', label: 'Centre' }, { id: 'right', label: 'Right' }];
-
-/** Em height in document heights. */
-export const emSize = (v: number) => 0.03 * Math.pow(12, v);
-
-const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
-
-export interface TextToolHandle {
- panel: HTMLElement;
- activate(): void;
- deactivate(): void;
- /** Stop writing, if writing. Returns whether anything was stopped. */
- stop(): boolean;
- readonly writing: boolean;
- readonly active: boolean;
-}
-
-export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canvas: HTMLCanvasElement, toast: (s: string) => void): TextToolHandle {
- let settings: TextSettings = { ...DEFAULTS, ...load() };
- if (!FONTS[settings.font]) settings.font = DEFAULT_FONT;
- let font: Font | null = null;
- let layout: TextLayout | null = null;
- let active = false;
- let hover: [number, number] | null = null; // document uv under the pointer
- const writer = new StrokeWriter(engine);
-
- /* ---------------------------------------------------------------- markup */
-
- const panel = document.createElement('div');
- panel.className = 'panel text';
- panel.hidden = true;
- panel.setAttribute('role', 'dialog');
- panel.setAttribute('aria-label', 'Text');
- const seg = (name: string, items: { id: string; label: string }[]) =>
- `<div class="seg" data-opt="${name}" role="radiogroup">${items.map(i => `<button role="radio" data-value="${i.id}">${i.label}</button>`).join('')}</div>`;
- panel.innerHTML = `
- <div class="library-head">
- <span>Text</span>
- <span class="sub">Tap the paper to write there. Each letter is drawn stroke by stroke with the current brush and pigment.</span>
- <button class="icon" data-action="text-close" title="Close">${icon('close', 16)}</button>
- </div>
- <div class="text-body">
- <input class="text-input" type="text" placeholder="Write something…" maxlength="160" spellcheck="false" autocomplete="off" aria-label="Text to write">
- <div class="fontlist" role="listbox" aria-label="Font">
- ${fontGroups().map(g => `<div class="fontgroup">${esc(g.label)}</div>${g.keys.map(k => {
- const row = ATLAS.row(k);
- return `<div class="fontrow" role="option" data-font="${esc(k)}" title="${esc(fontLabel(k))}" tabindex="0" aria-selected="false">${
- row >= 0 ? `<i style="background-position:0 ${-row * ATLAS.rowHeight}px"></i>` : `<span>${esc(fontLabel(k))}</span>`}</div>`;
- }).join('')}`).join('')}
- </div>
- <div class="text-rows">
- <label class="slider"><span>Draw with</span>${seg('tool', TOOLS)}</label>
- <label class="slider"><span>Anchor</span>${seg('align', ALIGNS)}</label>
- ${SLIDERS.map(s => `<label class="slider" title="${s.hint}"><span>${s.label}</span><input type="range" min="${s.min}" max="${s.max}" step="0.01" data-opt="${s.key}"></label>`).join('')}
- </div>
- <div class="text-foot">
- <span class="status"></span>
- <button class="stop" data-action="text-stop" hidden>${icon('close', 14)}<span>Stop</span></button>
- <a class="credit" target="_blank" rel="noopener"></a>
- </div>
- </div>`;
- root.appendChild(panel);
-
- const ghost = createGhost(root); // the text under the pointer
-
- const input = panel.querySelector<HTMLInputElement>('.text-input')!;
- const fontList = panel.querySelector<HTMLElement>('.fontlist')!;
- const status = panel.querySelector<HTMLElement>('.status')!;
- const stopBtn = panel.querySelector<HTMLButtonElement>('.stop')!;
- const credit = panel.querySelector<HTMLAnchorElement>('.credit')!;
- const sliders = [...panel.querySelectorAll<HTMLInputElement>('input[type="range"][data-opt]')];
- const style = document.createElement('style');
- style.textContent = `.fontrow i { background-image: url("${ATLAS.url}"); }`;
- document.head.appendChild(style);
-
- /* ------------------------------------------------------------- rendering */
-
- function render() {
- input.value = settings.text;
- for (const s of sliders) s.value = String(settings[s.dataset.opt as keyof TextSettings]);
- for (const el of panel.querySelectorAll<HTMLElement>('.seg')) {
- const v = settings[el.dataset.opt as 'tool' | 'align'];
- for (const b of el.querySelectorAll<HTMLElement>('button')) {
- b.classList.toggle('on', b.dataset.value === v);
- b.setAttribute('aria-checked', String(b.dataset.value === v));
- }
- }
- for (const el of fontList.querySelectorAll<HTMLElement>('.fontrow')) {
- const on = el.dataset.font === settings.font;
- el.classList.toggle('on', on);
- el.setAttribute('aria-selected', String(on));
- }
- credit.textContent = `${fontLabel(settings.font)} ↗`;
- credit.href = FONTS[settings.font].source;
- credit.title = 'Font source';
- renderStatus();
- }
-
- function renderStatus(progress?: [number, number]) {
- stopBtn.hidden = !writer.busy;
- if (writer.busy) status.textContent = progress ? `Writing… ${progress[0]} / ${progress[1]} strokes` : 'Writing…';
- else if (!font) status.textContent = 'Loading font…';
- else if (!settings.text.trim()) status.textContent = 'Type something to write';
- else if (!layout?.strokes.length) status.textContent = 'This font has none of those characters';
- else status.textContent = active ? 'Tap the paper to write' : '';
- }
-
- /** Client-space path of the ghost at the hovered anchor. */
- function renderGhost() {
- if (!active || !layout || !hover || writer.busy) { ghost.hide(); return; }
- const em = emSize(settings.size), a = engine.aspect;
- const [ax, ay] = hover;
- let d = '';
- for (const pl of layout.strokes) {
- pl.forEach(([x, y], i) => {
- const [cx, cy] = engine.docToClient(ax + (x * em) / a, ay - y * em);
- d += `${i ? 'L' : 'M'}${cx.toFixed(1)} ${cy.toFixed(1)}`;
- });
- }
- // baseline tick at the anchor
- const [bx, by] = engine.docToClient(ax, ay);
- d += `M${(bx - 6).toFixed(1)} ${by.toFixed(1)}h12M${bx.toFixed(1)} ${(by - 6).toFixed(1)}v12`;
- ghost.set(d);
- }
-
- /* --------------------------------------------------------------- actions */
-
- function save() {
- try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
- }
-
- function relayout() {
- layout = font ? layoutText(settings.text, font, settings.spacing, settings.align) : null;
- renderStatus();
- renderGhost();
- }
-
- let fontGen = 0;
- function useFont(key: string) {
- const gen = ++fontGen;
- font = null;
- relayout();
- loadFont(key, fontUrl(key)).then(f => {
- if (gen !== fontGen) return;
- font = f;
- relayout();
- }).catch(e => {
- if (gen !== fontGen) return;
- toast(e instanceof Error ? e.message : 'Could not load that font');
- });
- }
-
- function set(p: Partial<TextSettings>) {
- const fontChanged = p.font !== undefined && p.font !== settings.font;
- settings = { ...settings, ...p };
- save();
- render();
- if (fontChanged) {
- useFont(settings.font);
- fontList.querySelector<HTMLElement>('.fontrow.on')?.scrollIntoView({ block: 'nearest' });
- } else relayout();
- }
-
- function writeAt(anchor: [number, number]) {
- if (!layout?.strokes.length || writer.busy) return;
- const em = emSize(settings.size);
- const opts = {
- tool: settings.tool, ref: em, speed: penSpeed(settings.speed),
- pressure: settings.pressure, taper: settings.taper, wobble: settings.wobble,
- };
- // em units (y down) -> document heights relative to the anchor (y up)
- const strokes = layout.strokes.map(pl => pl.map(([x, y]) => [x * em, -y * em] as [number, number]));
- writer.write(strokes, anchor, opts, {
- onProgress: (done, total) => renderStatus([done, total]),
- onDone: () => { renderStatus(); renderGhost(); },
- });
- renderStatus([0, layout.strokes.length]);
- renderGhost();
- }
-
- /* ---------------------------------------------------------------- wiring */
-
- input.addEventListener('input', () => set({ text: input.value }));
- input.addEventListener('keydown', e => { if (e.key === 'Enter') input.blur(); e.stopPropagation(); });
-
- panel.addEventListener('input', e => {
- const s = e.target as HTMLInputElement;
- if (s.type === 'range' && s.dataset.opt) set({ [s.dataset.opt]: Number(s.value) } as Partial<TextSettings>);
- });
-
- panel.addEventListener('click', e => {
- const el = (e.target as Element).closest<HTMLElement>('[data-font], .seg button, [data-action]');
- if (!el) return;
- if (el.dataset.font) set({ font: el.dataset.font });
- else if (el.dataset.value) set({ [el.parentElement!.dataset.opt!]: el.dataset.value } as Partial<TextSettings>);
- else if (el.dataset.action === 'text-stop') writer.cancel();
- });
-
- fontList.addEventListener('keydown', e => {
- if (e.key !== 'Enter' && e.key !== ' ') return;
- const el = (e.target as Element).closest<HTMLElement>('[data-font]');
- if (el?.dataset.font) { e.preventDefault(); set({ font: el.dataset.font }); }
- });
-
- // the ghost follows the pointer over the paper and goes when it moves onto a panel
- root.addEventListener('pointermove', e => {
- if (!active) return;
- hover = e.target === canvas ? engine.clientToDoc(e.clientX, e.clientY) : null;
- renderGhost();
- });
- canvas.addEventListener('pointerleave', () => { hover = null; renderGhost(); });
- canvas.addEventListener('pointerdown', e => {
- if (!active) return;
- if (writer.busy) { toast('Still writing… press Stop or Esc'); return; }
- if (!font) { toast('Loading font…'); return; }
- if (!layout?.strokes.length) { input.focus(); toast('Type something first'); return; }
- hover = engine.clientToDoc(e.clientX, e.clientY);
- writeAt(hover);
- });
- window.addEventListener('resize', renderGhost);
-
- render();
- useFont(settings.font);
-
- return {
- panel,
- get writing() { return writer.busy; },
- get active() { return active; },
- activate() {
- active = true;
- panel.hidden = false;
- canvas.classList.add('placing');
- renderStatus();
- fontList.querySelector<HTMLElement>('.fontrow.on')?.scrollIntoView({ block: 'center' });
- if (!settings.text.trim()) input.focus();
- },
- deactivate() {
- active = false;
- writer.cancel();
- panel.hidden = true;
- canvas.classList.remove('placing');
- hover = null;
- renderGhost();
- },
- stop() {
- if (!writer.busy) return false;
- writer.cancel();
- return true;
- },
- };
-}
-
-function load(): Partial<TextSettings> {
- try {
- const raw = localStorage.getItem(KEY);
- if (!raw) return {};
- const v = JSON.parse(raw) as Partial<TextSettings>;
- return typeof v === 'object' && v ? v : {};
- } catch { return {}; }
-}
diff --git a/src/ui/icons.ts b/src/ui/Icon.tsx
similarity index 77%
rename from src/ui/icons.ts
rename to src/ui/Icon.tsx
index 5c6f4b7..d9ae267 100644
--- a/src/ui/icons.ts
+++ b/src/ui/Icon.tsx
@@ -19,8 +19,12 @@ const PATHS: Record<string, string> = {
chevron: 'M9 6l6 6-6 6',
};
-/** Inline SVG markup for a 20px stroke icon. */
-export function icon(name: string, size = 20): string {
- return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.5"
- stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${PATHS[name]}"/></svg>`;
+/** A stroke icon from the table above, or any 24×24 path via `d`. */
+export function Icon({ name, d, size = 20 }: { name?: string; d?: string; size?: number }) {
+ return (
+ <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" stroke-width="1.5"
+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d={d ?? PATHS[name!]} />
+ </svg>
+ );
}
diff --git a/src/ui/Panel.tsx b/src/ui/Panel.tsx
new file mode 100644
index 0000000..24059b0
--- /dev/null
+++ b/src/ui/Panel.tsx
@@ -0,0 +1,21 @@
+import type { AriaRole, ComponentChildren } from "preact";
+import { Icon } from './Icon';
+
+/** A floating glass panel. `open` false renders it with the `hidden` attribute (so it keeps its state). */
+export function Panel({ class: cls, open = true, role, label, children, ...rest }: {
+ class: string; open?: boolean; role?: AriaRole; label?: string; children: ComponentChildren;
+ style?: string | Record<string, string | number>; onClick?: (e: MouseEvent) => void;
+}) {
+ return <div class={`panel ${cls}`} hidden={!open} role={role} aria-label={label} {...rest}>{children}</div>;
+}
+
+/** Title, optional one-line explanation and an optional close button. */
+export function PanelHead({ title, sub, onClose }: { title: string; sub?: string; onClose?: () => void }) {
+ return (
+ <div class="panel-head">
+ <span>{title}</span>
+ {sub && <span class="sub">{sub}</span>}
+ {onClose && <button class="icon" title="Close" onClick={onClose}><Icon name="close" size={16} /></button>}
+ </div>
+ );
+}
diff --git a/src/ui/Seg.tsx b/src/ui/Seg.tsx
new file mode 100644
index 0000000..06147f9
--- /dev/null
+++ b/src/ui/Seg.tsx
@@ -0,0 +1,17 @@
+/** A segmented radio group: one button per option, the chosen one marked `on`. */
+export function Seg<V extends string | boolean | number>({ options, value, onChange, title, label }: {
+ options: { id: V; label: string; title?: string; disabled?: boolean }[];
+ value: V;
+ onChange(v: V): void;
+ title?: string;
+ label?: string;
+}) {
+ return (
+ <div class="seg" role="radiogroup" title={title} aria-label={label}>
+ {options.map(o => (
+ <button key={String(o.id)} role="radio" class={o.id === value ? 'on' : ''} aria-checked={o.id === value}
+ title={o.title} disabled={o.disabled} onClick={() => onChange(o.id)}>{o.label}</button>
+ ))}
+ </div>
+ );
+}
diff --git a/src/ui/Slider.tsx b/src/ui/Slider.tsx
new file mode 100644
index 0000000..6fa9b41
--- /dev/null
+++ b/src/ui/Slider.tsx
@@ -0,0 +1,42 @@
+import type { ComponentChildren } from 'preact';
+
+/** A labelled row: caption on the left, a control on the right. */
+export function Row({ label, title, children, hidden }: { label: string; title?: string; children: ComponentChildren; hidden?: boolean }) {
+ return <label class="slider" title={title} hidden={hidden}><span>{label}</span>{children}</label>;
+}
+
+export function Slider({ label, value, min = 0, max = 1, step = 0.01, title, disabled, hidden, onInput }: {
+ label: string; value: number; min?: number; max?: number; step?: number; title?: string; disabled?: boolean; hidden?: boolean;
+ onInput(v: number): void;
+}) {
+ return (
+ <Row label={label} title={title} hidden={hidden}>
+ <input type="range" min={min} max={max} step={step} value={value} disabled={disabled}
+ onInput={e => onInput(Number((e.currentTarget as HTMLInputElement).value))} />
+ </Row>
+ );
+}
+
+/** Declarative description of one numeric setting. */
+export interface SliderSpec<S> {
+ key: keyof S & string;
+ label: string;
+ min?: number;
+ max?: number;
+ step?: number;
+ hint?: string;
+ /** Hide the slider for some settings (e.g. star-only controls). */
+ show?(settings: S): boolean;
+}
+
+/** One <Slider/> per spec, bound to the matching numeric field of `settings`. */
+export function SliderRows<S extends object>({ spec, settings, onChange }: {
+ spec: SliderSpec<S>[]; settings: S; onChange(patch: Partial<S>): void;
+}) {
+ return <>{spec.map(s => (
+ <Slider key={s.key} label={s.label} min={s.min} max={s.max} step={s.step} title={s.hint}
+ hidden={s.show ? !s.show(settings) : false}
+ value={settings[s.key] as unknown as number}
+ onInput={v => onChange({ [s.key]: v } as unknown as Partial<S>)} />
+ ))}</>;
+}
diff --git a/src/ui/ToolPanel.tsx b/src/ui/ToolPanel.tsx
new file mode 100644
index 0000000..16f3e03
--- /dev/null
+++ b/src/ui/ToolPanel.tsx
@@ -0,0 +1,26 @@
+import type { ComponentChildren } from 'preact';
+import { Icon } from './Icon';
+import { Panel, PanelHead } from './Panel';
+
+/**
+ * The layout shared by the text, shape and fill tools: a head, a scrolling body of
+ * controls, and a foot with a status line and a Stop button while the tool is busy.
+ */
+export function ToolPanel({ title, sub, open, status, busy, onStop, onClose, class: cls = '', children, foot }: {
+ title: string; sub: string; open: boolean; status: string; busy: boolean;
+ onStop(): void; onClose(): void; class?: string; children: ComponentChildren; foot?: ComponentChildren;
+}) {
+ return (
+ <Panel class={`tool-panel ${cls}`} open={open} role="dialog" label={title}>
+ <PanelHead title={title} sub={sub} onClose={onClose} />
+ <div class="tool-body">
+ {children}
+ <div class="tool-foot">
+ <span class="status">{status}</span>
+ {busy && <button class="stop" onClick={onStop}><Icon name="close" size={14} /><span>Stop</span></button>}
+ {foot}
+ </div>
+ </div>
+ </Panel>
+ );
+}
diff --git a/tsconfig.json b/tsconfig.json
index 75947b0..c33d359 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -4,6 +4,8 @@
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "jsxImportSource": "preact",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
diff --git a/vite.config.ts b/vite.config.ts
index b257bfe..b1a76de 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,7 +1,10 @@
+import preact from '@preact/preset-vite';
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
+ // Preact JSX plus Prefresh, so component edits hot-swap without reloading the page (and losing the painting)
+ plugins: [preact()],
server: { host: true },
// the HEIC decoder (~3 MB) is its own chunk, only fetched when an iPhone photo needs it
build: { chunkSizeWarningLimit: 3500 },