@capyclaw/offline-ddr0 0.0.0-stage → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +441 -2
- package/client/client.js +603 -0
- package/cordis.patch.yml +13 -0
- package/docs/STORAGE-MIGRATION.md +136 -0
- package/lib/atomic.mjs +40 -0
- package/lib/http-cache.mjs +42 -0
- package/lib/inbox.mjs +64 -0
- package/lib/media.mjs +242 -0
- package/lib/migrate-json.mjs +101 -0
- package/lib/mirror-index.mjs +105 -0
- package/lib/mirror.mjs +123 -0
- package/lib/proxy.mjs +188 -0
- package/lib/remote.mjs +158 -0
- package/lib/render.mjs +93 -0
- package/lib/repository.mjs +71 -0
- package/lib/store.mjs +610 -0
- package/lib/surface.mjs +74 -0
- package/lib/sync-ui.mjs +108 -0
- package/lib/sync.mjs +433 -0
- package/lib/wire.mjs +211 -0
- package/lib/workstore-repository.mjs +316 -0
- package/lib/workstore.mjs +348 -0
- package/mirror/files/00001.html +2045 -0
- package/mirror/files/00002.json +1 -0
- package/mirror/files/00003.json +1 -0
- package/mirror/files/00004.json +1 -0
- package/mirror/files/00005.json +1 -0
- package/mirror/files/00006.json +1 -0
- package/mirror/files/00007.json +1 -0
- package/mirror/files/00008.json +1 -0
- package/mirror/files/00009.json +1 -0
- package/mirror/files/00010.json +1 -0
- package/mirror/files/00011.json +1 -0
- package/mirror/files/00012.json +1 -0
- package/mirror/files/00013.json +1 -0
- package/mirror/files/00014.json +1 -0
- package/mirror/files/00015.json +1 -0
- package/mirror/files/00016.json +1 -0
- package/mirror/files/00017.json +1 -0
- package/mirror/files/00018.json +1 -0
- package/mirror/files/00019.json +1 -0
- package/mirror/files/00020.json +1 -0
- package/mirror/files/00021.json +1 -0
- package/mirror/files/00022.json +1 -0
- package/mirror/files/00023.js +205 -0
- package/mirror/files/00024.json +1 -0
- package/mirror/files/00025.json +1 -0
- package/mirror/files/00026.json +1 -0
- package/mirror/files/00027.js +51 -0
- package/mirror/files/00028.json +1 -0
- package/mirror/files/00029.json +1 -0
- package/mirror/files/00030.json +1 -0
- package/mirror/files/00031.json +1 -0
- package/mirror/files/00032.json +1 -0
- package/mirror/files/00033.json +1 -0
- package/mirror/files/00034.json +1 -0
- package/mirror/files/00035.json +1 -0
- package/mirror/files/00036.json +1 -0
- package/mirror/files/00037.json +1 -0
- package/mirror/files/00038.json +1 -0
- package/mirror/files/00039.json +1 -0
- package/mirror/files/00040.js +2311 -0
- package/mirror/files/00041.json +1 -0
- package/mirror/files/00042.json +1 -0
- package/mirror/files/00043.json +1 -0
- package/mirror/files/00044.json +1 -0
- package/mirror/files/00045.js +575 -0
- package/mirror/files/00046.json +1 -0
- package/mirror/files/00047.js +575 -0
- package/mirror/files/00048.js +575 -0
- package/mirror/files/00049.json +1 -0
- package/mirror/files/00050.json +1 -0
- package/mirror/files/00051.json +1 -0
- package/mirror/files/00052.json +1 -0
- package/mirror/files/00053.js +575 -0
- package/mirror/files/00054.json +1 -0
- package/mirror/files/00055.json +1 -0
- package/mirror/files/00056.js +575 -0
- package/mirror/files/00057.json +1 -0
- package/mirror/files/00058.json +1 -0
- package/mirror/files/00059.js +360 -0
- package/mirror/files/00060.json +1 -0
- package/mirror/files/00061.json +1 -0
- package/mirror/files/00062.json +1 -0
- package/mirror/files/00063.json +1 -0
- package/mirror/files/00064.json +1 -0
- package/mirror/files/00065.js +144 -0
- package/mirror/files/00066.js +7 -0
- package/mirror/files/00067.json +1 -0
- package/mirror/files/00068.json +1 -0
- package/mirror/files/00069.json +1 -0
- package/mirror/files/00070.json +1 -0
- package/mirror/files/00071.json +1 -0
- package/mirror/files/00072.json +1 -0
- package/mirror/files/00073.js +1 -0
- package/mirror/files/00074.json +1 -0
- package/mirror/files/00075.json +1 -0
- package/mirror/files/00076.json +1 -0
- package/mirror/files/00077.js +45 -0
- package/mirror/files/00078.js +1348 -0
- package/mirror/files/00079.json +1 -0
- package/mirror/files/00080.json +1 -0
- package/mirror/files/00081.js +1 -0
- package/mirror/files/00082.json +1 -0
- package/mirror/files/00083.json +1 -0
- package/mirror/files/00084.js +7 -0
- package/mirror/files/00085.json +1 -0
- package/mirror/files/00086.json +1 -0
- package/mirror/files/00087.js +7 -0
- package/mirror/files/00088.json +1 -0
- package/mirror/files/00089.json +1 -0
- package/mirror/files/00090.js +7 -0
- package/mirror/files/00091.json +1 -0
- package/mirror/files/00092.json +1 -0
- package/mirror/files/00093.js +102 -0
- package/mirror/files/00094.json +1 -0
- package/mirror/files/00095.json +1 -0
- package/mirror/files/00096.json +1 -0
- package/mirror/files/00097.json +1 -0
- package/mirror/files/00098.json +1 -0
- package/mirror/files/00099.json +1 -0
- package/mirror/files/00100.json +1 -0
- package/mirror/files/00101.js +102 -0
- package/mirror/files/00102.json +1 -0
- package/mirror/files/00103.json +1 -0
- package/mirror/files/00104.json +1 -0
- package/mirror/files/00105.json +1 -0
- package/mirror/files/00106.json +1 -0
- package/mirror/files/00107.js +110 -0
- package/mirror/files/00108.json +1 -0
- package/mirror/files/00109.json +1 -0
- package/mirror/files/00110.json +1 -0
- package/mirror/files/00111.json +1 -0
- package/mirror/files/00112.json +1 -0
- package/mirror/files/00113.json +1 -0
- package/mirror/files/00114.json +1 -0
- package/mirror/files/00115.json +1 -0
- package/mirror/files/00116.json +1 -0
- package/mirror/files/00117.json +1 -0
- package/mirror/files/00118.json +1 -0
- package/mirror/files/00119.json +1 -0
- package/mirror/files/00120.json +1 -0
- package/mirror/files/00121.json +1 -0
- package/mirror/files/00122.json +1 -0
- package/mirror/files/00123.json +1 -0
- package/mirror/files/00124.json +1 -0
- package/mirror/files/00125.json +1 -0
- package/mirror/files/00126.json +1 -0
- package/mirror/files/00127.json +1 -0
- package/mirror/files/00128.json +1 -0
- package/mirror/files/00129.json +1 -0
- package/mirror/files/00130.json +1 -0
- package/mirror/files/00131.json +1 -0
- package/mirror/files/00132.js +110 -0
- package/mirror/files/00133.json +1 -0
- package/mirror/files/00134.json +1 -0
- package/mirror/files/00135.json +1 -0
- package/mirror/files/00136.json +1 -0
- package/mirror/files/00137.js +26 -0
- package/mirror/files/00138.json +1 -0
- package/mirror/files/00139.json +1 -0
- package/mirror/files/00140.json +1 -0
- package/mirror/files/00141.json +1 -0
- package/mirror/files/00142.json +1 -0
- package/mirror/files/00143.json +1 -0
- package/mirror/files/00144.js +26 -0
- package/mirror/files/00145.json +1 -0
- package/mirror/files/00146.json +1 -0
- package/mirror/files/00147.js +29 -0
- package/mirror/files/00148.json +1 -0
- package/mirror/files/00149.json +1 -0
- package/mirror/files/00150.js +23 -0
- package/mirror/files/00151.json +1 -0
- package/mirror/files/00152.json +1 -0
- package/mirror/files/00153.js +719 -0
- package/mirror/files/00154.js +9575 -0
- package/mirror/files/00155.js +108 -0
- package/mirror/files/00156.js +379 -0
- package/mirror/files/00157.js +48 -0
- package/mirror/files/00158.json +16 -0
- package/mirror/manifest.json +1582 -0
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +310 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/suite-kit/README.md +289 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +58 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
- package/node_modules/@capyclaw/work-store/README.md +83 -0
- package/node_modules/@capyclaw/work-store/STANDARD.md +263 -0
- package/node_modules/@capyclaw/work-store/cordis.patch.yml +3 -0
- package/node_modules/@capyclaw/work-store/dsh-suite.json +33 -0
- package/node_modules/@capyclaw/work-store/icon.svg +7 -0
- package/node_modules/@capyclaw/work-store/lib/host.mjs +21 -0
- package/node_modules/@capyclaw/work-store/package.json +68 -0
- package/node_modules/@capyclaw/work-store/src/backend.mjs +90 -0
- package/node_modules/@capyclaw/work-store/src/db.mjs +199 -0
- package/node_modules/@capyclaw/work-store/src/envelope.mjs +132 -0
- package/node_modules/@capyclaw/work-store/src/index.mjs +571 -0
- package/node_modules/@capyclaw/work-store/src/interop.mjs +70 -0
- package/node_modules/@capyclaw/work-store/src/refs.mjs +99 -0
- package/node_modules/@capyclaw/work-store/src/routes.mjs +135 -0
- package/package.json +82 -4
- package/plugin.mjs +644 -0
- package/static/index.html +2068 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/* Squiggle —— 每日同款曲线的涂鸦便签(doodling.html 上架适配)。
|
|
2
|
+
WorkView 沙箱入口:样式/标记/三段原码全部内嵌,零外部依赖;
|
|
3
|
+
存档走沙箱 localStorage 假面(自动镜像作品数据区),音频生命周期
|
|
4
|
+
由引导程序托管。原文件 test/doodling.mjs 可单测 core 段。 */
|
|
5
|
+
(function () {
|
|
6
|
+
'use strict';
|
|
7
|
+
var CSS = ":root{\n --leather:#1f3530;--leather2:#182a26;--paper:#f5efe2;--print:#e4553a;--cream:#efe6d4;--ink:#3a2f26;\n --walnut:#5b3f2c;--board:#8b7a62;--glue:#5e2a20;\n --pw:300px;--ph:450px;--cs:46px;--ease:cubic-bezier(.2,.8,.2,1);--spring:cubic-bezier(.3,1.45,.5,1);\n}\n*{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%;overflow:hidden;background:var(--leather2);overscroll-behavior:none}\nbody{font-family:Fraunces,Georgia,'Times New Roman',serif;color:var(--cream);-webkit-tap-highlight-color:transparent;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}\nbutton{font:inherit;color:inherit;background:none;border:0;cursor:pointer;touch-action:manipulation}\nbutton:focus-visible{outline:2px solid #f3d9a8;outline-offset:2px;border-radius:6px}\n[hidden]{display:none!important}\n\n/* the desk: walnut under a leather blotter */\n#desk{position:absolute;inset:0;background:#2b1c13 center/900px 180px}\n#blotter{position:absolute;inset:0;background:var(--leather) center/300px 300px}\n#blotter::after{content:\"\";position:absolute;inset:0;border-radius:inherit;pointer-events:none;\n background:linear-gradient(115deg,transparent 30%,rgba(255,250,230,.045) 45%,transparent 60%),radial-gradient(75% 55% at 45% 35%,rgba(255,236,190,.12),transparent 70%),radial-gradient(140% 100% at 50% 45%,transparent 40%,rgba(0,0,0,.45))}\n.corner{display:none;position:absolute;width:120px;height:120px;z-index:1;background:#5a3a2a;filter:drop-shadow(0 2px 3px rgba(0,0,0,.45))}\n.corner svg{position:absolute;inset:0}\n.corner.tl{left:0;top:0;clip-path:polygon(0 0,100% 0,0 100%)}\n.corner.tr{right:0;top:0;clip-path:polygon(0 0,100% 0,100% 100%)}\n.corner.bl{left:0;bottom:0;clip-path:polygon(0 0,0 100%,100% 100%)}\n.corner.br{right:0;bottom:0;clip-path:polygon(100% 0,100% 100%,0 100%)}\n.side #blotter{inset:14px 72px;border-radius:12px;box-shadow:0 10px 28px rgba(0,0,0,.55),0 2px 4px rgba(0,0,0,.4)}\n.side #blotter::before{content:\"\";position:absolute;inset:10px;border:1.4px dashed rgba(220,235,210,.15);border-radius:8px;pointer-events:none}\n.side .corner{display:block}\n\n#app{position:absolute;inset:0;display:grid;grid-template-columns:100%;grid-template-rows:auto 1fr auto;\n padding:env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left)}\n#top{display:flex;align-items:center;justify-content:space-between;padding:14px 16px 0;height:62px}\n#stage{position:relative;min-height:0;min-width:0;display:grid;place-items:center;padding:16px 16px 10px}\n\n/* the pad */\n#pad{position:relative;width:var(--pw);height:var(--ph);transition:opacity .25s}\n.board{position:absolute;left:0;right:0;top:-12px;bottom:-15px;border-radius:3px;background:var(--board) 0 0/256px;\n box-shadow:6px 26px 40px rgba(0,0,0,.45),1px 3px 3px rgba(0,0,0,.45),0 1px 0 rgba(0,0,0,.6)}\n.edges{position:absolute;left:0;right:0;top:4px;bottom:-12px;border-radius:0 0 2px 2px;background:repeating-linear-gradient(#efe8d7 0 1px,#d3c8b1 1px 1.7px)}\n.sheet{position:absolute;inset:0;overflow:hidden;background:var(--paper);box-shadow:0 1px 1px rgba(0,0,0,.12);touch-action:none;cursor:crosshair}\n.sheet canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}\n#cLive.multiply{mix-blend-mode:multiply}\n.glue{position:absolute;left:-1px;right:-1px;top:-10px;height:14px;border-radius:2px 2px 1px 1px;pointer-events:none;\n background:linear-gradient(#3e1a14,#5e2a20 35%,#8a4c3c 52%,#5e2a20 68%,#43201a);box-shadow:0 1px 1.5px rgba(60,20,10,.45)}\n#curl{position:absolute;right:0;bottom:0;width:var(--cs);height:var(--cs);touch-action:none;cursor:grab;z-index:2}\n#curl svg{position:absolute;right:0;bottom:0;overflow:visible;pointer-events:none}\n#curl::before{content:\"\";position:absolute;inset:-14px -6px -6px -14px} /* a thumb is bigger than the corner */\n#curl:active{cursor:grabbing}\n.fly{position:absolute;z-index:30;pointer-events:none;transform-origin:50% 0;filter:drop-shadow(0 1px 1px rgba(60,40,20,.35)) drop-shadow(0 14px 18px rgba(0,0,0,.3));\n}\n\n/* the tray */\n#tray{position:relative;display:grid;grid-template-columns:44px minmax(0,330px) auto;justify-content:center;align-items:end;gap:0 4px;padding:10px 8px 0;\n border-radius:16px 16px 0 0;background:var(--walnut) 0 0/600px 120px;box-shadow:0 -10px 24px rgba(0,0,0,.4),inset 0 1px 0 rgba(255,220,180,.3)}\n#tray::after{content:\"\";position:absolute;left:0;right:0;bottom:0;height:calc(24px + env(safe-area-inset-bottom));z-index:2;pointer-events:none;\n background:inherit;background-position:0 40px;border-radius:6px 6px 0 0;filter:brightness(1.12);\n box-shadow:inset 0 1px 0 rgba(255,220,180,.35),inset 0 -1px 0 rgba(0,0,0,.3),0 -8px 14px rgba(0,0,0,.42)}\n.acts{display:flex;flex-direction:column;gap:6px;align-self:center;padding-bottom:calc(30px + env(safe-area-inset-bottom))}\n.act{width:44px;height:44px;display:grid;place-items:center;color:#f3e6cf;transition:opacity .2s,transform .15s}\n.act svg{width:26px;height:26px;stroke:currentColor;fill:none;stroke-width:2.1;stroke-linecap:round;stroke-linejoin:round}\n.act:disabled{opacity:.3;cursor:default}\n.act:active:not(:disabled){transform:scale(.88)}\n.pens{display:flex;justify-content:space-around;height:148px;overflow:hidden;overflow:clip;padding-bottom:env(safe-area-inset-bottom);min-width:0}\n.pen{position:relative;flex:0 1 50px;min-width:34px;height:150px;transform:translateY(44px);transition:transform .32s var(--spring)}\n.pen svg{width:46px;height:150px;display:block;margin:0 auto;filter:drop-shadow(3px 4px 3px rgba(20,10,5,.4));transition:filter .3s}\n.pen.on{transform:translateY(2px)}\n.pen.on svg{filter:drop-shadow(5px 10px 6px rgba(20,10,5,.45))}\n.pen:active:not(.on){transform:translateY(36px)}\n.inks{display:grid;grid-template-columns:repeat(4,34px);grid-template-rows:repeat(2,42px);padding:0 2px calc(30px + env(safe-area-inset-bottom));align-self:end}\n.inkb{position:relative;width:34px;height:42px;display:grid;place-items:center}\n.well.mix{background:conic-gradient(from 20deg,#e24b3b,#e8a93a,#e4d84a,#5ba35b,#3f86c9,#6a52b0,#c4528f,#e24b3b);box-shadow:inset 0 0 0 2px rgba(0,0,0,.2),inset 0 2px 3px rgba(0,0,0,.3),0 0 0 3px rgba(30,18,10,.45),0 1px 0 3px rgba(255,220,180,.16)}\n.well.mix::before{content:\"+\";position:absolute;inset:0;display:grid;place-items:center;font:600 18px/1 system-ui,sans-serif;color:#fff;text-shadow:0 1px 2px rgba(0,0,0,.6)}\n.mixer input{position:absolute;left:50%;top:50%;width:1px;height:1px;opacity:0;border:0;padding:0;pointer-events:none}\n.well{width:28px;height:28px;border-radius:50%;background:var(--c);position:relative;transition:transform .25s var(--spring);\n box-shadow:inset 0 0 0 2px color-mix(in srgb,var(--c) 72%,#000),inset 0 2px 3px rgba(0,0,0,.35),0 0 0 3px rgba(30,18,10,.45),0 1px 0 3px rgba(255,220,180,.16)}\n.well::after{content:\"\";position:absolute;inset:3px;border-radius:50%;border-top:1.5px solid rgba(255,255,255,.2);transform:rotate(-30deg)}\n.inkb.on .well{transform:scale(1.1)}\n.ring{position:absolute;left:-1px;top:2px;width:38px;height:38px;pointer-events:none;overflow:visible}\n.ring path{fill:none;stroke:#f1e4cc;stroke-width:1.6;stroke-linecap:round;stroke-dasharray:120;stroke-dashoffset:120;transition:stroke-dashoffset .35s var(--ease)}\n.inkb.on .ring path{stroke-dashoffset:0}\n\n/* the sketchbook on the desk */\n#bookBtn{display:flex;align-items:center;gap:10px;padding:10px 4px 2px 10px;min-height:48px;text-align:right}\n/* the sketchbook itself: a closed cloth book, the last torn sheet tucked in at the top */\n.sb{position:relative;display:block;width:40px;height:52px;flex:none}\n.cover{position:absolute;inset:0;z-index:1;border-radius:2px 5px 5px 2px;\n background:linear-gradient(90deg,#24191560 0 12%,transparent 15%),linear-gradient(#4a3029,#3b2620);\n box-shadow:inset 3px 0 0 rgba(0,0,0,.25),inset -1px 0 0 rgba(255,220,190,.08),0 4px 10px rgba(0,0,0,.45),0 1px 2px rgba(0,0,0,.4);transition:transform .35s var(--spring)}\n.cover::after{content:\"\";position:absolute;top:-1px;bottom:-1px;right:16%;width:2.5px;background:#1a110e;box-shadow:1px 0 0 rgba(255,255,255,.07)}\n#bookNum{position:absolute;left:24%;right:30%;top:24%;padding:1px 0 2px;background:#e9e0cc;color:#4b4236;font:italic 600 10px/1.1 Fraunces,serif;text-align:center;border-radius:1px;box-shadow:0 0 0 .5px rgba(0,0,0,.2)}\n#bookNum:empty{opacity:.55;height:8px}\n.peek{position:absolute;left:14%;top:-26%;width:66%;height:80%;background:var(--paper);overflow:hidden;transform:rotate(-4deg);box-shadow:0 1px 3px rgba(0,0,0,.35);transition:transform .45s var(--spring),opacity .3s}\n.peek canvas{display:block;width:100%;height:auto}\n.sb.empty .peek{opacity:0;transform:translateY(40%) rotate(-4deg)}\n.bump .cover{animation:bump .45s var(--spring)}\n@keyframes bump{40%{transform:scale(1.1) rotate(-2deg)}}\n.lbl{font:italic 500 14px/1.2 Fraunces,serif;color:rgba(239,230,212,.78)}\n.lbl b{display:none}\n.side .lbl b{display:inline}\n.side .lbl{display:inline-block}\n\n/* wide screens: the tray lies beside a landscape pad */\n.side #app{inset:14px 72px;grid-template-columns:1fr 236px var(--pw) 1fr;grid-template-rows:1fr;column-gap:40px;padding:0}\n.side #top{display:none}\n.side #stage{grid-column:3;grid-row:1;padding:0}\n.side #col{grid-column:2;grid-row:1;align-self:center;height:calc(var(--ph) + 20px);display:flex;flex-direction:column;justify-content:space-between;transform-origin:50% 50%;transform:scale(var(--k,1))}\n#col{display:contents}\n.side #tray{display:flex;flex-direction:column;align-items:stretch;border-radius:14px;padding:12px 12px 8px;gap:0;\n box-shadow:0 14px 26px rgba(0,0,0,.45),0 3px 5px rgba(0,0,0,.35),inset 0 1px 0 rgba(255,220,180,.25),inset 0 -2px 0 rgba(0,0,0,.25)}\n.side #tray::after{display:none}\n.side .pens{order:1;flex-direction:column;height:auto;overflow:visible;padding:8px 0;border-radius:10px;background:rgba(0,0,0,.2);box-shadow:inset 0 3px 7px rgba(0,0,0,.5),0 1px 0 rgba(255,220,180,.14);gap:4px}\n.side .pen{flex:none;width:100%;height:54px;transform:translateX(0)}\n.side .pen svg{position:absolute;left:69px;top:-48px;transform:rotate(90deg);filter:drop-shadow(-4px 3px 2px rgba(20,10,5,.4))}\n.side .pen.on{transform:translate(16px,-3px) rotate(-2.5deg)}\n.side .pen.on svg{filter:drop-shadow(-12px 9px 7px rgba(20,10,5,.42))}\n.side .pen:active:not(.on){transform:translateX(5px)}\n.side .inks{order:2;align-self:stretch;grid-template-columns:repeat(4,1fr);grid-template-rows:repeat(2,44px);justify-items:center;padding:12px 0 2px;margin-top:10px;border-top:1px solid rgba(0,0,0,.35);box-shadow:inset 0 1px 0 rgba(255,255,240,.07)}\n.side .inkb{width:auto}\n.side .acts{order:3;flex-direction:row;justify-content:center;gap:40px;padding:4px 0 0}\n.side .act svg{width:30px;height:30px}\n.side #top2{display:flex;justify-content:center}\n#top2{display:none}\n.side #bookBtn{flex-direction:column-reverse;align-items:center;gap:12px;text-align:center;padding:30px 0 0}\n.side .sb{width:116px;height:150px}\n.side #bookNum{font-size:15px;padding:3px 0 4px}\n.side #bookNum:empty{height:20px}\n.side .lbl{display:inline-block;padding:4px 10px 5px;background:#efe6d2;color:#4b4236;border-radius:2px;box-shadow:0 2px 4px rgba(0,0,0,.4);transform:rotate(-2deg);font-size:14px}\n.side .lbl b{display:inline;margin-left:6px;color:#857a68;font-size:11px}\n\n/* the sketchbook: an open book, the torn sheets taped in */\n.overlay{position:absolute;inset:0;z-index:20;display:flex;flex-direction:column;color:#3a3128;background:#e6dcc7 0 0/512px;\n padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)}\n.overlay::before{content:\"\";position:absolute;inset:0;pointer-events:none;background:radial-gradient(120% 90% at 50% 30%,transparent 50%,rgba(90,60,30,.18))}\n#book{animation:open .34s var(--ease)}\n@keyframes open{from{opacity:0;transform:translateY(18px) scale(.985)}}\n.ohead{position:relative;display:flex;align-items:center;gap:6px;padding:12px 12px 8px 18px;border-bottom:1px solid rgba(90,70,40,.18)}\n.ohead h2{font:italic 600 26px Fraunces,serif;letter-spacing:.005em;margin-right:auto;color:#3a3128}\n.ohead h2 small{font:400 14px Fraunces,serif;color:#8a7c66;margin-left:10px;font-style:normal}\n.ibtn{width:44px;height:44px;display:grid;place-items:center;border-radius:50%;color:#3a3128;flex:none}\n.ibtn svg{width:24px;height:24px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}\n.ibtn:active{background:rgba(60,40,20,.08)}\n#grid{position:relative;flex:1;overflow-y:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:34px 22px;padding:30px max(22px,calc(50% - 560px)) 48px;align-content:start;-webkit-overflow-scrolling:touch}\n.side #grid{grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:44px 34px}\n.card{display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center;color:#3a3128}\n.card .pg{position:relative;width:100%;background:var(--paper);transform:rotate(var(--r));transition:transform .3s var(--spring);\n box-shadow:0 1px 2px rgba(60,40,20,.25),0 8px 18px rgba(60,40,20,.18)}\n.card .pg canvas{display:block;width:100%;height:100%}\n.card .pg::after{content:\"\";position:absolute;top:-9px;left:50%;width:46px;height:17px;margin-left:-23px;transform:rotate(var(--t));\n background:rgba(232,220,182,.78);box-shadow:0 1px 1px rgba(60,40,20,.12);\n -webkit-mask:linear-gradient(90deg,transparent,#000 3px calc(100% - 3px),transparent);mask:linear-gradient(90deg,transparent,#000 3px calc(100% - 3px),transparent)}\n.card:hover .pg,.card:focus-visible .pg{transform:rotate(0) translateY(-3px)}\n.card span{font:italic 500 15px Fraunces,serif;white-space:nowrap}\n.card span b{font:400 12px Fraunces,serif;color:#8a7c66;font-style:normal;margin-left:6px}\n#bookEmpty{position:relative;margin:auto;max-width:300px;text-align:center;font:italic 400 19px/1.5 Fraunces,serif;color:#7a6c57;padding:40px 20px}\n#view{z-index:21}\n#view .vstage{position:relative;flex:1;min-height:0;display:grid;place-items:center;padding:14px 18px}\n#cView{display:block;background:var(--paper)}\n#vSheet{filter:drop-shadow(0 1px 2px rgba(60,40,20,.3)) drop-shadow(0 14px 20px rgba(60,40,20,.2))}\n#vnav{position:relative;display:flex;flex-wrap:wrap;justify-content:center;gap:8px 10px;padding:16px 16px 20px}\n.vb{display:flex;align-items:center;gap:7px;min-height:44px;padding:0 12px;border-radius:22px;font:400 15px Fraunces,serif;color:#3a3128}\n#vRemove{color:#8a7c66;font-size:14px}\n.vb:not(.main):hover{background:rgba(58,49,40,.06)}\n.vb svg{width:19px;height:19px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}\n.vb.main{background:#3a3128;color:#f3ead8;font-weight:500;padding:0 16px;box-shadow:0 2px 6px rgba(40,25,10,.3)}\n.vb:active{transform:scale(.96)}\n#vReplay{position:absolute;right:calc(50% - var(--vw,0px) / 2 + 12px);bottom:calc(50% - var(--vh,0px) / 2 + 12px);width:46px;height:46px;border-radius:50%;background:rgba(58,49,40,.8);color:#f3ead8;opacity:0;transition:opacity .3s;pointer-events:none}\n#vReplay.show{opacity:1;pointer-events:auto}\n#vReplay svg{width:18px;height:18px;fill:currentColor;margin-left:3px}\n.zoom{position:absolute;z-index:25;pointer-events:none;filter:drop-shadow(0 1px 2px rgba(60,40,20,.3)) drop-shadow(0 14px 20px rgba(60,40,20,.2))}\n#toast{position:absolute;left:50%;bottom:calc(178px + env(safe-area-inset-bottom));z-index:40;transform:translate(-50%,20px);opacity:0;pointer-events:none;\n display:flex;align-items:center;gap:12px;padding:10px 12px 10px 16px;border-radius:22px;background:#3a3128;color:#f3ead8;font:500 14px Fraunces,serif;box-shadow:0 8px 24px rgba(0,0,0,.35);transition:opacity .25s,transform .3s var(--ease);max-width:calc(100vw - 32px)}\n#toast.show{opacity:1;transform:translate(-50%,0);pointer-events:auto}\n#toast button{font:600 14px Fraunces,serif;color:#f0b49f;padding:4px 6px}\n.side #toast{bottom:40px}\n@media (prefers-reduced-motion:reduce){\n *,*::before,*::after{animation-duration:.01ms!important;transition-duration:.01ms!important}\n}\n#top #mute{opacity:.7}\n#mute svg{width:22px;height:22px}\n/* nib sizes: a small card that rises from the button */\n#sizes{position:absolute;z-index:35;display:flex;align-items:center;gap:2px;padding:6px 8px;border-radius:14px;background:#3a2a1e;\n box-shadow:0 10px 26px rgba(0,0,0,.5),inset 0 1px 0 rgba(255,220,180,.2);animation:rise .22s var(--ease)}\n@keyframes rise{from{opacity:0;transform:translateY(8px)}}\n.szb{position:relative;width:46px;height:46px;display:grid;place-items:center;border-radius:10px}\n.szb i{display:block;border-radius:50%;background:var(--c);box-shadow:0 0 0 1.5px rgba(255,240,220,.18)}\n.szb.on{background:rgba(255,235,200,.14);box-shadow:inset 0 0 0 1.5px rgba(241,228,204,.7)}\n#sizeBtn circle{fill:currentColor;stroke:none}\n#topL{display:flex;gap:2px}\n#top #setBtn{opacity:.7}\n#setBtn svg{width:22px;height:22px}\n.side .acts{justify-content:space-between;gap:0}\n.side .act{width:40px}\n/* the pad's settings: a card of the same paper as the sketchbook */\n#prefs{position:absolute;inset:0;z-index:22;display:grid;place-items:center;padding:16px;background:rgba(12,18,16,.55);animation:fade .2s}\n@keyframes fade{from{opacity:0}}\n.pcard{position:relative;width:min(440px,100%);max-height:100%;overflow:auto;border-radius:10px;color:#3a3128;background:#efe6d2;box-shadow:0 20px 50px rgba(0,0,0,.5);animation:open .3s var(--ease)}\n.pcard .ohead{position:sticky;top:0;background:#efe6d2;z-index:1}\n.pbody{padding:6px 18px 22px}\n.pbody h3{font:600 13px Fraunces,serif;letter-spacing:.06em;text-transform:uppercase;color:#8a7c66;margin:18px 0 10px}\n.opts{display:flex;flex-wrap:wrap;gap:10px}\n.opt{display:flex;flex-direction:column;align-items:center;gap:6px;font:400 13px Fraunces,serif;color:#5a4e3e;min-width:56px}\n.opt i{width:52px;height:66px;border-radius:3px;background-color:var(--c);box-shadow:0 1px 2px rgba(60,40,20,.3),0 0 0 1px rgba(60,40,20,.12);transition:transform .2s var(--spring)}\n.opt.on i{box-shadow:0 0 0 2px #efe6d2,0 0 0 4px #3a3128}\n.opt.on{color:#3a3128;font-weight:600}\n.opt:active i{transform:scale(.94)}\n.opts.txt .opt{min-width:0;flex-direction:row;padding:9px 14px;border-radius:20px;box-shadow:inset 0 0 0 1px rgba(60,40,20,.25);font-size:14px}\n.opts.txt .opt.on{background:#3a3128;color:#f3ead8;box-shadow:none}\n.r-lined{background-image:linear-gradient(90deg,transparent 7px,rgba(200,80,70,.4) 7px 8px,transparent 8px),repeating-linear-gradient(transparent 0 7px,rgba(70,110,150,.4) 7px 8px);background-position:0 0,0 14px}\n.r-grid{background-image:repeating-linear-gradient(transparent 0 7px,rgba(70,110,150,.4) 7px 8px),repeating-linear-gradient(90deg,transparent 0 7px,rgba(70,110,150,.4) 7px 8px)}\n.r-dots{background-image:radial-gradient(circle,rgba(60,80,100,.55) 1px,transparent 1.3px);background-size:8px 8px}\n.pnote{font:italic 400 13px/1.4 Fraunces,serif;color:#8a7c66;margin-top:10px}\n.tog{display:flex;align-items:center;gap:12px;min-height:40px;font:400 16px Fraunces,serif;cursor:pointer}\n.tog input{appearance:none;-webkit-appearance:none;width:40px;height:24px;border-radius:12px;background:#cdbfa5;position:relative;transition:background .2s;cursor:pointer;flex:none}\n.tog input::after{content:\"\";position:absolute;left:3px;top:3px;width:18px;height:18px;border-radius:50%;background:#fbf6ea;box-shadow:0 1px 2px rgba(0,0,0,.3);transition:transform .2s var(--spring)}\n.tog input:checked{background:#3a3128}\n.tog input:checked::after{transform:translateX(16px)}\n.tog input:focus-visible{outline:2px solid #3a3128;outline-offset:2px}";
|
|
8
|
+
var HTML = "<div id=\"desk\"></div>\n<div id=\"blotter\"><i class=\"corner tl\"></i><i class=\"corner tr\"></i><i class=\"corner bl\"></i><i class=\"corner br\"></i></div>\n<main id=\"app\">\n <div id=\"top\"><span id=\"topL\"><button class=\"act\" id=\"mute\" aria-label=\"Sound off\"><svg viewBox=\"0 0 24 24\"></svg></button><button class=\"act\" id=\"setBtn\" aria-label=\"Paper and sheet settings\" aria-haspopup=\"dialog\"><svg viewBox=\"0 0 24 24\"><path d=\"M5 4h11l3 3v13H5z\"/><path d=\"M8 10h8M8 13.5h8M8 17h5\"/></svg></button></span></div>\n <section id=\"stage\">\n <div id=\"pad\">\n <div class=\"board\"></div>\n <div class=\"edges\"></div>\n <div class=\"sheet\" id=\"sheet\" role=\"img\" aria-label=\"Today's sheet\">\n <canvas id=\"cPaper\"></canvas><canvas id=\"cDots\"></canvas><canvas id=\"cInk\"></canvas><canvas id=\"cLive\"></canvas>\n </div>\n <div class=\"glue\"></div>\n <button id=\"curl\" aria-label=\"Tear off this sheet and file it in the sketchbook\"><svg></svg></button>\n </div>\n </section>\n <div id=\"col\">\n <aside id=\"tray\" aria-label=\"Pens and inks\">\n <div class=\"acts\">\n <button class=\"act\" id=\"sizeBtn\" aria-haspopup=\"true\" aria-expanded=\"false\" aria-label=\"Nib size\"><svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4\"/></svg></button>\n <button class=\"act\" id=\"undo\" aria-label=\"Undo\" disabled><svg viewBox=\"0 0 24 24\"><path d=\"M8.6 5.2C7 7 5.6 8.4 4.2 9.9c1.6 1.4 3 2.9 4.6 4.6\"/><path d=\"M4.5 10.1c3.4-.3 6.8-.6 9.7.3 3.6 1.1 5.2 4.4 3.9 7.3-.9 2-3 3-5.6 3.1\"/></svg></button>\n <button class=\"act\" id=\"redo\" aria-label=\"Redo\" disabled><svg viewBox=\"0 0 24 24\"><path d=\"M15.4 5.2c1.6 1.8 3 3.2 4.4 4.7-1.6 1.4-3 2.9-4.6 4.6\"/><path d=\"M19.5 10.1c-3.4-.3-6.8-.6-9.7.3-3.6 1.1-5.2 4.4-3.9 7.3.9 2 3 3 5.6 3.1\"/></svg></button>\n </div>\n <div class=\"pens\" id=\"pens\" role=\"radiogroup\" aria-label=\"Pens\"></div>\n <div class=\"inks\" id=\"inks\" role=\"radiogroup\" aria-label=\"Inks\"></div>\n </aside>\n <div id=\"top2\"></div>\n </div>\n <button id=\"bookBtn\" aria-label=\"Open the sketchbook\"><span class=\"lbl\">Sketchbook<b id=\"bookCount\">empty</b></span><span class=\"sb empty\" id=\"stack\"><span class=\"peek\"><canvas id=\"cStack\"></canvas></span><span class=\"cover\"><em id=\"bookNum\"></em></span></span></button>\n</main>\n\n<section id=\"book\" class=\"overlay\" hidden aria-label=\"Sketchbook\">\n <div class=\"ohead\">\n <h2>Sketchbook<small id=\"bookCount2\"></small></h2>\n <button class=\"ibtn\" id=\"bookClose\" aria-label=\"Close the sketchbook\"><svg viewBox=\"0 0 24 24\"><path d=\"M6 6l12 12M18 6 6 18\"/></svg></button>\n </div>\n <div id=\"grid\"></div>\n <p id=\"bookEmpty\" hidden>Sheets you tear off the pad are kept here, with every stroke, so they can draw themselves again.</p>\n</section>\n\n<section id=\"view\" class=\"overlay\" hidden aria-label=\"A sheet from the sketchbook\">\n <div class=\"ohead\">\n <button class=\"ibtn\" id=\"viewBack\" aria-label=\"Back to the sketchbook\"><svg viewBox=\"0 0 24 24\"><path d=\"M15 5l-7 7 7 7\"/></svg></button>\n <h2 id=\"viewTitle\" style=\"font-size:19px\"></h2>\n </div>\n <div class=\"vstage\"><div id=\"vSheet\"><canvas id=\"cView\"></canvas></div><button id=\"vReplay\" aria-label=\"Draw it again\"><svg viewBox=\"0 0 24 24\"><path d=\"M7 4.5v15l12.5-7.5z\"/></svg></button></div>\n <nav id=\"vnav\">\n <button class=\"vb main\" id=\"vDraw\"><svg viewBox=\"0 0 24 24\"><path d=\"M4 20l4-1 11-11-3-3L5 16z\"/><path d=\"M14 7l3 3\"/></svg>Draw on it</button>\n <button class=\"vb\" id=\"vSave\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 4v11M7 10l5 5 5-5M5 20h14\"/></svg>Save image</button>\n <button class=\"vb\" id=\"vSend\"><svg viewBox=\"0 0 24 24\"><path d=\"M4 12l16-8-6 16-3-6z\"/></svg>Send the squiggle</button>\n <button class=\"vb\" id=\"vRemove\"><svg viewBox=\"0 0 24 24\"><path d=\"M5 7h14M10 7V5h4v2M7 7l1 13h8l1-13\"/></svg>Remove</button>\n </nav>\n</section>\n\n<div id=\"sizes\" role=\"radiogroup\" aria-label=\"Nib size\" hidden></div>\n\n<section id=\"prefs\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"prefsTitle\" hidden>\n <div class=\"pcard\">\n <div class=\"ohead\"><h2 id=\"prefsTitle\">The pad</h2><button class=\"ibtn\" id=\"prefsClose\" aria-label=\"Close\"><svg viewBox=\"0 0 24 24\"><path d=\"M6 6l12 12M18 6 6 18\"/></svg></button></div>\n <div class=\"pbody\">\n <h3>Paper</h3><div class=\"opts\" id=\"optPaper\" role=\"radiogroup\" aria-label=\"Paper\"></div>\n <h3>Ruling</h3><div class=\"opts\" id=\"optRule\" role=\"radiogroup\" aria-label=\"Ruling\"></div>\n <p class=\"pnote\">Changes this sheet and every sheet after it. The ones in the sketchbook keep their own.</p>\n <h3>Printed at the top</h3>\n <label class=\"tog\"><input type=\"checkbox\" id=\"optDate\"><span>The date</span></label>\n <label class=\"tog\"><input type=\"checkbox\" id=\"optNumber\"><span>The sheet's number</span></label>\n <h3>Date written in</h3><div class=\"opts txt\" id=\"optLang\" role=\"radiogroup\" aria-label=\"Date language\"></div>\n </div>\n </div>\n</section>\n\n<div id=\"toast\" role=\"status\" aria-live=\"polite\"><span id=\"toastMsg\"></span><button id=\"toastBtn\" hidden></button></div>\n\n<script id=\"core\">\n// Squiggle core - DOM-free: the day, the seeded squiggle and its dots, the pen model, the\n// stroke codec, and the pad and sketchbook the sheets move between. test/doodling.mjs runs it.\nvar SQ = (function () {\n 'use strict';\n var W = 1000, H = 1500; // a sheet in page units: 1000 x 1500, or turned\n var EPOCH = Date.UTC(2026, 9, 1); // No. 1 is Thursday 1 October 2026\n var DAY = 86400000;\n\n function rng(seed) { // mulberry32\n var s = seed >>> 0;\n return function () {\n s = (s + 0x6D2B79F5) >>> 0;\n var t = Math.imul(s ^ (s >>> 15), 1 | s);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n }\n function hash(str) {\n var h = 2166136261 >>> 0;\n for (var i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }\n return h;\n }\n\n // The day number everyone on the same calendar date shares: local date, not UTC instant.\n function dayNumber(date) {\n var d = date || new Date();\n return Math.floor((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - EPOCH) / DAY) + 1;\n }\n function dayDate(n) { var d = new Date(EPOCH + (n - 1) * DAY); return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); }\n function daySeed(n) { return hash('squiggle/day/' + n); }\n\n // Short codes for extra sheets, so a squiggle can be sent as a link. Six letters of five bits:\n // extra sheets draw their seeds below 2^30 so every one of them has a code.\n var ALPHA = 'abcdefghijkmnpqrstuvwxyz23456789';\n function codeFor(seed) { var s = ''; seed >>>= 0; for (var i = 0; i < 6; i++) { s += ALPHA[seed % 32]; seed = Math.floor(seed / 32); } return s; }\n function seedFor(code) {\n if (!/^[a-km-np-z2-9]{6}$/.test(code || '')) return null;\n var v = 0; for (var i = 5; i >= 0; i--) v = v * 32 + ALPHA.indexOf(code[i]);\n return v >>> 0;\n }\n\n // ---- the squiggle -------------------------------------------------------------------\n // A turtle walks with a curvature that drifts as a sum of slow sines, so the line turns,\n // loops and straightens the way a hand does. Candidates that cross themselves too often,\n // barely bend, or bunch into a knot are thrown away; the survivor is scaled into the\n // middle of the sheet. The same seed always gives the same line.\n var BOX_TALL = {x0: 190, y0: 430, x1: 810, y1: 1110}; // portrait sheet, 1000 x 1500\n var BOX_WIDE = {x0: 380, y0: 260, x1: 1120, y1: 850}; // landscape sheet, 1500 x 1000\n function sheetSize(wide) { return wide ? {w: H, h: W} : {w: W, h: H}; }\n\n function segIntersect(a, b, c, d) {\n var d1 = (d[0] - c[0]) * (a[1] - c[1]) - (d[1] - c[1]) * (a[0] - c[0]);\n var d2 = (d[0] - c[0]) * (b[1] - c[1]) - (d[1] - c[1]) * (b[0] - c[0]);\n var d3 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);\n var d4 = (b[0] - a[0]) * (d[1] - a[1]) - (b[1] - a[1]) * (d[0] - a[0]);\n return d1 * d2 < 0 && d3 * d4 < 0;\n }\n function crossings(p) {\n var n = 0, step = 3, q = [];\n for (var i = 0; i < p.length; i += step) q.push(p[i]);\n for (var a = 0; a < q.length - 1; a++)\n for (var b = a + 2; b < q.length - 1; b++)\n if (segIntersect(q[a], q[a + 1], q[b], q[b + 1])) n++;\n return n;\n }\n function turning(p) {\n var t = 0;\n for (var i = 1; i < p.length - 1; i++) {\n var a1 = Math.atan2(p[i][1] - p[i - 1][1], p[i][0] - p[i - 1][0]);\n var a2 = Math.atan2(p[i + 1][1] - p[i][1], p[i + 1][0] - p[i][0]);\n var d = a2 - a1; while (d > Math.PI) d -= 2 * Math.PI; while (d < -Math.PI) d += 2 * Math.PI;\n t += Math.abs(d);\n }\n return t;\n }\n function bbox(p) {\n var b = {x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9};\n for (var i = 0; i < p.length; i++) {\n if (p[i][0] < b.x0) b.x0 = p[i][0]; if (p[i][0] > b.x1) b.x1 = p[i][0];\n if (p[i][1] < b.y0) b.y0 = p[i][1]; if (p[i][1] > b.y1) b.y1 = p[i][1];\n }\n return b;\n }\n function walk(r) {\n var n = 150 + Math.floor(r() * 110), step = 4;\n var waves = [], k = 1 + Math.floor(r() * 3);\n var bias = (r() - 0.5) * 0.02;\n for (var i = 0; i < k; i++) waves.push({a: (0.012 + r() * 0.03) * (r() < 0.5 ? -1 : 1), f: 0.4 + r() * 2.6, ph: r() * 6.283});\n var x = 0, y = 0, h = r() * 6.283, p = [[0, 0]];\n for (var j = 0; j < n; j++) {\n var t = j / n, c = bias;\n for (var w = 0; w < waves.length; w++) c += waves[w].a * Math.sin(waves[w].f * 6.283 * t + waves[w].ph);\n h += c * step;\n x += Math.cos(h) * step; y += Math.sin(h) * step;\n p.push([x, y]);\n }\n return p;\n }\n function squiggle(seed, wide) {\n var r = rng(seed), p, tries = 0, BOX = wide ? BOX_WIDE : BOX_TALL;\n for (;;) {\n tries++;\n p = walk(r);\n var b = bbox(p), bw = b.x1 - b.x0, bh = b.y1 - b.y0;\n var turn = turning(p), cr = crossings(p);\n var ok = turn > 2.2 && turn < 13 && cr <= 2 && Math.max(bw, bh) > 1.6 * Math.min(bw, bh) * 0.5;\n if (ok || tries > 60) break;\n }\n // fit into the box, keep the aspect, a little smaller when the line is long\n var bb = bbox(p), sw = (BOX.x1 - BOX.x0) / (bb.x1 - bb.x0), sh = (BOX.y1 - BOX.y0) / (bb.y1 - bb.y0);\n var fit = Math.min(sw, sh), L = Math.max(bb.x1 - bb.x0, bb.y1 - bb.y0);\n var s = Math.min(fit, Math.max(fit * (0.7 + r() * 0.25), 520 / L));\n var cx = (bb.x0 + bb.x1) / 2, cy = (bb.y0 + bb.y1) / 2;\n var ox = (BOX.x0 + BOX.x1) / 2 + (r() - 0.5) * 80, oy = (BOX.y0 + BOX.y1) / 2 + (r() - 0.5) * 120;\n var out = [];\n for (var i = 0; i < p.length; i++) {\n var X = ox + (p[i][0] - cx) * s, Y = oy + (p[i][1] - cy) * s;\n out.push([Math.min(BOX.x1, Math.max(BOX.x0, X)), Math.min(BOX.y1, Math.max(BOX.y0, Y))]);\n }\n return resample(out, 5);\n }\n function resample(p, d) {\n var out = [p[0].slice()], carry = 0;\n for (var i = 1; i < p.length; i++) {\n var ax = p[i - 1][0], ay = p[i - 1][1], bx = p[i][0], by = p[i][1];\n var L = Math.hypot(bx - ax, by - ay), pos = d - carry;\n while (pos <= L) { out.push([ax + (bx - ax) * pos / L, ay + (by - ay) * pos / L]); pos += d; }\n carry = L - (pos - d);\n }\n var last = p[p.length - 1];\n if (Math.hypot(last[0] - out[out.length - 1][0], last[1] - out[out.length - 1][1]) > d * 0.3) out.push(last.slice());\n return out;\n }\n\n // ---- pens ---------------------------------------------------------------------------\n // Widths are decided once, while drawing, and stored with the point, so a replay or a\n // thumbnail draws exactly what was drawn.\n var TOOLS = ['pencil', 'fine', 'brush', 'marker', 'eraser'];\n var INKS = ['#262b36', '#3a5ba6', '#43795a', '#d9a23a', '#c96f8b', '#6f5592'];\n var BASE = {pencil: 5.5, fine: 4.4, brush: 30, marker: 34, eraser: 44};\n // Nib sizes, as a factor on BASE: a pen of each size is a different pen, not a zoom.\n var SIZES = [0.45, 0.7, 1, 1.5, 2.2];\n // The papers a pad can be, and what is printed on them.\n var PAPERS = ['#f5efe2', '#fbfaf6', '#e9e7e2', '#ddc8a4', '#e1eaec'];\n var RULES = ['plain', 'lined', 'grid', 'dots'];\n\n // A stroke's ink: 0-5 are the six inks; 16 and up carry any colour, 16 + 0xRRGGBB, so a\n // stroke stores its own colour in the same field old saves already use.\n function inkColor(i) {\n if (i >= 16) { var v = (i - 16) & 0xffffff; return '#' + ('00000' + v.toString(16)).slice(-6); }\n return INKS[i] || INKS[0];\n }\n function inkOf(hex) { var m = /^#?([0-9a-f]{6})$/i.exec(hex || ''); return m ? 16 + parseInt(m[1], 16) : 0; }\n function validInk(i) { return (i >= 0 && i < INKS.length) || (i >= 16 && i < 16 + 0x1000000); }\n\n // A pen in the hand: feed it pointer samples (page units, ms, pressure or -1), it returns\n // the points to keep. Steadied a little so a trembling finger still draws a clean line.\n function Pen(tool, x, y, t, pressure, size) {\n this.tool = tool; this.k = size > 0 ? size : 1; this.x = x; this.y = y; this.t = t; this.v = 0.6; this.n = 0;\n this.p = pressure; this.w = this.width(0.6, pressure) * (tool === 'brush' ? 0.35 : 1);\n this.pts = [[q(x, 2), q(y, 2), q(this.w, 4), 0]];\n }\n // points are kept at the precision they are stored with, so a sheet looks the same after a reload\n function q(v, k) { return Math.round(v * k) / k; }\n Pen.prototype.width = function (v, pr) {\n var b = BASE[this.tool] * this.k;\n if (this.tool === 'fine') return b * (0.78 + 0.32 * Math.exp(-v / 1.2)); // a fineliner bleeds a little when it lingers\n if (this.tool !== 'brush') return b;\n if (pr >= 0) return 1.6 * Math.min(1, this.k) + (b + 2) * Math.pow(Math.min(1, pr), 1.2) * (0.75 + 0.25 * Math.exp(-v / 1.6));\n return 1.2 * Math.min(1, this.k) + b * Math.exp(-v / 0.75);\n };\n Pen.prototype.add = function (x, y, t, pressure) {\n var k = this.tool === 'marker' || this.tool === 'eraser' ? 0.7 : 0.55; // steadying\n var nx = this.x + (x - this.x) * k, ny = this.y + (y - this.y) * k;\n var d = Math.hypot(nx - this.x, ny - this.y), dt = Math.max(1, t - this.t);\n if (d < 1.2) return null;\n this.v += (Math.min(8, d / dt) - this.v) * 0.3;\n this.n++;\n var target = this.width(this.v, pressure);\n var ramp = this.tool === 'brush' ? Math.min(1, 0.35 + this.n * 0.16) : 1;\n this.w += (target * ramp - this.w) * (this.tool === 'brush' ? 0.28 : this.tool === 'fine' ? 0.2 : 1);\n this.x = nx; this.y = ny;\n var pt = [q(nx, 2), q(ny, 2), q(this.w, 4), Math.min(250, Math.round(dt))];\n this.t = t; this.pts.push(pt);\n return pt;\n };\n Pen.prototype.end = function (x, y, t) { // the last stretch the steadying held back\n var d = Math.hypot(x - this.x, y - this.y);\n if (d > 1.2 && this.pts.length > 1) {\n var pt = [q(x, 2), q(y, 2), q(this.w * (this.tool === 'brush' ? 0.6 : 1), 4), Math.min(250, Math.max(1, Math.round(t - this.t)))];\n this.pts.push(pt); return pt;\n }\n return null;\n };\n\n // ---- codec --------------------------------------------------------------------------\n // A sheet is a list of strokes {tool, ink, gap, pts:[[x,y,w,dt]]}. Stored as zigzag\n // varints of deltas in half units (x, y), quarter units (w) and ms (dt), then base64:\n // around six bytes a point, so a busy page is tens of kilobytes, not megabytes.\n function zz(n) { return n >= 0 ? n * 2 : -n * 2 - 1; }\n function unzz(n) { return n & 1 ? -(n + 1) / 2 : n / 2; }\n function encode(strokes) {\n var out = [];\n function put(n) { n = zz(n); while (n >= 128) { out.push((n & 127) | 128); n = Math.floor(n / 128); } out.push(n); }\n put(1); put(strokes.length);\n for (var i = 0; i < strokes.length; i++) {\n var s = strokes[i];\n put(TOOLS.indexOf(s.tool)); put(s.ink | 0); put(Math.min(5000, Math.round(s.gap || 0))); put(s.pts.length);\n var px = 0, py = 0, pw = 0;\n for (var j = 0; j < s.pts.length; j++) {\n var p = s.pts[j], X = Math.round(p[0] * 2), Y = Math.round(p[1] * 2), Wq = Math.round(p[2] * 4);\n put(X - px); put(Y - py); put(Wq - pw); put(Math.round(p[3] || 0));\n px = X; py = Y; pw = Wq;\n }\n }\n var bin = ''; for (var k = 0; k < out.length; k++) bin += String.fromCharCode(out[k]);\n return b64e(bin);\n }\n function decode(str) {\n var bin = b64d(str), i = 0;\n function get() { var n = 0, m = 1, b; do { if (i >= bin.length) throw new Error('truncated'); b = bin.charCodeAt(i++); n += (b & 127) * m; m *= 128; } while (b & 128); return unzz(n); }\n var ver = get(); if (ver !== 1) throw new Error('version ' + ver);\n var n = get(), strokes = [];\n for (var s = 0; s < n; s++) {\n var tool = TOOLS[get()], ink = get(), gap = get(), c = get(), pts = [], px = 0, py = 0, pw = 0;\n if (!tool || c < 0 || c > 1e6) throw new Error('bad stroke');\n for (var j = 0; j < c; j++) { px += get(); py += get(); pw += get(); pts.push([px / 2, py / 2, pw / 4, get()]); }\n strokes.push({tool: tool, ink: ink, gap: gap, pts: pts});\n }\n return strokes;\n }\n var B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n function b64e(bin) {\n if (typeof btoa === 'function') return btoa(bin);\n var o = '';\n for (var i = 0; i < bin.length; i += 3) {\n var a = bin.charCodeAt(i), b = bin.charCodeAt(i + 1), c = bin.charCodeAt(i + 2), n = (a << 16) | ((b || 0) << 8) | (c || 0);\n o += B64[n >> 18 & 63] + B64[n >> 12 & 63] + (i + 1 < bin.length ? B64[n >> 6 & 63] : '=') + (i + 2 < bin.length ? B64[n & 63] : '=');\n }\n return o;\n }\n function b64d(s) {\n if (typeof atob === 'function') return atob(s);\n var o = '', buf = 0, bits = 0;\n for (var i = 0; i < s.length; i++) {\n var v = B64.indexOf(s[i]); if (v < 0) continue;\n buf = (buf << 6) | v; bits += 6;\n if (bits >= 8) { bits -= 8; o += String.fromCharCode((buf >> bits) & 255); }\n }\n return o;\n }\n\n\n // ---- the squiggle's dots ------------------------------------------------------------\n // The squiggle is printed as dots every DOT units along the line; `upto` (0..1) is how much\n // has been printed so far, and the newest dots swell into place. Where the line crosses\n // itself a dot that would land on an earlier one is left out (radius 0), so the crossing\n // reads as one line and not as a blot.\n var DOT = 15, DOTR = 4.2;\n function dots(pts, upto) {\n if (upto == null) upto = 1;\n var out = [], acc = 0, next = 0, total = 0, i;\n for (i = 1; i < pts.length; i++) total += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);\n var n = Math.max(1, Math.round(total / DOT)), step = total / n, lim = upto * total;\n for (i = 1; i < pts.length && next <= total + 0.01; i++) {\n var L = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);\n while (next <= acc + L + 0.01 && next <= total + 0.01) {\n if (next > lim + 0.01) return out;\n var f = L ? (next - acc) / L : 0, grow = Math.min(1, (lim - next) / (DOT * 3) + 0.25);\n var X = pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * f, Y = pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * f;\n var R = DOTR * (upto >= 1 ? 1 : grow);\n for (var c = 0; c < out.length - 2; c++)\n if (Math.hypot(out[c][0] - X, out[c][1] - Y) < DOT * 0.7) { R = 0; break; }\n out.push([X, Y, R]);\n next += step;\n }\n acc += L;\n }\n return out;\n }\n // Any pen that passes over a dot takes it in (the eraser too: it rubs the print away).\n // Returns the indices it took, so the page can answer each one.\n function absorb(list, hid, pts) {\n var got = [];\n for (var j = 0; j < pts.length; j++) {\n var r = pts[j][2] / 2 + 10, x = pts[j][0], y = pts[j][1];\n for (var q = 0; q < list.length; q++) {\n if (hid[q] || !list[q][2]) continue;\n var dx = list[q][0] - x, dy = list[q][1] - y;\n if (dx < r && dx > -r && dy < r && dy > -r && dx * dx + dy * dy < r * r) { hid[q] = 1; got.push(q); }\n }\n }\n // a dot or two left stranded between taken ones reads as a slip, not as a prompt\n for (var k = 0; k < list.length; k++) {\n if (hid[k]) continue;\n var e = k; while (e < list.length && !hid[e]) e++;\n if (e - k <= 2 && k > 0 && e < list.length) for (var m = k; m < e; m++) { hid[m] = 1; got.push(m); }\n k = e;\n }\n return got;\n }\n function covered(list, strokes) {\n var hid = new Uint8Array(list.length);\n for (var i = 0; i < strokes.length; i++) absorb(list, hid, strokes[i].pts);\n return hid;\n }\n\n // ---- sheets, the pad and the sketchbook ---------------------------------------------\n // A sheet: {id, kind: 'day' | 'extra', day, seed, wide, created, torn, paper, rule, strokes, redo}.\n // The pad holds one sheet; the sketchbook holds the torn ones, newest first.\n function sheet(o) {\n return {id: o.id, kind: o.kind, day: o.day, seed: o.seed >>> 0, wide: !!o.wide, created: o.created || 0,\n torn: o.torn || 0, n: o.n || 0, tip: !!o.tip, paper: pick(o.paper, PAPERS), rule: pick(o.rule, RULES), strokes: o.strokes || [], redo: []};\n }\n function pick(i, list) { return i >= 0 && i < list.length ? i | 0 : 0; }\n // a new sheet comes off the pad on the paper the person chose last\n function look(sh, opt) { if (opt) { sh.paper = pick(opt.paper, PAPERS); sh.rule = pick(opt.rule, RULES); } return sh; }\n function addStroke(sh, st) { sh.strokes.push(st); sh.redo.length = 0; }\n function undo(sh) { var st = sh.strokes.pop(); if (st) sh.redo.push(st); return st || null; }\n function redo(sh) { var st = sh.redo.pop(); if (st) sh.strokes.push(st); return st || null; }\n function inked(sh) { return !!sh && sh.strokes.length > 0; }\n function pack(sh) {\n return {id: sh.id, kind: sh.kind, day: sh.day, seed: sh.seed, wide: sh.wide, created: sh.created, torn: sh.torn,\n n: sh.n, tip: sh.tip, paper: sh.paper, rule: sh.rule, data: encode(sh.strokes)};\n }\n function unpack(o) {\n var sh = sheet(o);\n if (o.data) sh.strokes = decode(o.data);\n return sh;\n }\n\n // `opt` brings what the core cannot know: {wide, now, id(), seed()}.\n function daySheet(day, opt) { return look(sheet({id: opt.id(), kind: 'day', day: day, seed: daySeed(day), wide: opt.wide, created: opt.now, n: 1}), opt); }\n // The extra sheets of a day are numbered after today's: sheet 2, sheet 3... (n 0: one that came in a link)\n function extraSheet(seed, today, opt, n) { return look(sheet({id: opt.id(), kind: 'extra', day: today, seed: seed, wide: opt.wide, created: opt.now, n: n || 0}), opt); }\n function nextNumber(st, today) {\n var n = 1;\n st.book.forEach(function (b) { if (b.day === today && b.n > 0) n = Math.max(n, b.n + 1); else if (b.kind === 'day' && b.day === today) n = Math.max(n, 2); });\n if (st.pad && st.pad.day === today) n = Math.max(n, (st.pad.kind === 'day' ? 1 : st.pad.n) + 1);\n return Math.max(2, n);\n }\n function file(st, sh, now) { sh.torn = now; sh.redo = []; st.book.unshift(sh); return sh; }\n function tornToday(st, today) { return st.book.some(function (b) { return b.kind === 'day' && b.day === today; }); }\n\n // Opening the pad. On a new day today's sheet goes on top and the one that was there is\n // filed if it has ink in it; the same day leaves the pad as it was. Returns what was filed.\n function open(st, today, opt) {\n var filed = [];\n if (st.day !== today || !st.pad) {\n if (st.day !== today && st.pad && !(st.pad.kind === 'day' && st.pad.day === today)) {\n if (inked(st.pad)) filed.push(file(st, st.pad, opt.now));\n st.pad = null;\n }\n if (!st.pad) st.pad = tornToday(st, today) ? extraSheet(opt.seed(), today, opt, nextNumber(st, today)) : daySheet(today, opt);\n }\n st.day = today;\n return filed;\n }\n // Tearing the sheet off: filed if it has ink, and the next sheet carries a fresh squiggle.\n function tear(st, today, opt) {\n var n = nextNumber(st, today), out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n st.pad = extraSheet(opt.seed(), today, opt, n);\n return out;\n }\n // Taking a sheet back out of the sketchbook to draw on it again.\n function reopen(st, id, opt) {\n var i = indexOf(st, id); if (i < 0) return null;\n var sh = st.book.splice(i, 1)[0], out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n sh.torn = 0; st.pad = sh;\n return out;\n }\n // A squiggle that came in a link goes on a fresh sheet.\n function receive(st, kind, value, today, opt) {\n if (kind === 'day' && value === today && st.pad && st.pad.kind === 'day' && st.pad.day === today) return null;\n var out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n st.pad = kind === 'day' ? daySheet(value, opt) : extraSheet(value, today, opt, 0);\n return out;\n }\n function remove(st, id) { var i = indexOf(st, id); return i < 0 ? null : {sheet: st.book.splice(i, 1)[0], index: i}; }\n function restore(st, r) { st.book.splice(Math.min(r.index, st.book.length), 0, r.sheet); }\n function indexOf(st, id) { for (var i = 0; i < st.book.length; i++) if (st.book[i].id === id) return i; return -1; }\n\n // How long a replay of these strokes takes: real timing, pauses capped, then squeezed\n // so a sheet never takes longer than `max` ms to draw itself again.\n function replayPlan(strokes, max) {\n var total = 0, marks = [];\n for (var i = 0; i < strokes.length; i++) {\n total += Math.min(350, strokes[i].gap || 0);\n var start = total;\n for (var j = 0; j < strokes[i].pts.length; j++) total += Math.min(60, strokes[i].pts[j][3] || 0);\n marks.push([start, total]);\n }\n var k = total > max ? max / total : 1;\n return {duration: total * k, scale: k, marks: marks.map(function (m) { return [m[0] * k, m[1] * k]; })};\n }\n\n return {W: W, H: H, rng: rng, hash: hash, dayNumber: dayNumber, dayDate: dayDate, daySeed: daySeed,\n codeFor: codeFor, seedFor: seedFor, squiggle: squiggle, crossings: crossings, turning: turning, bbox: bbox, BOX: BOX_TALL, BOX_WIDE: BOX_WIDE, sheetSize: sheetSize,\n TOOLS: TOOLS, INKS: INKS, inkColor: inkColor, inkOf: inkOf, validInk: validInk, BASE: BASE, SIZES: SIZES, PAPERS: PAPERS, RULES: RULES, Pen: Pen, encode: encode, decode: decode, replayPlan: replayPlan,\n DOT: DOT, DOTR: DOTR, dots: dots, absorb: absorb, covered: covered,\n sheet: sheet, addStroke: addStroke, undo: undo, redo: redo, inked: inked, pack: pack, unpack: unpack,\n nextNumber: nextNumber, open: open, tear: tear, reopen: reopen, receive: receive, remove: remove, restore: restore};\n})();\n</script>\n<script id=\"ink\">\n// Ink: lays strokes onto a canvas the way each pen would put them on paper. Everything is in\n// page units; `s` is canvas pixels per unit.\nvar Ink = (function () {\n 'use strict';\n var PAPER = '#f5efe2', PRINT = '#e4553a';\n var tiles = {};\n\n // Paper tooth: a binary mask of where a dry point catches the grain. Sized in page units,\n // so the pencil looks the same on a phone and a monitor.\n function tooth(kind, s) {\n var key = kind + s.toFixed(3);\n if (tiles[key]) return tiles[key];\n var N = kind === 'paper' ? 512 : 256, c = document.createElement('canvas'); c.width = c.height = N;\n var g = c.getContext('2d'), img = g.createImageData(N, N), d = img.data;\n var cell = Math.max(1, 1.6 * s), r = SQ.rng(kind === 'print' ? 11 : 7);\n var gw = Math.ceil(N / cell) + 2, grid = new Float32Array(gw * gw);\n for (var i = 0; i < grid.length; i++) grid[i] = r();\n // wrap so the tile repeats without a seam\n var cols = Math.round(N / cell); if (cols < 1) cols = 1;\n for (var y = 0; y < N; y++) for (var x = 0; x < N; x++) {\n var fx = x / N * cols, fy = y / N * cols, ix = Math.floor(fx), iy = Math.floor(fy), tx = fx - ix, ty = fy - iy;\n var a = grid[(iy % cols) * gw + ix % cols], b = grid[(iy % cols) * gw + (ix + 1) % cols];\n var cc = grid[((iy + 1) % cols) * gw + ix % cols], dd = grid[((iy + 1) % cols) * gw + (ix + 1) % cols];\n tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);\n var v = (a + (b - a) * tx) * (1 - ty) + (cc + (dd - cc) * tx) * ty;\n v = v * 0.7 + r() * 0.3;\n var o = (y * N + x) * 4;\n d[o] = d[o + 1] = d[o + 2] = 0;\n if (kind === 'pencil') d[o + 3] = v > 0.3 ? 255 : (v > 0.22 ? 120 : 0);\n else if (kind === 'print') d[o + 3] = v > 0.12 ? 255 : 90;\n else if (kind === 'marker') d[o + 3] = v > 0.2 ? 255 : 150;\n else { d[o] = d[o + 1] = d[o + 2] = v > 0.5 ? 255 : 70; d[o + 3] = Math.round(Math.abs(v - 0.5) * 50); }\n }\n g.putImageData(img, 0, 0);\n return (tiles[key] = c);\n }\n\n // A sheet's paper: its colour, its grain, and whatever ruling it was printed with.\n function paper(ctx, wpx, hpx, s, sh) {\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 1;\n ctx.fillStyle = SQ.PAPERS[sh && sh.paper] || PAPER; ctx.fillRect(0, 0, wpx, hpx);\n rule(ctx, SQ.RULES[sh && sh.rule], wpx / s, hpx / s, s);\n ctx.fillStyle = ctx.createPattern(tooth('paper', s), 'repeat'); ctx.fillRect(0, 0, wpx, hpx);\n ctx.restore();\n }\n var GAP = 40; // the ruling's pitch, in page units: a school exercise book's\n function rule(ctx, kind, w, h, s) {\n if (!kind || kind === 'plain') return;\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n var x0 = (w % GAP) / 2, y0 = (h % GAP) / 2;\n if (kind === 'dots') {\n ctx.fillStyle = 'rgba(60,80,100,.42)'; ctx.beginPath();\n for (var x = x0; x <= w; x += GAP) for (var y = y0; y <= h; y += GAP) { ctx.moveTo(x + 1.8, y); ctx.arc(x, y, 1.8, 0, 6.2832); }\n ctx.fill();\n } else {\n ctx.strokeStyle = 'rgba(70,110,150,.3)'; ctx.lineWidth = Math.max(1 / s, 1.3); ctx.beginPath();\n var top = kind === 'lined' ? 200 : y0; // lines start below the printed head\n for (var yy = top; yy <= h - 30; yy += GAP) { ctx.moveTo(0, yy); ctx.lineTo(w, yy); }\n if (kind === 'grid') for (var xx = x0; xx <= w; xx += GAP) { ctx.moveTo(xx, 0); ctx.lineTo(xx, h); }\n ctx.stroke();\n if (kind === 'lined') { ctx.strokeStyle = 'rgba(200,80,70,.32)'; ctx.beginPath(); ctx.moveTo(60, 0); ctx.lineTo(60, h); ctx.stroke(); }\n }\n ctx.restore();\n }\n\n // Segments of a stroke between point i0 and i1 (exclusive end), as quadratic curves through\n // the midpoints, so a stroke drawn a piece at a time looks the same as one drawn whole.\n function segments(ctx, pts, i0, i1, variable) {\n var n = pts.length;\n if (n === 1) {\n if (i0 > 0) return;\n ctx.beginPath(); ctx.arc(pts[0][0], pts[0][1], pts[0][2] / 2, 0, 6.2832); ctx.fill(); return;\n }\n if (!variable) ctx.beginPath();\n for (var k = Math.max(0, i0); k < Math.min(i1, n); k++) {\n // segment k runs from m(k-1) to m(k) with control p[k]; m(-1)=p0, m(n-1)=p(n-1)\n var a = k === 0 ? pts[0] : mid(pts[k - 1], pts[k]);\n var b = k >= n - 1 ? pts[n - 1] : mid(pts[k], pts[k + 1]);\n var c = pts[k];\n if (!variable) {\n ctx.moveTo(a[0], a[1]); ctx.quadraticCurveTo(c[0], c[1], b[0], b[1]);\n continue;\n }\n var L = Math.hypot(c[0] - a[0], c[1] - a[1]) + Math.hypot(b[0] - c[0], b[1] - c[1]);\n var m = Math.max(1, Math.ceil(L / 2.5)), px = a[0], py = a[1];\n for (var j = 1; j <= m; j++) {\n var t = j / m, u = 1 - t;\n var x = u * u * a[0] + 2 * u * t * c[0] + t * t * b[0], y = u * u * a[1] + 2 * u * t * c[1] + t * t * b[1];\n ctx.lineWidth = a[2] + (b[2] - a[2]) * (t - 0.5 / m);\n ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x, y); ctx.stroke();\n px = x; py = y;\n }\n }\n if (!variable) ctx.stroke();\n }\n function offset(pts, o) {\n var out = [], n = pts.length;\n for (var i = 0; i < n; i++) {\n var a = pts[Math.max(0, i - 1)], b = pts[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1;\n out.push([pts[i][0] - dy / L * o, pts[i][1] + dx / L * o, pts[i][2]]);\n }\n return out;\n }\n function mid(p, q) { return [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]; }\n\n function style(tool) {\n // how the opaque shape is laid onto the sheet\n switch (tool) {\n case 'pencil': return {alpha: 0.88, op: 'multiply', mask: 'pencil'};\n case 'marker': return {alpha: 0.82, op: 'multiply', mask: 'marker'};\n case 'eraser': return {alpha: 1, op: 'destination-out', paper: true};\n case 'print': return {alpha: 0.95, op: 'multiply', mask: 'print'};\n case 'brush': return {alpha: 1, op: 'source-over', scratch: true};\n default: return {alpha: 1, op: 'source-over'};\n }\n }\n\n // Brush pens lift off to a point: the last stretch of a finished stroke narrows.\n function tapered(st, floor, len) {\n var p = st.pts, n = p.length, out = new Array(n), L = 0, i;\n var acc = new Float32Array(n);\n for (i = n - 1; i > 0; i--) { acc[i - 1] = acc[i] + Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]); }\n L = acc[0];\n var T = Math.min(len, L * 0.35), S0 = Math.min(len * 0.45, L * 0.2);\n for (i = 0; i < n; i++) {\n var k = T > 0 ? Math.min(1, floor + (1 - floor) * acc[i] / T) : 1;\n if (S0 > 0) k *= Math.min(1, (floor < 0.3 ? 0.25 : 0.45) + (floor < 0.3 ? 0.75 : 0.55) * (L - acc[i]) / S0); // and touches down to a point too\n out[i] = [p[i][0], p[i][1], p[i][2] * k];\n }\n return out;\n }\n\n // Draw a stroke opaque into `ctx` (a live layer, or scratch) - shape only.\n function shape(ctx, st, s, done) {\n var color = st.tool === 'print' ? PRINT : st.tool === 'eraser' ? '#000' : SQ.inkColor(st.ink);\n var pts = (st.tool === 'brush' || st.tool === 'fine') && done ? tapered(st, st.tool === 'fine' ? 0.55 : 0.12, st.tool === 'fine' ? 14 : 60) : st.pts, n = pts.length;\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n ctx.lineCap = ctx.lineJoin = 'round';\n if (st.tool === 'print') { // printed: an even row of dots, laid by a machine\n ctx.fillStyle = color;\n var d = st.dots || SQ.dots(pts, st.upto);\n ctx.beginPath();\n for (var q = 0; q < d.length; q++) {\n if (!d[q][2] || (st.hidden && st.hidden[q])) continue;\n ctx.moveTo(d[q][0] + d[q][2], d[q][1]); ctx.arc(d[q][0], d[q][1], d[q][2], 0, 6.2832);\n }\n ctx.fill();\n ctx.restore(); return;\n }\n ctx.strokeStyle = ctx.fillStyle = color;\n if (st.tool === 'marker') {\n chisel(ctx, pts);\n if (done && n > 8) { // the felt floods where it starts and stops\n ctx.globalCompositeOperation = 'destination-out'; ctx.globalAlpha = 0.14;\n chisel(ctx, pts.slice(3, n - 3));\n // and runs a little drier in lines, the way the felt was pulled\n var r = SQ.rng(Math.round(pts[0][0] * 7 + pts[0][1] * 13)), W = pts[0][2];\n ctx.lineCap = 'round'; ctx.lineWidth = W * 0.06;\n for (var q = 0; q < 4; q++) {\n ctx.globalAlpha = 0.05 + r() * 0.06;\n var off = offset(pts, (r() - 0.5) * W * 0.62);\n segments(ctx, off, 0, off.length, false);\n }\n }\n ctx.restore(); return;\n }\n var variable = st.tool === 'brush' || st.tool === 'fine';\n if (!variable) ctx.lineWidth = pts[0][2];\n segments(ctx, pts, 0, n, variable);\n if (st.tool === 'brush' && done) dry(ctx, pts);\n ctx.restore();\n }\n\n // Live drawing: only the segments i0..i1 of an unfinished stroke, opaque, onto a layer that\n // already holds the ones before. Returns the pixel box it touched, for finish().\n function part(ctx, st, s, i0, i1) {\n var color = st.tool === 'eraser' ? '#000' : SQ.inkColor(st.ink), pts = st.pts, n = pts.length;\n var a = Math.max(0, i0 - 1), sub = {pts: pts.slice(a, Math.min(n, i1 + 1))};\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0); ctx.lineCap = ctx.lineJoin = 'round';\n ctx.strokeStyle = ctx.fillStyle = color;\n if (st.tool === 'marker') chisel(ctx, sub.pts);\n else { if (st.tool !== 'brush' && st.tool !== 'fine') ctx.lineWidth = pts[0][2]; segments(ctx, pts, i0, i1, st.tool === 'brush' || st.tool === 'fine'); }\n ctx.restore();\n return bounds(sub, s, ctx.canvas.width, ctx.canvas.height);\n }\n\n // A chisel nib held at a slant: wide pulled one way, thin the other, square at the ends.\n var NIB = -0.62;\n function chisel(ctx, pts) {\n var W = pts[0][2], hx = Math.cos(NIB) * W * 0.42, hy = Math.sin(NIB) * W * 0.42;\n var q = sample(pts, 2.5);\n ctx.beginPath();\n for (var i = 0; i < q.length; i++) {\n var x = q[i][0], y = q[i][1];\n if (i) { var px = q[i - 1][0], py = q[i - 1][1];\n ctx.moveTo(px + hx, py + hy); ctx.lineTo(x + hx, y + hy); ctx.lineTo(x - hx, y - hy); ctx.lineTo(px - hx, py - hy); ctx.closePath(); }\n }\n ctx.fill('nonzero');\n // the felt tip itself: a worn wedge with soft corners\n ctx.lineWidth = W * 0.18; ctx.lineCap = 'round'; ctx.beginPath();\n for (var j = 0; j < q.length; j++) { ctx.moveTo(q[j][0] + hx, q[j][1] + hy); ctx.lineTo(q[j][0] - hx, q[j][1] - hy); }\n ctx.stroke();\n }\n // The smoothed centre line of a stroke, every `d` units.\n function sample(pts, d) {\n var out = [], n = pts.length;\n if (n === 1) return [pts[0]];\n for (var k = 0; k < n; k++) {\n var a = k === 0 ? pts[0] : mid(pts[k - 1], pts[k]), b = k >= n - 1 ? pts[n - 1] : mid(pts[k], pts[k + 1]), c = pts[k];\n var L = Math.hypot(c[0] - a[0], c[1] - a[1]) + Math.hypot(b[0] - c[0], b[1] - c[1]), m = Math.max(1, Math.ceil(L / d));\n for (var j = k ? 1 : 0; j <= m; j++) { var t = j / m, u = 1 - t;\n out.push([u * u * a[0] + 2 * u * t * c[0] + t * t * b[0], u * u * a[1] + 2 * u * t * c[1] + t * t * b[1], a[2] + (b[2] - a[2]) * t]); }\n }\n return out;\n }\n // Where a brush pen ran fast it runs dry: hairline gaps open along the stroke.\n function dry(ctx, pts) {\n var q = sample(pts, 2), max = 0, i;\n for (i = 0; i < q.length; i++) if (q[i][2] > max) max = q[i][2];\n var thr = max * 0.42, r = SQ.rng(Math.round(pts[0][0] * 31 + pts[0][1] * 17));\n ctx.save(); ctx.globalCompositeOperation = 'destination-out'; ctx.lineCap = 'round';\n var offs = [-0.34 + r() * 0.08, 0.3 + r() * 0.08];\n for (var o = 0; o < offs.length; o++) {\n for (i = 1; i < q.length; i++) {\n var w = q[i][2]; if (w > thr || q[i - 1][2] > thr) continue;\n var k = 1 - w / thr; // drier the thinner (faster) it got\n var dx = q[i][0] - q[i - 1][0], dy = q[i][1] - q[i - 1][1], L = Math.hypot(dx, dy) || 1, nx = -dy / L, ny = dx / L;\n ctx.globalAlpha = Math.min(0.55, k * 0.9); ctx.lineWidth = Math.max(0.35, w * 0.12);\n ctx.beginPath(); ctx.moveTo(q[i - 1][0] + nx * offs[o] * q[i - 1][2], q[i - 1][1] + ny * offs[o] * q[i - 1][2]); ctx.lineTo(q[i][0] + nx * offs[o] * w, q[i][1] + ny * offs[o] * w); ctx.stroke();\n }\n }\n ctx.restore();\n }\n function bounds(st, s, wpx, hpx) {\n var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;\n for (var i = 0; i < st.pts.length; i++) {\n var p = st.pts[i], r = p[2] / 2 + 5;\n if (p[0] - r < x0) x0 = p[0] - r; if (p[0] + r > x1) x1 = p[0] + r;\n if (p[1] - r < y0) y0 = p[1] - r; if (p[1] + r > y1) y1 = p[1] + r;\n }\n x0 = Math.max(0, Math.floor(x0 * s) - 2); y0 = Math.max(0, Math.floor(y0 * s) - 2);\n x1 = Math.min(wpx, Math.ceil(x1 * s) + 2); y1 = Math.min(hpx, Math.ceil(y1 * s) + 2);\n return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null;\n }\n // After drawing shape into a layer, give it its material (paper grain or the paper itself).\n function finish(ctx, st, s, box, paperCanvas) {\n var sty = style(st.tool);\n if (!box) return;\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0);\n if (sty.mask) { // destination-in clears all it is not drawn over: keep it to the box\n ctx.beginPath(); ctx.rect(box[0], box[1], box[2], box[3]); ctx.clip();\n ctx.globalCompositeOperation = 'destination-in';\n ctx.fillStyle = ctx.createPattern(tooth(sty.mask, s), 'repeat');\n ctx.fillRect(box[0], box[1], box[2], box[3]);\n } else if (sty.paper && paperCanvas) {\n ctx.globalCompositeOperation = 'source-atop';\n ctx.drawImage(paperCanvas, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n }\n ctx.restore();\n }\n\n // Lay a whole stroke onto the sheet.\n var scratch = null;\n function draw(ctx, st, s, paperCanvas) {\n var wpx = ctx.canvas.width, hpx = ctx.canvas.height, sty = style(st.tool);\n if (sty.alpha === 1 && sty.op === 'source-over' && !sty.mask && !sty.paper && !sty.scratch) { shape(ctx, st, s, true); return; }\n if (!scratch) scratch = document.createElement('canvas');\n if (scratch.width < wpx || scratch.height < hpx) { scratch.width = Math.max(scratch.width, wpx); scratch.height = Math.max(scratch.height, hpx); }\n var g = scratch.getContext('2d'), box = bounds(st, s, wpx, hpx);\n if (!box) return;\n g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(box[0], box[1], box[2], box[3]);\n g.save(); g.beginPath(); g.rect(box[0], box[1], box[2], box[3]); g.clip();\n shape(g, st, s, true);\n g.restore();\n finish(g, st, s, box, paperCanvas);\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = sty.alpha; ctx.globalCompositeOperation = sty.op;\n ctx.drawImage(scratch, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n ctx.restore();\n }\n\n return {part: part, PAPER: PAPER, PRINT: PRINT, paper: paper, draw: draw, shape: shape, finish: finish, bounds: bounds, style: style, tooth: tooth};\n})();\n</script>\n<script>\n(function () {\n'use strict';\nvar $ = function (id) { return document.getElementById(id); };\nvar KEY = 'squiggle', reduced = matchMedia('(prefers-reduced-motion: reduce)');\nvar DPR = function () { return Math.min(2, window.devicePixelRatio || 1); };\nvar TOOL_NAMES = {pencil: 'Pencil', fine: 'Fineliner', brush: 'Brush pen', marker: 'Chisel marker', eraser: 'Eraser'};\nvar INK_NAMES = ['Blue-black', 'Cobalt', 'Leaf', 'Ochre', 'Rose', 'Plum'];\n\n// ---- state -----------------------------------------------------------------------------\nvar S = {pad: null, book: [], day: 0};\nvar MIXED = 5;\nvar P = {mixed: [], size: {}, paper: 0, rule: 0, date: true, number: true, lang: '', tool: 'brush', ink: 0, mute: false, hinted: false, strokes: 0, printed: false, torn: 0};\nvar opt = function (wide) {\n return {wide: wide, now: Date.now(), paper: P.paper, rule: P.rule, id: function () { return 's' + Date.now().toString(36) + Math.floor(Math.random() * 1e6).toString(36); },\n seed: function () { return Math.floor(Math.random() * 1073741824); }}; // 30 bits: what a six-letter code carries\n};\n\nfunction load() {\n var raw = null;\n try { raw = JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { raw = null; }\n if (raw && raw.v === 1) {\n try { S.pad = raw.pad ? SQ.unpack(raw.pad) : null; } catch (e) { S.pad = null; }\n S.book = (raw.book || []).map(function (o) { try { return SQ.unpack(o); } catch (e) { return null; } }).filter(Boolean);\n S.day = raw.day || 0;\n if (raw.prefs) for (var k in P) if (k in raw.prefs) P[k] = raw.prefs[k];\n }\n if (SQ.TOOLS.indexOf(P.tool) < 0) P.tool = 'brush';\n if (!SQ.validInk(P.ink)) P.ink = 0;\n var sz = {}; SQ.TOOLS.forEach(function (t) { var v = P.size && P.size[t]; sz[t] = v >= 0 && v < SQ.SIZES.length ? v | 0 : 2; }); P.size = sz;\n if (!(P.paper >= 0 && P.paper < SQ.PAPERS.length)) P.paper = 0;\n if (!(P.rule >= 0 && P.rule < SQ.RULES.length)) P.rule = 0;\n P.date = P.date !== false; P.number = P.number !== false; if (P.lang !== 'en') P.lang = '';\n P.mixed = (Array.isArray(P.mixed) ? P.mixed : []).filter(function (v) { return v >= 16 && SQ.validInk(v); }).slice(0, MIXED);\n}\nvar saveT = 0, warned = false;\nfunction save(now) {\n clearTimeout(saveT);\n var go = function () {\n try {\n localStorage.setItem(KEY, JSON.stringify({v: 1, day: S.day, pad: S.pad ? SQ.pack(S.pad) : null, book: S.book.map(SQ.pack), prefs: P}));\n } catch (e) {\n if (!warned) { warned = true; toast('The sketchbook is full. Save a few sheets as images and remove them.'); }\n }\n };\n if (now) go(); else saveT = setTimeout(go, 250);\n}\n\n// ---- layout ----------------------------------------------------------------------------\nvar root = document.documentElement, side = false, dims = {w: 1000, h: 1500}, scale = 1, cssW = 300, cssH = 450;\nvar C = {paper: $('cPaper'), dots: $('cDots'), ink: $('cInk'), live: $('cLive')}, X = {};\nfor (var k in C) X[k] = C[k].getContext('2d');\n\nfunction wantSide() { return innerWidth / innerHeight > 1.15 && innerWidth >= 640; }\nfunction layout() {\n side = wantSide();\n root.classList.toggle('side', side);\n var book = $('bookBtn');\n (side ? $('top2') : $('top')).appendChild(book);\n if (side) { document.querySelector('.acts').appendChild($('mute')); document.querySelector('.acts').appendChild($('setBtn')); }\n else { $('topL').appendChild($('mute')); $('topL').appendChild($('setBtn')); }\n closeSizes();\n dims = SQ.sheetSize(S.pad && S.pad.wide);\n root.classList.toggle('tallsheet', !!(S.pad && !S.pad.wide));\n var aw, ah;\n if (side) {\n var k = Math.min(1, (innerHeight - 60) / 600);\n $('col').style.setProperty('--k', k.toFixed(3));\n aw = innerWidth - 144 - 236 - 40 - 60; ah = innerHeight - 28 - 70;\n } else {\n var st = $('stage').getBoundingClientRect(), cs = getComputedStyle($('stage'));\n aw = st.width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);\n ah = st.height - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom) - 14;\n }\n var ratio = dims.h / dims.w;\n cssW = Math.max(120, Math.floor(Math.min(aw, ah / ratio)));\n cssH = Math.round(cssW * ratio);\n var pad = $('pad');\n root.style.setProperty('--pw', cssW + 'px'); root.style.setProperty('--ph', cssH + 'px');\n pad.style.setProperty('--pw', cssW + 'px'); pad.style.setProperty('--ph', cssH + 'px');\n var cs2 = Math.round(Math.min(cssW, cssH) * 0.13);\n pad.style.setProperty('--cs', cs2 + 'px');\n var px = Math.round(cssW * DPR()), py = Math.round(cssH * DPR());\n for (var n in C) { C[n].width = px; C[n].height = py; }\n scale = px / dims.w;\n curlSize = cs2; drawCurl(0);\n redrawAll();\n}\n\n// ---- the sheet's layers ------------------------------------------------------------------\nvar squig = null, dotList = [], hidden = new Uint8Array(0), printUpto = 1;\nfunction setSheet() {\n var sh = S.pad;\n squig = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n dotList = SQ.dots(squig.pts, 1);\n hidden = SQ.covered(dotList, sh.strokes);\n $('sheet').setAttribute('aria-label', 'Sheet for ' + dateLabel(sh) + ', with a dotted squiggle to turn into a drawing');\n}\nfunction dateLabel(sh) {\n var d = sh.kind === 'day' ? SQ.dayDate(sh.day) : new Date(sh.created || Date.now());\n return d.toLocaleDateString(P.lang || undefined, {weekday: 'long', day: 'numeric', month: 'long'});\n}\n// The printed head of a sheet: the date and, at the right, which of the day's sheets it is. The\n// first few sheets someone ever gets also print the one line of instructions there is.\nfunction header(ctx, sh, s, w) {\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n ctx.textBaseline = 'alphabetic';\n ctx.fillStyle = '#5f574b'; ctx.font = '500 34px Fraunces, Georgia, serif';\n if (P.date) ctx.fillText(dateLabel(sh), 72, 108);\n if (sh.tip) {\n ctx.fillStyle = Ink.PRINT;\n for (var i = 0; i < 3; i++) { ctx.beginPath(); ctx.arc(77 + i * 12, 140, 4.2, 0, 6.2832); ctx.fill(); }\n ctx.fillStyle = '#8f8473'; ctx.font = 'italic 400 26px Fraunces, Georgia, serif';\n ctx.fillText('Turn the squiggle into anything', 113, 148);\n }\n var tag = P.number ? sheetTag(sh) || 'No. ' + sh.day : '';\n if (tag) { ctx.textAlign = 'right'; ctx.fillStyle = '#a89c86'; ctx.font = 'italic 400 24px Fraunces, Georgia, serif'; ctx.fillText(tag, w - 72, 108); }\n ctx.restore();\n}\nfunction sheetTag(sh) { return sh.kind === 'day' ? '' : sh.n >= 2 ? 'sheet ' + sh.n + ', just yours' : 'sent to you'; }\n// a sheet that has just been laid on the pad\nfunction laid(before) { if (S.pad !== before && !S.pad.strokes.length) S.pad.tip = P.torn < 3; }\nfunction drawPaper() {\n Ink.paper(X.paper, C.paper.width, C.paper.height, scale, S.pad);\n $('sheet').style.background = SQ.PAPERS[S.pad.paper];\n header(X.paper, S.pad, scale, dims.w);\n}\nfunction drawDots() {\n var g = X.dots; g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, C.dots.width, C.dots.height);\n var list = printUpto >= 1 ? dotList : SQ.dots(squig.pts, printUpto);\n Ink.draw(g, {tool: 'print', pts: squig.pts, dots: list, hidden: hidden}, scale, null);\n}\nfunction drawInk() {\n var g = X.ink; g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, C.ink.width, C.ink.height);\n var st = S.pad.strokes;\n for (var i = 0; i < st.length; i++) Ink.draw(g, st[i], scale, C.paper);\n}\nfunction redrawAll() { drawPaper(); drawDots(); drawInk(); clearLive(); updateActs(); }\nfunction clearLive() { X.live.setTransform(1, 0, 0, 1, 0, 0); X.live.clearRect(0, 0, C.live.width, C.live.height); }\n\n// ---- drawing -----------------------------------------------------------------------------\nvar cur = null, pen = null, touches = new Map(), gesture = null, sawPen = false, lastEnd = 0;\nvar sheetEl = $('sheet');\nfunction toPage(e) {\n var r = sheetEl.getBoundingClientRect();\n return [(e.clientX - r.left) / r.width * dims.w, (e.clientY - r.top) / r.height * dims.h];\n}\nsheetEl.addEventListener('pointerdown', function (e) {\n if (e.button > 0 || busy) return;\n unlock();\n if (e.pointerType === 'pen') sawPen = true;\n if (e.pointerType === 'touch') {\n if (sawPen) return; // a pencil is in use: a resting palm is not a stroke\n touches.set(e.pointerId, {x: e.clientX, y: e.clientY, t: performance.now()});\n if (touches.size >= 2) { startGesture(); return; }\n }\n try { sheetEl.setPointerCapture(e.pointerId); } catch (_) {}\n var p = toPage(e), t = performance.now();\n pen = new SQ.Pen(P.tool, p[0], p[1], t, e.pointerType === 'pen' ? e.pressure : -1, SQ.SIZES[P.size[P.tool]]);\n cur = {tool: P.tool, ink: P.ink, gap: lastEnd ? Math.min(5000, Math.round(t - lastEnd)) : 0, pts: pen.pts, id: e.pointerId};\n C.live.className = Ink.style(P.tool).op === 'multiply' ? 'multiply' : '';\n C.live.style.opacity = P.tool === 'eraser' ? 1 : Ink.style(P.tool).alpha;\n absorbLive(pen.pts);\n paintLive();\n scratchStart(P.tool);\n});\nsheetEl.addEventListener('pointermove', function (e) {\n if (touches.has(e.pointerId)) { var tt = touches.get(e.pointerId); tt.mx = Math.max(tt.mx || 0, Math.hypot(e.clientX - tt.x, e.clientY - tt.y)); }\n if (!cur || e.pointerId !== cur.id) return;\n var evs = e.getCoalescedEvents ? e.getCoalescedEvents() : [e];\n if (!evs.length) evs = [e];\n var added = [], v = 0;\n for (var i = 0; i < evs.length; i++) {\n var p = toPage(evs[i]), before = pen.v;\n var pt = pen.add(p[0], p[1], evs[i].timeStamp || performance.now(), e.pointerType === 'pen' ? evs[i].pressure : -1);\n if (pt) { added.push(pt); v = pen.v; }\n }\n if (added.length) { absorbLive(added); paintLive(); scratchMove(v); }\n});\nfunction endStroke(e, cancel) {\n if (touches.has(e.pointerId)) {\n var tt = touches.get(e.pointerId); touches.delete(e.pointerId);\n if (gesture) { gesture.ups++; if (!(tt.mx > 24)) gesture.still++; if (touches.size === 0) endGesture(); return; }\n }\n if (!cur || e.pointerId !== cur.id) return;\n scratchStop();\n if (cancel) { cur = null; pen = null; clearLive(); hidden = SQ.covered(dotList, S.pad.strokes); drawDots(); return; }\n var p = toPage(e); pen.end(p[0], p[1], performance.now());\n var st = {tool: cur.tool, ink: cur.ink, gap: cur.gap, pts: pen.pts};\n cur = null; pen = null; lastEnd = performance.now();\n SQ.addStroke(S.pad, st);\n Ink.draw(X.ink, st, scale, C.paper);\n clearLive();\n updateActs(); save();\n P.strokes++;\n if (P.strokes >= 6 && !P.hinted) { P.hinted = true; setTimeout(hintCurl, 500); }\n // a drawing left alone for a while: the corner lifts once, in case it is finished\n clearTimeout(idleT);\n var sh = S.pad;\n idleT = setTimeout(function () { if (S.pad === sh && !cur && !busy && sh.strokes.length >= 3 && !sh.nudged && $('book').hidden) { sh.nudged = true; hintCurl(); } }, 25000);\n}\nsheetEl.addEventListener('pointerup', function (e) { endStroke(e, false); });\nsheetEl.addEventListener('pointercancel', function (e) { endStroke(e, true); });\n\n// the live stroke is laid down a few segments a frame; the last one is drawn provisionally and\n// again once the next point says where the curve goes\nvar liveRaf = 0, shapeBuf = null;\nfunction paintLive() {\n if (liveRaf) return;\n liveRaf = requestAnimationFrame(function () {\n liveRaf = 0;\n if (!cur) return;\n var n = cur.pts.length, from = cur.drawn || 0;\n if (!Ink.style(cur.tool).mask && cur.tool !== 'eraser') {\n Ink.part(X.live, cur, scale, from, n);\n } else {\n // the grain is applied to a fresh copy of what changed, never twice to the same\n // pixels - a mask laid again every frame would fade the stroke away as it is drawn\n if (!shapeBuf || shapeBuf.width !== C.live.width || shapeBuf.height !== C.live.height) {\n shapeBuf = document.createElement('canvas'); shapeBuf.width = C.live.width; shapeBuf.height = C.live.height;\n }\n var sg = shapeBuf.getContext('2d');\n if (!from) { sg.setTransform(1, 0, 0, 1, 0, 0); sg.clearRect(0, 0, shapeBuf.width, shapeBuf.height); }\n var box = Ink.part(sg, cur, scale, from, n);\n if (box) {\n var g = X.live; g.save(); g.setTransform(1, 0, 0, 1, 0, 0);\n g.clearRect(box[0], box[1], box[2], box[3]);\n g.drawImage(shapeBuf, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n g.restore();\n Ink.finish(g, cur, scale, box, cur.tool === 'eraser' ? C.paper : null);\n }\n }\n cur.drawn = Math.max(0, n - 1);\n });\n}\nvar tickT = 0, idleT = 0;\nfunction absorbLive(pts) {\n var got = SQ.absorb(dotList, hidden, pts);\n if (got.length) { drawDots(); var n = performance.now(); if (n - tickT > 45) { tickT = n; sfx('tick'); } }\n}\n\n// two fingers tapped together take the last stroke back; three bring it again\nfunction startGesture() {\n if (cur) { // the first finger had started a stroke: drop it\n scratchStop(); cur = null; pen = null; clearLive();\n hidden = SQ.covered(dotList, S.pad.strokes); drawDots();\n }\n if (!gesture) gesture = {n: 0, ups: 0, still: 0, t: performance.now()};\n gesture.n = Math.max(gesture.n, touches.size);\n}\nfunction endGesture() {\n var g = gesture; gesture = null;\n if (performance.now() - g.t > 450 || g.still < g.n) return;\n if (g.n === 2) doUndo(); else if (g.n >= 3) doRedo();\n}\n\n// ---- undo, redo ----------------------------------------------------------------------------\nfunction doUndo() {\n if (busy) return;\n var st = SQ.undo(S.pad); if (!st) return;\n hidden = SQ.covered(dotList, S.pad.strokes);\n drawInk(); drawDots(); fadeOut(st); updateActs(); save(); sfx('undo');\n}\nfunction doRedo() {\n if (busy) return;\n var st = SQ.redo(S.pad); if (!st) return;\n SQ.absorb(dotList, hidden, st.pts);\n drawDots(); updateActs(); save(); sfx('undo');\n if (reduced.matches) { Ink.draw(X.ink, st, scale, C.paper); return; }\n var g = X.live; clearLive(); C.live.className = ''; C.live.style.opacity = 1;\n Ink.draw(g, st, scale, C.paper);\n C.live.animate([{opacity: 0}, {opacity: 1}], {duration: 180, easing: 'ease-out'}).onfinish = function () {\n Ink.draw(X.ink, st, scale, C.paper); if (!cur) clearLive();\n };\n}\nfunction fadeOut(st) {\n if (reduced.matches) return;\n var g = X.live; clearLive(); C.live.className = ''; C.live.style.opacity = 1;\n Ink.draw(g, st, scale, C.paper);\n C.live.animate([{opacity: 1}, {opacity: 0}], {duration: 180, easing: 'ease-out'}).onfinish = function () { if (!cur) clearLive(); };\n}\nfunction updateActs() { $('undo').disabled = !S.pad.strokes.length; $('redo').disabled = !S.pad.redo.length; }\n$('undo').onclick = function () { unlock(); doUndo(); };\n$('redo').onclick = function () { unlock(); doRedo(); };\n\n// ---- the tray ----------------------------------------------------------------------------\nfunction hex(c) { return [1, 3, 5].map(function (i) { return parseInt(c.slice(i, i + 2), 16); }); }\nfunction mix(c, t, k) { var a = hex(c), b = hex(t); return '#' + a.map(function (v, i) { return Math.round(v + (b[i] - v) * k).toString(16).padStart(2, '0'); }).join(''); }\nvar gid = 0;\nfunction penSvg(kind, c) {\n var defs = [];\n var C2 = function (col) {\n var id = 'g' + (gid++);\n defs.push('<linearGradient id=\"' + id + '\" x1=\"0\" x2=\"1\"><stop offset=\"0\" stop-color=\"' + mix(col, '#000000', .35) + '\"/><stop offset=\".22\" stop-color=\"' + mix(col, '#ffffff', .38) + '\"/><stop offset=\".42\" stop-color=\"' + col + '\"/><stop offset=\".8\" stop-color=\"' + mix(col, '#000000', .22) + '\"/><stop offset=\"1\" stop-color=\"' + mix(col, '#000000', .45) + '\"/></linearGradient>');\n return 'url(#' + id + ')';\n };\n var b = '';\n if (kind === 'pencil') b = '<path d=\"M13 46 23 6 33 46Z\" fill=\"' + C2('#e9c495') + '\"/><path d=\"M19.4 21 23 6 26.6 21Z\" fill=\"' + C2(c) + '\"/><rect x=\"13\" y=\"46\" width=\"20\" height=\"104\" fill=\"' + C2('#e8b52e') + '\"/><rect x=\"13\" y=\"46\" width=\"6\" height=\"104\" fill=\"rgba(255,255,255,.18)\"/><rect x=\"27\" y=\"46\" width=\"6\" height=\"104\" fill=\"rgba(80,50,0,.22)\"/><path d=\"M19.4 48v102M26.6 48v102\" stroke=\"rgba(120,80,0,.35)\" stroke-width=\".7\"/><path d=\"M13 46q1.7 3 3.3 0t3.3 0 3.4 0 3.3 0 3.3 0 3.4 0\" fill=\"#e9c495\"/><rect x=\"13\" y=\"118\" width=\"20\" height=\"32\" fill=\"' + C2('#4a4d55') + '\"/>';\n if (kind === 'fine') b = '<rect x=\"21.6\" y=\"4\" width=\"2.8\" height=\"16\" rx=\"1.2\" fill=\"' + C2(c) + '\"/><path d=\"M17 40 20 18h6l3 22Z\" fill=\"' + C2('#c3c8ce') + '\"/><rect x=\"14\" y=\"40\" width=\"18\" height=\"110\" rx=\"3\" fill=\"' + C2('#6f7782') + '\"/><rect x=\"14\" y=\"40\" width=\"18\" height=\"16\" fill=\"' + C2('#2c2f36') + '\"/><rect x=\"14\" y=\"48\" width=\"18\" height=\"4\" fill=\"' + C2(c) + '\"/><rect x=\"29\" y=\"58\" width=\"5\" height=\"58\" rx=\"2.5\" fill=\"' + C2('#d9dde2') + '\"/>';\n if (kind === 'brush') b = '<path d=\"M23 2C18 14 16 28 16 40h14c0-12-2-26-7-38Z\" fill=\"' + C2(c) + '\"/><rect x=\"15\" y=\"40\" width=\"16\" height=\"7\" fill=\"' + C2('#c9a24a') + '\"/><rect x=\"13\" y=\"47\" width=\"20\" height=\"103\" rx=\"3\" fill=\"' + C2('#2c2f36') + '\"/><rect x=\"13\" y=\"58\" width=\"20\" height=\"5\" fill=\"' + C2(c) + '\"/><rect x=\"13\" y=\"69\" width=\"20\" height=\"2\" fill=\"#c9a24a\"/>';\n if (kind === 'marker') b = '<path d=\"M16 22 30 8v16H16Z\" fill=\"' + C2(c) + '\"/><path d=\"M13 44 16 24h14l3 20Z\" fill=\"' + C2('#cfc8ba') + '\"/><rect x=\"7\" y=\"44\" width=\"32\" height=\"106\" rx=\"6\" fill=\"' + C2('#f2eee6') + '\"/><rect x=\"7\" y=\"44\" width=\"32\" height=\"34\" rx=\"6\" fill=\"' + C2('#3b3e45') + '\"/><rect x=\"7\" y=\"74\" width=\"32\" height=\"4\" fill=\"rgba(0,0,0,.25)\"/><rect x=\"7\" y=\"84\" width=\"32\" height=\"10\" fill=\"' + C2(c) + '\"/>';\n if (kind === 'eraser') b = '<path d=\"M3 64V50q0-5 5-6l30-3q5 0 5 5v18Z\" fill=\"' + C2('#f7f3ea') + '\"/><path d=\"M6 50q0-4 4-5l24-2.6\" stroke=\"rgba(255,255,255,.8)\" stroke-width=\"2\" fill=\"none\"/><rect x=\"2\" y=\"62\" width=\"42\" height=\"88\" rx=\"1.5\" fill=\"' + C2('#3d6db0') + '\"/><rect x=\"2\" y=\"62\" width=\"42\" height=\"5\" fill=\"' + C2('#f2cf3a') + '\"/><path d=\"M10 96h26M10 103h17\" stroke=\"rgba(255,255,255,.6)\" stroke-width=\"2.4\" stroke-linecap=\"round\"/>';\n var gloss = kind === 'marker' ? 11 : kind === 'eraser' ? 7 : 16, gy = kind === 'eraser' ? 66 : 48;\n return '<svg viewBox=\"0 0 46 150\" aria-hidden=\"true\"><defs>' + defs.join('') + '</defs>' + b + '<rect x=\"' + gloss + '\" y=\"' + gy + '\" width=\"2.4\" height=\"' + (150 - gy) + '\" rx=\"1.2\" fill=\"rgba(255,255,255,.5)\"/></svg>';\n}\nfunction buildTray() {\n var pens = $('pens'); pens.innerHTML = '';\n // focusing a half-hidden pen must not scroll the row (where overflow: clip is missing)\n pens.addEventListener('scroll', function () { pens.scrollTop = 0; pens.scrollLeft = 0; });\n SQ.TOOLS.forEach(function (t, i) {\n var b = document.createElement('button');\n b.className = 'pen' + (t === P.tool ? ' on' : ''); b.dataset.tool = t;\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', t === P.tool); b.setAttribute('aria-label', TOOL_NAMES[t] + ' (' + (i + 1) + ')');\n b.innerHTML = penSvg(t, t === P.tool ? SQ.inkColor(P.ink) : REST);\n b.onclick = function () { unlock(); pickTool(t); };\n pens.appendChild(b);\n });\n buildInks();\n}\n// The six inks, the last colour mixed, and a well that mixes any colour at all.\nfunction ringPath(i) {\n var r = SQ.rng(i * 31 + 7);\n return 'M5 ' + (21 + r() * 3).toFixed(1) + 'C3 ' + (10 + r() * 3).toFixed(1) + ' 13 3 22 4c10 1 15 9 12 ' + (18 + r() * 2).toFixed(1) + '-3 10-15 14-23 8-3-3-4-6-3-' + (9 + r() * 2).toFixed(1);\n}\nfunction inkButton(value, label, extra) {\n var b = document.createElement('button'), on = value === P.ink;\n b.className = 'inkb' + (on ? ' on' : ''); b.dataset.ink = value;\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on); b.setAttribute('aria-label', label);\n b.innerHTML = (extra || '<span class=\"well\" style=\"--c:' + SQ.inkColor(value) + '\"></span>') + '<svg class=\"ring\" viewBox=\"-2 -2 42 42\" aria-hidden=\"true\"><path d=\"' + ringPath(value % 97) + '\"/></svg>';\n b.onclick = function () { unlock(); pickInk(value); };\n return b;\n}\nfunction buildInks() {\n var inks = $('inks'); inks.innerHTML = '';\n SQ.INKS.forEach(function (c, i) { inks.appendChild(inkButton(i, INK_NAMES[i] + ' ink')); });\n P.mixed.forEach(function (v) { inks.appendChild(inkButton(v, 'Mixed colour ' + SQ.inkColor(v))); });\n var mixb = document.createElement('button');\n mixb.className = 'inkb mixer'; mixb.setAttribute('aria-label', 'Mix any colour');\n mixb.innerHTML = '<span class=\"well mix\"></span><input type=\"color\" tabindex=\"-1\" aria-hidden=\"true\">';\n var input = mixb.lastChild;\n mixb.onclick = function (e) { if (e.target === input) return; unlock(); input.value = SQ.inkColor(P.ink); input.click(); };\n // the pens take the colour while it is being mixed; the well keeps it once it is chosen\n input.addEventListener('input', function () { var v = SQ.inkOf(input.value); P.ink = v; tintPens(); });\n input.addEventListener('change', function () { var v = SQ.inkOf(input.value); keepMixed(v); P.ink = -1; buildInks(); pickInk(v); });\n inks.appendChild(mixb);\n}\n// the last few mixed colours stay in the tray, newest first, beside the six inks\nfunction keepMixed(v) { if (v < 16) return; P.mixed = [v].concat(P.mixed.filter(function (x) { return x !== v; })).slice(0, MIXED); }\nfunction tintPens() { [].forEach.call($('pens').children, function (b) { if (b.dataset.tool === P.tool) b.innerHTML = penSvg(P.tool, SQ.inkColor(P.ink)); }); }\nvar REST = '#4a4d55'; // pens lying in the tray show a plain dark nib; the one in hand shows the ink\nfunction pickTool(t) {\n if (t === P.tool) return;\n P.tool = t;\n [].forEach.call($('pens').children, function (b) { var on = b.dataset.tool === t; b.classList.toggle('on', on); b.setAttribute('aria-checked', on); b.innerHTML = penSvg(b.dataset.tool, on ? SQ.inkColor(P.ink) : REST); });\n sizeIcon(); if (!$('sizes').hidden) openSizes();\n sfx('tock'); buzz(); save();\n}\nfunction pickInk(i) {\n if (i === P.ink) return;\n P.ink = i;\n [].forEach.call($('inks').children, function (b) { var on = +b.dataset.ink === i; b.classList.toggle('on', on); if (b.dataset.ink) b.setAttribute('aria-checked', on); });\n if (P.tool === 'eraser') pickTool('brush');\n tintPens();\n sfx('plip'); save();\n}\nfunction buzz() { if (navigator.vibrate) try { navigator.vibrate(6); } catch (e) {} }\n\n// ---- the corner, peeling and tearing -----------------------------------------------------\nvar curlSize = 46, peel = null, busy = false;\nfunction curlSvg(c) {\n var A = [0, c], B = [c, 0], T = [c * .27, c * .27];\n var flap = 'M' + A + ' Q' + c * .1 + ' ' + c * .6 + ' ' + T + ' Q' + c * .6 + ' ' + c * .1 + ' ' + B + ' Z';\n return '<defs><linearGradient id=\"fl\" x1=\"' + c * .62 + '\" y1=\"' + c * .62 + '\" x2=\"' + c * .2 + '\" y2=\"' + c * .2 + '\" gradientUnits=\"userSpaceOnUse\"><stop offset=\"0\" stop-color=\"#fbf6ea\"/><stop offset=\".18\" stop-color=\"#efe6d3\"/><stop offset=\".7\" stop-color=\"#ddd1b8\"/><stop offset=\"1\" stop-color=\"#cfc2a6\"/></linearGradient>' +\n '<linearGradient id=\"un\" x1=\"' + c * .5 + '\" y1=\"' + c * .5 + '\" x2=\"' + c + '\" y2=\"' + c + '\" gradientUnits=\"userSpaceOnUse\"><stop offset=\"0\" stop-color=\"#d4c7aa\"/><stop offset=\".45\" stop-color=\"#ebe3d1\"/><stop offset=\"1\" stop-color=\"#f1eadb\"/></linearGradient>' +\n '<filter id=\"sh\" x=\"-60%\" y=\"-60%\" width=\"220%\" height=\"220%\"><feGaussianBlur stdDeviation=\"' + (c * .07).toFixed(2) + '\"/></filter></defs>' +\n '<path d=\"M' + A + ' L' + B + ' L' + c + ' ' + c + 'Z\" fill=\"url(#un)\"/>' +\n '<path d=\"' + flap + '\" fill=\"rgba(45,30,10,.38)\" filter=\"url(#sh)\" transform=\"translate(' + (-c * .05).toFixed(1) + ' ' + (-c * .03).toFixed(1) + ')\"/>' +\n '<path d=\"' + flap + '\" fill=\"url(#fl)\"/><path d=\"M' + A + ' L' + B + '\" stroke=\"rgba(255,255,255,.85)\" stroke-width=\"1.2\"/>' +\n '<path d=\"M' + c * .1 + ' ' + c * .86 + ' Q' + c * .25 + ' ' + c * .42 + ' ' + T + '\" stroke=\"rgba(255,255,255,.35)\" stroke-width=\"' + (c * .03).toFixed(1) + '\" fill=\"none\"/>';\n}\n// p: 0 = resting curl, 1 = the corner pulled a long way back\nfunction drawCurl(p) {\n var c = Math.round(curlSize * (1 + p * 3.2)), svg = $('curl').firstChild;\n svg.setAttribute('width', c); svg.setAttribute('height', c); svg.setAttribute('viewBox', '0 0 ' + c + ' ' + c);\n svg.innerHTML = curlSvg(c);\n}\nvar curl = $('curl');\ncurl.addEventListener('pointerdown', function (e) {\n if (busy) return;\n unlock(); e.preventDefault(); e.stopPropagation();\n try { curl.setPointerCapture(e.pointerId); } catch (_) {}\n peel = {x: e.clientX, y: e.clientY, t: performance.now(), p: 0};\n sfx('rustle');\n});\ncurl.addEventListener('pointermove', function (e) {\n if (!peel) return;\n var d = ((peel.x - e.clientX) + (peel.y - e.clientY)) / Math.SQRT2;\n peel.p = Math.max(0, Math.min(1, d / (Math.min(cssW, cssH) * 0.55)));\n drawCurl(peel.p);\n});\nfunction peelEnd(e) {\n if (!peel) return;\n var p = peel.p, quick = performance.now() - peel.t < 300 && p < 0.05;\n peel = null;\n if (p > 0.4) return tearOff(p);\n if (quick) return hintCurl();\n settleCurl(p);\n}\ncurl.addEventListener('pointerup', peelEnd);\ncurl.addEventListener('pointercancel', function () { if (peel) { var p = peel.p; peel = null; settleCurl(p); } });\ncurl.addEventListener('click', function (e) { if (e.detail === 0) { unlock(); tearOff(0); } });\nfunction animate(ms, fn, done) {\n var t0 = performance.now();\n (function step(n) { var k = Math.min(1, (n - t0) / ms); fn(k); if (k < 1) requestAnimationFrame(step); else if (done) done(); })(t0);\n}\nfunction settleCurl(p) { animate(260, function (k) { var e = 1 - Math.pow(1 - k, 3); drawCurl(p * (1 - e)); }); }\nfunction hintCurl() {\n if (reduced.matches) return;\n animate(1100, function (k) { drawCurl(Math.sin(k * Math.PI * 2) ** 2 * 0.22 * (1 - k * 0.5)); });\n}\n\n// Compose a sheet into one canvas: paper, the dots left, and the ink.\nfunction compose(sh, wpx, opts) {\n opts = opts || {};\n var dm = SQ.sheetSize(sh.wide), s = wpx / dm.w, hpx = Math.round(dm.h * s);\n var out = document.createElement('canvas'); out.width = wpx; out.height = hpx;\n var g = out.getContext('2d'), paper = document.createElement('canvas'); paper.width = wpx; paper.height = hpx;\n Ink.paper(paper.getContext('2d'), wpx, hpx, s, sh); header(paper.getContext('2d'), sh, s, dm.w);\n g.drawImage(paper, 0, 0);\n var strokes = opts.strokes || sh.strokes;\n var sq = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n sq.dots = SQ.dots(sq.pts, 1); sq.hidden = SQ.covered(sq.dots, strokes);\n Ink.draw(g, sq, s, null);\n var ink = document.createElement('canvas'); ink.width = wpx; ink.height = hpx;\n var gi = ink.getContext('2d');\n for (var i = 0; i < strokes.length; i++) Ink.draw(gi, strokes[i], s, paper);\n g.drawImage(ink, 0, 0);\n return out;\n}\n\n// the ragged top a sheet keeps from the perforation it was torn along\nfunction tornEdge(w, seed) {\n var zig = [], n = Math.round(w / 4), rz = SQ.rng(seed);\n for (var z = 0; z <= n; z++) zig.push((z / n * 100).toFixed(2) + '% ' + (rz() * (z % 2 ? 4 : 1.6)).toFixed(1) + 'px');\n return 'polygon(' + zig.join(',') + ',100% 100%,0 100%)';\n}\nfunction tearOff(p) {\n if (busy) return;\n busy = true;\n var old = S.pad, inked = SQ.inked(old), r = sheetEl.getBoundingClientRect();\n var snap = null;\n if (!reduced.matches) {\n snap = document.createElement('canvas'); snap.width = C.paper.width; snap.height = C.paper.height;\n var g = snap.getContext('2d'); g.drawImage(C.paper, 0, 0); g.drawImage(C.dots, 0, 0); g.drawImage(C.ink, 0, 0);\n snap.style.cssText = 'display:block;width:100%;height:100%';\n var wrap = document.createElement('div'); wrap.className = 'fly'; wrap.appendChild(snap);\n wrap.style.cssText = 'left:' + r.left + 'px;top:' + r.top + 'px;width:' + r.width + 'px;height:' + r.height + 'px';\n snap.style.clipPath = tornEdge(r.width, old.seed);\n document.body.appendChild(wrap); snap = wrap;\n }\n sfx('rip'); buzz();\n var was = S.pad;\n SQ.tear(S, SQ.dayNumber(), opt(side));\n if (inked) P.torn++;\n laid(was);\n drawCurl(0);\n newSheet(snap ? 380 : 0);\n save(true);\n var finish = function () { if (snap) snap.remove(); busy = false; if (inked) bumpBook(); };\n if (!snap) { finish(); return; }\n var b = $('stack').getBoundingClientRect();\n var tx = b.left + b.width / 2 - (r.left + r.width / 2), ty = b.top - r.top, sc = Math.max(0.06, b.width / r.width);\n if (!inked) { tx = -r.width * 0.15; ty = -r.height * 0.4; sc = 0.9; }\n var lift = 'translate(' + (-r.width * 0.04) + 'px,' + (-r.height * 0.08) + 'px) rotate(-5deg)';\n // up off the pad, then an arc over to the sketchbook, landing small on the stack\n var mid = 'translate(' + (tx * 0.45 - r.width * 0.06) + 'px,' + (ty * 0.45 - r.height * 0.16) + 'px) rotate(-10deg) scale(' + (0.55 + sc * 0.45) + ')';\n var anim = snap.animate([\n {transform: 'none', opacity: 1, easing: 'cubic-bezier(.3,0,.4,1)'},\n {transform: lift, opacity: 1, offset: 0.22, easing: 'cubic-bezier(.4,0,.6,1)'},\n {transform: mid, opacity: 1, offset: 0.62, easing: 'cubic-bezier(.3,0,.2,1)'},\n {transform: 'translate(' + tx + 'px,' + ty + 'px) rotate(' + (inked ? -6 : -20) + 'deg) scale(' + sc + ')', opacity: inked ? 1 : 0}\n ], {duration: 950});\n anim.onfinish = finish;\n}\nfunction bumpBook() {\n stackThumb(); bookCount();\n var b = $('bookBtn'); b.classList.remove('bump'); void b.offsetWidth; b.classList.add('bump');\n sfx('drop');\n}\n// a new sheet on the pad: its dots are printed one after another\nfunction newSheet(wait) {\n setSheet(); layout();\n if (reduced.matches) { printUpto = 1; drawDots(); return; }\n var ms = P.printed ? 900 : 1900;\n P.printed = true;\n printUpto = 0; drawDots();\n if (wait) return setTimeout(function () { printDots(ms); }, wait);\n printDots(ms);\n}\nfunction printDots(ms) {\n var lastN = 0;\n animate(ms, function (k) {\n printUpto = k < 1 ? k : 1;\n var n = SQ.dots(squig.pts, printUpto).length;\n if (n > lastN + 2) { lastN = n; sfx('dot'); }\n drawDots();\n });\n}\n\n// ---- the sketchbook ------------------------------------------------------------------------\nfunction bookCount() {\n var n = S.book.length;\n $('bookCount').textContent = n ? n + (n === 1 ? ' sheet' : ' sheets') : 'empty';\n $('bookCount2').textContent = n ? n + (n === 1 ? ' sheet' : ' sheets') : '';\n $('bookNum').textContent = n ? n : '';\n $('bookBtn').setAttribute('aria-label', 'Open the sketchbook' + (n ? ', ' + n + (n === 1 ? ' sheet' : ' sheets') : ''));\n $('stack').classList.toggle('empty', !n);\n}\nfunction stackThumb() {\n var cv = $('cStack'), sh = S.book[0];\n bookCount();\n if (!sh) return;\n var w = Math.round(cv.parentNode.clientWidth * DPR()) || 60;\n var img = compose(sh, Math.max(60, w));\n cv.width = img.width; cv.height = img.height; cv.getContext('2d').drawImage(img, 0, 0);\n}\nvar thumbs = new WeakMap(), io = null;\nfunction openBook() {\n unlock(); sfx('rustle');\n var grid = $('grid'); grid.innerHTML = '';\n $('bookEmpty').hidden = S.book.length > 0;\n bookCount(); muteIcon();\n if (io) io.disconnect();\n io = 'IntersectionObserver' in window ? new IntersectionObserver(function (es) {\n es.forEach(function (en) { if (en.isIntersecting) { paintThumb(en.target); io.unobserve(en.target); } });\n }, {root: grid, rootMargin: '200px'}) : null;\n S.book.forEach(function (sh, i) {\n var card = document.createElement('button'); card.className = 'card';\n var dm = SQ.sheetSize(sh.wide), rr = SQ.rng(sh.seed + i);\n card.style.setProperty('--r', ((rr() - 0.5) * 3.2).toFixed(2) + 'deg');\n card.style.setProperty('--t', ((rr() - 0.5) * 7).toFixed(2) + 'deg');\n var tag = sheetTag(sh);\n card.innerHTML = '<div class=\"pg\" style=\"aspect-ratio:' + dm.w + '/' + dm.h + '\"></div><span>' + shortDate(sh) + (tag ? '<b>' + tag + '</b>' : '') + '</span>';\n card.setAttribute('aria-label', 'Sheet from ' + dateLabel(sh) + (tag ? ', ' + tag : ''));\n card._sheet = sh;\n card.onclick = function () { openView(sh, card.firstChild); };\n grid.appendChild(card);\n if (io) io.observe(card); else paintThumb(card);\n });\n $('book').hidden = false;\n $('bookClose').focus({preventScroll: true});\n}\nfunction shortDate(sh) {\n var d = sh.kind === 'day' ? SQ.dayDate(sh.day) : new Date(sh.created || Date.now()), o = {weekday: 'short', day: 'numeric', month: 'short'};\n if (d.getFullYear() !== new Date().getFullYear()) o.year = 'numeric';\n return d.toLocaleDateString(P.lang || undefined, o);\n}\nfunction paintThumb(card) {\n var pg = card.firstChild, w = Math.round(pg.clientWidth * DPR());\n if (!w) return;\n var img = compose(card._sheet, w);\n pg.appendChild(img);\n}\nfunction closeBook() { $('book').hidden = true; $('bookBtn').focus({preventScroll: true}); }\n$('bookBtn').onclick = openBook;\n$('bookClose').onclick = closeBook;\n$('book').addEventListener('click', function (e) { if (e.target === $('book') || e.target === $('grid')) closeBook(); });\n\n// one sheet, drawing itself again\nvar viewing = null, replayRaf = 0;\nfunction openView(sh, from) {\n viewing = sh; sfx('rustle');\n $('viewTitle').textContent = '';\n $('view').hidden = false;\n var cv = $('cView'), img = from && from.querySelector('canvas');\n if (!img || reduced.matches) { requestAnimationFrame(replay); return; }\n // the taped sheet comes up off the page to its full size\n var vs = viewSize(), a = from.getBoundingClientRect(), st = document.querySelector('#view .vstage').getBoundingClientRect();\n var bx = st.left + (st.width - vs.w) / 2, by = st.top + (st.height - vs.h) / 2;\n var z = document.createElement('canvas'); z.width = img.width; z.height = img.height; z.getContext('2d').drawImage(img, 0, 0);\n z.className = 'zoom'; z.style.cssText = 'left:' + bx + 'px;top:' + by + 'px;width:' + vs.w + 'px;height:' + vs.h + 'px';\n z.style.clipPath = tornEdge(vs.w, sh.seed);\n document.body.appendChild(z);\n cv.style.visibility = 'hidden';\n var k = a.width / vs.w;\n z.animate([{transform: 'translate(' + (a.left - bx) + 'px,' + (a.top - by) + 'px) scale(' + k + ')', transformOrigin: '0 0'},\n {transform: 'none', transformOrigin: '0 0'}], {duration: 380, easing: 'cubic-bezier(.2,.8,.2,1)'}).onfinish = function () {\n cv.style.visibility = ''; replay(); requestAnimationFrame(function () { z.remove(); });\n };\n}\nfunction viewSize() {\n var st = document.querySelector('#view .vstage').getBoundingClientRect(), dm = SQ.sheetSize(viewing.wide);\n var w = Math.min(st.width - 36, (st.height - 12) * dm.w / dm.h);\n return {w: Math.max(100, Math.floor(w)), h: Math.floor(w * dm.h / dm.w)};\n}\nfunction replay() {\n cancelAnimationFrame(replayRaf);\n var sh = viewing, vs = viewSize(), cv = $('cView'), d = DPR();\n cv.style.width = vs.w + 'px'; cv.style.height = vs.h + 'px';\n var vst = document.querySelector('#view .vstage'); vst.style.setProperty('--vw', vs.w + 'px'); vst.style.setProperty('--vh', vs.h + 'px');\n cv.style.clipPath = tornEdge(vs.w, sh.seed);\n cv.width = Math.round(vs.w * d); cv.height = Math.round(vs.h * d);\n var dm = SQ.sheetSize(sh.wide), s = cv.width / dm.w, g = cv.getContext('2d');\n var paper = document.createElement('canvas'); paper.width = cv.width; paper.height = cv.height;\n Ink.paper(paper.getContext('2d'), cv.width, cv.height, s, sh); header(paper.getContext('2d'), sh, s, dm.w);\n var ink = document.createElement('canvas'); ink.width = cv.width; ink.height = cv.height;\n var part = document.createElement('canvas'); part.width = cv.width; part.height = cv.height;\n var sq = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n sq.dots = SQ.dots(sq.pts, 1); sq.hidden = new Uint8Array(sq.dots.length);\n var plan = SQ.replayPlan(sh.strokes, Math.min(9000, 1200 + sh.strokes.length * 650)), done = 0, t0 = performance.now();\n $('vReplay').classList.remove('show');\n if (reduced.matches || !sh.strokes.length) {\n g.drawImage(compose(sh, cv.width), 0, 0); $('vReplay').classList.toggle('show', !!sh.strokes.length); return;\n }\n function frame(now) {\n var t = now - t0;\n while (done < sh.strokes.length && plan.marks[done][1] <= t) {\n Ink.draw(ink.getContext('2d'), sh.strokes[done], s, paper); SQ.absorb(sq.dots, sq.hidden, sh.strokes[done].pts); done++;\n }\n var pg = part.getContext('2d'); pg.clearRect(0, 0, part.width, part.height);\n if (done < sh.strokes.length && t > plan.marks[done][0]) {\n var st = sh.strokes[done], m = plan.marks[done], f = (t - m[0]) / Math.max(1, m[1] - m[0]);\n var cut = {tool: st.tool, ink: st.ink, pts: st.pts.slice(0, Math.max(1, Math.ceil(st.pts.length * f)))};\n Ink.draw(pg, cut, s, paper); SQ.absorb(sq.dots, sq.hidden, cut.pts);\n }\n g.drawImage(paper, 0, 0); Ink.draw(g, sq, s, null); g.drawImage(ink, 0, 0); g.drawImage(part, 0, 0);\n if (done < sh.strokes.length) replayRaf = requestAnimationFrame(frame);\n else { g.drawImage(paper, 0, 0); sq.hidden = SQ.covered(sq.dots, sh.strokes); Ink.draw(g, sq, s, null); g.drawImage(ink, 0, 0); $('vReplay').classList.add('show'); }\n }\n replayRaf = requestAnimationFrame(frame);\n}\nfunction closeView() { cancelAnimationFrame(replayRaf); $('view').hidden = true; viewing = null; }\n$('viewBack').onclick = function () { closeView(); };\n$('vReplay').onclick = function () { replay(); };\n$('vDraw').onclick = function () {\n var id = viewing.id; closeView(); closeBook();\n var out = SQ.reopen(S, id, opt(side));\n setSheet(); printUpto = 1; layout(); save(true);\n if (out) bumpBook();\n};\n$('vSave').onclick = function () {\n var sh = viewing, dm = SQ.sheetSize(sh.wide), img = compose(sh, Math.round(dm.w * 1.6));\n var name = 'squiggle-' + new Date(sh.kind === 'day' ? SQ.dayDate(sh.day) : sh.created).toISOString().slice(0, 10) + '.png';\n img.toBlob(function (blob) {\n if (!blob) return;\n var file = null;\n try { file = new File([blob], name, {type: 'image/png'}); } catch (e) {}\n if (file && navigator.canShare && navigator.canShare({files: [file]}) && matchMedia('(pointer:coarse)').matches) {\n navigator.share({files: [file]}).catch(function () {});\n } else {\n var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name;\n document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 4000);\n toast('Saved ' + name);\n }\n }, 'image/png');\n};\n$('vSend').onclick = function () {\n var sh = viewing, u = new URL(location.href.split('?')[0].split('#')[0]);\n if (sh.kind === 'day') u.searchParams.set('day', sh.day); else u.searchParams.set('s', SQ.codeFor(sh.seed));\n var url = u.toString();\n if (navigator.share && matchMedia('(pointer:coarse)').matches) navigator.share({title: 'Squiggle', text: 'Turn this squiggle into anything.', url: url}).catch(function () {});\n else if (navigator.clipboard) navigator.clipboard.writeText(url).then(function () { toast('Link copied - whoever opens it gets this squiggle'); }, function () { toast(url); });\n else toast(url);\n};\n$('vRemove').onclick = function () {\n var r = SQ.remove(S, viewing.id); if (!r) return;\n closeView(); save(true); openBook(); stackThumb();\n toast('Sheet removed', 'Undo', function () { SQ.restore(S, r); save(true); openBook(); stackThumb(); });\n};\naddEventListener('resize', function () { if (viewing) replay(); });\n\n// ---- toast -----------------------------------------------------------------------------------\nvar toastT = 0;\nfunction toast(msg, label, fn) {\n $('toastMsg').textContent = msg;\n var b = $('toastBtn'); b.hidden = !label; b.textContent = label || '';\n b.onclick = function () { $('toast').classList.remove('show'); if (fn) fn(); };\n $('toast').classList.add('show');\n clearTimeout(toastT); toastT = setTimeout(function () { $('toast').classList.remove('show'); }, label ? 5000 : 2600);\n}\n\n// ---- sound -----------------------------------------------------------------------------------\n// Everything is made here: the nib on paper is noise through a filter that follows the pen's\n// speed; the rest are short bursts and plucks.\nvar A = null, master = null, noise = null, scr = null;\nvar VOICE = {pencil: [3200, .9, .5, 9000], fine: [5600, 1.3, .32, 12000], brush: [1500, .6, .22, 4200], marker: [2300, 2.2, .3, 7000], eraser: [700, .8, .5, 2600]};\nfunction unlock() {\n if (P.mute) return null;\n if (!A) {\n try { A = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return null; }\n master = A.createGain(); master.gain.value = 0.55; master.connect(A.destination);\n noise = A.createBuffer(1, A.sampleRate * 2, A.sampleRate);\n var d = noise.getChannelData(0), r = SQ.rng(99);\n for (var i = 0; i < d.length; i++) d[i] = r() * 2 - 1;\n }\n if (A.state === 'suspended') A.resume();\n return A;\n}\nfunction scratchStart(tool) {\n if (P.mute || !A) return;\n if (!scr) {\n var src = A.createBufferSource(); src.buffer = noise; src.loop = true;\n var bp = A.createBiquadFilter(); bp.type = 'bandpass';\n var lp = A.createBiquadFilter(); lp.type = 'lowpass';\n var g = A.createGain(); g.gain.value = 0;\n src.connect(bp); bp.connect(lp); lp.connect(g); g.connect(master); src.start();\n scr = {bp: bp, lp: lp, g: g};\n }\n var v = VOICE[tool], t = A.currentTime;\n scr.bp.frequency.setTargetAtTime(v[0], t, .01); scr.bp.Q.setTargetAtTime(v[1], t, .01); scr.lp.frequency.setTargetAtTime(v[3], t, .01);\n scr.vol = v[2]; scr.g.gain.setTargetAtTime(v[2] * 0.15, t, .02);\n}\nfunction scratchMove(speed) {\n if (P.mute || !scr || !A) return;\n var t = A.currentTime, k = Math.min(1, speed / 2.2);\n scr.g.gain.setTargetAtTime(scr.vol * (0.12 + 0.88 * k), t, .03);\n scr.bp.frequency.setTargetAtTime(VOICE[P.tool][0] * (0.85 + 0.35 * k), t, .05);\n clearTimeout(scr.idle); scr.idle = setTimeout(function () { if (scr && A) scr.g.gain.setTargetAtTime(scr.vol * 0.06, A.currentTime, .05); }, 60);\n}\nfunction scratchStop() { if (scr && A) { clearTimeout(scr.idle); scr.g.gain.setTargetAtTime(0, A.currentTime, .035); } }\nfunction burst(t, dur, f0, f1, q, vol, type) {\n var src = A.createBufferSource(); src.buffer = noise; src.loop = true;\n var f = A.createBiquadFilter(); f.type = type || 'bandpass'; f.Q.value = q;\n f.frequency.setValueAtTime(f0, t); f.frequency.exponentialRampToValueAtTime(f1, t + dur);\n var g = A.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + Math.min(.012, dur / 4)); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);\n src.connect(f); f.connect(g); g.connect(master); src.start(t, Math.random()); src.stop(t + dur + .02);\n}\nfunction pluck(t, f0, f1, dur, vol, type) {\n var o = A.createOscillator(); o.type = type || 'sine'; o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(f1, t + dur);\n var g = A.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + .006); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);\n o.connect(g); g.connect(master); o.start(t); o.stop(t + dur + .02);\n}\nfunction sfx(name) {\n if (P.mute || !A || A.state !== 'running') return;\n var t = A.currentTime + .005;\n switch (name) {\n case 'tick': pluck(t, 2600 + Math.random() * 500, 1900, .035, .05); break;\n case 'dot': pluck(t, 1500 + Math.random() * 300, 1100, .04, .035); break;\n case 'tock': pluck(t, 420, 260, .09, .22, 'triangle'); burst(t, .05, 1800, 900, 1.5, .08); break;\n case 'plip': pluck(t, 900, 520, .12, .16); break;\n case 'undo': burst(t, .12, 2400, 900, .8, .05); break;\n case 'rustle': burst(t, .22, 1800, 3600, .6, .06); break;\n case 'rip':\n for (var i = 0; i < 9; i++) burst(t + i * .032 + Math.random() * .012, .06, 1400 + i * 260, 3800, .9, .09 + Math.random() * .05);\n burst(t, .4, 900, 2600, .5, .05); break;\n case 'drop': burst(t, .16, 600, 260, .7, .12, 'lowpass'); pluck(t, 180, 120, .12, .08); break;\n }\n}\nfunction muteIcon() {\n var b = $('mute');\n b.setAttribute('aria-label', P.mute ? 'Sound on' : 'Sound off');\n b.firstChild.innerHTML = P.mute ? '<path d=\"M4 9h4l5-4v14l-5-4H4z\"/><path d=\"M17 9l4 6M21 9l-4 6\"/>' : '<path d=\"M4 9h4l5-4v14l-5-4H4z\"/><path d=\"M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12\"/>';\n}\n// muted means silent: the scratch loop is stopped and the whole context is put to sleep\n$('mute').onclick = function () { P.mute = !P.mute; if (P.mute) { scratchStop(); if (A && A.state === 'running') A.suspend(); } else unlock(); muteIcon(); save(); };\n\n// ---- nib sizes -----------------------------------------------------------------------------\n// Each pen keeps its own size: a fine pencil and a fat marker are both what someone reaches for.\nvar SIZE_NAMES = ['Finest', 'Fine', 'Medium', 'Broad', 'Broadest'];\nfunction nibPx(t, i) { var w = SQ.BASE[t] * SQ.SIZES[i] * (t === 'brush' ? 0.55 : 1); return Math.round(Math.max(4 + i * 3.5, Math.min(34, w * 0.62))); } // never so small the steps blur\nfunction sizeIcon() {\n var t = P.tool, i = P.size[t];\n $('sizeBtn').firstChild.innerHTML = '<circle cx=\"12\" cy=\"12\" r=\"' + (1.6 + i * 1.6).toFixed(1) + '\"/>';\n $('sizeBtn').setAttribute('aria-label', 'Nib size: ' + SIZE_NAMES[i].toLowerCase());\n}\nfunction openSizes() {\n var box = $('sizes'), t = P.tool, col = t === 'eraser' ? '#f2eee6' : SQ.inkColor(P.ink);\n box.innerHTML = '';\n SQ.SIZES.forEach(function (k, i) {\n var b = document.createElement('button'), d = nibPx(t, i), on = i === P.size[t];\n b.className = 'szb' + (on ? ' on' : ''); b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on);\n b.setAttribute('aria-label', SIZE_NAMES[i]); b.tabIndex = on ? 0 : -1;\n b.innerHTML = '<i style=\"width:' + d + 'px;height:' + d + 'px;--c:' + col + '\"></i>';\n b.onclick = function () { pickSize(i); closeSizes(); };\n box.appendChild(b);\n });\n box.hidden = false; $('sizeBtn').setAttribute('aria-expanded', 'true');\n var r = $('sizeBtn').getBoundingClientRect(), w = box.offsetWidth, h = box.offsetHeight;\n var x = side ? r.left + r.width / 2 - w / 2 : r.left, y = r.top - h - 10;\n box.style.left = Math.max(8, Math.min(innerWidth - w - 8, x)) + 'px'; box.style.top = Math.max(8, y) + 'px';\n var on = box.querySelector('.on'); if (on) on.focus({preventScroll: true});\n}\nfunction closeSizes() { $('sizes').hidden = true; $('sizeBtn').setAttribute('aria-expanded', 'false'); }\nfunction pickSize(i) {\n i = Math.max(0, Math.min(SQ.SIZES.length - 1, i));\n if (i === P.size[P.tool]) return;\n P.size[P.tool] = i; sizeIcon(); sfx('tick'); save();\n if (!$('sizes').hidden) [].forEach.call($('sizes').children, function (b, j) { b.classList.toggle('on', j === i); b.setAttribute('aria-checked', j === i); });\n}\n$('sizeBtn').onclick = function (e) { e.stopPropagation(); unlock(); if ($('sizes').hidden) openSizes(); else closeSizes(); };\n$('sizes').addEventListener('keydown', function (e) {\n var d = e.key === 'ArrowRight' || e.key === 'ArrowUp' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowDown' ? -1 : 0;\n if (!d) return; e.preventDefault(); pickSize(P.size[P.tool] + d); var b = $('sizes').children[P.size[P.tool]]; if (b) b.focus();\n});\ndocument.addEventListener('pointerdown', function (e) { if (!$('sizes').hidden && !$('sizes').contains(e.target) && e.target.closest('#sizeBtn') === null) closeSizes(); }, true);\n\n// ---- the pad's settings ----------------------------------------------------------------------\nvar PAPER_NAMES = ['Cream', 'White', 'Grey', 'Kraft', 'Mist'], RULE_NAMES = ['Plain', 'Lined', 'Grid', 'Dots'];\nfunction optButton(label, on, inner, fn) {\n var b = document.createElement('button'); b.className = 'opt' + (on ? ' on' : '');\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on); b.innerHTML = inner + '<span>' + label + '</span>';\n b.onclick = function () { fn(); sfx('plip'); fillPrefs(); }; return b;\n}\nfunction fillPrefs() {\n var pp = $('optPaper'), pr = $('optRule'), pl = $('optLang'), pc = SQ.PAPERS[P.paper];\n pp.innerHTML = pr.innerHTML = pl.innerHTML = '';\n SQ.PAPERS.forEach(function (c, i) { pp.appendChild(optButton(PAPER_NAMES[i], i === P.paper, '<i style=\"--c:' + c + '\"></i>', function () { setLook(i, P.rule); })); });\n SQ.RULES.forEach(function (r, i) { pr.appendChild(optButton(RULE_NAMES[i], i === P.rule, '<i class=\"r-' + r + '\" style=\"--c:' + pc + '\"></i>', function () { setLook(P.paper, i); })); });\n var mine = '';\n try { mine = new Intl.DisplayNames([navigator.language], {type: 'language'}).of(navigator.language.split('@')[0]); } catch (e) { mine = navigator.language || ''; }\n [['', 'Your language' + (mine ? ' (' + mine + ')' : '')], ['en', 'English']].forEach(function (o) {\n var b = optButton(o[1], P.lang === o[0], '', function () { P.lang = o[0]; reprint(); }); b.lastChild.outerHTML = o[1]; pl.appendChild(b);\n });\n $('optDate').checked = P.date; $('optNumber').checked = P.number;\n}\n// The choice goes onto the sheet on the pad, and onto every sheet torn after it.\nfunction setLook(paper, rule) {\n P.paper = paper; P.rule = rule;\n if (S.pad) { S.pad.paper = paper; S.pad.rule = rule; drawPaper(); drawInk(); }\n save();\n}\nfunction reprint() { if (S.pad) { drawPaper(); drawInk(); } bookCount(); save(); }\n$('optDate').onchange = function () { P.date = this.checked; sfx('tick'); reprint(); };\n$('optNumber').onchange = function () { P.number = this.checked; sfx('tick'); reprint(); };\nvar prefsFrom = null;\nfunction openPrefs() { closeSizes(); fillPrefs(); prefsFrom = document.activeElement; $('prefs').hidden = false; $('prefsClose').focus({preventScroll: true}); }\nfunction closePrefs() { $('prefs').hidden = true; if (prefsFrom && prefsFrom.focus) prefsFrom.focus({preventScroll: true}); }\n$('setBtn').onclick = function () { unlock(); sfx('rustle'); openPrefs(); };\n$('prefsClose').onclick = closePrefs;\n$('prefs').addEventListener('click', function (e) { if (e.target === this) closePrefs(); });\n$('prefs').addEventListener('keydown', function (e) { // keep Tab inside the card\n if (e.key !== 'Tab') return;\n var f = [].filter.call(this.querySelectorAll('button,input'), function (x) { return x.offsetParent; }), a = f[0], z = f[f.length - 1];\n if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); } else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }\n});\n\n// ---- keys --------------------------------------------------------------------------------------\naddEventListener('keydown', function (e) {\n if (e.key === 'Escape') { if (!$('sizes').hidden) { closeSizes(); $('sizeBtn').focus(); return; } if (!$('prefs').hidden) { closePrefs(); return; } if (!$('view').hidden) closeView(); else if (!$('book').hidden) closeBook(); return; }\n if (!$('book').hidden || !$('view').hidden || !$('prefs').hidden) return;\n if ((e.key === '[' || e.key === ']') && !e.ctrlKey && !e.metaKey) { pickSize(P.size[P.tool] + (e.key === ']' ? 1 : -1)); return; }\n var mod = e.ctrlKey || e.metaKey;\n if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); unlock(); if (e.shiftKey) doRedo(); else doUndo(); return; }\n if (mod && e.key.toLowerCase() === 'y') { e.preventDefault(); unlock(); doRedo(); return; }\n if (!mod && e.key >= '1' && e.key <= '5') { unlock(); pickTool(SQ.TOOLS[+e.key - 1]); }\n});\n\n// ---- the walnut, the leather and the board are drawn once ----------------------------------------\nfunction tex(w, h, base, fn) {\n var c = document.createElement('canvas'); c.width = w; c.height = h;\n var g = c.getContext('2d'); g.fillStyle = base; g.fillRect(0, 0, w, h); fn(g, w, h, SQ.rng(w * 7 + h)); return c.toDataURL();\n}\nfunction materials() {\n var wood = tex(600, 120, '#5b3f2c', function (g, w, h, r) {\n for (var y = 0; y < h; y++) {\n var v = Math.sin(y * .21 + Math.sin(y * .05) * 3) * .5 + Math.sin(y * .83) * .25 + (r() - .5) * .5;\n g.fillStyle = v > 0 ? 'rgba(255,215,170,' + v * .06 + ')' : 'rgba(25,12,4,' + (-v * .14) + ')'; g.fillRect(0, y, w, 1);\n }\n for (var k = 0; k < 160; k++) {\n var yy = r() * h, x = r() * w, l = 20 + r() * 120; g.strokeStyle = 'rgba(25,12,4,' + (.1 + r() * .14) + ')'; g.lineWidth = .6 + r();\n g.beginPath(); g.moveTo(x, yy); g.bezierCurveTo(x + l * .3, yy + (r() - .5) * 3, x + l * .6, yy + (r() - .5) * 3, x + l, yy + (r() - .5) * 2); g.stroke();\n }\n });\n $('tray').style.backgroundImage = 'url(' + wood + ')';\n $('desk').style.backgroundImage = 'url(' + wood + ')';\n $('blotter').style.backgroundImage = 'url(' + tex(300, 300, '#1f3530', function (g, w, h, r) {\n var im = g.getImageData(0, 0, w, h), d = im.data;\n for (var i = 0; i < d.length; i += 4) { var n = (r() - .5) * 9; d[i] += n; d[i + 1] += n; d[i + 2] += n; }\n g.putImageData(im, 0, 0);\n for (var k = 0; k < 3200; k++) { g.strokeStyle = r() < .55 ? 'rgba(0,0,0,.16)' : 'rgba(255,255,230,.06)'; g.lineWidth = .8; g.beginPath(); g.arc(r() * w, r() * h, 1 + r() * 2.4, r() * 6, r() * 6 + 2); g.stroke(); }\n }) + ')';\n var page = 'url(' + tex(512, 512, '#e6dcc7', function (g, w, h, r) {\n var im = g.getImageData(0, 0, w, h), d = im.data;\n for (var i = 0; i < d.length; i += 4) { var n = (r() - .5) * 10; d[i] += n; d[i + 1] += n; d[i + 2] += n * 1.2; }\n g.putImageData(im, 0, 0);\n for (var k = 0; k < 900; k++) { g.strokeStyle = 'rgba(120,95,60,' + (.03 + r() * .05) + ')'; g.lineWidth = .6; var x = r() * w, y = r() * h, a = r() * 6.3, l = 3 + r() * 8; g.beginPath(); g.moveTo(x, y); g.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); g.stroke(); }\n }) + ')';\n $('book').style.backgroundImage = page; $('view').style.backgroundImage = page;\n document.querySelector('.board').style.backgroundImage = 'url(' + tex(256, 256, '#8b7a62', function (g, w, h, r) {\n for (var k = 0; k < 2600; k++) { g.fillStyle = r() < .5 ? 'rgba(60,45,25,' + (.08 + r() * .15) + ')' : 'rgba(255,240,210,' + (.05 + r() * .12) + ')'; g.fillRect(r() * w, r() * h, .6 + r() * 1.6, .6 + r() * 1.2); }\n }) + ')';\n [['tl', 0, 104, 104, 0], ['tr', 16, 0, 120, 104], ['bl', 0, 16, 104, 120], ['br', 120, 16, 16, 120]].forEach(function (c) {\n document.querySelector('.corner.' + c[0]).innerHTML = '<svg viewBox=\"0 0 120 120\"><line x1=\"' + c[1] + '\" y1=\"' + c[2] + '\" x2=\"' + c[3] + '\" y2=\"' + c[4] + '\" stroke=\"rgba(245,220,190,.45)\" stroke-width=\"1.4\" stroke-dasharray=\"5 4\"/></svg>';\n });\n}\n\n// ---- start ---------------------------------------------------------------------------------------\nfunction fromLink() {\n var q = new URLSearchParams(location.search), today = SQ.dayNumber(), got = false;\n var code = q.get('s'), day = parseInt(q.get('day'), 10);\n if (code && SQ.seedFor(code.toLowerCase()) != null) { if (SQ.receive(S, 'extra', SQ.seedFor(code.toLowerCase()), today, opt(wantSide()))) got = true; }\n else if (day > 0 && day <= today) { if (SQ.receive(S, 'day', day, today, opt(wantSide()))) got = true; }\n if (code || q.has('day')) history.replaceState(null, '', location.pathname);\n return got;\n}\nfunction checkDay() {\n if (cur || busy) return;\n var today = SQ.dayNumber();\n if (today === S.day) return;\n var before = S.pad, filed = SQ.open(S, today, opt(wantSide()));\n laid(before);\n if (S.pad !== before) { newSheet(); save(true); if (filed.length) bumpBook(); }\n}\nfunction start() {\n load();\n materials();\n buildTray();\n var before = S.pad, filed = SQ.open(S, SQ.dayNumber(), opt(wantSide()));\n laid(before); before = S.pad;\n if (fromLink()) filed.push(S.book[0]);\n laid(before);\n muteIcon(); sizeIcon();\n setSheet(); layout(); stackThumb();\n save(true);\n if (filed.length) bumpBook();\n if (SQ.inked(S.pad)) { printUpto = 1; drawDots(); } else newSheet();\n var fonts = document.fonts;\n if (fonts && fonts.load) Promise.all([fonts.load('500 34px Fraunces'), fonts.load('italic 400 26px Fraunces')]).then(function () { drawPaper(); stackThumb(); }, function () {});\n}\nvar rt = 0;\naddEventListener('resize', function () { clearTimeout(rt); rt = setTimeout(function () { if (!cur && !busy) { layout(); stackThumb(); } }, 80); });\ndocument.addEventListener('visibilitychange', function () { if (!document.hidden) checkDay(); else { scratchStop(); save(true); } });\naddEventListener('pagehide', function () { save(true); });\nstart();\n})();\n</script>";
|
|
9
|
+
var CORE = "// Squiggle core - DOM-free: the day, the seeded squiggle and its dots, the pen model, the\n// stroke codec, and the pad and sketchbook the sheets move between. test/doodling.mjs runs it.\nvar SQ = (function () {\n 'use strict';\n var W = 1000, H = 1500; // a sheet in page units: 1000 x 1500, or turned\n var EPOCH = Date.UTC(2026, 9, 1); // No. 1 is Thursday 1 October 2026\n var DAY = 86400000;\n\n function rng(seed) { // mulberry32\n var s = seed >>> 0;\n return function () {\n s = (s + 0x6D2B79F5) >>> 0;\n var t = Math.imul(s ^ (s >>> 15), 1 | s);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n }\n function hash(str) {\n var h = 2166136261 >>> 0;\n for (var i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }\n return h;\n }\n\n // The day number everyone on the same calendar date shares: local date, not UTC instant.\n function dayNumber(date) {\n var d = date || new Date();\n return Math.floor((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - EPOCH) / DAY) + 1;\n }\n function dayDate(n) { var d = new Date(EPOCH + (n - 1) * DAY); return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); }\n function daySeed(n) { return hash('squiggle/day/' + n); }\n\n // Short codes for extra sheets, so a squiggle can be sent as a link. Six letters of five bits:\n // extra sheets draw their seeds below 2^30 so every one of them has a code.\n var ALPHA = 'abcdefghijkmnpqrstuvwxyz23456789';\n function codeFor(seed) { var s = ''; seed >>>= 0; for (var i = 0; i < 6; i++) { s += ALPHA[seed % 32]; seed = Math.floor(seed / 32); } return s; }\n function seedFor(code) {\n if (!/^[a-km-np-z2-9]{6}$/.test(code || '')) return null;\n var v = 0; for (var i = 5; i >= 0; i--) v = v * 32 + ALPHA.indexOf(code[i]);\n return v >>> 0;\n }\n\n // ---- the squiggle -------------------------------------------------------------------\n // A turtle walks with a curvature that drifts as a sum of slow sines, so the line turns,\n // loops and straightens the way a hand does. Candidates that cross themselves too often,\n // barely bend, or bunch into a knot are thrown away; the survivor is scaled into the\n // middle of the sheet. The same seed always gives the same line.\n var BOX_TALL = {x0: 190, y0: 430, x1: 810, y1: 1110}; // portrait sheet, 1000 x 1500\n var BOX_WIDE = {x0: 380, y0: 260, x1: 1120, y1: 850}; // landscape sheet, 1500 x 1000\n function sheetSize(wide) { return wide ? {w: H, h: W} : {w: W, h: H}; }\n\n function segIntersect(a, b, c, d) {\n var d1 = (d[0] - c[0]) * (a[1] - c[1]) - (d[1] - c[1]) * (a[0] - c[0]);\n var d2 = (d[0] - c[0]) * (b[1] - c[1]) - (d[1] - c[1]) * (b[0] - c[0]);\n var d3 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);\n var d4 = (b[0] - a[0]) * (d[1] - a[1]) - (b[1] - a[1]) * (d[0] - a[0]);\n return d1 * d2 < 0 && d3 * d4 < 0;\n }\n function crossings(p) {\n var n = 0, step = 3, q = [];\n for (var i = 0; i < p.length; i += step) q.push(p[i]);\n for (var a = 0; a < q.length - 1; a++)\n for (var b = a + 2; b < q.length - 1; b++)\n if (segIntersect(q[a], q[a + 1], q[b], q[b + 1])) n++;\n return n;\n }\n function turning(p) {\n var t = 0;\n for (var i = 1; i < p.length - 1; i++) {\n var a1 = Math.atan2(p[i][1] - p[i - 1][1], p[i][0] - p[i - 1][0]);\n var a2 = Math.atan2(p[i + 1][1] - p[i][1], p[i + 1][0] - p[i][0]);\n var d = a2 - a1; while (d > Math.PI) d -= 2 * Math.PI; while (d < -Math.PI) d += 2 * Math.PI;\n t += Math.abs(d);\n }\n return t;\n }\n function bbox(p) {\n var b = {x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9};\n for (var i = 0; i < p.length; i++) {\n if (p[i][0] < b.x0) b.x0 = p[i][0]; if (p[i][0] > b.x1) b.x1 = p[i][0];\n if (p[i][1] < b.y0) b.y0 = p[i][1]; if (p[i][1] > b.y1) b.y1 = p[i][1];\n }\n return b;\n }\n function walk(r) {\n var n = 150 + Math.floor(r() * 110), step = 4;\n var waves = [], k = 1 + Math.floor(r() * 3);\n var bias = (r() - 0.5) * 0.02;\n for (var i = 0; i < k; i++) waves.push({a: (0.012 + r() * 0.03) * (r() < 0.5 ? -1 : 1), f: 0.4 + r() * 2.6, ph: r() * 6.283});\n var x = 0, y = 0, h = r() * 6.283, p = [[0, 0]];\n for (var j = 0; j < n; j++) {\n var t = j / n, c = bias;\n for (var w = 0; w < waves.length; w++) c += waves[w].a * Math.sin(waves[w].f * 6.283 * t + waves[w].ph);\n h += c * step;\n x += Math.cos(h) * step; y += Math.sin(h) * step;\n p.push([x, y]);\n }\n return p;\n }\n function squiggle(seed, wide) {\n var r = rng(seed), p, tries = 0, BOX = wide ? BOX_WIDE : BOX_TALL;\n for (;;) {\n tries++;\n p = walk(r);\n var b = bbox(p), bw = b.x1 - b.x0, bh = b.y1 - b.y0;\n var turn = turning(p), cr = crossings(p);\n var ok = turn > 2.2 && turn < 13 && cr <= 2 && Math.max(bw, bh) > 1.6 * Math.min(bw, bh) * 0.5;\n if (ok || tries > 60) break;\n }\n // fit into the box, keep the aspect, a little smaller when the line is long\n var bb = bbox(p), sw = (BOX.x1 - BOX.x0) / (bb.x1 - bb.x0), sh = (BOX.y1 - BOX.y0) / (bb.y1 - bb.y0);\n var fit = Math.min(sw, sh), L = Math.max(bb.x1 - bb.x0, bb.y1 - bb.y0);\n var s = Math.min(fit, Math.max(fit * (0.7 + r() * 0.25), 520 / L));\n var cx = (bb.x0 + bb.x1) / 2, cy = (bb.y0 + bb.y1) / 2;\n var ox = (BOX.x0 + BOX.x1) / 2 + (r() - 0.5) * 80, oy = (BOX.y0 + BOX.y1) / 2 + (r() - 0.5) * 120;\n var out = [];\n for (var i = 0; i < p.length; i++) {\n var X = ox + (p[i][0] - cx) * s, Y = oy + (p[i][1] - cy) * s;\n out.push([Math.min(BOX.x1, Math.max(BOX.x0, X)), Math.min(BOX.y1, Math.max(BOX.y0, Y))]);\n }\n return resample(out, 5);\n }\n function resample(p, d) {\n var out = [p[0].slice()], carry = 0;\n for (var i = 1; i < p.length; i++) {\n var ax = p[i - 1][0], ay = p[i - 1][1], bx = p[i][0], by = p[i][1];\n var L = Math.hypot(bx - ax, by - ay), pos = d - carry;\n while (pos <= L) { out.push([ax + (bx - ax) * pos / L, ay + (by - ay) * pos / L]); pos += d; }\n carry = L - (pos - d);\n }\n var last = p[p.length - 1];\n if (Math.hypot(last[0] - out[out.length - 1][0], last[1] - out[out.length - 1][1]) > d * 0.3) out.push(last.slice());\n return out;\n }\n\n // ---- pens ---------------------------------------------------------------------------\n // Widths are decided once, while drawing, and stored with the point, so a replay or a\n // thumbnail draws exactly what was drawn.\n var TOOLS = ['pencil', 'fine', 'brush', 'marker', 'eraser'];\n var INKS = ['#262b36', '#3a5ba6', '#43795a', '#d9a23a', '#c96f8b', '#6f5592'];\n var BASE = {pencil: 5.5, fine: 4.4, brush: 30, marker: 34, eraser: 44};\n // Nib sizes, as a factor on BASE: a pen of each size is a different pen, not a zoom.\n var SIZES = [0.45, 0.7, 1, 1.5, 2.2];\n // The papers a pad can be, and what is printed on them.\n var PAPERS = ['#f5efe2', '#fbfaf6', '#e9e7e2', '#ddc8a4', '#e1eaec'];\n var RULES = ['plain', 'lined', 'grid', 'dots'];\n\n // A stroke's ink: 0-5 are the six inks; 16 and up carry any colour, 16 + 0xRRGGBB, so a\n // stroke stores its own colour in the same field old saves already use.\n function inkColor(i) {\n if (i >= 16) { var v = (i - 16) & 0xffffff; return '#' + ('00000' + v.toString(16)).slice(-6); }\n return INKS[i] || INKS[0];\n }\n function inkOf(hex) { var m = /^#?([0-9a-f]{6})$/i.exec(hex || ''); return m ? 16 + parseInt(m[1], 16) : 0; }\n function validInk(i) { return (i >= 0 && i < INKS.length) || (i >= 16 && i < 16 + 0x1000000); }\n\n // A pen in the hand: feed it pointer samples (page units, ms, pressure or -1), it returns\n // the points to keep. Steadied a little so a trembling finger still draws a clean line.\n function Pen(tool, x, y, t, pressure, size) {\n this.tool = tool; this.k = size > 0 ? size : 1; this.x = x; this.y = y; this.t = t; this.v = 0.6; this.n = 0;\n this.p = pressure; this.w = this.width(0.6, pressure) * (tool === 'brush' ? 0.35 : 1);\n this.pts = [[q(x, 2), q(y, 2), q(this.w, 4), 0]];\n }\n // points are kept at the precision they are stored with, so a sheet looks the same after a reload\n function q(v, k) { return Math.round(v * k) / k; }\n Pen.prototype.width = function (v, pr) {\n var b = BASE[this.tool] * this.k;\n if (this.tool === 'fine') return b * (0.78 + 0.32 * Math.exp(-v / 1.2)); // a fineliner bleeds a little when it lingers\n if (this.tool !== 'brush') return b;\n if (pr >= 0) return 1.6 * Math.min(1, this.k) + (b + 2) * Math.pow(Math.min(1, pr), 1.2) * (0.75 + 0.25 * Math.exp(-v / 1.6));\n return 1.2 * Math.min(1, this.k) + b * Math.exp(-v / 0.75);\n };\n Pen.prototype.add = function (x, y, t, pressure) {\n var k = this.tool === 'marker' || this.tool === 'eraser' ? 0.7 : 0.55; // steadying\n var nx = this.x + (x - this.x) * k, ny = this.y + (y - this.y) * k;\n var d = Math.hypot(nx - this.x, ny - this.y), dt = Math.max(1, t - this.t);\n if (d < 1.2) return null;\n this.v += (Math.min(8, d / dt) - this.v) * 0.3;\n this.n++;\n var target = this.width(this.v, pressure);\n var ramp = this.tool === 'brush' ? Math.min(1, 0.35 + this.n * 0.16) : 1;\n this.w += (target * ramp - this.w) * (this.tool === 'brush' ? 0.28 : this.tool === 'fine' ? 0.2 : 1);\n this.x = nx; this.y = ny;\n var pt = [q(nx, 2), q(ny, 2), q(this.w, 4), Math.min(250, Math.round(dt))];\n this.t = t; this.pts.push(pt);\n return pt;\n };\n Pen.prototype.end = function (x, y, t) { // the last stretch the steadying held back\n var d = Math.hypot(x - this.x, y - this.y);\n if (d > 1.2 && this.pts.length > 1) {\n var pt = [q(x, 2), q(y, 2), q(this.w * (this.tool === 'brush' ? 0.6 : 1), 4), Math.min(250, Math.max(1, Math.round(t - this.t)))];\n this.pts.push(pt); return pt;\n }\n return null;\n };\n\n // ---- codec --------------------------------------------------------------------------\n // A sheet is a list of strokes {tool, ink, gap, pts:[[x,y,w,dt]]}. Stored as zigzag\n // varints of deltas in half units (x, y), quarter units (w) and ms (dt), then base64:\n // around six bytes a point, so a busy page is tens of kilobytes, not megabytes.\n function zz(n) { return n >= 0 ? n * 2 : -n * 2 - 1; }\n function unzz(n) { return n & 1 ? -(n + 1) / 2 : n / 2; }\n function encode(strokes) {\n var out = [];\n function put(n) { n = zz(n); while (n >= 128) { out.push((n & 127) | 128); n = Math.floor(n / 128); } out.push(n); }\n put(1); put(strokes.length);\n for (var i = 0; i < strokes.length; i++) {\n var s = strokes[i];\n put(TOOLS.indexOf(s.tool)); put(s.ink | 0); put(Math.min(5000, Math.round(s.gap || 0))); put(s.pts.length);\n var px = 0, py = 0, pw = 0;\n for (var j = 0; j < s.pts.length; j++) {\n var p = s.pts[j], X = Math.round(p[0] * 2), Y = Math.round(p[1] * 2), Wq = Math.round(p[2] * 4);\n put(X - px); put(Y - py); put(Wq - pw); put(Math.round(p[3] || 0));\n px = X; py = Y; pw = Wq;\n }\n }\n var bin = ''; for (var k = 0; k < out.length; k++) bin += String.fromCharCode(out[k]);\n return b64e(bin);\n }\n function decode(str) {\n var bin = b64d(str), i = 0;\n function get() { var n = 0, m = 1, b; do { if (i >= bin.length) throw new Error('truncated'); b = bin.charCodeAt(i++); n += (b & 127) * m; m *= 128; } while (b & 128); return unzz(n); }\n var ver = get(); if (ver !== 1) throw new Error('version ' + ver);\n var n = get(), strokes = [];\n for (var s = 0; s < n; s++) {\n var tool = TOOLS[get()], ink = get(), gap = get(), c = get(), pts = [], px = 0, py = 0, pw = 0;\n if (!tool || c < 0 || c > 1e6) throw new Error('bad stroke');\n for (var j = 0; j < c; j++) { px += get(); py += get(); pw += get(); pts.push([px / 2, py / 2, pw / 4, get()]); }\n strokes.push({tool: tool, ink: ink, gap: gap, pts: pts});\n }\n return strokes;\n }\n var B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n function b64e(bin) {\n if (typeof btoa === 'function') return btoa(bin);\n var o = '';\n for (var i = 0; i < bin.length; i += 3) {\n var a = bin.charCodeAt(i), b = bin.charCodeAt(i + 1), c = bin.charCodeAt(i + 2), n = (a << 16) | ((b || 0) << 8) | (c || 0);\n o += B64[n >> 18 & 63] + B64[n >> 12 & 63] + (i + 1 < bin.length ? B64[n >> 6 & 63] : '=') + (i + 2 < bin.length ? B64[n & 63] : '=');\n }\n return o;\n }\n function b64d(s) {\n if (typeof atob === 'function') return atob(s);\n var o = '', buf = 0, bits = 0;\n for (var i = 0; i < s.length; i++) {\n var v = B64.indexOf(s[i]); if (v < 0) continue;\n buf = (buf << 6) | v; bits += 6;\n if (bits >= 8) { bits -= 8; o += String.fromCharCode((buf >> bits) & 255); }\n }\n return o;\n }\n\n\n // ---- the squiggle's dots ------------------------------------------------------------\n // The squiggle is printed as dots every DOT units along the line; `upto` (0..1) is how much\n // has been printed so far, and the newest dots swell into place. Where the line crosses\n // itself a dot that would land on an earlier one is left out (radius 0), so the crossing\n // reads as one line and not as a blot.\n var DOT = 15, DOTR = 4.2;\n function dots(pts, upto) {\n if (upto == null) upto = 1;\n var out = [], acc = 0, next = 0, total = 0, i;\n for (i = 1; i < pts.length; i++) total += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);\n var n = Math.max(1, Math.round(total / DOT)), step = total / n, lim = upto * total;\n for (i = 1; i < pts.length && next <= total + 0.01; i++) {\n var L = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);\n while (next <= acc + L + 0.01 && next <= total + 0.01) {\n if (next > lim + 0.01) return out;\n var f = L ? (next - acc) / L : 0, grow = Math.min(1, (lim - next) / (DOT * 3) + 0.25);\n var X = pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * f, Y = pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * f;\n var R = DOTR * (upto >= 1 ? 1 : grow);\n for (var c = 0; c < out.length - 2; c++)\n if (Math.hypot(out[c][0] - X, out[c][1] - Y) < DOT * 0.7) { R = 0; break; }\n out.push([X, Y, R]);\n next += step;\n }\n acc += L;\n }\n return out;\n }\n // Any pen that passes over a dot takes it in (the eraser too: it rubs the print away).\n // Returns the indices it took, so the page can answer each one.\n function absorb(list, hid, pts) {\n var got = [];\n for (var j = 0; j < pts.length; j++) {\n var r = pts[j][2] / 2 + 10, x = pts[j][0], y = pts[j][1];\n for (var q = 0; q < list.length; q++) {\n if (hid[q] || !list[q][2]) continue;\n var dx = list[q][0] - x, dy = list[q][1] - y;\n if (dx < r && dx > -r && dy < r && dy > -r && dx * dx + dy * dy < r * r) { hid[q] = 1; got.push(q); }\n }\n }\n // a dot or two left stranded between taken ones reads as a slip, not as a prompt\n for (var k = 0; k < list.length; k++) {\n if (hid[k]) continue;\n var e = k; while (e < list.length && !hid[e]) e++;\n if (e - k <= 2 && k > 0 && e < list.length) for (var m = k; m < e; m++) { hid[m] = 1; got.push(m); }\n k = e;\n }\n return got;\n }\n function covered(list, strokes) {\n var hid = new Uint8Array(list.length);\n for (var i = 0; i < strokes.length; i++) absorb(list, hid, strokes[i].pts);\n return hid;\n }\n\n // ---- sheets, the pad and the sketchbook ---------------------------------------------\n // A sheet: {id, kind: 'day' | 'extra', day, seed, wide, created, torn, paper, rule, strokes, redo}.\n // The pad holds one sheet; the sketchbook holds the torn ones, newest first.\n function sheet(o) {\n return {id: o.id, kind: o.kind, day: o.day, seed: o.seed >>> 0, wide: !!o.wide, created: o.created || 0,\n torn: o.torn || 0, n: o.n || 0, tip: !!o.tip, paper: pick(o.paper, PAPERS), rule: pick(o.rule, RULES), strokes: o.strokes || [], redo: []};\n }\n function pick(i, list) { return i >= 0 && i < list.length ? i | 0 : 0; }\n // a new sheet comes off the pad on the paper the person chose last\n function look(sh, opt) { if (opt) { sh.paper = pick(opt.paper, PAPERS); sh.rule = pick(opt.rule, RULES); } return sh; }\n function addStroke(sh, st) { sh.strokes.push(st); sh.redo.length = 0; }\n function undo(sh) { var st = sh.strokes.pop(); if (st) sh.redo.push(st); return st || null; }\n function redo(sh) { var st = sh.redo.pop(); if (st) sh.strokes.push(st); return st || null; }\n function inked(sh) { return !!sh && sh.strokes.length > 0; }\n function pack(sh) {\n return {id: sh.id, kind: sh.kind, day: sh.day, seed: sh.seed, wide: sh.wide, created: sh.created, torn: sh.torn,\n n: sh.n, tip: sh.tip, paper: sh.paper, rule: sh.rule, data: encode(sh.strokes)};\n }\n function unpack(o) {\n var sh = sheet(o);\n if (o.data) sh.strokes = decode(o.data);\n return sh;\n }\n\n // `opt` brings what the core cannot know: {wide, now, id(), seed()}.\n function daySheet(day, opt) { return look(sheet({id: opt.id(), kind: 'day', day: day, seed: daySeed(day), wide: opt.wide, created: opt.now, n: 1}), opt); }\n // The extra sheets of a day are numbered after today's: sheet 2, sheet 3... (n 0: one that came in a link)\n function extraSheet(seed, today, opt, n) { return look(sheet({id: opt.id(), kind: 'extra', day: today, seed: seed, wide: opt.wide, created: opt.now, n: n || 0}), opt); }\n function nextNumber(st, today) {\n var n = 1;\n st.book.forEach(function (b) { if (b.day === today && b.n > 0) n = Math.max(n, b.n + 1); else if (b.kind === 'day' && b.day === today) n = Math.max(n, 2); });\n if (st.pad && st.pad.day === today) n = Math.max(n, (st.pad.kind === 'day' ? 1 : st.pad.n) + 1);\n return Math.max(2, n);\n }\n function file(st, sh, now) { sh.torn = now; sh.redo = []; st.book.unshift(sh); return sh; }\n function tornToday(st, today) { return st.book.some(function (b) { return b.kind === 'day' && b.day === today; }); }\n\n // Opening the pad. On a new day today's sheet goes on top and the one that was there is\n // filed if it has ink in it; the same day leaves the pad as it was. Returns what was filed.\n function open(st, today, opt) {\n var filed = [];\n if (st.day !== today || !st.pad) {\n if (st.day !== today && st.pad && !(st.pad.kind === 'day' && st.pad.day === today)) {\n if (inked(st.pad)) filed.push(file(st, st.pad, opt.now));\n st.pad = null;\n }\n if (!st.pad) st.pad = tornToday(st, today) ? extraSheet(opt.seed(), today, opt, nextNumber(st, today)) : daySheet(today, opt);\n }\n st.day = today;\n return filed;\n }\n // Tearing the sheet off: filed if it has ink, and the next sheet carries a fresh squiggle.\n function tear(st, today, opt) {\n var n = nextNumber(st, today), out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n st.pad = extraSheet(opt.seed(), today, opt, n);\n return out;\n }\n // Taking a sheet back out of the sketchbook to draw on it again.\n function reopen(st, id, opt) {\n var i = indexOf(st, id); if (i < 0) return null;\n var sh = st.book.splice(i, 1)[0], out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n sh.torn = 0; st.pad = sh;\n return out;\n }\n // A squiggle that came in a link goes on a fresh sheet.\n function receive(st, kind, value, today, opt) {\n if (kind === 'day' && value === today && st.pad && st.pad.kind === 'day' && st.pad.day === today) return null;\n var out = inked(st.pad) ? file(st, st.pad, opt.now) : null;\n st.pad = kind === 'day' ? daySheet(value, opt) : extraSheet(value, today, opt, 0);\n return out;\n }\n function remove(st, id) { var i = indexOf(st, id); return i < 0 ? null : {sheet: st.book.splice(i, 1)[0], index: i}; }\n function restore(st, r) { st.book.splice(Math.min(r.index, st.book.length), 0, r.sheet); }\n function indexOf(st, id) { for (var i = 0; i < st.book.length; i++) if (st.book[i].id === id) return i; return -1; }\n\n // How long a replay of these strokes takes: real timing, pauses capped, then squeezed\n // so a sheet never takes longer than `max` ms to draw itself again.\n function replayPlan(strokes, max) {\n var total = 0, marks = [];\n for (var i = 0; i < strokes.length; i++) {\n total += Math.min(350, strokes[i].gap || 0);\n var start = total;\n for (var j = 0; j < strokes[i].pts.length; j++) total += Math.min(60, strokes[i].pts[j][3] || 0);\n marks.push([start, total]);\n }\n var k = total > max ? max / total : 1;\n return {duration: total * k, scale: k, marks: marks.map(function (m) { return [m[0] * k, m[1] * k]; })};\n }\n\n return {W: W, H: H, rng: rng, hash: hash, dayNumber: dayNumber, dayDate: dayDate, daySeed: daySeed,\n codeFor: codeFor, seedFor: seedFor, squiggle: squiggle, crossings: crossings, turning: turning, bbox: bbox, BOX: BOX_TALL, BOX_WIDE: BOX_WIDE, sheetSize: sheetSize,\n TOOLS: TOOLS, INKS: INKS, inkColor: inkColor, inkOf: inkOf, validInk: validInk, BASE: BASE, SIZES: SIZES, PAPERS: PAPERS, RULES: RULES, Pen: Pen, encode: encode, decode: decode, replayPlan: replayPlan,\n DOT: DOT, DOTR: DOTR, dots: dots, absorb: absorb, covered: covered,\n sheet: sheet, addStroke: addStroke, undo: undo, redo: redo, inked: inked, pack: pack, unpack: unpack,\n nextNumber: nextNumber, open: open, tear: tear, reopen: reopen, receive: receive, remove: remove, restore: restore};\n})();";
|
|
10
|
+
var INK = "// Ink: lays strokes onto a canvas the way each pen would put them on paper. Everything is in\n// page units; `s` is canvas pixels per unit.\nvar Ink = (function () {\n 'use strict';\n var PAPER = '#f5efe2', PRINT = '#e4553a';\n var tiles = {};\n\n // Paper tooth: a binary mask of where a dry point catches the grain. Sized in page units,\n // so the pencil looks the same on a phone and a monitor.\n function tooth(kind, s) {\n var key = kind + s.toFixed(3);\n if (tiles[key]) return tiles[key];\n var N = kind === 'paper' ? 512 : 256, c = document.createElement('canvas'); c.width = c.height = N;\n var g = c.getContext('2d'), img = g.createImageData(N, N), d = img.data;\n var cell = Math.max(1, 1.6 * s), r = SQ.rng(kind === 'print' ? 11 : 7);\n var gw = Math.ceil(N / cell) + 2, grid = new Float32Array(gw * gw);\n for (var i = 0; i < grid.length; i++) grid[i] = r();\n // wrap so the tile repeats without a seam\n var cols = Math.round(N / cell); if (cols < 1) cols = 1;\n for (var y = 0; y < N; y++) for (var x = 0; x < N; x++) {\n var fx = x / N * cols, fy = y / N * cols, ix = Math.floor(fx), iy = Math.floor(fy), tx = fx - ix, ty = fy - iy;\n var a = grid[(iy % cols) * gw + ix % cols], b = grid[(iy % cols) * gw + (ix + 1) % cols];\n var cc = grid[((iy + 1) % cols) * gw + ix % cols], dd = grid[((iy + 1) % cols) * gw + (ix + 1) % cols];\n tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);\n var v = (a + (b - a) * tx) * (1 - ty) + (cc + (dd - cc) * tx) * ty;\n v = v * 0.7 + r() * 0.3;\n var o = (y * N + x) * 4;\n d[o] = d[o + 1] = d[o + 2] = 0;\n if (kind === 'pencil') d[o + 3] = v > 0.3 ? 255 : (v > 0.22 ? 120 : 0);\n else if (kind === 'print') d[o + 3] = v > 0.12 ? 255 : 90;\n else if (kind === 'marker') d[o + 3] = v > 0.2 ? 255 : 150;\n else { d[o] = d[o + 1] = d[o + 2] = v > 0.5 ? 255 : 70; d[o + 3] = Math.round(Math.abs(v - 0.5) * 50); }\n }\n g.putImageData(img, 0, 0);\n return (tiles[key] = c);\n }\n\n // A sheet's paper: its colour, its grain, and whatever ruling it was printed with.\n function paper(ctx, wpx, hpx, s, sh) {\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 1;\n ctx.fillStyle = SQ.PAPERS[sh && sh.paper] || PAPER; ctx.fillRect(0, 0, wpx, hpx);\n rule(ctx, SQ.RULES[sh && sh.rule], wpx / s, hpx / s, s);\n ctx.fillStyle = ctx.createPattern(tooth('paper', s), 'repeat'); ctx.fillRect(0, 0, wpx, hpx);\n ctx.restore();\n }\n var GAP = 40; // the ruling's pitch, in page units: a school exercise book's\n function rule(ctx, kind, w, h, s) {\n if (!kind || kind === 'plain') return;\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n var x0 = (w % GAP) / 2, y0 = (h % GAP) / 2;\n if (kind === 'dots') {\n ctx.fillStyle = 'rgba(60,80,100,.42)'; ctx.beginPath();\n for (var x = x0; x <= w; x += GAP) for (var y = y0; y <= h; y += GAP) { ctx.moveTo(x + 1.8, y); ctx.arc(x, y, 1.8, 0, 6.2832); }\n ctx.fill();\n } else {\n ctx.strokeStyle = 'rgba(70,110,150,.3)'; ctx.lineWidth = Math.max(1 / s, 1.3); ctx.beginPath();\n var top = kind === 'lined' ? 200 : y0; // lines start below the printed head\n for (var yy = top; yy <= h - 30; yy += GAP) { ctx.moveTo(0, yy); ctx.lineTo(w, yy); }\n if (kind === 'grid') for (var xx = x0; xx <= w; xx += GAP) { ctx.moveTo(xx, 0); ctx.lineTo(xx, h); }\n ctx.stroke();\n if (kind === 'lined') { ctx.strokeStyle = 'rgba(200,80,70,.32)'; ctx.beginPath(); ctx.moveTo(60, 0); ctx.lineTo(60, h); ctx.stroke(); }\n }\n ctx.restore();\n }\n\n // Segments of a stroke between point i0 and i1 (exclusive end), as quadratic curves through\n // the midpoints, so a stroke drawn a piece at a time looks the same as one drawn whole.\n function segments(ctx, pts, i0, i1, variable) {\n var n = pts.length;\n if (n === 1) {\n if (i0 > 0) return;\n ctx.beginPath(); ctx.arc(pts[0][0], pts[0][1], pts[0][2] / 2, 0, 6.2832); ctx.fill(); return;\n }\n if (!variable) ctx.beginPath();\n for (var k = Math.max(0, i0); k < Math.min(i1, n); k++) {\n // segment k runs from m(k-1) to m(k) with control p[k]; m(-1)=p0, m(n-1)=p(n-1)\n var a = k === 0 ? pts[0] : mid(pts[k - 1], pts[k]);\n var b = k >= n - 1 ? pts[n - 1] : mid(pts[k], pts[k + 1]);\n var c = pts[k];\n if (!variable) {\n ctx.moveTo(a[0], a[1]); ctx.quadraticCurveTo(c[0], c[1], b[0], b[1]);\n continue;\n }\n var L = Math.hypot(c[0] - a[0], c[1] - a[1]) + Math.hypot(b[0] - c[0], b[1] - c[1]);\n var m = Math.max(1, Math.ceil(L / 2.5)), px = a[0], py = a[1];\n for (var j = 1; j <= m; j++) {\n var t = j / m, u = 1 - t;\n var x = u * u * a[0] + 2 * u * t * c[0] + t * t * b[0], y = u * u * a[1] + 2 * u * t * c[1] + t * t * b[1];\n ctx.lineWidth = a[2] + (b[2] - a[2]) * (t - 0.5 / m);\n ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x, y); ctx.stroke();\n px = x; py = y;\n }\n }\n if (!variable) ctx.stroke();\n }\n function offset(pts, o) {\n var out = [], n = pts.length;\n for (var i = 0; i < n; i++) {\n var a = pts[Math.max(0, i - 1)], b = pts[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1;\n out.push([pts[i][0] - dy / L * o, pts[i][1] + dx / L * o, pts[i][2]]);\n }\n return out;\n }\n function mid(p, q) { return [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]; }\n\n function style(tool) {\n // how the opaque shape is laid onto the sheet\n switch (tool) {\n case 'pencil': return {alpha: 0.88, op: 'multiply', mask: 'pencil'};\n case 'marker': return {alpha: 0.82, op: 'multiply', mask: 'marker'};\n case 'eraser': return {alpha: 1, op: 'destination-out', paper: true};\n case 'print': return {alpha: 0.95, op: 'multiply', mask: 'print'};\n case 'brush': return {alpha: 1, op: 'source-over', scratch: true};\n default: return {alpha: 1, op: 'source-over'};\n }\n }\n\n // Brush pens lift off to a point: the last stretch of a finished stroke narrows.\n function tapered(st, floor, len) {\n var p = st.pts, n = p.length, out = new Array(n), L = 0, i;\n var acc = new Float32Array(n);\n for (i = n - 1; i > 0; i--) { acc[i - 1] = acc[i] + Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]); }\n L = acc[0];\n var T = Math.min(len, L * 0.35), S0 = Math.min(len * 0.45, L * 0.2);\n for (i = 0; i < n; i++) {\n var k = T > 0 ? Math.min(1, floor + (1 - floor) * acc[i] / T) : 1;\n if (S0 > 0) k *= Math.min(1, (floor < 0.3 ? 0.25 : 0.45) + (floor < 0.3 ? 0.75 : 0.55) * (L - acc[i]) / S0); // and touches down to a point too\n out[i] = [p[i][0], p[i][1], p[i][2] * k];\n }\n return out;\n }\n\n // Draw a stroke opaque into `ctx` (a live layer, or scratch) - shape only.\n function shape(ctx, st, s, done) {\n var color = st.tool === 'print' ? PRINT : st.tool === 'eraser' ? '#000' : SQ.inkColor(st.ink);\n var pts = (st.tool === 'brush' || st.tool === 'fine') && done ? tapered(st, st.tool === 'fine' ? 0.55 : 0.12, st.tool === 'fine' ? 14 : 60) : st.pts, n = pts.length;\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n ctx.lineCap = ctx.lineJoin = 'round';\n if (st.tool === 'print') { // printed: an even row of dots, laid by a machine\n ctx.fillStyle = color;\n var d = st.dots || SQ.dots(pts, st.upto);\n ctx.beginPath();\n for (var q = 0; q < d.length; q++) {\n if (!d[q][2] || (st.hidden && st.hidden[q])) continue;\n ctx.moveTo(d[q][0] + d[q][2], d[q][1]); ctx.arc(d[q][0], d[q][1], d[q][2], 0, 6.2832);\n }\n ctx.fill();\n ctx.restore(); return;\n }\n ctx.strokeStyle = ctx.fillStyle = color;\n if (st.tool === 'marker') {\n chisel(ctx, pts);\n if (done && n > 8) { // the felt floods where it starts and stops\n ctx.globalCompositeOperation = 'destination-out'; ctx.globalAlpha = 0.14;\n chisel(ctx, pts.slice(3, n - 3));\n // and runs a little drier in lines, the way the felt was pulled\n var r = SQ.rng(Math.round(pts[0][0] * 7 + pts[0][1] * 13)), W = pts[0][2];\n ctx.lineCap = 'round'; ctx.lineWidth = W * 0.06;\n for (var q = 0; q < 4; q++) {\n ctx.globalAlpha = 0.05 + r() * 0.06;\n var off = offset(pts, (r() - 0.5) * W * 0.62);\n segments(ctx, off, 0, off.length, false);\n }\n }\n ctx.restore(); return;\n }\n var variable = st.tool === 'brush' || st.tool === 'fine';\n if (!variable) ctx.lineWidth = pts[0][2];\n segments(ctx, pts, 0, n, variable);\n if (st.tool === 'brush' && done) dry(ctx, pts);\n ctx.restore();\n }\n\n // Live drawing: only the segments i0..i1 of an unfinished stroke, opaque, onto a layer that\n // already holds the ones before. Returns the pixel box it touched, for finish().\n function part(ctx, st, s, i0, i1) {\n var color = st.tool === 'eraser' ? '#000' : SQ.inkColor(st.ink), pts = st.pts, n = pts.length;\n var a = Math.max(0, i0 - 1), sub = {pts: pts.slice(a, Math.min(n, i1 + 1))};\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0); ctx.lineCap = ctx.lineJoin = 'round';\n ctx.strokeStyle = ctx.fillStyle = color;\n if (st.tool === 'marker') chisel(ctx, sub.pts);\n else { if (st.tool !== 'brush' && st.tool !== 'fine') ctx.lineWidth = pts[0][2]; segments(ctx, pts, i0, i1, st.tool === 'brush' || st.tool === 'fine'); }\n ctx.restore();\n return bounds(sub, s, ctx.canvas.width, ctx.canvas.height);\n }\n\n // A chisel nib held at a slant: wide pulled one way, thin the other, square at the ends.\n var NIB = -0.62;\n function chisel(ctx, pts) {\n var W = pts[0][2], hx = Math.cos(NIB) * W * 0.42, hy = Math.sin(NIB) * W * 0.42;\n var q = sample(pts, 2.5);\n ctx.beginPath();\n for (var i = 0; i < q.length; i++) {\n var x = q[i][0], y = q[i][1];\n if (i) { var px = q[i - 1][0], py = q[i - 1][1];\n ctx.moveTo(px + hx, py + hy); ctx.lineTo(x + hx, y + hy); ctx.lineTo(x - hx, y - hy); ctx.lineTo(px - hx, py - hy); ctx.closePath(); }\n }\n ctx.fill('nonzero');\n // the felt tip itself: a worn wedge with soft corners\n ctx.lineWidth = W * 0.18; ctx.lineCap = 'round'; ctx.beginPath();\n for (var j = 0; j < q.length; j++) { ctx.moveTo(q[j][0] + hx, q[j][1] + hy); ctx.lineTo(q[j][0] - hx, q[j][1] - hy); }\n ctx.stroke();\n }\n // The smoothed centre line of a stroke, every `d` units.\n function sample(pts, d) {\n var out = [], n = pts.length;\n if (n === 1) return [pts[0]];\n for (var k = 0; k < n; k++) {\n var a = k === 0 ? pts[0] : mid(pts[k - 1], pts[k]), b = k >= n - 1 ? pts[n - 1] : mid(pts[k], pts[k + 1]), c = pts[k];\n var L = Math.hypot(c[0] - a[0], c[1] - a[1]) + Math.hypot(b[0] - c[0], b[1] - c[1]), m = Math.max(1, Math.ceil(L / d));\n for (var j = k ? 1 : 0; j <= m; j++) { var t = j / m, u = 1 - t;\n out.push([u * u * a[0] + 2 * u * t * c[0] + t * t * b[0], u * u * a[1] + 2 * u * t * c[1] + t * t * b[1], a[2] + (b[2] - a[2]) * t]); }\n }\n return out;\n }\n // Where a brush pen ran fast it runs dry: hairline gaps open along the stroke.\n function dry(ctx, pts) {\n var q = sample(pts, 2), max = 0, i;\n for (i = 0; i < q.length; i++) if (q[i][2] > max) max = q[i][2];\n var thr = max * 0.42, r = SQ.rng(Math.round(pts[0][0] * 31 + pts[0][1] * 17));\n ctx.save(); ctx.globalCompositeOperation = 'destination-out'; ctx.lineCap = 'round';\n var offs = [-0.34 + r() * 0.08, 0.3 + r() * 0.08];\n for (var o = 0; o < offs.length; o++) {\n for (i = 1; i < q.length; i++) {\n var w = q[i][2]; if (w > thr || q[i - 1][2] > thr) continue;\n var k = 1 - w / thr; // drier the thinner (faster) it got\n var dx = q[i][0] - q[i - 1][0], dy = q[i][1] - q[i - 1][1], L = Math.hypot(dx, dy) || 1, nx = -dy / L, ny = dx / L;\n ctx.globalAlpha = Math.min(0.55, k * 0.9); ctx.lineWidth = Math.max(0.35, w * 0.12);\n ctx.beginPath(); ctx.moveTo(q[i - 1][0] + nx * offs[o] * q[i - 1][2], q[i - 1][1] + ny * offs[o] * q[i - 1][2]); ctx.lineTo(q[i][0] + nx * offs[o] * w, q[i][1] + ny * offs[o] * w); ctx.stroke();\n }\n }\n ctx.restore();\n }\n function bounds(st, s, wpx, hpx) {\n var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;\n for (var i = 0; i < st.pts.length; i++) {\n var p = st.pts[i], r = p[2] / 2 + 5;\n if (p[0] - r < x0) x0 = p[0] - r; if (p[0] + r > x1) x1 = p[0] + r;\n if (p[1] - r < y0) y0 = p[1] - r; if (p[1] + r > y1) y1 = p[1] + r;\n }\n x0 = Math.max(0, Math.floor(x0 * s) - 2); y0 = Math.max(0, Math.floor(y0 * s) - 2);\n x1 = Math.min(wpx, Math.ceil(x1 * s) + 2); y1 = Math.min(hpx, Math.ceil(y1 * s) + 2);\n return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null;\n }\n // After drawing shape into a layer, give it its material (paper grain or the paper itself).\n function finish(ctx, st, s, box, paperCanvas) {\n var sty = style(st.tool);\n if (!box) return;\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0);\n if (sty.mask) { // destination-in clears all it is not drawn over: keep it to the box\n ctx.beginPath(); ctx.rect(box[0], box[1], box[2], box[3]); ctx.clip();\n ctx.globalCompositeOperation = 'destination-in';\n ctx.fillStyle = ctx.createPattern(tooth(sty.mask, s), 'repeat');\n ctx.fillRect(box[0], box[1], box[2], box[3]);\n } else if (sty.paper && paperCanvas) {\n ctx.globalCompositeOperation = 'source-atop';\n ctx.drawImage(paperCanvas, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n }\n ctx.restore();\n }\n\n // Lay a whole stroke onto the sheet.\n var scratch = null;\n function draw(ctx, st, s, paperCanvas) {\n var wpx = ctx.canvas.width, hpx = ctx.canvas.height, sty = style(st.tool);\n if (sty.alpha === 1 && sty.op === 'source-over' && !sty.mask && !sty.paper && !sty.scratch) { shape(ctx, st, s, true); return; }\n if (!scratch) scratch = document.createElement('canvas');\n if (scratch.width < wpx || scratch.height < hpx) { scratch.width = Math.max(scratch.width, wpx); scratch.height = Math.max(scratch.height, hpx); }\n var g = scratch.getContext('2d'), box = bounds(st, s, wpx, hpx);\n if (!box) return;\n g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(box[0], box[1], box[2], box[3]);\n g.save(); g.beginPath(); g.rect(box[0], box[1], box[2], box[3]); g.clip();\n shape(g, st, s, true);\n g.restore();\n finish(g, st, s, box, paperCanvas);\n ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = sty.alpha; ctx.globalCompositeOperation = sty.op;\n ctx.drawImage(scratch, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n ctx.restore();\n }\n\n return {part: part, PAPER: PAPER, PRINT: PRINT, paper: paper, draw: draw, shape: shape, finish: finish, bounds: bounds, style: style, tooth: tooth};\n})();";
|
|
11
|
+
var MAIN = "(function () {\n'use strict';\nvar $ = function (id) { return document.getElementById(id); };\nvar KEY = 'squiggle', reduced = matchMedia('(prefers-reduced-motion: reduce)');\nvar DPR = function () { return Math.min(2, window.devicePixelRatio || 1); };\nvar TOOL_NAMES = {pencil: 'Pencil', fine: 'Fineliner', brush: 'Brush pen', marker: 'Chisel marker', eraser: 'Eraser'};\nvar INK_NAMES = ['Blue-black', 'Cobalt', 'Leaf', 'Ochre', 'Rose', 'Plum'];\n\n// ---- state -----------------------------------------------------------------------------\nvar S = {pad: null, book: [], day: 0};\nvar MIXED = 5;\nvar P = {mixed: [], size: {}, paper: 0, rule: 0, date: true, number: true, lang: '', tool: 'brush', ink: 0, mute: false, hinted: false, strokes: 0, printed: false, torn: 0};\nvar opt = function (wide) {\n return {wide: wide, now: Date.now(), paper: P.paper, rule: P.rule, id: function () { return 's' + Date.now().toString(36) + Math.floor(Math.random() * 1e6).toString(36); },\n seed: function () { return Math.floor(Math.random() * 1073741824); }}; // 30 bits: what a six-letter code carries\n};\n\nfunction load() {\n var raw = null;\n try { raw = JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { raw = null; }\n if (raw && raw.v === 1) {\n try { S.pad = raw.pad ? SQ.unpack(raw.pad) : null; } catch (e) { S.pad = null; }\n S.book = (raw.book || []).map(function (o) { try { return SQ.unpack(o); } catch (e) { return null; } }).filter(Boolean);\n S.day = raw.day || 0;\n if (raw.prefs) for (var k in P) if (k in raw.prefs) P[k] = raw.prefs[k];\n }\n if (SQ.TOOLS.indexOf(P.tool) < 0) P.tool = 'brush';\n if (!SQ.validInk(P.ink)) P.ink = 0;\n var sz = {}; SQ.TOOLS.forEach(function (t) { var v = P.size && P.size[t]; sz[t] = v >= 0 && v < SQ.SIZES.length ? v | 0 : 2; }); P.size = sz;\n if (!(P.paper >= 0 && P.paper < SQ.PAPERS.length)) P.paper = 0;\n if (!(P.rule >= 0 && P.rule < SQ.RULES.length)) P.rule = 0;\n P.date = P.date !== false; P.number = P.number !== false; if (P.lang !== 'en') P.lang = '';\n P.mixed = (Array.isArray(P.mixed) ? P.mixed : []).filter(function (v) { return v >= 16 && SQ.validInk(v); }).slice(0, MIXED);\n}\nvar saveT = 0, warned = false;\nfunction save(now) {\n clearTimeout(saveT);\n var go = function () {\n try {\n localStorage.setItem(KEY, JSON.stringify({v: 1, day: S.day, pad: S.pad ? SQ.pack(S.pad) : null, book: S.book.map(SQ.pack), prefs: P}));\n } catch (e) {\n if (!warned) { warned = true; toast('The sketchbook is full. Save a few sheets as images and remove them.'); }\n }\n };\n if (now) go(); else saveT = setTimeout(go, 250);\n}\n\n// ---- layout ----------------------------------------------------------------------------\nvar root = document.documentElement, side = false, dims = {w: 1000, h: 1500}, scale = 1, cssW = 300, cssH = 450;\nvar C = {paper: $('cPaper'), dots: $('cDots'), ink: $('cInk'), live: $('cLive')}, X = {};\nfor (var k in C) X[k] = C[k].getContext('2d');\n\nfunction wantSide() { return innerWidth / innerHeight > 1.15 && innerWidth >= 640; }\nfunction layout() {\n side = wantSide();\n root.classList.toggle('side', side);\n var book = $('bookBtn');\n (side ? $('top2') : $('top')).appendChild(book);\n if (side) { document.querySelector('.acts').appendChild($('mute')); document.querySelector('.acts').appendChild($('setBtn')); }\n else { $('topL').appendChild($('mute')); $('topL').appendChild($('setBtn')); }\n closeSizes();\n dims = SQ.sheetSize(S.pad && S.pad.wide);\n root.classList.toggle('tallsheet', !!(S.pad && !S.pad.wide));\n var aw, ah;\n if (side) {\n var k = Math.min(1, (innerHeight - 60) / 600);\n $('col').style.setProperty('--k', k.toFixed(3));\n aw = innerWidth - 144 - 236 - 40 - 60; ah = innerHeight - 28 - 70;\n } else {\n var st = $('stage').getBoundingClientRect(), cs = getComputedStyle($('stage'));\n aw = st.width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);\n ah = st.height - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom) - 14;\n }\n var ratio = dims.h / dims.w;\n cssW = Math.max(120, Math.floor(Math.min(aw, ah / ratio)));\n cssH = Math.round(cssW * ratio);\n var pad = $('pad');\n root.style.setProperty('--pw', cssW + 'px'); root.style.setProperty('--ph', cssH + 'px');\n pad.style.setProperty('--pw', cssW + 'px'); pad.style.setProperty('--ph', cssH + 'px');\n var cs2 = Math.round(Math.min(cssW, cssH) * 0.13);\n pad.style.setProperty('--cs', cs2 + 'px');\n var px = Math.round(cssW * DPR()), py = Math.round(cssH * DPR());\n for (var n in C) { C[n].width = px; C[n].height = py; }\n scale = px / dims.w;\n curlSize = cs2; drawCurl(0);\n redrawAll();\n}\n\n// ---- the sheet's layers ------------------------------------------------------------------\nvar squig = null, dotList = [], hidden = new Uint8Array(0), printUpto = 1;\nfunction setSheet() {\n var sh = S.pad;\n squig = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n dotList = SQ.dots(squig.pts, 1);\n hidden = SQ.covered(dotList, sh.strokes);\n $('sheet').setAttribute('aria-label', 'Sheet for ' + dateLabel(sh) + ', with a dotted squiggle to turn into a drawing');\n}\nfunction dateLabel(sh) {\n var d = sh.kind === 'day' ? SQ.dayDate(sh.day) : new Date(sh.created || Date.now());\n return d.toLocaleDateString(P.lang || undefined, {weekday: 'long', day: 'numeric', month: 'long'});\n}\n// The printed head of a sheet: the date and, at the right, which of the day's sheets it is. The\n// first few sheets someone ever gets also print the one line of instructions there is.\nfunction header(ctx, sh, s, w) {\n ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);\n ctx.textBaseline = 'alphabetic';\n ctx.fillStyle = '#5f574b'; ctx.font = '500 34px Fraunces, Georgia, serif';\n if (P.date) ctx.fillText(dateLabel(sh), 72, 108);\n if (sh.tip) {\n ctx.fillStyle = Ink.PRINT;\n for (var i = 0; i < 3; i++) { ctx.beginPath(); ctx.arc(77 + i * 12, 140, 4.2, 0, 6.2832); ctx.fill(); }\n ctx.fillStyle = '#8f8473'; ctx.font = 'italic 400 26px Fraunces, Georgia, serif';\n ctx.fillText('Turn the squiggle into anything', 113, 148);\n }\n var tag = P.number ? sheetTag(sh) || 'No. ' + sh.day : '';\n if (tag) { ctx.textAlign = 'right'; ctx.fillStyle = '#a89c86'; ctx.font = 'italic 400 24px Fraunces, Georgia, serif'; ctx.fillText(tag, w - 72, 108); }\n ctx.restore();\n}\nfunction sheetTag(sh) { return sh.kind === 'day' ? '' : sh.n >= 2 ? 'sheet ' + sh.n + ', just yours' : 'sent to you'; }\n// a sheet that has just been laid on the pad\nfunction laid(before) { if (S.pad !== before && !S.pad.strokes.length) S.pad.tip = P.torn < 3; }\nfunction drawPaper() {\n Ink.paper(X.paper, C.paper.width, C.paper.height, scale, S.pad);\n $('sheet').style.background = SQ.PAPERS[S.pad.paper];\n header(X.paper, S.pad, scale, dims.w);\n}\nfunction drawDots() {\n var g = X.dots; g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, C.dots.width, C.dots.height);\n var list = printUpto >= 1 ? dotList : SQ.dots(squig.pts, printUpto);\n Ink.draw(g, {tool: 'print', pts: squig.pts, dots: list, hidden: hidden}, scale, null);\n}\nfunction drawInk() {\n var g = X.ink; g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, C.ink.width, C.ink.height);\n var st = S.pad.strokes;\n for (var i = 0; i < st.length; i++) Ink.draw(g, st[i], scale, C.paper);\n}\nfunction redrawAll() { drawPaper(); drawDots(); drawInk(); clearLive(); updateActs(); }\nfunction clearLive() { X.live.setTransform(1, 0, 0, 1, 0, 0); X.live.clearRect(0, 0, C.live.width, C.live.height); }\n\n// ---- drawing -----------------------------------------------------------------------------\nvar cur = null, pen = null, touches = new Map(), gesture = null, sawPen = false, lastEnd = 0;\nvar sheetEl = $('sheet');\nfunction toPage(e) {\n var r = sheetEl.getBoundingClientRect();\n return [(e.clientX - r.left) / r.width * dims.w, (e.clientY - r.top) / r.height * dims.h];\n}\nsheetEl.addEventListener('pointerdown', function (e) {\n if (e.button > 0 || busy) return;\n unlock();\n if (e.pointerType === 'pen') sawPen = true;\n if (e.pointerType === 'touch') {\n if (sawPen) return; // a pencil is in use: a resting palm is not a stroke\n touches.set(e.pointerId, {x: e.clientX, y: e.clientY, t: performance.now()});\n if (touches.size >= 2) { startGesture(); return; }\n }\n try { sheetEl.setPointerCapture(e.pointerId); } catch (_) {}\n var p = toPage(e), t = performance.now();\n pen = new SQ.Pen(P.tool, p[0], p[1], t, e.pointerType === 'pen' ? e.pressure : -1, SQ.SIZES[P.size[P.tool]]);\n cur = {tool: P.tool, ink: P.ink, gap: lastEnd ? Math.min(5000, Math.round(t - lastEnd)) : 0, pts: pen.pts, id: e.pointerId};\n C.live.className = Ink.style(P.tool).op === 'multiply' ? 'multiply' : '';\n C.live.style.opacity = P.tool === 'eraser' ? 1 : Ink.style(P.tool).alpha;\n absorbLive(pen.pts);\n paintLive();\n scratchStart(P.tool);\n});\nsheetEl.addEventListener('pointermove', function (e) {\n if (touches.has(e.pointerId)) { var tt = touches.get(e.pointerId); tt.mx = Math.max(tt.mx || 0, Math.hypot(e.clientX - tt.x, e.clientY - tt.y)); }\n if (!cur || e.pointerId !== cur.id) return;\n var evs = e.getCoalescedEvents ? e.getCoalescedEvents() : [e];\n if (!evs.length) evs = [e];\n var added = [], v = 0;\n for (var i = 0; i < evs.length; i++) {\n var p = toPage(evs[i]), before = pen.v;\n var pt = pen.add(p[0], p[1], evs[i].timeStamp || performance.now(), e.pointerType === 'pen' ? evs[i].pressure : -1);\n if (pt) { added.push(pt); v = pen.v; }\n }\n if (added.length) { absorbLive(added); paintLive(); scratchMove(v); }\n});\nfunction endStroke(e, cancel) {\n if (touches.has(e.pointerId)) {\n var tt = touches.get(e.pointerId); touches.delete(e.pointerId);\n if (gesture) { gesture.ups++; if (!(tt.mx > 24)) gesture.still++; if (touches.size === 0) endGesture(); return; }\n }\n if (!cur || e.pointerId !== cur.id) return;\n scratchStop();\n if (cancel) { cur = null; pen = null; clearLive(); hidden = SQ.covered(dotList, S.pad.strokes); drawDots(); return; }\n var p = toPage(e); pen.end(p[0], p[1], performance.now());\n var st = {tool: cur.tool, ink: cur.ink, gap: cur.gap, pts: pen.pts};\n cur = null; pen = null; lastEnd = performance.now();\n SQ.addStroke(S.pad, st);\n Ink.draw(X.ink, st, scale, C.paper);\n clearLive();\n updateActs(); save();\n P.strokes++;\n if (P.strokes >= 6 && !P.hinted) { P.hinted = true; setTimeout(hintCurl, 500); }\n // a drawing left alone for a while: the corner lifts once, in case it is finished\n clearTimeout(idleT);\n var sh = S.pad;\n idleT = setTimeout(function () { if (S.pad === sh && !cur && !busy && sh.strokes.length >= 3 && !sh.nudged && $('book').hidden) { sh.nudged = true; hintCurl(); } }, 25000);\n}\nsheetEl.addEventListener('pointerup', function (e) { endStroke(e, false); });\nsheetEl.addEventListener('pointercancel', function (e) { endStroke(e, true); });\n\n// the live stroke is laid down a few segments a frame; the last one is drawn provisionally and\n// again once the next point says where the curve goes\nvar liveRaf = 0, shapeBuf = null;\nfunction paintLive() {\n if (liveRaf) return;\n liveRaf = requestAnimationFrame(function () {\n liveRaf = 0;\n if (!cur) return;\n var n = cur.pts.length, from = cur.drawn || 0;\n if (!Ink.style(cur.tool).mask && cur.tool !== 'eraser') {\n Ink.part(X.live, cur, scale, from, n);\n } else {\n // the grain is applied to a fresh copy of what changed, never twice to the same\n // pixels - a mask laid again every frame would fade the stroke away as it is drawn\n if (!shapeBuf || shapeBuf.width !== C.live.width || shapeBuf.height !== C.live.height) {\n shapeBuf = document.createElement('canvas'); shapeBuf.width = C.live.width; shapeBuf.height = C.live.height;\n }\n var sg = shapeBuf.getContext('2d');\n if (!from) { sg.setTransform(1, 0, 0, 1, 0, 0); sg.clearRect(0, 0, shapeBuf.width, shapeBuf.height); }\n var box = Ink.part(sg, cur, scale, from, n);\n if (box) {\n var g = X.live; g.save(); g.setTransform(1, 0, 0, 1, 0, 0);\n g.clearRect(box[0], box[1], box[2], box[3]);\n g.drawImage(shapeBuf, box[0], box[1], box[2], box[3], box[0], box[1], box[2], box[3]);\n g.restore();\n Ink.finish(g, cur, scale, box, cur.tool === 'eraser' ? C.paper : null);\n }\n }\n cur.drawn = Math.max(0, n - 1);\n });\n}\nvar tickT = 0, idleT = 0;\nfunction absorbLive(pts) {\n var got = SQ.absorb(dotList, hidden, pts);\n if (got.length) { drawDots(); var n = performance.now(); if (n - tickT > 45) { tickT = n; sfx('tick'); } }\n}\n\n// two fingers tapped together take the last stroke back; three bring it again\nfunction startGesture() {\n if (cur) { // the first finger had started a stroke: drop it\n scratchStop(); cur = null; pen = null; clearLive();\n hidden = SQ.covered(dotList, S.pad.strokes); drawDots();\n }\n if (!gesture) gesture = {n: 0, ups: 0, still: 0, t: performance.now()};\n gesture.n = Math.max(gesture.n, touches.size);\n}\nfunction endGesture() {\n var g = gesture; gesture = null;\n if (performance.now() - g.t > 450 || g.still < g.n) return;\n if (g.n === 2) doUndo(); else if (g.n >= 3) doRedo();\n}\n\n// ---- undo, redo ----------------------------------------------------------------------------\nfunction doUndo() {\n if (busy) return;\n var st = SQ.undo(S.pad); if (!st) return;\n hidden = SQ.covered(dotList, S.pad.strokes);\n drawInk(); drawDots(); fadeOut(st); updateActs(); save(); sfx('undo');\n}\nfunction doRedo() {\n if (busy) return;\n var st = SQ.redo(S.pad); if (!st) return;\n SQ.absorb(dotList, hidden, st.pts);\n drawDots(); updateActs(); save(); sfx('undo');\n if (reduced.matches) { Ink.draw(X.ink, st, scale, C.paper); return; }\n var g = X.live; clearLive(); C.live.className = ''; C.live.style.opacity = 1;\n Ink.draw(g, st, scale, C.paper);\n C.live.animate([{opacity: 0}, {opacity: 1}], {duration: 180, easing: 'ease-out'}).onfinish = function () {\n Ink.draw(X.ink, st, scale, C.paper); if (!cur) clearLive();\n };\n}\nfunction fadeOut(st) {\n if (reduced.matches) return;\n var g = X.live; clearLive(); C.live.className = ''; C.live.style.opacity = 1;\n Ink.draw(g, st, scale, C.paper);\n C.live.animate([{opacity: 1}, {opacity: 0}], {duration: 180, easing: 'ease-out'}).onfinish = function () { if (!cur) clearLive(); };\n}\nfunction updateActs() { $('undo').disabled = !S.pad.strokes.length; $('redo').disabled = !S.pad.redo.length; }\n$('undo').onclick = function () { unlock(); doUndo(); };\n$('redo').onclick = function () { unlock(); doRedo(); };\n\n// ---- the tray ----------------------------------------------------------------------------\nfunction hex(c) { return [1, 3, 5].map(function (i) { return parseInt(c.slice(i, i + 2), 16); }); }\nfunction mix(c, t, k) { var a = hex(c), b = hex(t); return '#' + a.map(function (v, i) { return Math.round(v + (b[i] - v) * k).toString(16).padStart(2, '0'); }).join(''); }\nvar gid = 0;\nfunction penSvg(kind, c) {\n var defs = [];\n var C2 = function (col) {\n var id = 'g' + (gid++);\n defs.push('<linearGradient id=\"' + id + '\" x1=\"0\" x2=\"1\"><stop offset=\"0\" stop-color=\"' + mix(col, '#000000', .35) + '\"/><stop offset=\".22\" stop-color=\"' + mix(col, '#ffffff', .38) + '\"/><stop offset=\".42\" stop-color=\"' + col + '\"/><stop offset=\".8\" stop-color=\"' + mix(col, '#000000', .22) + '\"/><stop offset=\"1\" stop-color=\"' + mix(col, '#000000', .45) + '\"/></linearGradient>');\n return 'url(#' + id + ')';\n };\n var b = '';\n if (kind === 'pencil') b = '<path d=\"M13 46 23 6 33 46Z\" fill=\"' + C2('#e9c495') + '\"/><path d=\"M19.4 21 23 6 26.6 21Z\" fill=\"' + C2(c) + '\"/><rect x=\"13\" y=\"46\" width=\"20\" height=\"104\" fill=\"' + C2('#e8b52e') + '\"/><rect x=\"13\" y=\"46\" width=\"6\" height=\"104\" fill=\"rgba(255,255,255,.18)\"/><rect x=\"27\" y=\"46\" width=\"6\" height=\"104\" fill=\"rgba(80,50,0,.22)\"/><path d=\"M19.4 48v102M26.6 48v102\" stroke=\"rgba(120,80,0,.35)\" stroke-width=\".7\"/><path d=\"M13 46q1.7 3 3.3 0t3.3 0 3.4 0 3.3 0 3.3 0 3.4 0\" fill=\"#e9c495\"/><rect x=\"13\" y=\"118\" width=\"20\" height=\"32\" fill=\"' + C2('#4a4d55') + '\"/>';\n if (kind === 'fine') b = '<rect x=\"21.6\" y=\"4\" width=\"2.8\" height=\"16\" rx=\"1.2\" fill=\"' + C2(c) + '\"/><path d=\"M17 40 20 18h6l3 22Z\" fill=\"' + C2('#c3c8ce') + '\"/><rect x=\"14\" y=\"40\" width=\"18\" height=\"110\" rx=\"3\" fill=\"' + C2('#6f7782') + '\"/><rect x=\"14\" y=\"40\" width=\"18\" height=\"16\" fill=\"' + C2('#2c2f36') + '\"/><rect x=\"14\" y=\"48\" width=\"18\" height=\"4\" fill=\"' + C2(c) + '\"/><rect x=\"29\" y=\"58\" width=\"5\" height=\"58\" rx=\"2.5\" fill=\"' + C2('#d9dde2') + '\"/>';\n if (kind === 'brush') b = '<path d=\"M23 2C18 14 16 28 16 40h14c0-12-2-26-7-38Z\" fill=\"' + C2(c) + '\"/><rect x=\"15\" y=\"40\" width=\"16\" height=\"7\" fill=\"' + C2('#c9a24a') + '\"/><rect x=\"13\" y=\"47\" width=\"20\" height=\"103\" rx=\"3\" fill=\"' + C2('#2c2f36') + '\"/><rect x=\"13\" y=\"58\" width=\"20\" height=\"5\" fill=\"' + C2(c) + '\"/><rect x=\"13\" y=\"69\" width=\"20\" height=\"2\" fill=\"#c9a24a\"/>';\n if (kind === 'marker') b = '<path d=\"M16 22 30 8v16H16Z\" fill=\"' + C2(c) + '\"/><path d=\"M13 44 16 24h14l3 20Z\" fill=\"' + C2('#cfc8ba') + '\"/><rect x=\"7\" y=\"44\" width=\"32\" height=\"106\" rx=\"6\" fill=\"' + C2('#f2eee6') + '\"/><rect x=\"7\" y=\"44\" width=\"32\" height=\"34\" rx=\"6\" fill=\"' + C2('#3b3e45') + '\"/><rect x=\"7\" y=\"74\" width=\"32\" height=\"4\" fill=\"rgba(0,0,0,.25)\"/><rect x=\"7\" y=\"84\" width=\"32\" height=\"10\" fill=\"' + C2(c) + '\"/>';\n if (kind === 'eraser') b = '<path d=\"M3 64V50q0-5 5-6l30-3q5 0 5 5v18Z\" fill=\"' + C2('#f7f3ea') + '\"/><path d=\"M6 50q0-4 4-5l24-2.6\" stroke=\"rgba(255,255,255,.8)\" stroke-width=\"2\" fill=\"none\"/><rect x=\"2\" y=\"62\" width=\"42\" height=\"88\" rx=\"1.5\" fill=\"' + C2('#3d6db0') + '\"/><rect x=\"2\" y=\"62\" width=\"42\" height=\"5\" fill=\"' + C2('#f2cf3a') + '\"/><path d=\"M10 96h26M10 103h17\" stroke=\"rgba(255,255,255,.6)\" stroke-width=\"2.4\" stroke-linecap=\"round\"/>';\n var gloss = kind === 'marker' ? 11 : kind === 'eraser' ? 7 : 16, gy = kind === 'eraser' ? 66 : 48;\n return '<svg viewBox=\"0 0 46 150\" aria-hidden=\"true\"><defs>' + defs.join('') + '</defs>' + b + '<rect x=\"' + gloss + '\" y=\"' + gy + '\" width=\"2.4\" height=\"' + (150 - gy) + '\" rx=\"1.2\" fill=\"rgba(255,255,255,.5)\"/></svg>';\n}\nfunction buildTray() {\n var pens = $('pens'); pens.innerHTML = '';\n // focusing a half-hidden pen must not scroll the row (where overflow: clip is missing)\n pens.addEventListener('scroll', function () { pens.scrollTop = 0; pens.scrollLeft = 0; });\n SQ.TOOLS.forEach(function (t, i) {\n var b = document.createElement('button');\n b.className = 'pen' + (t === P.tool ? ' on' : ''); b.dataset.tool = t;\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', t === P.tool); b.setAttribute('aria-label', TOOL_NAMES[t] + ' (' + (i + 1) + ')');\n b.innerHTML = penSvg(t, t === P.tool ? SQ.inkColor(P.ink) : REST);\n b.onclick = function () { unlock(); pickTool(t); };\n pens.appendChild(b);\n });\n buildInks();\n}\n// The six inks, the last colour mixed, and a well that mixes any colour at all.\nfunction ringPath(i) {\n var r = SQ.rng(i * 31 + 7);\n return 'M5 ' + (21 + r() * 3).toFixed(1) + 'C3 ' + (10 + r() * 3).toFixed(1) + ' 13 3 22 4c10 1 15 9 12 ' + (18 + r() * 2).toFixed(1) + '-3 10-15 14-23 8-3-3-4-6-3-' + (9 + r() * 2).toFixed(1);\n}\nfunction inkButton(value, label, extra) {\n var b = document.createElement('button'), on = value === P.ink;\n b.className = 'inkb' + (on ? ' on' : ''); b.dataset.ink = value;\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on); b.setAttribute('aria-label', label);\n b.innerHTML = (extra || '<span class=\"well\" style=\"--c:' + SQ.inkColor(value) + '\"></span>') + '<svg class=\"ring\" viewBox=\"-2 -2 42 42\" aria-hidden=\"true\"><path d=\"' + ringPath(value % 97) + '\"/></svg>';\n b.onclick = function () { unlock(); pickInk(value); };\n return b;\n}\nfunction buildInks() {\n var inks = $('inks'); inks.innerHTML = '';\n SQ.INKS.forEach(function (c, i) { inks.appendChild(inkButton(i, INK_NAMES[i] + ' ink')); });\n P.mixed.forEach(function (v) { inks.appendChild(inkButton(v, 'Mixed colour ' + SQ.inkColor(v))); });\n var mixb = document.createElement('button');\n mixb.className = 'inkb mixer'; mixb.setAttribute('aria-label', 'Mix any colour');\n mixb.innerHTML = '<span class=\"well mix\"></span><input type=\"color\" tabindex=\"-1\" aria-hidden=\"true\">';\n var input = mixb.lastChild;\n mixb.onclick = function (e) { if (e.target === input) return; unlock(); input.value = SQ.inkColor(P.ink); input.click(); };\n // the pens take the colour while it is being mixed; the well keeps it once it is chosen\n input.addEventListener('input', function () { var v = SQ.inkOf(input.value); P.ink = v; tintPens(); });\n input.addEventListener('change', function () { var v = SQ.inkOf(input.value); keepMixed(v); P.ink = -1; buildInks(); pickInk(v); });\n inks.appendChild(mixb);\n}\n// the last few mixed colours stay in the tray, newest first, beside the six inks\nfunction keepMixed(v) { if (v < 16) return; P.mixed = [v].concat(P.mixed.filter(function (x) { return x !== v; })).slice(0, MIXED); }\nfunction tintPens() { [].forEach.call($('pens').children, function (b) { if (b.dataset.tool === P.tool) b.innerHTML = penSvg(P.tool, SQ.inkColor(P.ink)); }); }\nvar REST = '#4a4d55'; // pens lying in the tray show a plain dark nib; the one in hand shows the ink\nfunction pickTool(t) {\n if (t === P.tool) return;\n P.tool = t;\n [].forEach.call($('pens').children, function (b) { var on = b.dataset.tool === t; b.classList.toggle('on', on); b.setAttribute('aria-checked', on); b.innerHTML = penSvg(b.dataset.tool, on ? SQ.inkColor(P.ink) : REST); });\n sizeIcon(); if (!$('sizes').hidden) openSizes();\n sfx('tock'); buzz(); save();\n}\nfunction pickInk(i) {\n if (i === P.ink) return;\n P.ink = i;\n [].forEach.call($('inks').children, function (b) { var on = +b.dataset.ink === i; b.classList.toggle('on', on); if (b.dataset.ink) b.setAttribute('aria-checked', on); });\n if (P.tool === 'eraser') pickTool('brush');\n tintPens();\n sfx('plip'); save();\n}\nfunction buzz() { if (navigator.vibrate) try { navigator.vibrate(6); } catch (e) {} }\n\n// ---- the corner, peeling and tearing -----------------------------------------------------\nvar curlSize = 46, peel = null, busy = false;\nfunction curlSvg(c) {\n var A = [0, c], B = [c, 0], T = [c * .27, c * .27];\n var flap = 'M' + A + ' Q' + c * .1 + ' ' + c * .6 + ' ' + T + ' Q' + c * .6 + ' ' + c * .1 + ' ' + B + ' Z';\n return '<defs><linearGradient id=\"fl\" x1=\"' + c * .62 + '\" y1=\"' + c * .62 + '\" x2=\"' + c * .2 + '\" y2=\"' + c * .2 + '\" gradientUnits=\"userSpaceOnUse\"><stop offset=\"0\" stop-color=\"#fbf6ea\"/><stop offset=\".18\" stop-color=\"#efe6d3\"/><stop offset=\".7\" stop-color=\"#ddd1b8\"/><stop offset=\"1\" stop-color=\"#cfc2a6\"/></linearGradient>' +\n '<linearGradient id=\"un\" x1=\"' + c * .5 + '\" y1=\"' + c * .5 + '\" x2=\"' + c + '\" y2=\"' + c + '\" gradientUnits=\"userSpaceOnUse\"><stop offset=\"0\" stop-color=\"#d4c7aa\"/><stop offset=\".45\" stop-color=\"#ebe3d1\"/><stop offset=\"1\" stop-color=\"#f1eadb\"/></linearGradient>' +\n '<filter id=\"sh\" x=\"-60%\" y=\"-60%\" width=\"220%\" height=\"220%\"><feGaussianBlur stdDeviation=\"' + (c * .07).toFixed(2) + '\"/></filter></defs>' +\n '<path d=\"M' + A + ' L' + B + ' L' + c + ' ' + c + 'Z\" fill=\"url(#un)\"/>' +\n '<path d=\"' + flap + '\" fill=\"rgba(45,30,10,.38)\" filter=\"url(#sh)\" transform=\"translate(' + (-c * .05).toFixed(1) + ' ' + (-c * .03).toFixed(1) + ')\"/>' +\n '<path d=\"' + flap + '\" fill=\"url(#fl)\"/><path d=\"M' + A + ' L' + B + '\" stroke=\"rgba(255,255,255,.85)\" stroke-width=\"1.2\"/>' +\n '<path d=\"M' + c * .1 + ' ' + c * .86 + ' Q' + c * .25 + ' ' + c * .42 + ' ' + T + '\" stroke=\"rgba(255,255,255,.35)\" stroke-width=\"' + (c * .03).toFixed(1) + '\" fill=\"none\"/>';\n}\n// p: 0 = resting curl, 1 = the corner pulled a long way back\nfunction drawCurl(p) {\n var c = Math.round(curlSize * (1 + p * 3.2)), svg = $('curl').firstChild;\n svg.setAttribute('width', c); svg.setAttribute('height', c); svg.setAttribute('viewBox', '0 0 ' + c + ' ' + c);\n svg.innerHTML = curlSvg(c);\n}\nvar curl = $('curl');\ncurl.addEventListener('pointerdown', function (e) {\n if (busy) return;\n unlock(); e.preventDefault(); e.stopPropagation();\n try { curl.setPointerCapture(e.pointerId); } catch (_) {}\n peel = {x: e.clientX, y: e.clientY, t: performance.now(), p: 0};\n sfx('rustle');\n});\ncurl.addEventListener('pointermove', function (e) {\n if (!peel) return;\n var d = ((peel.x - e.clientX) + (peel.y - e.clientY)) / Math.SQRT2;\n peel.p = Math.max(0, Math.min(1, d / (Math.min(cssW, cssH) * 0.55)));\n drawCurl(peel.p);\n});\nfunction peelEnd(e) {\n if (!peel) return;\n var p = peel.p, quick = performance.now() - peel.t < 300 && p < 0.05;\n peel = null;\n if (p > 0.4) return tearOff(p);\n if (quick) return hintCurl();\n settleCurl(p);\n}\ncurl.addEventListener('pointerup', peelEnd);\ncurl.addEventListener('pointercancel', function () { if (peel) { var p = peel.p; peel = null; settleCurl(p); } });\ncurl.addEventListener('click', function (e) { if (e.detail === 0) { unlock(); tearOff(0); } });\nfunction animate(ms, fn, done) {\n var t0 = performance.now();\n (function step(n) { var k = Math.min(1, (n - t0) / ms); fn(k); if (k < 1) requestAnimationFrame(step); else if (done) done(); })(t0);\n}\nfunction settleCurl(p) { animate(260, function (k) { var e = 1 - Math.pow(1 - k, 3); drawCurl(p * (1 - e)); }); }\nfunction hintCurl() {\n if (reduced.matches) return;\n animate(1100, function (k) { drawCurl(Math.sin(k * Math.PI * 2) ** 2 * 0.22 * (1 - k * 0.5)); });\n}\n\n// Compose a sheet into one canvas: paper, the dots left, and the ink.\nfunction compose(sh, wpx, opts) {\n opts = opts || {};\n var dm = SQ.sheetSize(sh.wide), s = wpx / dm.w, hpx = Math.round(dm.h * s);\n var out = document.createElement('canvas'); out.width = wpx; out.height = hpx;\n var g = out.getContext('2d'), paper = document.createElement('canvas'); paper.width = wpx; paper.height = hpx;\n Ink.paper(paper.getContext('2d'), wpx, hpx, s, sh); header(paper.getContext('2d'), sh, s, dm.w);\n g.drawImage(paper, 0, 0);\n var strokes = opts.strokes || sh.strokes;\n var sq = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n sq.dots = SQ.dots(sq.pts, 1); sq.hidden = SQ.covered(sq.dots, strokes);\n Ink.draw(g, sq, s, null);\n var ink = document.createElement('canvas'); ink.width = wpx; ink.height = hpx;\n var gi = ink.getContext('2d');\n for (var i = 0; i < strokes.length; i++) Ink.draw(gi, strokes[i], s, paper);\n g.drawImage(ink, 0, 0);\n return out;\n}\n\n// the ragged top a sheet keeps from the perforation it was torn along\nfunction tornEdge(w, seed) {\n var zig = [], n = Math.round(w / 4), rz = SQ.rng(seed);\n for (var z = 0; z <= n; z++) zig.push((z / n * 100).toFixed(2) + '% ' + (rz() * (z % 2 ? 4 : 1.6)).toFixed(1) + 'px');\n return 'polygon(' + zig.join(',') + ',100% 100%,0 100%)';\n}\nfunction tearOff(p) {\n if (busy) return;\n busy = true;\n var old = S.pad, inked = SQ.inked(old), r = sheetEl.getBoundingClientRect();\n var snap = null;\n if (!reduced.matches) {\n snap = document.createElement('canvas'); snap.width = C.paper.width; snap.height = C.paper.height;\n var g = snap.getContext('2d'); g.drawImage(C.paper, 0, 0); g.drawImage(C.dots, 0, 0); g.drawImage(C.ink, 0, 0);\n snap.style.cssText = 'display:block;width:100%;height:100%';\n var wrap = document.createElement('div'); wrap.className = 'fly'; wrap.appendChild(snap);\n wrap.style.cssText = 'left:' + r.left + 'px;top:' + r.top + 'px;width:' + r.width + 'px;height:' + r.height + 'px';\n snap.style.clipPath = tornEdge(r.width, old.seed);\n document.body.appendChild(wrap); snap = wrap;\n }\n sfx('rip'); buzz();\n var was = S.pad;\n SQ.tear(S, SQ.dayNumber(), opt(side));\n if (inked) P.torn++;\n laid(was);\n drawCurl(0);\n newSheet(snap ? 380 : 0);\n save(true);\n var finish = function () { if (snap) snap.remove(); busy = false; if (inked) bumpBook(); };\n if (!snap) { finish(); return; }\n var b = $('stack').getBoundingClientRect();\n var tx = b.left + b.width / 2 - (r.left + r.width / 2), ty = b.top - r.top, sc = Math.max(0.06, b.width / r.width);\n if (!inked) { tx = -r.width * 0.15; ty = -r.height * 0.4; sc = 0.9; }\n var lift = 'translate(' + (-r.width * 0.04) + 'px,' + (-r.height * 0.08) + 'px) rotate(-5deg)';\n // up off the pad, then an arc over to the sketchbook, landing small on the stack\n var mid = 'translate(' + (tx * 0.45 - r.width * 0.06) + 'px,' + (ty * 0.45 - r.height * 0.16) + 'px) rotate(-10deg) scale(' + (0.55 + sc * 0.45) + ')';\n var anim = snap.animate([\n {transform: 'none', opacity: 1, easing: 'cubic-bezier(.3,0,.4,1)'},\n {transform: lift, opacity: 1, offset: 0.22, easing: 'cubic-bezier(.4,0,.6,1)'},\n {transform: mid, opacity: 1, offset: 0.62, easing: 'cubic-bezier(.3,0,.2,1)'},\n {transform: 'translate(' + tx + 'px,' + ty + 'px) rotate(' + (inked ? -6 : -20) + 'deg) scale(' + sc + ')', opacity: inked ? 1 : 0}\n ], {duration: 950});\n anim.onfinish = finish;\n}\nfunction bumpBook() {\n stackThumb(); bookCount();\n var b = $('bookBtn'); b.classList.remove('bump'); void b.offsetWidth; b.classList.add('bump');\n sfx('drop');\n}\n// a new sheet on the pad: its dots are printed one after another\nfunction newSheet(wait) {\n setSheet(); layout();\n if (reduced.matches) { printUpto = 1; drawDots(); return; }\n var ms = P.printed ? 900 : 1900;\n P.printed = true;\n printUpto = 0; drawDots();\n if (wait) return setTimeout(function () { printDots(ms); }, wait);\n printDots(ms);\n}\nfunction printDots(ms) {\n var lastN = 0;\n animate(ms, function (k) {\n printUpto = k < 1 ? k : 1;\n var n = SQ.dots(squig.pts, printUpto).length;\n if (n > lastN + 2) { lastN = n; sfx('dot'); }\n drawDots();\n });\n}\n\n// ---- the sketchbook ------------------------------------------------------------------------\nfunction bookCount() {\n var n = S.book.length;\n $('bookCount').textContent = n ? n + (n === 1 ? ' sheet' : ' sheets') : 'empty';\n $('bookCount2').textContent = n ? n + (n === 1 ? ' sheet' : ' sheets') : '';\n $('bookNum').textContent = n ? n : '';\n $('bookBtn').setAttribute('aria-label', 'Open the sketchbook' + (n ? ', ' + n + (n === 1 ? ' sheet' : ' sheets') : ''));\n $('stack').classList.toggle('empty', !n);\n}\nfunction stackThumb() {\n var cv = $('cStack'), sh = S.book[0];\n bookCount();\n if (!sh) return;\n var w = Math.round(cv.parentNode.clientWidth * DPR()) || 60;\n var img = compose(sh, Math.max(60, w));\n cv.width = img.width; cv.height = img.height; cv.getContext('2d').drawImage(img, 0, 0);\n}\nvar thumbs = new WeakMap(), io = null;\nfunction openBook() {\n unlock(); sfx('rustle');\n var grid = $('grid'); grid.innerHTML = '';\n $('bookEmpty').hidden = S.book.length > 0;\n bookCount(); muteIcon();\n if (io) io.disconnect();\n io = 'IntersectionObserver' in window ? new IntersectionObserver(function (es) {\n es.forEach(function (en) { if (en.isIntersecting) { paintThumb(en.target); io.unobserve(en.target); } });\n }, {root: grid, rootMargin: '200px'}) : null;\n S.book.forEach(function (sh, i) {\n var card = document.createElement('button'); card.className = 'card';\n var dm = SQ.sheetSize(sh.wide), rr = SQ.rng(sh.seed + i);\n card.style.setProperty('--r', ((rr() - 0.5) * 3.2).toFixed(2) + 'deg');\n card.style.setProperty('--t', ((rr() - 0.5) * 7).toFixed(2) + 'deg');\n var tag = sheetTag(sh);\n card.innerHTML = '<div class=\"pg\" style=\"aspect-ratio:' + dm.w + '/' + dm.h + '\"></div><span>' + shortDate(sh) + (tag ? '<b>' + tag + '</b>' : '') + '</span>';\n card.setAttribute('aria-label', 'Sheet from ' + dateLabel(sh) + (tag ? ', ' + tag : ''));\n card._sheet = sh;\n card.onclick = function () { openView(sh, card.firstChild); };\n grid.appendChild(card);\n if (io) io.observe(card); else paintThumb(card);\n });\n $('book').hidden = false;\n $('bookClose').focus({preventScroll: true});\n}\nfunction shortDate(sh) {\n var d = sh.kind === 'day' ? SQ.dayDate(sh.day) : new Date(sh.created || Date.now()), o = {weekday: 'short', day: 'numeric', month: 'short'};\n if (d.getFullYear() !== new Date().getFullYear()) o.year = 'numeric';\n return d.toLocaleDateString(P.lang || undefined, o);\n}\nfunction paintThumb(card) {\n var pg = card.firstChild, w = Math.round(pg.clientWidth * DPR());\n if (!w) return;\n var img = compose(card._sheet, w);\n pg.appendChild(img);\n}\nfunction closeBook() { $('book').hidden = true; $('bookBtn').focus({preventScroll: true}); }\n$('bookBtn').onclick = openBook;\n$('bookClose').onclick = closeBook;\n$('book').addEventListener('click', function (e) { if (e.target === $('book') || e.target === $('grid')) closeBook(); });\n\n// one sheet, drawing itself again\nvar viewing = null, replayRaf = 0;\nfunction openView(sh, from) {\n viewing = sh; sfx('rustle');\n $('viewTitle').textContent = '';\n $('view').hidden = false;\n var cv = $('cView'), img = from && from.querySelector('canvas');\n if (!img || reduced.matches) { requestAnimationFrame(replay); return; }\n // the taped sheet comes up off the page to its full size\n var vs = viewSize(), a = from.getBoundingClientRect(), st = document.querySelector('#view .vstage').getBoundingClientRect();\n var bx = st.left + (st.width - vs.w) / 2, by = st.top + (st.height - vs.h) / 2;\n var z = document.createElement('canvas'); z.width = img.width; z.height = img.height; z.getContext('2d').drawImage(img, 0, 0);\n z.className = 'zoom'; z.style.cssText = 'left:' + bx + 'px;top:' + by + 'px;width:' + vs.w + 'px;height:' + vs.h + 'px';\n z.style.clipPath = tornEdge(vs.w, sh.seed);\n document.body.appendChild(z);\n cv.style.visibility = 'hidden';\n var k = a.width / vs.w;\n z.animate([{transform: 'translate(' + (a.left - bx) + 'px,' + (a.top - by) + 'px) scale(' + k + ')', transformOrigin: '0 0'},\n {transform: 'none', transformOrigin: '0 0'}], {duration: 380, easing: 'cubic-bezier(.2,.8,.2,1)'}).onfinish = function () {\n cv.style.visibility = ''; replay(); requestAnimationFrame(function () { z.remove(); });\n };\n}\nfunction viewSize() {\n var st = document.querySelector('#view .vstage').getBoundingClientRect(), dm = SQ.sheetSize(viewing.wide);\n var w = Math.min(st.width - 36, (st.height - 12) * dm.w / dm.h);\n return {w: Math.max(100, Math.floor(w)), h: Math.floor(w * dm.h / dm.w)};\n}\nfunction replay() {\n cancelAnimationFrame(replayRaf);\n var sh = viewing, vs = viewSize(), cv = $('cView'), d = DPR();\n cv.style.width = vs.w + 'px'; cv.style.height = vs.h + 'px';\n var vst = document.querySelector('#view .vstage'); vst.style.setProperty('--vw', vs.w + 'px'); vst.style.setProperty('--vh', vs.h + 'px');\n cv.style.clipPath = tornEdge(vs.w, sh.seed);\n cv.width = Math.round(vs.w * d); cv.height = Math.round(vs.h * d);\n var dm = SQ.sheetSize(sh.wide), s = cv.width / dm.w, g = cv.getContext('2d');\n var paper = document.createElement('canvas'); paper.width = cv.width; paper.height = cv.height;\n Ink.paper(paper.getContext('2d'), cv.width, cv.height, s, sh); header(paper.getContext('2d'), sh, s, dm.w);\n var ink = document.createElement('canvas'); ink.width = cv.width; ink.height = cv.height;\n var part = document.createElement('canvas'); part.width = cv.width; part.height = cv.height;\n var sq = {tool: 'print', pts: SQ.squiggle(sh.seed, sh.wide).map(function (p) { return [p[0], p[1], 6.5, 0]; })};\n sq.dots = SQ.dots(sq.pts, 1); sq.hidden = new Uint8Array(sq.dots.length);\n var plan = SQ.replayPlan(sh.strokes, Math.min(9000, 1200 + sh.strokes.length * 650)), done = 0, t0 = performance.now();\n $('vReplay').classList.remove('show');\n if (reduced.matches || !sh.strokes.length) {\n g.drawImage(compose(sh, cv.width), 0, 0); $('vReplay').classList.toggle('show', !!sh.strokes.length); return;\n }\n function frame(now) {\n var t = now - t0;\n while (done < sh.strokes.length && plan.marks[done][1] <= t) {\n Ink.draw(ink.getContext('2d'), sh.strokes[done], s, paper); SQ.absorb(sq.dots, sq.hidden, sh.strokes[done].pts); done++;\n }\n var pg = part.getContext('2d'); pg.clearRect(0, 0, part.width, part.height);\n if (done < sh.strokes.length && t > plan.marks[done][0]) {\n var st = sh.strokes[done], m = plan.marks[done], f = (t - m[0]) / Math.max(1, m[1] - m[0]);\n var cut = {tool: st.tool, ink: st.ink, pts: st.pts.slice(0, Math.max(1, Math.ceil(st.pts.length * f)))};\n Ink.draw(pg, cut, s, paper); SQ.absorb(sq.dots, sq.hidden, cut.pts);\n }\n g.drawImage(paper, 0, 0); Ink.draw(g, sq, s, null); g.drawImage(ink, 0, 0); g.drawImage(part, 0, 0);\n if (done < sh.strokes.length) replayRaf = requestAnimationFrame(frame);\n else { g.drawImage(paper, 0, 0); sq.hidden = SQ.covered(sq.dots, sh.strokes); Ink.draw(g, sq, s, null); g.drawImage(ink, 0, 0); $('vReplay').classList.add('show'); }\n }\n replayRaf = requestAnimationFrame(frame);\n}\nfunction closeView() { cancelAnimationFrame(replayRaf); $('view').hidden = true; viewing = null; }\n$('viewBack').onclick = function () { closeView(); };\n$('vReplay').onclick = function () { replay(); };\n$('vDraw').onclick = function () {\n var id = viewing.id; closeView(); closeBook();\n var out = SQ.reopen(S, id, opt(side));\n setSheet(); printUpto = 1; layout(); save(true);\n if (out) bumpBook();\n};\n$('vSave').onclick = function () {\n var sh = viewing, dm = SQ.sheetSize(sh.wide), img = compose(sh, Math.round(dm.w * 1.6));\n var name = 'squiggle-' + new Date(sh.kind === 'day' ? SQ.dayDate(sh.day) : sh.created).toISOString().slice(0, 10) + '.png';\n img.toBlob(function (blob) {\n if (!blob) return;\n var file = null;\n try { file = new File([blob], name, {type: 'image/png'}); } catch (e) {}\n if (file && navigator.canShare && navigator.canShare({files: [file]}) && matchMedia('(pointer:coarse)').matches) {\n navigator.share({files: [file]}).catch(function () {});\n } else {\n var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name;\n document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 4000);\n toast('Saved ' + name);\n }\n }, 'image/png');\n};\n$('vSend').onclick = function () {\n var sh = viewing, u = new URL(location.href.split('?')[0].split('#')[0]);\n if (sh.kind === 'day') u.searchParams.set('day', sh.day); else u.searchParams.set('s', SQ.codeFor(sh.seed));\n var url = u.toString();\n if (navigator.share && matchMedia('(pointer:coarse)').matches) navigator.share({title: 'Squiggle', text: 'Turn this squiggle into anything.', url: url}).catch(function () {});\n else if (navigator.clipboard) navigator.clipboard.writeText(url).then(function () { toast('Link copied - whoever opens it gets this squiggle'); }, function () { toast(url); });\n else toast(url);\n};\n$('vRemove').onclick = function () {\n var r = SQ.remove(S, viewing.id); if (!r) return;\n closeView(); save(true); openBook(); stackThumb();\n toast('Sheet removed', 'Undo', function () { SQ.restore(S, r); save(true); openBook(); stackThumb(); });\n};\naddEventListener('resize', function () { if (viewing) replay(); });\n\n// ---- toast -----------------------------------------------------------------------------------\nvar toastT = 0;\nfunction toast(msg, label, fn) {\n $('toastMsg').textContent = msg;\n var b = $('toastBtn'); b.hidden = !label; b.textContent = label || '';\n b.onclick = function () { $('toast').classList.remove('show'); if (fn) fn(); };\n $('toast').classList.add('show');\n clearTimeout(toastT); toastT = setTimeout(function () { $('toast').classList.remove('show'); }, label ? 5000 : 2600);\n}\n\n// ---- sound -----------------------------------------------------------------------------------\n// Everything is made here: the nib on paper is noise through a filter that follows the pen's\n// speed; the rest are short bursts and plucks.\nvar A = null, master = null, noise = null, scr = null;\nvar VOICE = {pencil: [3200, .9, .5, 9000], fine: [5600, 1.3, .32, 12000], brush: [1500, .6, .22, 4200], marker: [2300, 2.2, .3, 7000], eraser: [700, .8, .5, 2600]};\nfunction unlock() {\n if (P.mute) return null;\n if (!A) {\n try { A = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return null; }\n master = A.createGain(); master.gain.value = 0.55; master.connect(A.destination);\n noise = A.createBuffer(1, A.sampleRate * 2, A.sampleRate);\n var d = noise.getChannelData(0), r = SQ.rng(99);\n for (var i = 0; i < d.length; i++) d[i] = r() * 2 - 1;\n }\n if (A.state === 'suspended') A.resume();\n return A;\n}\nfunction scratchStart(tool) {\n if (P.mute || !A) return;\n if (!scr) {\n var src = A.createBufferSource(); src.buffer = noise; src.loop = true;\n var bp = A.createBiquadFilter(); bp.type = 'bandpass';\n var lp = A.createBiquadFilter(); lp.type = 'lowpass';\n var g = A.createGain(); g.gain.value = 0;\n src.connect(bp); bp.connect(lp); lp.connect(g); g.connect(master); src.start();\n scr = {bp: bp, lp: lp, g: g};\n }\n var v = VOICE[tool], t = A.currentTime;\n scr.bp.frequency.setTargetAtTime(v[0], t, .01); scr.bp.Q.setTargetAtTime(v[1], t, .01); scr.lp.frequency.setTargetAtTime(v[3], t, .01);\n scr.vol = v[2]; scr.g.gain.setTargetAtTime(v[2] * 0.15, t, .02);\n}\nfunction scratchMove(speed) {\n if (P.mute || !scr || !A) return;\n var t = A.currentTime, k = Math.min(1, speed / 2.2);\n scr.g.gain.setTargetAtTime(scr.vol * (0.12 + 0.88 * k), t, .03);\n scr.bp.frequency.setTargetAtTime(VOICE[P.tool][0] * (0.85 + 0.35 * k), t, .05);\n clearTimeout(scr.idle); scr.idle = setTimeout(function () { if (scr && A) scr.g.gain.setTargetAtTime(scr.vol * 0.06, A.currentTime, .05); }, 60);\n}\nfunction scratchStop() { if (scr && A) { clearTimeout(scr.idle); scr.g.gain.setTargetAtTime(0, A.currentTime, .035); } }\nfunction burst(t, dur, f0, f1, q, vol, type) {\n var src = A.createBufferSource(); src.buffer = noise; src.loop = true;\n var f = A.createBiquadFilter(); f.type = type || 'bandpass'; f.Q.value = q;\n f.frequency.setValueAtTime(f0, t); f.frequency.exponentialRampToValueAtTime(f1, t + dur);\n var g = A.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + Math.min(.012, dur / 4)); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);\n src.connect(f); f.connect(g); g.connect(master); src.start(t, Math.random()); src.stop(t + dur + .02);\n}\nfunction pluck(t, f0, f1, dur, vol, type) {\n var o = A.createOscillator(); o.type = type || 'sine'; o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(f1, t + dur);\n var g = A.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + .006); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);\n o.connect(g); g.connect(master); o.start(t); o.stop(t + dur + .02);\n}\nfunction sfx(name) {\n if (P.mute || !A || A.state !== 'running') return;\n var t = A.currentTime + .005;\n switch (name) {\n case 'tick': pluck(t, 2600 + Math.random() * 500, 1900, .035, .05); break;\n case 'dot': pluck(t, 1500 + Math.random() * 300, 1100, .04, .035); break;\n case 'tock': pluck(t, 420, 260, .09, .22, 'triangle'); burst(t, .05, 1800, 900, 1.5, .08); break;\n case 'plip': pluck(t, 900, 520, .12, .16); break;\n case 'undo': burst(t, .12, 2400, 900, .8, .05); break;\n case 'rustle': burst(t, .22, 1800, 3600, .6, .06); break;\n case 'rip':\n for (var i = 0; i < 9; i++) burst(t + i * .032 + Math.random() * .012, .06, 1400 + i * 260, 3800, .9, .09 + Math.random() * .05);\n burst(t, .4, 900, 2600, .5, .05); break;\n case 'drop': burst(t, .16, 600, 260, .7, .12, 'lowpass'); pluck(t, 180, 120, .12, .08); break;\n }\n}\nfunction muteIcon() {\n var b = $('mute');\n b.setAttribute('aria-label', P.mute ? 'Sound on' : 'Sound off');\n b.firstChild.innerHTML = P.mute ? '<path d=\"M4 9h4l5-4v14l-5-4H4z\"/><path d=\"M17 9l4 6M21 9l-4 6\"/>' : '<path d=\"M4 9h4l5-4v14l-5-4H4z\"/><path d=\"M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12\"/>';\n}\n// muted means silent: the scratch loop is stopped and the whole context is put to sleep\n$('mute').onclick = function () { P.mute = !P.mute; if (P.mute) { scratchStop(); if (A && A.state === 'running') A.suspend(); } else unlock(); muteIcon(); save(); };\n\n// ---- nib sizes -----------------------------------------------------------------------------\n// Each pen keeps its own size: a fine pencil and a fat marker are both what someone reaches for.\nvar SIZE_NAMES = ['Finest', 'Fine', 'Medium', 'Broad', 'Broadest'];\nfunction nibPx(t, i) { var w = SQ.BASE[t] * SQ.SIZES[i] * (t === 'brush' ? 0.55 : 1); return Math.round(Math.max(4 + i * 3.5, Math.min(34, w * 0.62))); } // never so small the steps blur\nfunction sizeIcon() {\n var t = P.tool, i = P.size[t];\n $('sizeBtn').firstChild.innerHTML = '<circle cx=\"12\" cy=\"12\" r=\"' + (1.6 + i * 1.6).toFixed(1) + '\"/>';\n $('sizeBtn').setAttribute('aria-label', 'Nib size: ' + SIZE_NAMES[i].toLowerCase());\n}\nfunction openSizes() {\n var box = $('sizes'), t = P.tool, col = t === 'eraser' ? '#f2eee6' : SQ.inkColor(P.ink);\n box.innerHTML = '';\n SQ.SIZES.forEach(function (k, i) {\n var b = document.createElement('button'), d = nibPx(t, i), on = i === P.size[t];\n b.className = 'szb' + (on ? ' on' : ''); b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on);\n b.setAttribute('aria-label', SIZE_NAMES[i]); b.tabIndex = on ? 0 : -1;\n b.innerHTML = '<i style=\"width:' + d + 'px;height:' + d + 'px;--c:' + col + '\"></i>';\n b.onclick = function () { pickSize(i); closeSizes(); };\n box.appendChild(b);\n });\n box.hidden = false; $('sizeBtn').setAttribute('aria-expanded', 'true');\n var r = $('sizeBtn').getBoundingClientRect(), w = box.offsetWidth, h = box.offsetHeight;\n var x = side ? r.left + r.width / 2 - w / 2 : r.left, y = r.top - h - 10;\n box.style.left = Math.max(8, Math.min(innerWidth - w - 8, x)) + 'px'; box.style.top = Math.max(8, y) + 'px';\n var on = box.querySelector('.on'); if (on) on.focus({preventScroll: true});\n}\nfunction closeSizes() { $('sizes').hidden = true; $('sizeBtn').setAttribute('aria-expanded', 'false'); }\nfunction pickSize(i) {\n i = Math.max(0, Math.min(SQ.SIZES.length - 1, i));\n if (i === P.size[P.tool]) return;\n P.size[P.tool] = i; sizeIcon(); sfx('tick'); save();\n if (!$('sizes').hidden) [].forEach.call($('sizes').children, function (b, j) { b.classList.toggle('on', j === i); b.setAttribute('aria-checked', j === i); });\n}\n$('sizeBtn').onclick = function (e) { e.stopPropagation(); unlock(); if ($('sizes').hidden) openSizes(); else closeSizes(); };\n$('sizes').addEventListener('keydown', function (e) {\n var d = e.key === 'ArrowRight' || e.key === 'ArrowUp' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowDown' ? -1 : 0;\n if (!d) return; e.preventDefault(); pickSize(P.size[P.tool] + d); var b = $('sizes').children[P.size[P.tool]]; if (b) b.focus();\n});\ndocument.addEventListener('pointerdown', function (e) { if (!$('sizes').hidden && !$('sizes').contains(e.target) && e.target.closest('#sizeBtn') === null) closeSizes(); }, true);\n\n// ---- the pad's settings ----------------------------------------------------------------------\nvar PAPER_NAMES = ['Cream', 'White', 'Grey', 'Kraft', 'Mist'], RULE_NAMES = ['Plain', 'Lined', 'Grid', 'Dots'];\nfunction optButton(label, on, inner, fn) {\n var b = document.createElement('button'); b.className = 'opt' + (on ? ' on' : '');\n b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', on); b.innerHTML = inner + '<span>' + label + '</span>';\n b.onclick = function () { fn(); sfx('plip'); fillPrefs(); }; return b;\n}\nfunction fillPrefs() {\n var pp = $('optPaper'), pr = $('optRule'), pl = $('optLang'), pc = SQ.PAPERS[P.paper];\n pp.innerHTML = pr.innerHTML = pl.innerHTML = '';\n SQ.PAPERS.forEach(function (c, i) { pp.appendChild(optButton(PAPER_NAMES[i], i === P.paper, '<i style=\"--c:' + c + '\"></i>', function () { setLook(i, P.rule); })); });\n SQ.RULES.forEach(function (r, i) { pr.appendChild(optButton(RULE_NAMES[i], i === P.rule, '<i class=\"r-' + r + '\" style=\"--c:' + pc + '\"></i>', function () { setLook(P.paper, i); })); });\n var mine = '';\n try { mine = new Intl.DisplayNames([navigator.language], {type: 'language'}).of(navigator.language.split('@')[0]); } catch (e) { mine = navigator.language || ''; }\n [['', 'Your language' + (mine ? ' (' + mine + ')' : '')], ['en', 'English']].forEach(function (o) {\n var b = optButton(o[1], P.lang === o[0], '', function () { P.lang = o[0]; reprint(); }); b.lastChild.outerHTML = o[1]; pl.appendChild(b);\n });\n $('optDate').checked = P.date; $('optNumber').checked = P.number;\n}\n// The choice goes onto the sheet on the pad, and onto every sheet torn after it.\nfunction setLook(paper, rule) {\n P.paper = paper; P.rule = rule;\n if (S.pad) { S.pad.paper = paper; S.pad.rule = rule; drawPaper(); drawInk(); }\n save();\n}\nfunction reprint() { if (S.pad) { drawPaper(); drawInk(); } bookCount(); save(); }\n$('optDate').onchange = function () { P.date = this.checked; sfx('tick'); reprint(); };\n$('optNumber').onchange = function () { P.number = this.checked; sfx('tick'); reprint(); };\nvar prefsFrom = null;\nfunction openPrefs() { closeSizes(); fillPrefs(); prefsFrom = document.activeElement; $('prefs').hidden = false; $('prefsClose').focus({preventScroll: true}); }\nfunction closePrefs() { $('prefs').hidden = true; if (prefsFrom && prefsFrom.focus) prefsFrom.focus({preventScroll: true}); }\n$('setBtn').onclick = function () { unlock(); sfx('rustle'); openPrefs(); };\n$('prefsClose').onclick = closePrefs;\n$('prefs').addEventListener('click', function (e) { if (e.target === this) closePrefs(); });\n$('prefs').addEventListener('keydown', function (e) { // keep Tab inside the card\n if (e.key !== 'Tab') return;\n var f = [].filter.call(this.querySelectorAll('button,input'), function (x) { return x.offsetParent; }), a = f[0], z = f[f.length - 1];\n if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); } else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }\n});\n\n// ---- keys --------------------------------------------------------------------------------------\naddEventListener('keydown', function (e) {\n if (e.key === 'Escape') { if (!$('sizes').hidden) { closeSizes(); $('sizeBtn').focus(); return; } if (!$('prefs').hidden) { closePrefs(); return; } if (!$('view').hidden) closeView(); else if (!$('book').hidden) closeBook(); return; }\n if (!$('book').hidden || !$('view').hidden || !$('prefs').hidden) return;\n if ((e.key === '[' || e.key === ']') && !e.ctrlKey && !e.metaKey) { pickSize(P.size[P.tool] + (e.key === ']' ? 1 : -1)); return; }\n var mod = e.ctrlKey || e.metaKey;\n if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); unlock(); if (e.shiftKey) doRedo(); else doUndo(); return; }\n if (mod && e.key.toLowerCase() === 'y') { e.preventDefault(); unlock(); doRedo(); return; }\n if (!mod && e.key >= '1' && e.key <= '5') { unlock(); pickTool(SQ.TOOLS[+e.key - 1]); }\n});\n\n// ---- the walnut, the leather and the board are drawn once ----------------------------------------\nfunction tex(w, h, base, fn) {\n var c = document.createElement('canvas'); c.width = w; c.height = h;\n var g = c.getContext('2d'); g.fillStyle = base; g.fillRect(0, 0, w, h); fn(g, w, h, SQ.rng(w * 7 + h)); return c.toDataURL();\n}\nfunction materials() {\n var wood = tex(600, 120, '#5b3f2c', function (g, w, h, r) {\n for (var y = 0; y < h; y++) {\n var v = Math.sin(y * .21 + Math.sin(y * .05) * 3) * .5 + Math.sin(y * .83) * .25 + (r() - .5) * .5;\n g.fillStyle = v > 0 ? 'rgba(255,215,170,' + v * .06 + ')' : 'rgba(25,12,4,' + (-v * .14) + ')'; g.fillRect(0, y, w, 1);\n }\n for (var k = 0; k < 160; k++) {\n var yy = r() * h, x = r() * w, l = 20 + r() * 120; g.strokeStyle = 'rgba(25,12,4,' + (.1 + r() * .14) + ')'; g.lineWidth = .6 + r();\n g.beginPath(); g.moveTo(x, yy); g.bezierCurveTo(x + l * .3, yy + (r() - .5) * 3, x + l * .6, yy + (r() - .5) * 3, x + l, yy + (r() - .5) * 2); g.stroke();\n }\n });\n $('tray').style.backgroundImage = 'url(' + wood + ')';\n $('desk').style.backgroundImage = 'url(' + wood + ')';\n $('blotter').style.backgroundImage = 'url(' + tex(300, 300, '#1f3530', function (g, w, h, r) {\n var im = g.getImageData(0, 0, w, h), d = im.data;\n for (var i = 0; i < d.length; i += 4) { var n = (r() - .5) * 9; d[i] += n; d[i + 1] += n; d[i + 2] += n; }\n g.putImageData(im, 0, 0);\n for (var k = 0; k < 3200; k++) { g.strokeStyle = r() < .55 ? 'rgba(0,0,0,.16)' : 'rgba(255,255,230,.06)'; g.lineWidth = .8; g.beginPath(); g.arc(r() * w, r() * h, 1 + r() * 2.4, r() * 6, r() * 6 + 2); g.stroke(); }\n }) + ')';\n var page = 'url(' + tex(512, 512, '#e6dcc7', function (g, w, h, r) {\n var im = g.getImageData(0, 0, w, h), d = im.data;\n for (var i = 0; i < d.length; i += 4) { var n = (r() - .5) * 10; d[i] += n; d[i + 1] += n; d[i + 2] += n * 1.2; }\n g.putImageData(im, 0, 0);\n for (var k = 0; k < 900; k++) { g.strokeStyle = 'rgba(120,95,60,' + (.03 + r() * .05) + ')'; g.lineWidth = .6; var x = r() * w, y = r() * h, a = r() * 6.3, l = 3 + r() * 8; g.beginPath(); g.moveTo(x, y); g.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); g.stroke(); }\n }) + ')';\n $('book').style.backgroundImage = page; $('view').style.backgroundImage = page;\n document.querySelector('.board').style.backgroundImage = 'url(' + tex(256, 256, '#8b7a62', function (g, w, h, r) {\n for (var k = 0; k < 2600; k++) { g.fillStyle = r() < .5 ? 'rgba(60,45,25,' + (.08 + r() * .15) + ')' : 'rgba(255,240,210,' + (.05 + r() * .12) + ')'; g.fillRect(r() * w, r() * h, .6 + r() * 1.6, .6 + r() * 1.2); }\n }) + ')';\n [['tl', 0, 104, 104, 0], ['tr', 16, 0, 120, 104], ['bl', 0, 16, 104, 120], ['br', 120, 16, 16, 120]].forEach(function (c) {\n document.querySelector('.corner.' + c[0]).innerHTML = '<svg viewBox=\"0 0 120 120\"><line x1=\"' + c[1] + '\" y1=\"' + c[2] + '\" x2=\"' + c[3] + '\" y2=\"' + c[4] + '\" stroke=\"rgba(245,220,190,.45)\" stroke-width=\"1.4\" stroke-dasharray=\"5 4\"/></svg>';\n });\n}\n\n// ---- start ---------------------------------------------------------------------------------------\nfunction fromLink() {\n var q = new URLSearchParams(location.search), today = SQ.dayNumber(), got = false;\n var code = q.get('s'), day = parseInt(q.get('day'), 10);\n if (code && SQ.seedFor(code.toLowerCase()) != null) { if (SQ.receive(S, 'extra', SQ.seedFor(code.toLowerCase()), today, opt(wantSide()))) got = true; }\n else if (day > 0 && day <= today) { if (SQ.receive(S, 'day', day, today, opt(wantSide()))) got = true; }\n if (code || q.has('day')) history.replaceState(null, '', location.pathname);\n return got;\n}\nfunction checkDay() {\n if (cur || busy) return;\n var today = SQ.dayNumber();\n if (today === S.day) return;\n var before = S.pad, filed = SQ.open(S, today, opt(wantSide()));\n laid(before);\n if (S.pad !== before) { newSheet(); save(true); if (filed.length) bumpBook(); }\n}\nfunction start() {\n load();\n materials();\n buildTray();\n var before = S.pad, filed = SQ.open(S, SQ.dayNumber(), opt(wantSide()));\n laid(before); before = S.pad;\n if (fromLink()) filed.push(S.book[0]);\n laid(before);\n muteIcon(); sizeIcon();\n setSheet(); layout(); stackThumb();\n save(true);\n if (filed.length) bumpBook();\n if (SQ.inked(S.pad)) { printUpto = 1; drawDots(); } else newSheet();\n var fonts = document.fonts;\n if (fonts && fonts.load) Promise.all([fonts.load('500 34px Fraunces'), fonts.load('italic 400 26px Fraunces')]).then(function () { drawPaper(); stackThumb(); }, function () {});\n}\nvar rt = 0;\naddEventListener('resize', function () { clearTimeout(rt); rt = setTimeout(function () { if (!cur && !busy) { layout(); stackThumb(); } }, 80); });\ndocument.addEventListener('visibilitychange', function () { if (!document.hidden) checkDay(); else { scratchStop(); save(true); } });\naddEventListener('pagehide', function () { save(true); });\nstart();\n})();";
|
|
12
|
+
var mounted = [];
|
|
13
|
+
|
|
14
|
+
function run(code) {
|
|
15
|
+
var s = document.createElement('script');
|
|
16
|
+
s.textContent = code;
|
|
17
|
+
document.body.appendChild(s);
|
|
18
|
+
mounted.push(s);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
Work.register({
|
|
22
|
+
mount: function (ctx) {
|
|
23
|
+
var style = document.createElement('style');
|
|
24
|
+
style.textContent = CSS;
|
|
25
|
+
document.documentElement.appendChild(style);
|
|
26
|
+
mounted.push(style);
|
|
27
|
+
var host = document.createElement('div');
|
|
28
|
+
host.id = 'sq-host';
|
|
29
|
+
host.innerHTML = HTML;
|
|
30
|
+
document.body.appendChild(host);
|
|
31
|
+
mounted.push(host);
|
|
32
|
+
run(CORE);
|
|
33
|
+
run(INK);
|
|
34
|
+
run(MAIN);
|
|
35
|
+
if (ctx && ctx.ready) ctx.ready();
|
|
36
|
+
},
|
|
37
|
+
destroy: function () {
|
|
38
|
+
for (var i = mounted.length - 1; i >= 0; i--) {
|
|
39
|
+
var n = mounted[i];
|
|
40
|
+
if (n.parentNode) n.parentNode.removeChild(n);
|
|
41
|
+
}
|
|
42
|
+
mounted = [];
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
})();
|