diff --git a/PRIVACY.md b/PRIVACY.md index a9c4ba9..34d2a33 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -55,6 +55,12 @@ You choose, before you start: requests, it loads nothing from anywhere else, and it sets no cookies and uses no browser storage. A letter saved as a file opens with no network at all. +- **Link previews.** If you paste a letter's link into a chat app that draws + link previews, that app fetches the reader page and its preview picture to + draw one, as it would for any link. It asks for the address without the `#` + part, so it gets the same page everyone gets and not the letter. The + preview shows a general picture and title, never anything from your letter. + The reader page itself never loads that picture. - **The app itself** is built on Electron (Chromium). On Windows and Linux, Chromium may download a spelling dictionary the first time you type; the spell check itself runs on your computer. On macOS it uses the system's own diff --git a/README.md b/README.md index a29358a..7dcf35f 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,11 @@ done, you seal it with a wax seal pressed from your own pulse wave. The person you send it to opens the envelope and watches the letter being written again at your pace: the pauses where you thought, the sentence you -rushed, the ink warming where your heart sped up, the page rising and falling -with your breath, a soft glow where you smiled. At the end they see where your -heart was quickest and where it was steadiest. +rushed. Down the left margin of the paper runs a strip of chart paper with +your heartline on it, drawn beside each line as it is written. Where your +heart sped up the line stands taller and the ink warms and feathers; where +you smiled there is a pencil stroke under the words. A postscript says where +your heart was quickest and where it was steadiest. The letter never goes to a server. A sealed letter lives inside its link (in the part after `#`, which browsers never send) or inside a single HTML file. @@ -72,8 +74,9 @@ by default. To host your own, deploy `dist/reader` anywhere static (a ``` or set `HEARTWRITTEN_READER_URL`. The reader has a Content Security Policy of -`default-src 'none'; connect-src 'none'`, so once it has loaded it can't send -anything anywhere. Whoever hosts the page sees an ordinary page request (an IP +`default-src 'none'; connect-src 'none'` (fonts and images may only come from +inside the file itself), so once it has loaded it can't send anything +anywhere. Whoever hosts the page sees an ordinary page request (an IP address and a browser), as any website does, but the letter in the `#` part of the link never reaches the host or its logs. @@ -81,15 +84,64 @@ the link never reaches the host or its logs. | Signal (SmartSpectra) | While writing | In the letter | | --- | --- | --- | -| Pulse rate (`cardio.pulseRate`, stable values only) | Live number, and each word takes its ink as you type it | Ink colour per character: iron-gall blue-black near the writer's own median, warming through claret to vermilion as the heart quickens, cooling to a clear blue-black as it settles. A pulse in the margin keeps time, and a heartline under the signature draws the whole letter's heart rate. The postscript finds the quickest and steadiest sentences. | -| Pulse wave (`cardio.arterialPressureTrace`) | Live trace | The wax seal: six seconds of the wave, wrapped into a ring and pressed into wax. Every seal is different. | -| Breathing (`breathing.upperTrace`, `breathing.rate`) | Breaths a minute | The paper rises and falls with the writer's breathing as it replays. | -| Smiles (`face.expression`, happy) | A small mark lights up | Words written while smiling glow softly. Optional. | +| Pulse rate (`cardio.pulseRate`, stable values only) | The same strip, live: the figure at the line you are on, the heartline growing beside your words, and each word taking its ink as you type it | The margin heartline: a pulse trace down a strip of chart paper bound into the left of the sheet, each line of writing beside the stretch drawn while it was written. Beats stand taller, closer and warmer where the heart was quicker, and the line goes quiet at a long pause. The live figure rides at the pen's tip with a mark that beats in time. Ink colour per character: iron-gall blue-black near the writer's own median, warming through claret to vermilion and feathering into the paper as the heart quickens, cooling to a clear blue as it settles. The postscript finds the quickest and steadiest sentences. | +| Pulse wave (`cardio.arterialPressureTrace`) | The live pulse wave at the top of the strip | The wax seal: six seconds of the wave, wrapped into a ring and pressed into wax. Every seal is different. | +| Breathing (`breathing.upperTrace`, `breathing.rate`) | Breaths a minute | A faint wash on the margin strip swells and ebbs with the writer's breathing as it replays. | +| Smiles (`face.expression`, happy) | A small mark, and a pencil stroke under the words | A hand-drawn pencil stroke under the words written while smiling. Optional. | | Validation status | Plain-language hints: "move a little closer or further", "a little more light, please" | | Typing is recorded as timed edits, so the replay keeps the real rhythm. Long -pauses (over eight seconds) are shortened in the replay but noted in the margin. -Words you delete are dropped from the letter unless you choose to share them. +pauses (over eight seconds) are shortened in the replay but pencilled in the +right margin ("paused 9 seconds"). Words you delete are dropped from the +letter unless you choose to share them. + +A letter keeps the heart rate four times a second, not every beat. The +heartline is drawn from that rate: the spacing and height of its beats follow +it, so it shows how fast the heart was going, not each beat as it happened. + +## How it looks + +A letter on a desk at night, with its heartline in the margin. Screenshots are +in [docs/screens](docs/screens) (the `margin-` files). + +- The sheet fits the letter. It comes out of the envelope folded in thirds, + opens to its first fold and grows as the writing does. +- One typeface, [Literata](src/fonts/README.md) (SIL Open Font License 1.1), + with small capitals and old-style figures for labels and numbers. Two small + font files are built into the reader page itself, so it still loads nothing + from anywhere. +- The front page at https://heartwritten.vercel.app is itself a letter to the + visitor, written the same way, with a scripted heartbeat that is labelled as + a demonstration. +- The first time the ink warms, a pencil note in the margin says what that + means, once. +- The camera reports in at the top of the writer's margin strip, where the + live pulse will be: waiting for permission, looking for your face, asking + for more light, finding your pulse, reading. If it stops, the strip says so + and you can keep writing. +- After sealing you see the envelope as it will arrive, and copying the link + is confirmed in words. +- The reader's icon is inside the page, and `og.png` beside it is the picture + chat apps show when a link is pasted. Both were made from the reader + itself; nothing is loaded from another site. + +## The writer in a browser + +The writer is an Electron app today because the SmartSpectra SDK it uses runs +there. Its page is written so it can also be served as a web page: + +- `dist/writer` is plain HTML, CSS and one script, laid out for a laptop and + for a phone (390 px wide). It only touches Electron through an optional + `window.heartwritten` bridge; without the bridge it runs on simulated + signals and says so. +- Signals reach the desk through one small interface (`start()`, `stop()` + and the events `stream`, `validationStatus`, `metrics`, `notice`, `error`). + `SOURCES` in `src/writer/writer.js` lists the two there are: the simulator + and the Electron SDK. A browser source would be a third entry. +- What a web version still needs: that browser source and whatever it talks + to, a place to serve the page (`/write`), a consent line that says where + the measuring happens if it is no longer on the writer's own computer, and + an update to [PRIVACY.md](PRIVACY.md) to match. ## Privacy and consent @@ -116,12 +168,16 @@ src/shared/ playback.js Replays the edits and maps the heart to ink summary.js Quickest and steadiest sentences, smiles, words taken back seal.js Draws the wax seal from the pulse wave - heartline.js Draws the letter's heart rate as one line of ink + heartline.js Draws the margin heartline from the heart rate, line by line + sheet.js The sheet on the page: ink runs, the strip, folds (shared by reader and writer) + sheet.css The paper, the strip, the ink and the type (shared by reader and writer) + composeLetter.js Writes a letter from a script: the sample and the front page +src/fonts/ Literata, cut down to two small files, and its licence sim-source.js Simulated SDK output for development and tests test/ node --test: the core, plus the built pages in jsdom ``` -`npm test` builds everything and runs 28 tests, including the reader replaying +`npm test` builds everything and runs 41 tests, including the reader replaying a full letter and the writer going from consent to a sealed letter in simulated mode. diff --git a/app/main.cjs b/app/main.cjs index 6cd53bc..03feb6d 100644 --- a/app/main.cjs +++ b/app/main.cjs @@ -40,7 +40,7 @@ function createWindow() { width: 1040, height: 860, minWidth: 720, - backgroundColor: '#e7dcc7', + backgroundColor: '#13100e', title: 'Heartwritten', webPreferences: { preload: path.join(DIST, 'preload.cjs'), @@ -66,7 +66,7 @@ function lockDown(win) { function openPreview(token) { if (!/^v1\.[A-Za-z0-9_-]+$/.test(token)) return false; const win = new BrowserWindow({ - width: 900, height: 900, title: 'Your letter, as they will see it', backgroundColor: '#e9dfcc', + width: 900, height: 900, title: 'Your letter, as they will see it', backgroundColor: '#13100e', webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false }, }); win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); diff --git a/docs/demo-script.md b/docs/demo-script.md index c33d935..ec51c2f 100644 --- a/docs/demo-script.md +++ b/docs/demo-script.md @@ -14,8 +14,8 @@ moment that actually moves you, and one line that makes you smile. | 2 | 0:08–0:18 | Heartwritten consent screen; tick agree; camera on; live heart trace and bpm settle | "Heartwritten reads your heartbeat, breathing and smiles through the webcam, with Presage SmartSpectra. Nothing is saved while you write, and the letter never goes to a server." | | 3 | 0:18–0:40 | Write the letter. Let the bpm visibly change at the emotional line. Smile once. Pause for a few seconds before the last line. | (Quiet. Let the typing and the live heart carry it.) | | 4 | 0:40–0:48 | Press **Seal it with my heartbeat**; the wax seal presses in | "You seal it with your own pulse wave. No two seals are the same." | -| 5 | 0:48–1:15 | Open the link in a browser as the recipient. Tap the seal, it cracks. The letter writes itself: ink warming at the emotional line, the margin heart beating, a glow on the smiling words, "paused 9 seconds" in the margin | "They watch it written again, at your pace. The ink warms where your heart sped up. The page breathes with you." | -| 6 | 1:15–1:25 | The closing card: quickest and steadiest sentences | "And at the end, where your heart was quickest, and where it was steadiest." | +| 5 | 0:48–1:15 | Open the link in a browser as the recipient. Tap the seal, it cracks. The letter writes itself: the heartline drawing down the margin strip beside each line, standing taller and turning red at the emotional line as the ink warms, the figure at the pen's tip, a pencil stroke under the smiling words, "paused 9 seconds" in the right margin | "They watch it written again, at your pace. That line in the margin is your heartbeat. The ink warms where your heart sped up." | +| 6 | 1:15–1:25 | The postscript at the foot of the letter: "P.S.", with the quickest and steadiest sentences | "And at the end, where your heart was quickest, and where it was steadiest." | | 7 | 1:25–1:30 | The seal again, with the line "lives only in its link" | "Heartwritten. Letters that carry your heartbeat." | Tips: diff --git a/docs/dev-post.md b/docs/dev-post.md index b31e46c..afe7dcb 100644 --- a/docs/dev-post.md +++ b/docs/dev-post.md @@ -17,14 +17,14 @@ You write a letter on your laptop. While you type, SmartSpectra reads your pulse The person you send it to taps the seal, it cracks, and they watch your letter being written again at your real pace: - the **ink warms** from blue-black through claret to vermilion where your heart sped up, and cools again as you calmed down -- a small **heart in the margin beats** at your rate, sentence by sentence -- the **paper rises and falls** with your breathing -- words you wrote **while smiling glow** -- **pauses** stay in, and the long ones are noted in the margin beside the line ("paused 14 seconds") -- under your signature, a **heartline** draws your whole heart rate across the letter +- a **heartline runs down the margin**, on a strip of chart paper bound into the letter, drawn beside each line as it is written: taller, tighter and warmer where your heart was quicker, with the figure and a beating mark at the pen's tip +- the quick-hearted words **feather** a little into the paper, and the calm ones stay crisp +- a faint wash on the strip **swells and ebbs** with your breathing +- words you wrote **while smiling** get a pencil stroke under them +- **pauses** stay in, and the long ones are pencilled in the margin beside the line ("paused 9 seconds") - if you allow it, they see the words you **typed and took back** -At the end, a card shows where your heart was quickest and where it was steadiest, with the sentences. +The letter ends with a postscript: where your heart was quickest and where it was steadiest, with the sentences. There's no backend, no database and no account. A sealed letter lives entirely inside its link (in the part after `#`, which browsers never send anywhere) or in a single HTML file you can attach to an email. @@ -51,10 +51,10 @@ Every signal changes something you can see or hold in the finished letter. None | SmartSpectra signal | What it becomes | | --- | --- | -| `cardio.pulseRate` (stable readings only) | The colour of each character's ink, measured against *your own* median for that letter, so a writer with a slow heart and one with a quick heart both get a full range. It also sets the beat of the margin heart, and finds the quickest and steadiest sentences. | +| `cardio.pulseRate` (stable readings only) | The colour of each character's ink, measured against *your own* median for that letter, so a writer with a slow heart and one with a quick heart both get a full range. It also draws the heartline down the margin, sets the beat of the mark at the pen's tip, and finds the quickest and steadiest sentences. | | `cardio.arterialPressureTrace` | The wax seal. Six seconds of the pulse wave, wrapped into a ring around your initial. | -| `breathing.upperTrace`, `breathing.rate` | The page breathing during replay. | -| `face.expression` (happy) | The glow on words you wrote smiling. Optional, and it's the only face metric I request. | +| `breathing.upperTrace`, `breathing.rate` | A faint wash on the margin strip that swells and ebbs during replay. | +| `face.expression` (happy) | The pencil stroke under words you wrote smiling. Optional, and it's the only face metric I request. | | Validation status | Gentle hints while you write: "move a little closer or further", "a little more light, please". | A few things I cared about: diff --git a/docs/screens/margin-after-envelope.png b/docs/screens/margin-after-envelope.png new file mode 100644 index 0000000..bb87f35 Binary files /dev/null and b/docs/screens/margin-after-envelope.png differ diff --git a/docs/screens/margin-after-front-end.png b/docs/screens/margin-after-front-end.png new file mode 100644 index 0000000..3868df8 Binary files /dev/null and b/docs/screens/margin-after-front-end.png differ diff --git a/docs/screens/margin-after-front.png b/docs/screens/margin-after-front.png new file mode 100644 index 0000000..74d6483 Binary files /dev/null and b/docs/screens/margin-after-front.png differ diff --git a/docs/screens/margin-after-phone-10s.png b/docs/screens/margin-after-phone-10s.png new file mode 100644 index 0000000..de73ca7 Binary files /dev/null and b/docs/screens/margin-after-phone-10s.png differ diff --git a/docs/screens/margin-after-phone-end.png b/docs/screens/margin-after-phone-end.png new file mode 100644 index 0000000..377b5fe Binary files /dev/null and b/docs/screens/margin-after-phone-end.png differ diff --git a/docs/screens/margin-after-phone-envelope.png b/docs/screens/margin-after-phone-envelope.png new file mode 100644 index 0000000..80a2271 Binary files /dev/null and b/docs/screens/margin-after-phone-envelope.png differ diff --git a/docs/screens/margin-after-phone-front-end.png b/docs/screens/margin-after-phone-front-end.png new file mode 100644 index 0000000..5ccc6ee Binary files /dev/null and b/docs/screens/margin-after-phone-front-end.png differ diff --git a/docs/screens/margin-after-phone-front.png b/docs/screens/margin-after-phone-front.png new file mode 100644 index 0000000..efb7ba1 Binary files /dev/null and b/docs/screens/margin-after-phone-front.png differ diff --git a/docs/screens/margin-after-phone-mid.png b/docs/screens/margin-after-phone-mid.png new file mode 100644 index 0000000..0270d64 Binary files /dev/null and b/docs/screens/margin-after-phone-mid.png differ diff --git a/docs/screens/margin-after-phone-writer-sealed.png b/docs/screens/margin-after-phone-writer-sealed.png new file mode 100644 index 0000000..56deda2 Binary files /dev/null and b/docs/screens/margin-after-phone-writer-sealed.png differ diff --git a/docs/screens/margin-after-phone-writer-state-face.png b/docs/screens/margin-after-phone-writer-state-face.png new file mode 100644 index 0000000..fae9be2 Binary files /dev/null and b/docs/screens/margin-after-phone-writer-state-face.png differ diff --git a/docs/screens/margin-after-phone-writer-write.png b/docs/screens/margin-after-phone-writer-write.png new file mode 100644 index 0000000..6448464 Binary files /dev/null and b/docs/screens/margin-after-phone-writer-write.png differ diff --git a/docs/screens/margin-after-replay-10s.png b/docs/screens/margin-after-replay-10s.png new file mode 100644 index 0000000..0f0c232 Binary files /dev/null and b/docs/screens/margin-after-replay-10s.png differ diff --git a/docs/screens/margin-after-replay-end.png b/docs/screens/margin-after-replay-end.png new file mode 100644 index 0000000..efdf2f6 Binary files /dev/null and b/docs/screens/margin-after-replay-end.png differ diff --git a/docs/screens/margin-after-replay-mid.png b/docs/screens/margin-after-replay-mid.png new file mode 100644 index 0000000..757490b Binary files /dev/null and b/docs/screens/margin-after-replay-mid.png differ diff --git a/docs/screens/margin-after-writer-consent.png b/docs/screens/margin-after-writer-consent.png new file mode 100644 index 0000000..dec5093 Binary files /dev/null and b/docs/screens/margin-after-writer-consent.png differ diff --git a/docs/screens/margin-after-writer-ready.png b/docs/screens/margin-after-writer-ready.png new file mode 100644 index 0000000..266e5b4 Binary files /dev/null and b/docs/screens/margin-after-writer-ready.png differ diff --git a/docs/screens/margin-after-writer-sealed.png b/docs/screens/margin-after-writer-sealed.png new file mode 100644 index 0000000..18349ff Binary files /dev/null and b/docs/screens/margin-after-writer-sealed.png differ diff --git a/docs/screens/margin-after-writer-state-error.png b/docs/screens/margin-after-writer-state-error.png new file mode 100644 index 0000000..29ebc32 Binary files /dev/null and b/docs/screens/margin-after-writer-state-error.png differ diff --git a/docs/screens/margin-after-writer-state-light.png b/docs/screens/margin-after-writer-state-light.png new file mode 100644 index 0000000..e2ba160 Binary files /dev/null and b/docs/screens/margin-after-writer-state-light.png differ diff --git a/docs/screens/margin-after-writer-write.png b/docs/screens/margin-after-writer-write.png new file mode 100644 index 0000000..b962faa Binary files /dev/null and b/docs/screens/margin-after-writer-write.png differ diff --git a/docs/screens/margin-before-envelope.png b/docs/screens/margin-before-envelope.png new file mode 100644 index 0000000..e5a9c5c Binary files /dev/null and b/docs/screens/margin-before-envelope.png differ diff --git a/docs/screens/margin-before-front.png b/docs/screens/margin-before-front.png new file mode 100644 index 0000000..e2c7c6b Binary files /dev/null and b/docs/screens/margin-before-front.png differ diff --git a/docs/screens/margin-before-phone-front.png b/docs/screens/margin-before-phone-front.png new file mode 100644 index 0000000..2725180 Binary files /dev/null and b/docs/screens/margin-before-phone-front.png differ diff --git a/docs/screens/margin-before-phone-mid.png b/docs/screens/margin-before-phone-mid.png new file mode 100644 index 0000000..c0131f1 Binary files /dev/null and b/docs/screens/margin-before-phone-mid.png differ diff --git a/docs/screens/margin-before-replay-10s.png b/docs/screens/margin-before-replay-10s.png new file mode 100644 index 0000000..4337535 Binary files /dev/null and b/docs/screens/margin-before-replay-10s.png differ diff --git a/docs/screens/margin-before-replay-end.png b/docs/screens/margin-before-replay-end.png new file mode 100644 index 0000000..2b14097 Binary files /dev/null and b/docs/screens/margin-before-replay-end.png differ diff --git a/docs/screens/margin-before-replay-mid.png b/docs/screens/margin-before-replay-mid.png new file mode 100644 index 0000000..37acfce Binary files /dev/null and b/docs/screens/margin-before-replay-mid.png differ diff --git a/docs/shot-list.md b/docs/shot-list.md index 4746cc2..c2d2ac0 100644 --- a/docs/shot-list.md +++ b/docs/shot-list.md @@ -18,20 +18,20 @@ The script is the story. This is what to capture and in what order. environment printed, or anyone else's face. - Two sources: - **SCREEN**: the screen recording of the app, then the browser. - - **CAM**: your face. The app's own camera tile (top left of the writing - desk, with the red dot) is enough. A separate picture-in-picture of you is + - **CAM**: your face. The app's own camera tile (top right of the sheet, + where a stamp would go, with the red dot) is enough. A separate picture-in-picture of you is optional and belongs in shot 2 only. ## Shots | # | Time | Length | Source | What is on screen | Action | Voice-over or caption | | --- | --- | --- | --- | --- | --- | --- | -| 1 | 0:00 to 0:06 | 6 s | SCREEN | A plain typed chat message, then cut to the Heartwritten front page (heartwritten.vercel.app) with the ink specimen | Still, slow push in | "Handwritten letters told you how they felt to write. Typed ones don't." | -| 2 | 0:06 to 0:18 | 12 s | SCREEN + CAM | The consent screen. Open "What the camera reads, and where it goes" for a beat. Tick "I'm the only person on camera, and I agree to this". Press **Turn on the camera**. The camera tile, red dot, pulse trace and bpm appear and settle | Move the pointer slowly. Hold two seconds on the live trace once the bpm shows | "Heartwritten asks first. Then it reads your pulse, breathing and smiles through the webcam, with the Presage SmartSpectra SDK. The measurement runs on this laptop." | -| 3 | 0:18 to 0:38 | 20 s | SCREEN (camera tile visible) | Typing the letter. The words take their ink as they are typed. The bpm number and the trace move at the line that matters. The "smiling" mark lights once. A real pause of a few seconds before the last line | Type at your real pace. Speed this shot up to 2x in the edit if it runs long, but leave the pause at real speed | No voice. Typing sound only. Caption: "Live from the camera. Ink follows the heart rate." | +| 1 | 0:00 to 0:06 | 6 s | SCREEN | A plain typed chat message, then cut to the Heartwritten front page (heartwritten.vercel.app), a letter writing itself with the heartline in its margin | Let it write for three seconds, slow push in | "Handwritten letters told you how they felt to write. Typed ones don't." | +| 2 | 0:06 to 0:18 | 12 s | SCREEN + CAM | The consent screen. Open "What the camera reads, and where it goes" for a beat. Tick "I'm the only person on camera, and I agree to this". Press **Turn on the camera**. The sheet appears with the camera tile where the stamp goes (red dot), and in the margin strip the live pulse wave and the beats-a-minute figure appear and settle | Move the pointer slowly. Hold two seconds on the strip once the figure shows | "Heartwritten asks first. Then it reads your pulse, breathing and smiles through the webcam, with the Presage SmartSpectra SDK. The measurement runs on this laptop." | +| 3 | 0:18 to 0:38 | 20 s | SCREEN (camera tile visible) | Typing the letter. The words take their ink as they are typed, and the heartline grows down the margin strip beside them. The figure and the line jump at the line that matters. The "smiling" mark shows once and those words get a pencil stroke. A real pause of a few seconds before the last line | Type at your real pace. Speed this shot up to 2x in the edit if it runs long, but leave the pause at real speed | No voice. Typing sound only. Caption: "Live from the camera. Ink follows the heart rate." | | 4 | 0:38 to 0:46 | 8 s | SCREEN | Press **Seal it with my heartbeat**. The wax seal appears, with "Sealed." and the private link | Hold on the seal for two seconds, then press **Copy link** | "You seal it with six seconds of your own pulse wave. No two seals are alike." | -| 5 | 0:46 to 1:08 | 22 s | SCREEN (browser, no camera) | Paste the link into a browser. The envelope with the seal. Press the seal, it breaks. The letter writes itself: ink warming at the line that mattered, the margin heart beating with its number, the glow on the smiling words, "paused ... seconds" in the margin | Leave it on "Their pace" for the line that matters, then press **Faster** | "They watch it written again, at your pace. The ink warms where your heart sped up, and the page moves with your breathing." | -| 6 | 1:08 to 1:16 | 8 s | SCREEN | Press **Show all**. The heartline under the signature and the closing card: "Quickest at", "Steadiest at" | Slow scroll to the card, hold | "At the end, where your heart was quickest, and where it was steadiest." | +| 5 | 0:46 to 1:08 | 22 s | SCREEN (browser, no camera) | Paste the link into a browser. The envelope with the seal. Press the seal, it breaks. The letter writes itself: the heartline drawing down the margin strip beside each line, tall and red at the line that mattered as the ink warms, the figure and its beating mark at the pen's tip, the pencil stroke under the smiling words, "paused ... seconds" in the right margin, and the one-time note "the ink warms where ...'s heart sped up" | Leave it on "Their pace" for the line that matters, then press **Faster** | "They watch it written again, at your pace. The line in the margin is your heartbeat, and the ink warms where it sped up." | +| 6 | 1:08 to 1:16 | 8 s | SCREEN | Press **Show all**. The whole heartline down the margin and the postscript: "P.S.", "Quickest at", "Steadiest at" | Slow scroll to the postscript, hold | "At the end, where your heart was quickest, and where it was steadiest." | | 7 | 1:16 to 1:20 | 4 s | SCREEN | Back to the envelope view with the line "This letter lives only in its link." | Still | "No server, no account, no video kept. Heartwritten." | Total: 80 seconds. If you need to cut to 60, drop shot 1 to 3 seconds, shot 3 @@ -44,10 +44,11 @@ demo video, and the template asks for a video "showing the live Presage signal(s)". So these must be visible: 1. The consent tick before the camera turns on (shot 2). -2. The live trace and bpm number changing while you are on camera (shots 2 - and 3). Keep the camera tile in frame so it is plain the signal is live. -3. The signal changing the result: ink colour, seal, breathing page, smile - glow (shots 3 to 6). +2. The live pulse wave and the beats-a-minute figure in the margin strip + changing while you are on camera (shots 2 and 3). Keep the camera tile + (top right of the sheet) in frame so it is plain the signal is live. +3. The signal changing the result: the margin heartline, ink colour, seal, + the pencil stroke under a smile (shots 3 to 6). ## Words to avoid in voice-over and captions diff --git a/scripts/build.mjs b/scripts/build.mjs index a122d83..b414ce7 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -14,11 +14,23 @@ const js = await build({ entryPoints: [src('reader/reader.js').pathname], bundle: true, minify: true, format: 'iife', write: false, target: ['es2022'], }); -const css = await readFile(src('reader/reader.css'), 'utf8'); +// One serif, Literata (SIL OFL 1.1, see src/fonts), cut down to two small +// files. The reader carries them inside itself as data: URLs, so it still +// loads nothing from anywhere; the writer loads them from its own folder. +const FONTS = [['Literata-Regular.woff2', 'normal'], ['Literata-Italic.woff2', 'italic']]; +const fontFace = (url, style) => `@font-face { font-family: "Literata"; font-style: ${style}; font-weight: 400; font-display: swap; src: url(${url}) format("woff2"); }`; +const inlineFonts = (await Promise.all(FONTS.map(async ([file, style]) => + fontFace(`data:font/woff2;base64,${(await readFile(src(`fonts/${file}`))).toString('base64')}`, style)))).join('\n'); +const sheetCss = await readFile(src('shared/sheet.css'), 'utf8'); +const css = [inlineFonts, sheetCss, await readFile(src('reader/reader.css'), 'utf8')].join('\n'); +// The address the reader is hosted at, for the link-preview picture only. +const site = (JSON.parse(await readFile(new URL('../heartwritten.config.json', import.meta.url), 'utf8')).readerUrl || '').replace(/\/?$/, '/'); const html = (await readFile(src('reader/index.html'), 'utf8')) + .replaceAll('__SITE__', site) .replace('/*__READER_CSS__*/', () => css) .replace('/*__READER_JS__*/', () => js.outputFiles[0].text.replace(/<\/script/gi, '<\\/script')); await writeFile(out('reader/index.html'), html); +try { await copyFile(src('reader/og.png'), out('reader/og.png')); } catch { /* the preview picture is optional */ } // 2. Writer renderer. await build({ @@ -27,7 +39,14 @@ await build({ outfile: out('writer/writer.js').pathname, loader: { '.html': 'text' }, logLevel: 'warning', }); await copyFile(src('writer/index.html'), out('writer/index.html')); -await copyFile(src('writer/writer.css'), out('writer/writer.css')); +await mkdir(out('writer/fonts/'), { recursive: true }); +for (const [file] of FONTS) await copyFile(src(`fonts/${file}`), out(`writer/fonts/${file}`)); +await copyFile(src('fonts/OFL.txt'), out('writer/fonts/OFL.txt')); +await writeFile(out('writer/writer.css'), [ + FONTS.map(([file, style]) => fontFace(`./fonts/${file}`, style)).join('\n'), + sheetCss, + await readFile(src('writer/writer.css'), 'utf8'), +].join('\n')); // 3. Preload: SmartSpectra's bridge plus ours, with only `electron` left external // so it runs in a sandboxed preload. diff --git a/scripts/make-sample.mjs b/scripts/make-sample.mjs index 19e2064..e30bda9 100644 --- a/scripts/make-sample.mjs +++ b/scripts/make-sample.mjs @@ -2,49 +2,30 @@ // sample) so the reader can be tried without the app. Prints its token and // writes dist/sample-letter.html and dist/reader/sample.html. import { writeFile, readFile } from 'node:fs/promises'; -import { LetterRecorder } from '../src/shared/recorder.js'; +import { composeLetter } from '../src/shared/composeLetter.js'; import { encodeLetter } from '../src/shared/letter-format.js'; +import { buildTimeline, bpmAt, heat } from '../src/shared/playback.js'; +import { median } from '../src/shared/summary.js'; -let t = 0; -const now = () => t; -const rec = new LetterRecorder({ now }); -let bpm = 66; -let smile = 0; -let wavePhase = 0; -const feed = () => { - rec.sample({ bpm: bpm + Math.sin(t / 9000) * 2, breath: Math.sin((t / 1000) * (14 / 60) * Math.PI * 2), smile }); -}; -const typeText = (s, gap = 135) => { - for (const ch of s) { - t += gap + ((ch.charCodeAt(0) * 37) % 70) + (ch === ' ' ? 40 : 0) + (/[.,]/.test(ch) ? 260 : 0); - rec.edit(rec.text + ch); - feed(); - } -}; -const back = (n) => { for (let i = 0; i < n; i++) { t += 95; rec.edit(rec.text.slice(0, -1)); feed(); } }; -const pause = (ms) => { const end = t + ms; while (t < end) { t += 250; feed(); } }; +// The news comes first, so the heart moves within the first ten seconds of +// the replay. The rest of the letter is calmer, which is what sets the +// writer's usual level and makes the opening stand out. +const { letter, text, ms } = composeLetter([ + ['type', 'Maya,\n\n'], + ['bpm', 85], ['type', 'They called this morning. '], + ['bpm', 93], ['smile', 0.9], ['type', 'I got it. I actually got it!'], + ['pause', 2500], ['smile', 0], ['bpm', 85], + ['type', ' You were the first person I wanted to tell. '], + ['bpm', 72], ['pause', 9000], + ['bpm', 67], ['type', 'I wanted to write this down instead of saying it on the phone, because I always rush the good parts. '], + ['type', 'I keep thinking about the night you sat on my floor and read my application out loud, and I was so sure it was '], + ['bpm', 75], ['type', 'terrible'], ['back', 8], ['type', 'not good enough'], + ['bpm', 68], ['type', '. You told me to send it anyway. '], + ['bpm', 60], ['type', 'I don’t think I would have.\n\n'], + ['bpm', 61], ['type', 'Thank you for believing in me before I did. Dinner is on me, wherever you want, as many times as you want.\n\n'], + ['bpm', 69], ['smile', 0.85], ['type', 'See you Friday.'], +], { from: 'Sam', to: 'Maya', day: '2026-11-12' }); -typeText('Maya,\n\n'); -typeText('I wanted to write this down instead of saying it on the phone, because I always rush the good parts. '); -pause(4000); -typeText('So, slowly: '); -bpm = 79; typeText('they called this morning. '); -bpm = 91; smile = 0.9; typeText('I got it. I actually got it!'); -pause(2500); smile = 0; -typeText(' You were the first person I wanted to tell. '); -bpm = 84; -pause(14000); -typeText('I keep thinking about the night you sat on my floor and read my application out loud, and I was so sure it was '); -typeText('terrible'); back(8); typeText('not good enough'); -typeText('. You told me to send it anyway. '); -bpm = 68; -typeText('I don’t think I would have.\n\n'); -bpm = 64; -typeText('Thank you for believing in me before I did. Dinner is on me, wherever you want, as many times as you want.\n\n'); -smile = 0.85; typeText('See you Friday.'); smile = 0; -for (let i = 0; i < 180; i++) { wavePhase += (66 / 60) / 30; const p = wavePhase % 1; rec.pushWave([p < 0.15 ? Math.sin(p / 0.15 * Math.PI / 2) : Math.exp(-3.2 * (p - 0.15) / 0.85) + 0.12 * Math.exp(-(((p - 0.15) / 0.85 - 0.28) ** 2) / 0.004)]); } - -const letter = rec.finish({ from: 'Sam', to: 'Maya', day: '2026-11-12', sim: true, share: { edits: true, smiles: true } }); const token = await encodeLetter(letter); const reader = await readFile(new URL('../dist/reader/index.html', import.meta.url), 'utf8'); const sampleHtml = reader.replace('', ``); @@ -52,4 +33,8 @@ await writeFile(new URL('../dist/sample-letter.html', import.meta.url), sampleHt // Also served by the hosted reader at /sample, so a sample opens from a short link. await writeFile(new URL('../dist/reader/sample.html', import.meta.url), sampleHtml); await writeFile(new URL('../dist/sample-token.txt', import.meta.url), token); -console.log(`sample letter: ${rec.text.length} chars, written over ${(t / 60000).toFixed(1)} min, token ${token.length} chars`); + +// When, in the replay, the ink first clearly warms. +const base = median(letter.vit.bpm); +const first = buildTimeline(letter).ops.find((op) => heat(bpmAt(letter, op.t), base) >= 0.5); +console.log(`sample letter: ${text.length} chars, written over ${(ms / 60000).toFixed(1)} min, token ${token.length} chars, usual heart ${base}, ink first warms ${(first.at / 1000).toFixed(1)} s into the replay`); diff --git a/src/fonts/Literata-Italic.woff2 b/src/fonts/Literata-Italic.woff2 new file mode 100644 index 0000000..d565370 Binary files /dev/null and b/src/fonts/Literata-Italic.woff2 differ diff --git a/src/fonts/Literata-Regular.woff2 b/src/fonts/Literata-Regular.woff2 new file mode 100644 index 0000000..6ee4ff7 Binary files /dev/null and b/src/fonts/Literata-Regular.woff2 differ diff --git a/src/fonts/OFL.txt b/src/fonts/OFL.txt new file mode 100644 index 0000000..9d3b4e3 --- /dev/null +++ b/src/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2017 The Literata Project Authors (https://github.com/googlefonts/literata) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/fonts/README.md b/src/fonts/README.md new file mode 100644 index 0000000..16de316 --- /dev/null +++ b/src/fonts/README.md @@ -0,0 +1,29 @@ +# Fonts + +Heartwritten sets everything in **Literata** (The Literata Project Authors, +https://github.com/googlefonts/literata), licensed under the SIL Open Font +License 1.1. The licence is in [OFL.txt](OFL.txt). + +The two files here are cut down from the upstream variable fonts so the reader +stays one small file: + +- `Literata-Regular.woff2`: optical size 16, weight 400 +- `Literata-Italic.woff2`: optical size 18, weight 400 + +Both keep Latin, Latin-1, Latin Extended-A and common punctuation, with small +caps (`smcp`, `c2sc`), old-style and lining figures, kerning and ligatures. +Text outside that range falls back to the reader's own serif. + +`scripts/build.mjs` inlines them into the reader as `data:` URLs, so the page +still loads nothing from anywhere. The writer loads the same files from its +own folder. + +Made with fontTools: + +``` +fonttools varLib.instancer "Literata[opsz,wght].ttf" opsz=16 wght=400 -o r.ttf +fonttools varLib.instancer "Literata-Italic[opsz,wght].ttf" opsz=18 wght=400 -o i.ttf +pyftsubset r.ttf --flavor=woff2 --no-hinting --desubroutinize \ + --unicodes="U+0020-007E,U+00A0-00FF,U+0100-017F,U+2010-2015,U+2018-201E,U+2020-2022,U+2026,U+2032-2033,U+2039-203A,U+20AC,U+2190-2193,U+2212" \ + --layout-features="kern,liga,smcp,c2sc,onum,pnum,tnum,lnum,ccmp,locl,mark,mkmk,case" +``` diff --git a/src/reader/index.html b/src/reader/index.html index e318618..4a1dadf 100644 --- a/src/reader/index.html +++ b/src/reader/index.html @@ -4,35 +4,26 @@ - - -Heartwritten - + + +Heartwritten · letters that carry a heartbeat + + + + + + + + + + + +
-
- -
-

Heartwritten

-

Letters that carry the heartbeat they were written with.

-

Write a letter while your camera reads your heartbeat. Whoever you send it to watches it being written again, at your pace, every word in the ink your heart gave it.

-
-
-

So, slowly: they called this morning. I got it. I actually got it! You were the first person I wanted to tell.

- -
From a sample lettersteady racing
-
-

Read a sample letter

-
    -
  1. 1
    Write in the Heartwritten app on a Mac. The Presage SmartSpectra SDK reads your pulse, breathing and smiles from the camera, on your computer.
  2. -
  3. 2
    Seal it. The letter keeps a few numbers a second, never video, and lives only inside its link or file.
  4. -
  5. 3
    Send the link. It opens here, sending nothing to any server.
  6. -
-

The writer is a Mac app. Heart rate and breathing are camera estimates, for feeling, not medicine.

-
- +

Opening the letter…

@@ -48,41 +39,52 @@

-

or press the seal

- +

+

This letter lives only in its link. Opening it sends nothing anywhere.

-
- + +

Heartwritten

+
-
- -

-
-
-

-
-
-
-
- + +
+
+ +

+
+
+

+ + +
+ +
+
+
+
@@ -95,16 +102,24 @@

Write a letter that carries your heartbeat.

-

Sealed.

+ @@ -112,7 +127,7 @@

Sealed.

- +

The camera is off. This letter isn’t saved on this computer. It exists only in that link and any file you save, so closing this window forgets it.

diff --git a/src/writer/writer.css b/src/writer/writer.css index cb79edb..16bcddf 100644 --- a/src/writer/writer.css +++ b/src/writer/writer.css @@ -1,194 +1,171 @@ -/* Heartwritten writer. The letter is serif ink on paper; everything around it is quiet UI. */ -:root { - --desk: #ebe5da; - --paper: #f8f4eb; - --ink: #1c2234; - --muted: #776f5f; - --on-desk: #26262a; - --on-desk-muted: #7a7366; - --hair: rgba(28, 34, 52, 0.12); - --line: rgba(60, 45, 20, 0.16); - --card: rgba(255, 252, 245, 0.72); - --stamp: #a8381e; - --wax: #9e2b25; - --serif: "Iowan Old Style", Charter, "Bitstream Charter", "Sitka Text", Cambria, Georgia, serif; - --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Inter, Roboto, "Helvetica Neue", sans-serif; - --tooth: url("data:image/svg+xml;utf8,"); - color-scheme: light dark; -} -@media (prefers-color-scheme: dark) { - :root { - --desk: #171513; --paper: #efe9dd; --on-desk: #ece4d5; --on-desk-muted: #9d9483; - --line: rgba(236, 228, 213, 0.16); --card: rgba(255, 250, 240, 0.05); - } -} -* { box-sizing: border-box; } -html, body { margin: 0; min-height: 100%; } -body { - background: var(--desk); color: var(--on-desk); - font: 16px/1.55 var(--sans); - -webkit-font-smoothing: antialiased; -} -main { max-width: 920px; margin: 0 auto; padding: 40px 28px 56px; } -.label { font: 600 12.5px/1.3 var(--sans); color: var(--on-desk-muted); margin: 0 0 10px; } -.note { color: var(--on-desk-muted); font-size: 13.5px; line-height: 1.45; } -.fine { color: var(--on-desk-muted); font-size: 12.5px; line-height: 1.5; margin: 22px 0 0; } - -/* Buttons */ -button { font: inherit; color: inherit; cursor: pointer; background: none; border: 0; padding: 0; } -.btn { - display: inline-flex; align-items: center; justify-content: center; gap: 8px; - font: 600 15px/1 var(--sans); padding: 13px 22px; border-radius: 999px; - transition: background-color 0.15s, border-color 0.15s, opacity 0.15s, transform 0.08s; -} -.btn:active:not(:disabled) { transform: translateY(1px); } -.btn:disabled { opacity: 0.38; cursor: default; } -.btn:focus-visible, input:focus-visible, summary:focus-visible { outline: 2px solid var(--ink); outline-offset: 3px; } -.btn.primary { background: var(--ink); color: #fbf8f1; } -.btn.primary:not(:disabled):hover { background: #2c3552; } -.btn.secondary { border: 1px solid var(--line); background: var(--card); color: var(--on-desk); } -.btn.secondary:hover { border-color: var(--on-desk-muted); } -.btn.ghost { color: var(--on-desk-muted); padding: 8px 12px; } -.btn.ghost:hover { color: var(--on-desk); background: var(--card); } -.btn.small { font-size: 13px; } -.btn.link { font: 500 14px var(--sans); color: var(--on-desk-muted); text-decoration: underline; text-underline-offset: 4px; text-decoration-color: var(--line); padding: 6px; } -.btn.link:hover { color: var(--on-desk); text-decoration-color: currentColor; } -@media (prefers-color-scheme: dark) { - .btn.primary { background: #f3ede1; color: #1c2234; } - .btn.primary:not(:disabled):hover { background: #fff; } - .btn:focus-visible, input:focus-visible, summary:focus-visible { outline-color: #f3ede1; } -} +/* Heartwritten writer: consent, the writing desk, the sealed letter. + The sheet itself is in shared/sheet.css. */ +:root { --strip-w: 126px; --notes-w: 60px; --line: rgba(234, 224, 207, 0.2); --card: rgba(255, 244, 224, 0.045); } +main { max-width: 940px; margin: 0 auto; padding: 40px 28px 56px; } +.label { font-variant-caps: all-small-caps; letter-spacing: 0.07em; font-size: 17px; line-height: 1.3; color: var(--on-desk-soft); margin: 0 0 8px; } +.note { color: var(--on-desk-soft); font-size: 15px; line-height: 1.45; font-style: italic; } +.fine { margin-top: 22px; } +.btn:focus-visible, input:focus-visible, summary:focus-visible { outline: 2px solid var(--on-desk); outline-offset: 3px; } /* Checkboxes and switches */ -.check { display: flex; gap: 10px; align-items: flex-start; font-size: 14.5px; line-height: 1.45; cursor: pointer; } -.check input { accent-color: var(--ink); width: 16px; height: 16px; margin: 2px 0 0; flex: none; } -.switch { appearance: none; -webkit-appearance: none; flex: none; width: 38px; height: 22px; border-radius: 999px; margin: 0; background: rgba(60, 45, 20, 0.2); position: relative; cursor: pointer; transition: background 0.2s; } -.switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); transition: transform 0.2s; } -.switch:checked { background: var(--ink); } -.switch:checked::after { transform: translateX(16px); } -@media (prefers-color-scheme: dark) { .switch { background: rgba(236, 228, 213, 0.2); } .switch:checked { background: #d9c9a8; } .check input { accent-color: #d9c9a8; } } +.check { display: flex; gap: 10px; align-items: flex-start; font-size: 16px; line-height: 1.45; cursor: pointer; } +.check input { accent-color: #d8694a; width: 17px; height: 17px; margin: 3px 0 0; flex: none; } +.switch { appearance: none; -webkit-appearance: none; flex: none; width: 40px; height: 22px; border-radius: 999px; margin: 0; background: rgba(234, 224, 207, 0.22); position: relative; cursor: pointer; transition: background 0.2s; } +.switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #f6f1e6; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4); transition: transform 0.2s; } +.switch:checked { background: var(--wax-lit); } +.switch:checked::after { transform: translateX(18px); } .step { display: none; } body[data-step="consent"] .step-consent, body[data-step="write"] .step-write, body[data-step="sealed"] .step-sealed { display: block; } -.card { background: var(--card); border: 1px solid var(--line); border-radius: 16px; } -.paper { background: var(--tooth), var(--paper); color: var(--ink); box-shadow: 0 0 0 1px rgba(60, 45, 20, 0.07), 0 30px 50px -36px rgba(40, 28, 10, 0.6); } +.card { background: var(--card); border: 1px solid var(--line); border-radius: 3px; } -/* 1. Welcome */ -.welcome { max-width: 600px; margin: 4vh auto 0; } -.brand { display: flex; align-items: center; gap: 9px; font: 600 14px var(--sans); margin: 0 0 22px; color: var(--on-desk); } -.brand-dot { width: 14px; height: 14px; border-radius: 50%; background: radial-gradient(circle at 35% 35%, #c9473d, var(--wax) 60%, #6f1c18); box-shadow: 0 1px 2px rgba(80, 10, 10, 0.3); } -.welcome h1 { font: italic 400 42px/1.12 var(--serif); letter-spacing: -0.015em; margin: 0 0 14px; } -.welcome .lede { font: 19px/1.5 var(--serif); margin: 0 0 30px; color: var(--on-desk); } -.how { list-style: none; padding: 0; margin: 0 0 26px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; } -.how li { display: flex; gap: 10px; align-items: flex-start; } -.how-n { flex: none; width: 24px; height: 24px; border-radius: 50%; border: 1px solid var(--line); display: grid; place-items: center; font: 600 12px var(--sans); color: var(--on-desk-muted); } -.how b { display: block; font-weight: 600; font-size: 14.5px; } -.how li span:not(.how-n) { display: block; font-size: 13.5px; color: var(--on-desk-muted); line-height: 1.4; margin-top: 2px; } +/* 1. Welcome and consent */ +.welcome { max-width: 620px; margin: 3vh auto 0; } +.brand { display: flex; align-items: center; gap: 10px; font: italic 400 21px/1 var(--serif); margin: 0 0 22px; color: var(--on-desk); } +.brand-dot { width: 15px; height: 15px; border-radius: 50%; background: radial-gradient(circle at 35% 35%, #d4504c, var(--wax) 60%, #6c1219); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.5); } +.welcome h1 { font: italic 400 44px/1.12 var(--serif); letter-spacing: -0.012em; margin: 0 0 14px; } +.welcome .lede { font-size: 20px; line-height: 1.5; margin: 0 0 30px; color: var(--on-desk); } +.how { list-style: none; padding: 0; margin: 0 0 26px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; } +.how li { display: flex; gap: 9px; align-items: baseline; } +.how-n { flex: none; font: italic 400 22px/1 var(--serif); color: #d8694a; } +.how b { display: block; font-variant-caps: all-small-caps; letter-spacing: 0.07em; font-size: 18px; line-height: 1.2; } +.how li span:not(.how-n) { display: block; font-size: 15.5px; color: var(--on-desk-soft); line-height: 1.4; margin-top: 3px; } .choices { margin: 0 0 14px; padding: 16px 18px 6px; } .choices legend { float: left; width: 100%; padding: 0; } .switch-row { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 10px 0; border-top: 1px solid var(--line); cursor: pointer; clear: both; } .switch-row:first-of-type { border-top: 0; } -.switch-row b { display: block; font-weight: 500; font-size: 15px; } -.switch-row small { display: block; font-size: 13px; color: var(--on-desk-muted); margin-top: 1px; } -.privacy { margin: 0 0 26px; font-size: 14px; } -.privacy summary { cursor: pointer; color: var(--on-desk-muted); font-weight: 500; padding: 6px 2px; list-style: none; display: inline-flex; align-items: center; gap: 8px; border-radius: 6px; } +.switch-row b { display: block; font-size: 17px; } +.switch-row small { display: block; font-size: 15px; font-style: italic; color: var(--on-desk-soft); margin-top: 1px; } +.privacy { margin: 0 0 26px; font-size: 16px; } +.privacy summary { cursor: pointer; color: var(--on-desk); padding: 6px 2px; list-style: none; display: inline-flex; align-items: center; gap: 8px; text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 5px; text-decoration-color: var(--line); } .privacy summary::-webkit-details-marker { display: none; } .privacy summary::before { content: ""; width: 7px; height: 7px; border-right: 1.5px solid currentColor; border-bottom: 1.5px solid currentColor; transform: rotate(-45deg); transition: transform 0.2s; margin-right: 2px; } .privacy[open] summary::before { transform: rotate(45deg); } -.privacy summary:hover { color: var(--on-desk); } -.facts { display: grid; grid-template-columns: 150px 1fr; gap: 10px 20px; margin: 12px 0 16px; padding: 16px 18px; border-radius: 14px; background: var(--card); border: 1px solid var(--line); } -.facts dt { font-weight: 600; font-size: 13px; color: var(--on-desk-muted); } -.facts dd { margin: 0; font-size: 14px; line-height: 1.5; } -.privacy .check { color: var(--on-desk-muted); font-size: 13.5px; } +.facts { display: grid; grid-template-columns: 160px 1fr; gap: 10px 20px; margin: 12px 0 16px; padding: 16px 18px; border-radius: 3px; background: var(--card); border: 1px solid var(--line); } +.facts dt { font-variant-caps: all-small-caps; letter-spacing: 0.06em; font-size: 16.5px; color: var(--on-desk-soft); } +.facts dd { margin: 0; font-size: 16px; line-height: 1.5; } +.privacy .check { color: var(--on-desk-soft); font-size: 15.5px; } .start { padding-top: 20px; border-top: 1px solid var(--line); } -.agree { margin: 0 0 16px; } +.agree { margin: 0 0 16px; font-size: 17px; } .row { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; } .row .note { flex: 1 1 240px; } -/* 2. Writing */ -.live { - display: grid; grid-template-columns: 52px 1fr auto; gap: 18px; align-items: center; - max-width: 760px; margin: 0 auto 18px; padding: 10px 14px 10px 10px; - background: var(--card); border: 1px solid var(--line); border-radius: 18px; +/* 2. Writing: the sheet, with your heartbeat drawing itself in its margin. */ +.step-write .sheet-wrap { max-width: 800px; } +/* The top of the strip is where the camera reports in: asking, looking + for a face, wanting more light, and then the live pulse itself. */ +.live { position: relative; z-index: 2; padding: 16px 12px 0 10px; text-align: right; color: var(--pencil); } +.live canvas { display: none; width: 100%; height: 40px; } +.live .quiet { display: block; width: 100%; height: 40px; fill: none; stroke: var(--pencil); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 3 5; } +.live[data-state="reading"] canvas { display: block; } +.live[data-state="reading"] .quiet { display: none; } +.live[data-state="connecting"] .quiet, .live[data-state="settling"] .quiet, .live[data-state="tuning"] .quiet { animation: march 1.2s linear infinite; } +.live[data-state="error"] .quiet, .live[data-state="off"] .quiet { stroke-dasharray: none; opacity: 0.45; } +@keyframes march { to { stroke-dashoffset: -16; } } +.hint { margin: 4px 0 0; font-style: italic; font-size: 15px; line-height: 1.25; color: #8a2a1c; text-wrap: balance; } +.live[data-state="reading"] .hint, .live[data-state="settling"] .hint, .live[data-state="connecting"] .hint, .live[data-state="off"] .hint { color: var(--pencil); } +.live:not([data-state="reading"]) .live-line, .live:not([data-state="reading"]) .smile-dot { display: none; } +.live-line { margin: 5px 0 0; font-size: 15px; line-height: 1.2; } +.live-line b { font-size: 19px; color: var(--ink); } +.live-line span { font-variant-caps: all-small-caps; letter-spacing: 0.04em; } +.smile-dot { margin: 3px 0 0; font-variant-caps: all-small-caps; letter-spacing: 0.06em; font-size: 15px; line-height: 1.2; opacity: 0; transition: opacity 0.4s; color: #8a5f10; } +.smile-dot.on { opacity: 1; } +.head-row { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; min-height: 92px; } +/* The camera sits where the stamp goes. */ +.cam { + position: relative; flex: none; width: 70px; height: 84px; padding: 5px; transform: rotate(2.5deg); + background: radial-gradient(circle at 50% 50%, #fbf7ee 60%, transparent 62%) 0 0 / 8px 8px, #e9e1d0; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25); } -.cam { position: relative; width: 52px; height: 52px; border-radius: 50%; overflow: hidden; background: radial-gradient(circle at 50% 38%, #4a443c, #26231f); } -.cam video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); } -.rec { position: absolute; right: 4px; bottom: 4px; width: 9px; height: 9px; border-radius: 50%; background: #e0492d; box-shadow: 0 0 0 2px var(--paper); } +.cam video { display: block; width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); background: radial-gradient(circle at 50% 38%, #4a443c, #26231f); } +.rec { position: absolute; right: 9px; bottom: 9px; width: 9px; height: 9px; border-radius: 50%; background: #e0492d; box-shadow: 0 0 0 2px rgba(246, 241, 230, 0.9); } .camera-off .rec { background: #8a8378; } -.live-heart { min-width: 0; } -.live-heart canvas { width: 100%; height: 34px; display: block; } -.live-stats { display: flex; gap: 16px; align-items: baseline; color: var(--on-desk-muted); font-size: 13px; margin-top: 2px; } -.live-stats b { font: 600 16px var(--sans); font-variant-numeric: tabular-nums; color: var(--on-desk); margin-right: 2px; } -.smile-dot { opacity: 0.35; transition: opacity 0.4s, color 0.4s; } -.smile-dot::before { content: ""; display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: currentColor; margin-right: 6px; vertical-align: 0.12em; } -.smile-dot.on { opacity: 1; color: #b9842a; } -.live-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; min-width: 150px; } -.hint { margin: 0; font-size: 13px; color: var(--stamp); text-align: right; } -.hint[data-ok="true"] { color: var(--on-desk-muted); } -.pill { margin: 0; display: inline-block; font: 600 11.5px/1 var(--sans); padding: 5px 9px; border-radius: 999px; } -.sim { color: var(--stamp); background: rgba(168, 56, 30, 0.1); } -.pill[hidden] { display: none; } - -.paper { max-width: 760px; margin: 0 auto; padding: 44px 64px 36px; border-radius: 3px; } -.paper label { display: flex; gap: 12px; align-items: baseline; } -.paper label > span { font: 500 13px var(--sans); color: var(--muted); } -.paper input { +.page label { display: flex; gap: 12px; align-items: baseline; } +.page label > span { font-variant-caps: all-small-caps; letter-spacing: 0.07em; font-size: 17px; color: var(--pencil); } +.page input { border: 0; border-bottom: 1px solid var(--hair); background: transparent; - font: italic 22px var(--serif); color: var(--ink); padding: 2px 2px 4px; flex: 0 1 280px; border-radius: 0; -} -.paper input::placeholder, textarea::placeholder { color: rgba(28, 34, 52, 0.32); -webkit-text-fill-color: rgba(28, 34, 52, 0.32); font-style: italic; } -.paper input:focus { outline: none; border-bottom-color: var(--ink); } -.paper input:focus-visible { outline: none; } -.field-from { justify-content: flex-end; margin-top: 10px; } -.ink-field { position: relative; margin: 26px 0 20px; min-height: 48vh; } -.ink-mirror, textarea { - font: 21px/1.62 var(--serif); font-variant-numeric: oldstyle-nums proportional-nums; - white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; - padding: 0; margin: 0; border: 0; letter-spacing: normal; + font: italic 23px var(--serif); color: var(--ink); padding: 2px 2px 4px; flex: 0 1 280px; min-width: 0; border-radius: 0; } +.page input::placeholder, textarea::placeholder { color: rgba(28, 34, 52, 0.55); -webkit-text-fill-color: rgba(28, 34, 52, 0.55); font-style: italic; } +.page input:focus, .page input:focus-visible { outline: none; border-bottom-color: var(--ink); } +.field-to { padding-top: 6px; } +.field-from { justify-content: flex-end; margin-top: 12px; } +.ink-field { position: relative; margin: 18px 0 18px; min-height: 5.6em; font-size: 22px; } +.ink-mirror, .ink-field textarea { padding: 0; margin: 0; border: 0; letter-spacing: normal; word-break: normal; } .ink-mirror { position: absolute; inset: 0; pointer-events: none; color: var(--ink); } -.ink-mirror span { transition: color 0.5s ease; } -textarea { - position: relative; display: block; width: 100%; min-height: 48vh; resize: none; overflow: hidden; +.ink-field textarea { + position: relative; display: block; width: 100%; min-height: 5.6em; resize: none; overflow: hidden; background: transparent; color: transparent; -webkit-text-fill-color: transparent; caret-color: var(--ink); } textarea::selection { background: rgba(28, 34, 52, 0.16); } textarea:focus, textarea:focus-visible { outline: none; } -.write-foot { display: flex; gap: 20px; align-items: center; justify-content: space-between; max-width: 760px; margin: 18px auto 0; } -.foot-notes { display: flex; flex-direction: column; gap: 2px; } +.write-foot { display: flex; gap: 22px; align-items: center; max-width: 800px; margin: 22px auto 0; position: sticky; bottom: 0; padding: 12px 0 14px; background: linear-gradient(180deg, transparent, var(--desk) 40%); z-index: 3; } +.foot-notes { display: flex; flex-direction: column; gap: 2px; margin-right: auto; flex: 1 1 260px; min-width: 0; } .foot-notes .note:empty { display: none; } +.sim { color: var(--pencil); margin: 0 0 14px; font-size: 16px; } +.write-foot .cap, .write-foot .text-btn, .write-foot .btn { white-space: nowrap; flex: none; } +.sim[hidden] { display: none; } +.write-foot .text-btn { color: var(--on-desk-soft); } +.write-foot .text-btn:hover { color: var(--on-desk); } +.write-foot .text-btn:disabled { opacity: 0.4; cursor: default; } -/* 3. Sealed */ -.sealed { max-width: 560px; margin: 5vh auto 0; text-align: center; } -.seal { width: 168px; height: 168px; margin: 0 auto 14px; animation: press 0.7s cubic-bezier(.2, .9, .3, 1.25); filter: drop-shadow(0 8px 8px rgba(60, 10, 10, 0.2)); } +/* 3. Sealed: the envelope as they will receive it, and the link to send. */ +.sealed { max-width: 580px; margin: 2vh auto 0; text-align: center; } +.step-sealed h2 { font: italic 400 46px/1.1 var(--serif); margin: 0; } +.step-sealed .lede { color: var(--on-desk-soft); font-size: 17px; font-style: italic; margin: 8px 0 22px; } +.sealed .envelope { max-width: 400px; margin: 0 auto 26px; animation: arrive 0.7s cubic-bezier(.2, .8, .3, 1); } +.sealed .seal { position: absolute; left: 50%; top: 58%; translate: -50% -50%; width: 118px; height: 118px; animation: press 0.7s cubic-bezier(.2, .9, .3, 1.25) 0.25s both; filter: drop-shadow(0 6px 6px rgba(60, 10, 10, 0.25)); } .seal svg { width: 100%; height: 100%; display: block; } -@keyframes press { from { transform: scale(1.5) rotate(-8deg); opacity: 0; } } -.step-sealed h2 { font: italic 400 42px/1.1 var(--serif); margin: 0; } -.step-sealed .lede { color: var(--on-desk-muted); font-size: 15px; margin: 8px 0 26px; } -.share { text-align: left; padding: 16px 16px 12px; } +@keyframes press { from { transform: scale(1.6) rotate(-8deg); opacity: 0; } } +@keyframes arrive { from { transform: translateY(14px); opacity: 0; } } +.share { text-align: left; padding: 16px 16px 14px; } .link-row { display: flex; gap: 10px; align-items: center; } .link-row input { - flex: 1; min-width: 0; font: 13px ui-monospace, Menlo, monospace; color: var(--on-desk); - padding: 12px 14px; border: 1px solid var(--line); border-radius: 999px; background: var(--desk); text-overflow: ellipsis; + flex: 1; min-width: 0; font: 14px ui-monospace, Menlo, monospace; color: var(--on-desk); + padding: 12px 14px; border: 1px solid var(--line); border-radius: 3px; background: rgba(0, 0, 0, 0.3); text-overflow: ellipsis; } -#link-note { display: block; margin: 8px 4px 0; } +.share.no-link .link-row { display: none; } +.copied { margin: 10px 2px 0; font-size: 17px; color: var(--on-desk); animation: arrive 0.4s ease; } +.copied::before { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 9px; background: radial-gradient(circle at 35% 35%, #d4504c, var(--wax) 60%, #6c1219); } +.copied[hidden] { display: none; } +#link-note { display: block; margin: 8px 2px 0; } #link-note:empty { display: none; } -.actions { justify-content: center; margin: 20px 0 8px; gap: 10px; } -.step-sealed .fine { max-width: 30em; margin: 22px auto 0; } +.actions { justify-content: center; margin: 20px 0 14px; gap: 10px; } +.again { color: var(--on-desk-soft); } +.again:hover { color: var(--on-desk); } +.step-sealed .fine { max-width: 32em; margin: 22px auto 0; } @media (max-width: 700px) { - main { padding: 20px 16px 40px; } + :root { --strip-w: 84px; --notes-w: 0px; } + main { padding: 0 0 24px; } + .step-consent, .step-sealed { padding: 22px 18px 0; } + .welcome { margin-top: 0; } .welcome h1 { font-size: 34px; } - .how { grid-template-columns: 1fr; } + .welcome .lede { font-size: 18px; } + .how { grid-template-columns: 1fr; gap: 10px; } .facts { grid-template-columns: 1fr; gap: 2px; } .facts dd { margin-bottom: 10px; } - .live { grid-template-columns: 44px 1fr; } - .cam { width: 44px; height: 44px; } - .live-side { grid-column: 1 / -1; flex-direction: row; align-items: center; justify-content: space-between; } - .paper { padding: 28px 22px; } - .write-foot { flex-direction: column; align-items: stretch; } - .link-row { flex-direction: column; align-items: stretch; } + .step-write .paper { border-radius: 0; } + .live { padding: 12px 8px 0 6px; } + .head-row { gap: 10px; } + .field-to { flex: 1 1 auto; min-width: 0; } + .field-to input { flex: 1 1 0; } + .u1 { display: none; } + .live[data-state="reading"] .hint { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } + .hint { font-size: 14px; } + .cam { width: 58px; height: 70px; padding: 4px; } + .page input { font-size: 20px; } + .ink-field { font-size: 19px; } + .write-foot { flex-wrap: wrap; gap: 10px 18px; padding: 10px 16px 12px; margin-top: 12px; } + .foot-notes { flex-basis: 100%; } + .write-foot .btn { flex: 1 1 auto; } + .step-sealed h2 { font-size: 38px; } + .link-row { flex-wrap: wrap; } + .link-row input { flex-basis: 100%; } + .link-row .btn { flex: 1 1 auto; } + .actions .btn { flex: 1 1 auto; } } +@media (prefers-reduced-motion: reduce) { .seal, .sealed .envelope, .live .quiet, .copied { animation: none !important; } } diff --git a/src/writer/writer.js b/src/writer/writer.js index 3233673..587251a 100644 --- a/src/writer/writer.js +++ b/src/writer/writer.js @@ -4,7 +4,8 @@ import { LetterRecorder } from '../shared/recorder.js'; import { VitalsTracker, hintFor } from '../shared/vitals.js'; import { encodeLetter, buildLink, finalText } from '../shared/letter-format.js'; -import { inkFor } from '../shared/playback.js'; +import { heat, inkAt } from '../shared/playback.js'; +import { inkHtml, layoutStops, stopAt, drawTrace } from '../shared/sheet.js'; import { median, formatDuration } from '../shared/summary.js'; import { sealSvg } from '../shared/seal.js'; import { SimulatedSource } from '../shared/sim-source.js'; @@ -22,7 +23,8 @@ const app = { sampler: 0, drawer: 0, bpmHistory: [], - inks: [], + marks: [], // one per character: { heat, smile, t } + lastIndex: 0, prevText: '', token: '', letter: null, @@ -42,41 +44,76 @@ async function init() { $('seal-it').addEventListener('click', seal); $('stop-camera').addEventListener('click', stopCamera); $('copy').addEventListener('click', copyLink); + $('share').addEventListener('click', shareLink); $('preview-letter').addEventListener('click', previewLetter); $('save-file').addEventListener('click', saveFile); $('again').addEventListener('click', () => location.reload()); + window.addEventListener('resize', () => { if (document.body.dataset.step === 'write') { syncHead(); drawInk(); } }); } // --------------------------------------------------------------------------- // Camera +// Where the signals come from. Every source speaks the same few events +// (stream, validationStatus, metrics, notice, error) and has start() and +// stop(), so the desk doesn't care which one it has. A source that reads +// the camera somewhere else (for a writer served as a web page) slots in +// here as a third entry. +const SOURCES = { + sim: async () => new SimulatedSource(), + sdk: async ({ telemetry, smiles }) => { + const { SmartSpectraSource } = await import('./sdk-source.js'); + return new SmartSpectraSource({ apiKey: await bridge.getApiKey(), telemetry, smiles }); + }, +}; + +// What the camera is doing, said in the margin strip where the live pulse +// will be: asking, looking for a face, wanting more light, reading. +const STATES = { 0: 'settling', 5: 'dim', 6: 'dim', 10: 'tuning', 11: 'tuning' }; +function setStatus(state, text) { + const live = $('live'); + live.dataset.state = state; + if (text) $('hint').textContent = text; + syncHead(); +} + +// The writing starts below whatever the strip has to say. +function syncHead() { + const field = $('ink-field'); + const live = $('live'); + if (!field || !live.offsetHeight) return; + const now = parseFloat(field.style.marginTop) || 18; + const natural = field.offsetTop - now; + field.style.marginTop = `${Math.max(18, live.offsetHeight + 14 - natural - ($('page').offsetTop || 0))}px`; +} + async function begin() { $('begin').disabled = true; const share = choices(); - if (app.simulated) { - app.source = new SimulatedSource(); - $('sim-flag').hidden = false; - } else { - const { SmartSpectraSource } = await import('./sdk-source.js'); - const apiKey = await bridge.getApiKey(); - app.source = new SmartSpectraSource({ apiKey, telemetry: share.telemetry, smiles: share.smiles }); - } + app.source = await SOURCES[app.simulated ? 'sim' : 'sdk'](share); + $('sim-flag').hidden = !app.simulated; const src = app.source; - src.on('stream', (stream) => { $('preview').srcObject = stream; $('preview').play().catch(() => {}); }); + src.on('stream', (stream) => { + $('preview').srcObject = stream; $('preview').play().catch(() => {}); + if ($('live').dataset.state === 'connecting') setStatus('searching', 'Looking for your face'); + }); src.on('validationStatus', (code, _ts, hint) => { - $('hint').textContent = hintFor(code, hint); - $('hint').dataset.ok = String(code === 0); + if (code === 0) return setStatus(app.tracker.bpm ? 'reading' : 'settling', app.tracker.bpm ? 'Reading you clearly' : 'Finding your pulse'); + return setStatus(STATES[code] || 'searching', hintFor(code, hint)); }); src.on('metrics', (m) => onMetrics(m)); src.on('notice', (msg) => { $('notice').textContent = msg; }); src.on('error', (code, message) => { - $('hint').textContent = code === 2 ? 'Your SmartSpectra key wasn’t accepted.' : `The camera stopped: ${message}`; - $('hint').dataset.ok = 'false'; + setStatus('error', code === 2 ? 'Your SmartSpectra key wasn’t accepted.' : `The camera stopped: ${message}`); + $('notice').textContent = 'You can keep writing. The words from here on carry no heartbeat.'; }); setStep('write'); + document.title = 'Writing · Heartwritten'; + setStatus('connecting', app.simulated ? 'Starting' : 'Waiting for the camera. Allow it if you are asked.'); await src.start(); app.sampler = setInterval(() => app.recorder.sample(app.tracker.snapshot()), 250); app.drawer = requestAnimationFrame(drawWave); + drawInk(); $('body').focus(); } @@ -86,8 +123,7 @@ async function stopCamera() { if (src) await src.stop(); app.tracker.reset(); $('preview').srcObject = null; - $('hint').textContent = 'Camera off. The rest of the letter keeps no heartbeat.'; - $('hint').dataset.ok = 'false'; + setStatus('off', 'Camera off. The rest of the letter keeps no heartbeat.'); $('stop-camera').disabled = true; document.body.classList.add('camera-off'); } @@ -100,14 +136,32 @@ function onMetrics(m) { app.bpmHistory.push(t.bpm); if (app.bpmHistory.length > 400) app.bpmHistory.shift(); } - $('live-bpm').textContent = t.bpm ? Math.round(t.bpm) : '—'; - // The cursor writes in the ink the heart is choosing right now. - if (t.bpm) $('body').style.caretColor = inkFor(t.bpm, median(app.bpmHistory)); - $('live-br').textContent = t.breathRate ? Math.round(t.breathRate) : '—'; + $('live-bpm').textContent = t.bpm ? Math.round(t.bpm) : '·'; + const state = $('live').dataset.state; + if (t.bpm && state === 'settling') setStatus('reading', 'Reading you clearly'); + else if (!t.bpm && state === 'reading') setStatus('settling', 'Finding your pulse'); + // The cursor, the figure and the mark at the pen's tip take the ink the + // heart is choosing right now. + if (t.bpm) { + const ink = inkAt(heatNow()); + $('body').style.caretColor = ink; + $('strip').style.setProperty('--pulse-ink', ink); + } + const breath = t.breathPhase(); + if (breath != null) $('strip').style.setProperty('--b', ((breath + 1) / 2).toFixed(3)); + $('live-br').textContent = t.breathRate ? Math.round(t.breathRate) : '·'; $('live-smile').classList.toggle('on', choices().smiles && t.smile >= 0.6); } -function drawWave() { +function drawWave(now) { + // The mark at the pen's tip beats in time with you. + if (app.tracker.bpm && now >= (app.nextBeat || 0)) { + app.nextBeat = now + 60000 / app.tracker.bpm; + const heart = $('heart'); + heart.classList.remove('beat'); + void heart.offsetWidth; + heart.classList.add('beat'); + } const c = $('wave'); const ctx = c.getContext && c.getContext('2d'); if (!ctx) return; @@ -120,9 +174,9 @@ function drawWave() { let lo = Infinity; let hi = -Infinity; for (const { t, v } of tr) if (t >= tEnd - span) { lo = Math.min(lo, v); hi = Math.max(hi, v); } const range = hi - lo || 1; - ctx.lineWidth = 3.2; + ctx.lineWidth = 2.6; ctx.lineJoin = 'round'; - ctx.strokeStyle = inkFor(app.tracker.bpm, median(app.bpmHistory)); + ctx.strokeStyle = inkAt(heatNow()); ctx.beginPath(); let first = true; for (const { t, v } of tr) { @@ -139,11 +193,13 @@ function drawWave() { // --------------------------------------------------------------------------- // Writing -// The words take the ink of the heart that wrote them, as you write. The -// textarea's own text is transparent; a mirror behind it draws the ink. -const CALM_INK = inkFor(0, 0); -function inkNow() { - return app.tracker.bpm ? inkFor(app.tracker.bpm, median(app.bpmHistory)) : CALM_INK; +// The words take the ink of the heart that wrote them, as you write, and the +// heartline grows down the margin beside them. The textarea's own text is +// transparent; a mirror behind it draws the ink. +const LONG_PAUSE_MS = 8000; + +function heatNow() { + return app.tracker.bpm ? heat(app.tracker.bpm, median(app.bpmHistory)) : 0; } function inkEdit(next) { @@ -153,31 +209,44 @@ function inkEdit(next) { while (a < n && prev[a] === next[a]) a++; let b = 0; while (b < n - a && prev[prev.length - 1 - b] === next[next.length - 1 - b]) b++; - const added = next.length - a - b; - app.inks.splice(a, prev.length - a - b, ...new Array(Math.max(0, added)).fill(inkNow())); + const added = Math.max(0, next.length - a - b); + const mark = { heat: heatNow(), smile: choices().smiles && app.tracker.smile >= 0.6, t: app.recorder.elapsed() }; + app.marks.splice(a, prev.length - a - b, ...Array.from({ length: added }, () => mark)); + app.lastIndex = Math.max(0, a + added - 1); app.prevText = next; drawInk(); } function drawInk() { const text = app.prevText; - let html = ''; - let i = 0; - while (i < text.length) { - const c = app.inks[i] || CALM_INK; - let j = i; - while (j < text.length && (app.inks[j] || CALM_INK) === c) j++; - html += `${escapeHtml(text.slice(i, j))}`; - i = j; - } - $('ink-mirror').innerHTML = `${html}${text.endsWith('\n') ? ' ' : ''}`; + const units = Array.from(text, (ch, i) => ({ ch, heat: (app.marks[i] || {}).heat || 0, smile: (app.marks[i] || {}).smile })); + const mirror = $('ink-mirror'); + mirror.innerHTML = `${inkHtml(units)}${text.endsWith('\n') ? ' ' : ''}`; const ta = $('body'); ta.style.height = 'auto'; ta.style.height = `${Math.max(ta.scrollHeight, 0)}px`; + drawMargin(units); } -function escapeHtml(s) { - return s.replace(/[<>&]/g, (ch) => ({ '<': '<', '>': '>', '&': '&' }[ch])); +// The strip beside the sheet: the heartline for what is written so far, and +// the live figure at the line being written. +function drawMargin(units) { + const field = $('ink-field'); + const top = field.offsetTop + ($('page').offsetTop || 0); + const { stops, lineH } = layoutStops($('ink-mirror'), units.map((u) => u.heat)); + const rests = []; + for (let i = 1; i < app.marks.length; i++) { + if (app.marks[i].t - app.marks[i - 1].t >= LONG_PAUSE_MS) { + const s = stopAt(stops, i - 1); + if (s) rests.push({ y: s.y, len: 15 }); + } + } + const head = drawTrace($('trace'), $('strip'), stops, { top, rests }); + const here = stopAt(stops, app.lastIndex); + const atEnd = head && app.lastIndex >= units.length - 1; + $('heart').hidden = !atEnd; + if (atEnd) { $('heart').style.left = `${head.x.toFixed(1)}px`; $('heart').style.top = `${head.y.toFixed(1)}px`; } + $('pulse').style.top = `${(top + (here ? here.y : lineH * 0.4) + 11).toFixed(1)}px`; } function onType(e) { @@ -237,22 +306,39 @@ async function seal() { if (base) bits.push(`your heart around ${base} bpm`); $('sealed-sub').textContent = `${bits.join(' · ')}.`; const link = app.cfg.readerUrl ? buildLink(app.cfg.readerUrl, app.token) : ''; - $('link').value = link || 'Set a reader address to share by link, or save it as a file.'; + $('link').value = link; $('copy').disabled = !link; + document.querySelector('.share').classList.toggle('no-link', !link); + $('share-label').textContent = link ? `Send ${letter.to || 'them'} this private link` : 'No link to send yet'; + $('share').hidden = !link || typeof navigator.share !== 'function'; + $('copied').hidden = true; + document.title = 'Sealed · Heartwritten'; $('link-note').textContent = link.length > 6000 ? 'This is a long letter, so the link is long. Some chat apps cut long links; if it won’t open for them, send the file instead.' - : (app.simulated ? 'Marked as a sample letter, because the signals were simulated.' : ''); + : !link ? 'No reader address is set, so there is no link. Save the letter as a file and send that instead.' + : (app.simulated ? 'Marked as a sample letter, because the signals were simulated.' : ''); + if (!link && app.simulated) $('link-note').textContent += ' It is marked as a sample letter, because the signals were simulated.'; setStep('sealed'); } async function copyLink() { + const who = (app.letter && app.letter.to) || 'them'; try { await navigator.clipboard.writeText($('link').value); $('copy').textContent = 'Copied'; - setTimeout(() => { $('copy').textContent = 'Copy link'; }, 1600); + $('copied').textContent = `The link is copied. Paste it into a message to ${who}.`; + setTimeout(() => { $('copy').textContent = 'Copy again'; }, 1600); } catch { + // No clipboard here: select it so one keystroke copies it. + $('link').focus(); $('link').select(); + $('copied').textContent = 'The link is selected. Copy it from the box above.'; } + $('copied').hidden = false; +} + +async function shareLink() { + try { await navigator.share({ title: 'A letter for you', url: $('link').value }); } catch { /* closed without sharing */ } } function previewLetter() { diff --git a/test/core.test.js b/test/core.test.js index 38d266c..f0ee8c1 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -6,7 +6,10 @@ import { } from '../src/shared/letter-format.js'; import { diffText, LetterRecorder, opsFromCharTimes, normalizeWave, VITALS_HZ } from '../src/shared/recorder.js'; import { VitalsTracker, resample, hintFor } from '../src/shared/vitals.js'; -import { Player, buildTimeline, bpmAt, inkFor, finalChars } from '../src/shared/playback.js'; +import { Player, buildTimeline, bpmAt, inkFor, inkAt, heat, featherAt, finalChars } from '../src/shared/playback.js'; +import { marginTrace, beatLength, beatHeight } from '../src/shared/heartline.js'; +import { inkHtml, foldHeight, stopAt } from '../src/shared/sheet.js'; +import { composeLetter } from '../src/shared/composeLetter.js'; import { summarize, sentences, median, formatDuration, excerpt } from '../src/shared/summary.js'; import { sealSvg } from '../src/shared/seal.js'; import { SimulatedSource } from '../src/shared/sim-source.js'; @@ -254,3 +257,99 @@ test('simulated source drives the same tracker path', async () => { assert.ok(v.pulseTrace.length > 100); assert.notEqual(v.breathPhase(), null); }); + +// --------------------------------------------------------------------------- +// The margin heartline, the ink and the sheet + +const lum = (rgb) => { + const [r, g, b] = rgb.match(/\d+/g).map((v) => { const x = v / 255; return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +}; +const contrast = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); return (x + 0.05) / (y + 0.05); }; + +test('heat is how far the heart sits from the writer’s usual level', () => { + assert.equal(heat(66, 66), 0); + assert.equal(heat(0, 66), 0, 'no reading is not a calm reading, but it draws as calm'); + assert.equal(heat(200, 66), 1); + assert.equal(heat(20, 66), -1); + assert.ok(heat(73, 66) > 0.4 && heat(73, 66) < 0.6); + assert.equal(inkFor(80, 66), inkAt(heat(80, 66))); +}); + +test('every ink the heart can choose is readable on the paper (WCAG AA)', () => { + const paper = 'rgb(246, 241, 230)'; + for (let h = -1; h <= 1.001; h += 0.05) { + const c = contrast(inkAt(h), paper); + assert.ok(c >= 4.5, `ink at heat ${h.toFixed(2)} has contrast ${c.toFixed(2)}`); + } +}); + +test('the change in ink is unmistakable: calm, quick and slow are far apart', () => { + const rgb = (h) => inkAt(h).match(/\d+/g).map(Number); + const dist = (a, b) => Math.hypot(...a.map((x, k) => x - b[k])); + assert.ok(dist(rgb(0), rgb(1)) > 150, 'calm to racing'); + assert.ok(dist(rgb(0), rgb(-1)) > 100, 'calm to slow'); + assert.ok(dist(rgb(0), rgb(0.5)) > 100, 'calm to halfway'); +}); + +test('only a quick heart feathers the ink', () => { + assert.equal(featherAt(0), 0); + assert.equal(featherAt(-1), 0); + assert.equal(featherAt(0.2), 0); + assert.ok(featherAt(0.5) >= 1); + assert.equal(featherAt(1), 3); +}); + +test('the heartline stands taller and tighter where the heart was quicker', () => { + assert.ok(beatLength(1) < beatLength(0) && beatLength(0) < beatLength(-1)); + assert.ok(beatHeight(1) > beatHeight(0) * 2 && beatHeight(0) > beatHeight(-1)); + const calm = marginTrace([{ y: 0, heat: 0 }, { y: 300, heat: 0 }]); + const quick = marginTrace([{ y: 0, heat: 1 }, { y: 300, heat: 1 }]); + assert.ok(quick.beats > calm.beats * 1.4, `${quick.beats} beats against ${calm.beats}`); + assert.ok(quick.peak > calm.peak * 2); + assert.match(calm.svg, /^ { + const t = marginTrace([{ y: 0, heat: 0 }, { y: 100, heat: 0 }, { y: 140, heat: 1 }, { y: 240, heat: 1 }]); + const colours = new Set(t.svg.match(/stroke="[^"]+"/g)); + assert.ok(colours.size > 4, 'it warms through several inks, not in one jump'); + const loud = marginTrace([{ y: 0, heat: 0.5 }, { y: 60, heat: 0.5 }]); + const quiet = marginTrace([{ y: 0, heat: 0.5 }, { y: 60, heat: 0.5 }], { rests: [{ y: 30, len: 200 }] }); + assert.ok(quiet.peak < loud.peak * 0.2, 'the pen rests'); + assert.deepEqual(marginTrace([]), { svg: '', head: null, beats: 0, peak: 0 }); +}); + +test('ink is drawn in runs, smiles are underlined together, and nothing unsafe gets through', () => { + const units = [...'hi you'].map((ch, i) => ({ ch, heat: i < 4 ? 0 : 1, smile: i >= 9 })); + const html = inkHtml(units, new Map([[4, '']])); + assert.ok(!html.includes(''), 'text is escaped'); + assert.match(html, /<b>h/); + assert.match(html, /<\/i>/); + assert.equal(html.match(/class="smiled"/g).length, 1, 'one stroke under the whole smile'); + assert.match(html, /]*> you<\/span><\/span>$/); +}); + +test('the sheet opens to its first fold, grows with the writing, and never outgrows the letter', () => { + assert.deepEqual(foldHeight(100, 900), { height: 300, panel: 300 }); + assert.deepEqual(foldHeight(100, 1500), { height: 320, panel: 500 }, 'a long sheet does not open onto a wall of blank paper'); + assert.equal(foldHeight(420, 900).height, 420); + assert.equal(foldHeight(2000, 900).height, 900); + assert.equal(foldHeight(100, 900, true).height, 900); + assert.deepEqual(foldHeight(50, 300), { height: 300, panel: 0 }, 'a short note has no folds'); + assert.deepEqual(foldHeight(50, 0), { height: 0, panel: 0 }); + assert.equal(stopAt([{ i: 0 }, { i: 4 }, { i: 8 }], 5).i, 4); +}); + +test('a composed letter is always marked as simulated, and its heart follows the script', () => { + const { letter, text } = composeLetter([ + ['type', 'Quiet start. '], ['bpm', 95], ['type', 'Then the news arrives and it is wonderful! '], ['pause', 9000], ['bpm', 60], ['type', 'And calm again, slowly, in the end.'], + ], { from: 'A', sim: false }); + assert.equal(letter.sim, 1, 'a scripted heartbeat can never pass for a measured one'); + assert.equal(finalText(letter), text); + assert.ok(Math.max(...letter.vit.bpm) > 88 && Math.min(...letter.vit.bpm.filter(Boolean)) < 66); + assert.equal(buildTimeline(letter).pauses.length, 1); + validate(letter); +}); diff --git a/test/dom.test.js b/test/dom.test.js index 1de727e..1a892c6 100644 --- a/test/dom.test.js +++ b/test/dom.test.js @@ -46,13 +46,27 @@ test('reader opens a letter from its link and replays it to the end', async () = const { win, doc, errors } = load(readerHtml, `https://reader.test/#${token}`); assert.ok(await until(() => doc.body.dataset.view === 'envelope'), 'envelope shows'); assert.match(doc.getElementById('envelope-to').textContent, /For Maya/); + assert.equal(doc.title, 'A letter for Maya · Heartwritten'); assert.match(doc.getElementById('envelope-from').textContent, /Sam’s heartbeat/); assert.ok(doc.querySelector('#seal svg'), 'wax seal drawn'); assert.equal(doc.getElementById('sim-badge').hidden, false, 'sample letters say so'); + assert.match(doc.getElementById('sim-badge').textContent, /sample letter · its heartbeat is simulated/); + assert.ok(doc.getElementById('sim-badge').classList.contains('cap'), 'in calm small capitals, not as a warning'); doc.getElementById('seal-button').click(); assert.ok(await until(() => doc.body.dataset.view === 'letter', 3000), 'letter opens after the seal breaks'); assert.ok(await until(() => doc.getElementById('body-text').textContent.length > 3, 3000), 'words start appearing'); + // While it is being written: the heartline and the live figure are in the + // strip bound into the sheet, beside the words, not floating outside it. + const paper = doc.getElementById('paper'); + const strip = doc.getElementById('strip'); + assert.equal(strip.parentElement, paper, 'the strip is part of the sheet'); + assert.ok(strip.contains(doc.getElementById('heart-bpm')) && strip.contains(doc.getElementById('heart')), 'the figure and its beating mark are in the strip'); + assert.ok(await until(() => /^\d+$/.test(doc.getElementById('heart-bpm').textContent)), 'the figure shows a heart rate'); + assert.equal(doc.getElementById('pulse').hidden, false); + assert.match(doc.getElementById('replay-sim').textContent, /Sample · simulated heartbeat/); + assert.equal(doc.getElementById('replay-sim').hidden, false); + assert.equal(doc.getElementById('summary').hidden, true, 'the postscript waits for the end'); doc.getElementById('skip').click(); assert.ok(await until(() => doc.body.classList.contains('finished'), 3000), 'replay finishes'); @@ -71,7 +85,31 @@ test('reader opens a letter from its link and replays it to the end', async () = assert.ok(colours.size > 3, 'ink changes colour with the heart'); assert.match(doc.getElementById('pauses').textContent, /paused/); assert.equal(doc.getElementById('signature').textContent, 'Sam'); - assert.ok(doc.querySelector('#heartline svg.heartline path'), 'the heartline is drawn under the signature'); + const trace = doc.querySelectorAll('#strip svg#trace path'); + assert.ok(trace.length > 6, 'the heartline runs down the margin'); + assert.ok(new Set([...trace].map((p) => p.getAttribute('stroke'))).size > 3, 'and changes ink where the heart did'); + assert.ok(Number(doc.getElementById('trace').dataset.beats) > 20); + assert.equal(doc.getElementById('heartline'), null, 'there is no second chart under the text'); + assert.ok(doc.querySelector('#body-text .f3'), 'the quickest words are feathered'); + assert.equal(doc.querySelectorAll('#body-text .smiled').length, 2, 'one pencil stroke per smile'); + assert.match(doc.getElementById('summary-title').textContent, /^P\.S\.$/, 'the closing card is a postscript'); + assert.equal(doc.getElementById('summary').hidden, false); + assert.ok(doc.getElementById('page').contains(doc.getElementById('summary')), 'and it is part of the letter'); + assert.match(summary, /between \d+ and \d+ beats a minute/); + const notes = [...doc.querySelectorAll('#pauses li')].map((li) => li.textContent); + assert.ok(notes.some((n) => /^paused 9 seconds$/.test(n)), `margin notes: ${notes.join(' | ')}`); + assert.ok(notes.some((n) => /^took back 8 characters$/.test(n))); + assert.equal(notes.filter((n) => n === 'the ink warms where Sam’s heart sped up').length, 1, 'the hint is pencilled in once'); + assert.equal(doc.getElementById('ink-hint').textContent, 'the ink warms where Sam’s heart sped up'); + assert.equal(doc.getElementById('pulse').hidden || doc.body.classList.contains('finished'), true); + + // Watching it again does not explain the ink a second time. + doc.getElementById('replay').click(); + assert.equal(doc.body.classList.contains('finished'), false); + doc.getElementById('skip').click(); + assert.ok(await until(() => doc.body.classList.contains('finished'), 3000), 'the second replay finishes'); + const again = [...doc.querySelectorAll('#pauses li')].map((li) => li.textContent); + assert.ok(again.some((n) => /paused/.test(n)) && !again.some((n) => /ink warms/.test(n)), 'the hint shows once and never again'); assert.ok(doc.querySelector('#body-text .pz-mark'), 'pauses are anchored to their place in the text'); assert.deepEqual(errors, []); win.close(); @@ -89,6 +127,8 @@ test('a cut-off link explains itself instead of breaking', async () => { const { win, doc } = load(readerHtml, `https://reader.test/#${token.slice(0, 200)}`); assert.ok(await until(() => doc.body.dataset.view === 'empty')); assert.match(doc.getElementById('empty-text').textContent, /cut short/); + assert.equal(doc.getElementById('empty-text').hidden, false); + assert.match(doc.title, /incomplete · Heartwritten/); win.close(); }); @@ -98,6 +138,102 @@ test('the reader page makes no network requests', () => { assert.match(readerHtml, /default-src 'none'/); assert.doesNotMatch(readerHtml, /<(link|img|iframe)[^>]+(href|src)="https?:/i); assert.doesNotMatch(readerHtml, /fetch\(/); + // The embedded font is inside the file, and the policy lets fonts come from nowhere else. + assert.match(readerHtml, /font-src data:;/); + assert.equal((readerHtml.match(/@font-face/g) || []).length, 2); + for (const m of readerHtml.matchAll(/url\(([^)]{0,40})/g)) assert.match(m[1], /^"?data:|^%23|^#/, `no url() points anywhere but the file itself: ${m[1]}`); + // The one address in the page is the preview picture that chat apps fetch + // for themselves. The page never loads it. + const og = readerHtml.match(//); + assert.equal(og[1], 'https://heartwritten.vercel.app/og.png'); + assert.doesNotMatch(readerHtml.replace(og[0], ''), /https?:\/\/(?!www\.w3\.org\/2000\/svg)/, 'no other address of any site is in the page'); + assert.match(readerHtml, /', ''); + const { win, doc, errors } = load(html, 'file:///app/dist/writer/index.html'); + let copied = ''; + Object.defineProperty(win.navigator, 'clipboard', { value: { writeText: async (t) => { copied = t; } }, configurable: true }); + win.heartwritten = { getConfig: async () => ({ hasKey: false, simulate: true, readerUrl: 'https://reader.test/' }), openPreview: () => true }; + win.eval(await readFile(new URL('dist/writer/writer.js', root), 'utf8')); + await wait(50); + const agree = doc.getElementById('agree'); + agree.checked = true; + agree.dispatchEvent(new win.Event('change')); + doc.getElementById('begin').click(); + assert.ok(await until(() => doc.body.dataset.step === 'write')); + doc.getElementById('to').value = 'Maya'; + const body = doc.getElementById('body'); + body.value = 'Hello.'; + body.dispatchEvent(new win.InputEvent('input', { data: '.' })); + doc.getElementById('seal-it').click(); + assert.ok(await until(() => doc.body.dataset.step === 'sealed')); + assert.match(doc.getElementById('link').value, /^https:\/\/reader\.test\/#v1\./); + assert.equal(doc.getElementById('share-label').textContent, 'Send Maya this private link'); + assert.equal(doc.getElementById('copied').hidden, true, 'no confirmation before anything is copied'); + doc.getElementById('copy').click(); + assert.ok(await until(() => doc.getElementById('copied').hidden === false)); + assert.equal(copied, doc.getElementById('link').value); + assert.equal(doc.getElementById('copied').textContent, 'The link is copied. Paste it into a message to Maya.'); + assert.equal(doc.getElementById('copy').textContent, 'Copied'); + assert.deepEqual(errors, []); + win.close(); +}); + +test('labels are one serif in small capitals, and nothing is set below 13px', async () => { + const css = [readerHtml.match(/