diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml new file mode 100644 index 0000000..f18c2c3 --- /dev/null +++ b/.github/workflows/auto-merge.yml @@ -0,0 +1,56 @@ +# Auto-merge — nobody is in the merge loop. +# +# Green, ready PRs merge themselves and deploy themselves. The policy lives +# ONCE, in bitbaum/fleet scripts/ci/auto-merge-sweep.sh (read it — it defines +# exactly what "ready" means and how a PR is held back). This file only says +# "run it, with these settings". Never copy the script: 22 copies once drifted +# into 8 versions and a fix landed in one reached almost none of the others. +# +# Copy this file to .github/workflows/auto-merge.yml and set the lines marked +# CHANGEME. Every other line is the same in every repo, and the shape is +# audited (scripts/ci/cicd-hygiene-audit.sh, `automerge-miswired`): a duplicate +# key, a hand-rolled job, or a workflow named here that the repo does not have +# turns the weekly hygiene run red. +# +# To stop all of this: delete this file, or add a `hold` label to a PR. +name: Auto-merge + +on: + workflow_run: + workflows: ["CI"] + types: [completed] + schedule: + # A safety net for PRs that went green off-cycle (an external status that + # reported after CI, or a check that finished while this workflow was + # broken). GitHub throttles it to roughly hourly whatever the cron says. + - cron: "*/10 * * * *" + workflow_dispatch: {} + +# Declared on the CALLER as well as inside the reusable workflow: a called +# workflow's token is capped by what the caller grants. With a read-only token +# the sweep merges nothing and still exits 0 — indistinguishable from having +# nothing to merge. +permissions: + contents: write # merge the PR + pull-requests: write # read PR state, delete the branch + actions: write # dispatch the re-arm and deploy workflows + checks: read # statusCheckRollup — only load-bearing on private repos + statuses: read + +jobs: + sweep: + uses: bitbaum/fleet/.github/workflows/auto-merge-sweep.yml@main + with: + base_branch: main + ci_workflow: ci.yml # the FILE of the workflow named under workflow_run + # SPACE-separated. Every workflow that runs on push and would therefore + # NOT fire after a merge made with GITHUB_TOKEN (ci.yml, publish.yml…). + # A comma becomes one bogus token: every dispatch fails, nothing ships, + # and the sweep still reports success. + rearm_workflows: "ci.yml" + secrets: + # Org secret, every bitbaum repo. A dispatch made with a PAT emits + # workflow_run, so after each merge the next PR's sweep fires at CI speed + # instead of waiting for the throttled schedule. Undefined resolves to + # empty and the reusable workflow falls back to github.token. + token: ${{ secrets.FLEET_PAT }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f07987d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + # Re-arm strand: a GITHUB_TOKEN merge starts no workflow on its own, so the + # auto-merge sweep must be able to start CI on main explicitly. + workflow_dispatch: {} + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # pnpm version comes from "packageManager" in package.json (SSOT). + - uses: pnpm/action-setup@v6 + - uses: actions/setup-node@v7 + with: + node-version: "24" + cache: pnpm + - run: pnpm install --frozen-lockfile + # The browser checks drive a real Chromium — the only way to prove the + # mic falls back, text is 16px and nothing overflows at 390px. + - run: pnpm exec playwright install --with-deps chromium + # Identical to what runs locally: format, lint, types, build, unit + + # render tests, browser checks. + - run: pnpm run verify + # dist/ is committed so a `github:` install needs no build step (pnpm + # refuses git-dependency builds without a per-SHA allowBuilds entry in + # every consumer). It must be exactly what the source builds to. + - name: Committed dist/ matches the source + run: git diff --exit-code --stat -- dist diff --git a/.gitignore b/.gitignore index aafcb34..2d6d322 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ node_modules/ .DS_Store *.log +.claude/ +demo/dist/ diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..238ac90 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,22 @@ +# Build output and vendored trees — formatting these is noise. +node_modules +.next +dist +build +out +coverage +.turbo +.vercel +*.min.js +*.min.css + +# Lockfiles are generated; prettier would rewrite them wholesale. +package-lock.json +pnpm-lock.yaml +yarn.lock + +# Markdown is deliberately out of scope for now. Prettier rewraps prose, which +# is where it is most opinionated and least useful, and it would bury the real +# diff. Remove this line when you want docs formatted too. +*.md +demo/dist diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..a2f11f0 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "semi": true, + "singleQuote": false, + "printWidth": 100, + "tabWidth": 2, + "trailingComma": "all", + "arrowParens": "always", + "endOfLine": "lf" +} diff --git a/README.md b/README.md index 428bcc0..b3c4a8c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,119 @@ # chatkit -One chat for every bitbaum product. Work in progress: see the first pull request. +**One chat for every bitbaum product.** A composer with a microphone that never +goes dead, a thread that does not fight the reader, answers with Copy and Retry, +and LLM markdown — the fleet's chat standard as a package, so a fix made once +reaches every product. + +Why it exists: on 2026-09-25 there were 13 chats in 10 repos, each written from +scratch, each missing something another had already fixed — most often the +microphone. The person using them found every gap by hand. This package is the +one place those fixes now live. (Model calls, streaming and transcription stay +in [`ai-kit`](https://github.com/bitbaum/ai-kit), server-side; chatkit is the +interface that calls them.) + +## Install + +```sh +pnpm add github:bitbaum/chatkit#v0.1.0 +``` + +`dist/` is committed, so the install needs no build step and no `allowBuilds` +entry. (npm publishing is set up once the package has its first release there.) + +## Use + +```tsx +import { ChatStarters, ChatThread, Composer } from "@bitbaum/chatkit/react"; +import "@bitbaum/chatkit/styles.css"; + +} +/> + send(text, attachments)} // return false to keep the draft + placeholder="Ask about any project…" + sending={streaming} + onStop={stop} + voice={{ transcribeUrl: "/api/transcribe" }} + attach // only if your API accepts attachments + tools={} // app-specific controls go in slots +/> +``` + +### The microphone + +`voice` is on by default. Give it a server leg so it works everywhere: + +- `transcribeUrl`: an endpoint taking `multipart/form-data` `{ audio, locale }` + and answering `{ text }` — implement it with `ai-kit`'s `transcribe()`. +- or `transcribe: (audio, locale) => Promise` for a custom call. + +The browser's own recogniser is tried first (free, instant). Where it is +missing, **or accepts `start()` and then says nothing** — Chromium without +Google's speech service does exactly that — the same press records and the +server transcribes. The dead recogniser is remembered for 30 days so the next +press records immediately. Every failure is shown in words (blocked mic, +nothing heard, not available), never as a button that does nothing. +`prefer: "server"` skips the browser leg (one model everywhere, language +detected by the model). `rememberKey: null` stores nothing on the device. + +### Look + +Every colour, radius and face is a `--ck-*` variable. They default to +[`@bitbaum/design-tokens`](https://github.com/bitbaum/design-tokens), so +OrangeCat, Loki, Solon and bitbaum match with no work. Any other app sets +`--ck-*` on the chat's container and keeps its own look. What you cannot +change is the behaviour — that is the point. + +### Language + +Every visible word is a label: `labels={{ send: "Senden", dictation: {...} }}` +on `Composer`, `labels` on `ChatThread`. + +## The standard (what this package guarantees) + +1. A microphone in the composer, with the server fallback above. +2. 16px text in the input and the messages (below that iOS zooms the page). +3. A composer that belongs to the conversation: auto-growing textarea, Enter + sends, Shift+Enter breaks the line, IME composition respected, 44px targets, + usable above the phone keyboard (`useViewportHeight`). +4. Stop in the send slot while a turn is in flight. +5. A failed turn shows as a failure with Retry — never silence. +6. Scroll follows new tokens only while the reader is at the bottom, with a + jump-down button otherwise. +7. Markdown rendered, never as HTML; `javascript:` links stay text; Copy on + every answer. +8. Starters in the empty state; the speaker's name on every answer once more + than one agent speaks. +9. Nothing overflows at 320–390px. + +`pnpm run verify` proves all of it: unit and render tests, then +`test/browser.mjs` drives Chromium through the demo at desktop and 390px, light +and dark, and speaks into a fake microphone past a silent recogniser. + +## Improving it — here, never in your app + +When a chat in any product has a bug or is missing something, **fix it in this +repo**, add the check that would have caught it, bump the version, and let the +products pick the release up. A local patch in one app is how the fleet got 13 +different chats. If your app needs something truly its own, it goes in a slot +(`tools`, `header`, `footer`, `renderFooter`, `renderLink`) — ask for a new slot +here rather than forking the component. + +Release: bump `version` in `package.json`, merge, then +`git tag v origin/main && git push origin v`. + +## Develop + +```sh +pnpm install +pnpm run demo # builds demo/dist; open demo/index.html +pnpm run verify # everything CI runs +``` + +MIT © Cato diff --git a/demo/demo.tsx b/demo/demo.tsx new file mode 100644 index 0000000..2c0f3b1 --- /dev/null +++ b/demo/demo.tsx @@ -0,0 +1,90 @@ +// The visual check: every part of the chat on one page, in light and dark. +// `pnpm run demo` builds demo/dist/; open demo/index.html. Screenshot it at +// 390px and at desktop width before calling a change to chatkit done. +import { useState } from "react"; +import { createRoot } from "react-dom/client"; +import { ChatStarters, ChatThread, Composer, type ChatMessageData } from "../src/react/index.js"; + +const SEED: ChatMessageData[] = [ + { id: "1", role: "user", content: "I want to get paid in Bitcoin for my illustrations" }, + { + id: "2", + role: "assistant", + speaker: { name: "Cat", id: "cat" }, + content: + "You can set that up with me on **OrangeCat**: a pay link at `orangecat.ch/pay/you`, settled straight to your wallet. It is in beta.\n\n- Lightning or on-chain\n- nothing taken by OrangeCat", + }, + { + id: "3", + role: "assistant", + speaker: { name: "Loki", id: "loki" }, + content: + "If you want a portfolio site around it, I can build that too — see https://loki.orangecat.ch.", + }, +]; + +function Demo({ empty, failed }: { empty?: boolean; failed?: boolean }) { + const [messages, setMessages] = useState( + empty + ? [] + : failed + ? [SEED[0]!, { id: "f", role: "assistant", content: "", failed: true }] + : SEED, + ); + const [sending, setSending] = useState(false); + const send = (text: string) => { + setMessages((m) => [...m, { id: String(Date.now()), role: "user", content: text }]); + setSending(true); + setTimeout(() => { + setMessages((m) => [ + ...m, + { + id: `${Date.now()}a`, + role: "assistant", + speaker: { name: "Loki", id: "loki" }, + content: "Heard you.", + }, + ]); + setSending(false); + }, 900); + }; + return ( +
+ setSending(false)} + onRetry={() => {}} + empty={ + + } + /> + send(t)} + placeholder="Ask about any project…" + sending={sending} + onStop={() => setSending(false)} + attach + voice={{ transcribeUrl: "/api/transcribe" }} + hint="Enter sends · Shift+Enter new line" + /> +
+ ); +} + +for (const [id, props] of [ + ["conversation", {}], + ["empty", { empty: true }], + ["failed", { failed: true }], +] as const) { + const el = document.getElementById(id); + if (el) createRoot(el).render(); +} diff --git a/demo/index.html b/demo/index.html new file mode 100644 index 0000000..a7364af --- /dev/null +++ b/demo/index.html @@ -0,0 +1,63 @@ + + + + + + chatkit demo + + + + + +
+
+
+

Conversation — two agents

+
+
+
+

Empty — starters

+
+
+
+

Failed turn — retry

+
+
+
+
+ + + diff --git a/dist/attachments.d.ts b/dist/attachments.d.ts new file mode 100644 index 0000000..8115072 --- /dev/null +++ b/dist/attachments.d.ts @@ -0,0 +1,41 @@ +/** + * What a composer can attach, and the wire shape an app's API receives. + * + * From loki `lib/loki/attachments.ts`. The limits are defaults, not law — an + * app passes its own to `useAttachments` when its model or API differs. + */ +export type TextAttachment = { + kind: "text"; + name: string; + content: string; +}; +export type ImageAttachment = { + kind: "image"; + name: string; + mimeType: string; + dataBase64: string; +}; +export type Attachment = TextAttachment | ImageAttachment; +/** Client-only preview URL — never sent to the API. */ +export type StagedAttachment = Attachment & { + previewUrl?: string; +}; +export type AttachmentLimits = { + /** Files per message. */ + maxFiles: number; + /** Characters per text file (it is inlined into a prompt). */ + maxTextChars: number; + /** Raw image bytes before base64. */ + maxImageBytes: number; +}; +export declare const DEFAULT_ATTACHMENT_LIMITS: AttachmentLimits; +export declare function isImageMime(mime: string): boolean; +/** `data:image/png;base64,AAAA` → `AAAA`: FileReader hands back a data URL, + * the wire carries raw base64. */ +export declare function stripDataUrlBase64(dataUrl: string): string; +/** Identity for dedupe and removal: the same name and bytes are the same + * attachment however they arrived (picker, paste, drop). */ +export declare function attachmentKey(a: Attachment): string; +/** Strip client-only fields: what the API validates. */ +export declare function toWire(staged: StagedAttachment[]): Attachment[]; +//# sourceMappingURL=attachments.d.ts.map \ No newline at end of file diff --git a/dist/attachments.d.ts.map b/dist/attachments.d.ts.map new file mode 100644 index 0000000..5e30327 --- /dev/null +++ b/dist/attachments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"attachments.d.ts","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,MAAM,cAAc,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAC7E,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,eAAe,CAAC;AAE1D,uDAAuD;AACvD,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG;IAAE,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,yBAAyB;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,YAAY,EAAE,MAAM,CAAC;IACrB,qCAAqC;IACrC,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,gBAIvC,CAAC;AAIF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED;mCACmC;AACnC,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAG1D;AAED;6DAC6D;AAC7D,wBAAgB,aAAa,CAAC,CAAC,EAAE,UAAU,GAAG,MAAM,CAInD;AAED,wDAAwD;AACxD,wBAAgB,MAAM,CAAC,MAAM,EAAE,gBAAgB,EAAE,GAAG,UAAU,EAAE,CAM/D"} \ No newline at end of file diff --git a/dist/attachments.js b/dist/attachments.js new file mode 100644 index 0000000..718913a --- /dev/null +++ b/dist/attachments.js @@ -0,0 +1,37 @@ +/** + * What a composer can attach, and the wire shape an app's API receives. + * + * From loki `lib/loki/attachments.ts`. The limits are defaults, not law — an + * app passes its own to `useAttachments` when its model or API differs. + */ +export const DEFAULT_ATTACHMENT_LIMITS = { + maxFiles: 5, + maxTextChars: 100_000, + maxImageBytes: 2_800_000, +}; +const IMAGE_MIME = /^image\/(jpeg|jpg|png|gif|webp)$/i; +export function isImageMime(mime) { + return IMAGE_MIME.test(mime); +} +/** `data:image/png;base64,AAAA` → `AAAA`: FileReader hands back a data URL, + * the wire carries raw base64. */ +export function stripDataUrlBase64(dataUrl) { + const i = dataUrl.indexOf(","); + return i >= 0 ? dataUrl.slice(i + 1) : dataUrl; +} +/** Identity for dedupe and removal: the same name and bytes are the same + * attachment however they arrived (picker, paste, drop). */ +export function attachmentKey(a) { + return a.kind === "image" + ? `image:${a.name}:${a.dataBase64.length}` + : `text:${a.name}:${a.content.length}`; +} +/** Strip client-only fields: what the API validates. */ +export function toWire(staged) { + return staged.map((a) => { + const { previewUrl: _preview, ...rest } = a; + void _preview; + return rest; + }); +} +//# sourceMappingURL=attachments.js.map \ No newline at end of file diff --git a/dist/attachments.js.map b/dist/attachments.js.map new file mode 100644 index 0000000..4f88a8e --- /dev/null +++ b/dist/attachments.js.map @@ -0,0 +1 @@ +{"version":3,"file":"attachments.js","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAuBH,MAAM,CAAC,MAAM,yBAAyB,GAAqB;IACzD,QAAQ,EAAE,CAAC;IACX,YAAY,EAAE,OAAO;IACrB,aAAa,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,GAAG,mCAAmC,CAAC;AAEvD,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED;mCACmC;AACnC,MAAM,UAAU,kBAAkB,CAAC,OAAe;IAChD,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;AACjD,CAAC;AAED;6DAC6D;AAC7D,MAAM,UAAU,aAAa,CAAC,CAAa;IACzC,OAAO,CAAC,CAAC,IAAI,KAAK,OAAO;QACvB,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,UAAU,CAAC,MAAM,EAAE;QAC1C,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;AAC3C,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,MAAM,CAAC,MAA0B;IAC/C,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;QACtB,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC,CAAC;QAC5C,KAAK,QAAQ,CAAC;QACd,OAAO,IAAkB,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/dist/composer.d.ts b/dist/composer.d.ts new file mode 100644 index 0000000..456c313 --- /dev/null +++ b/dist/composer.d.ts @@ -0,0 +1,34 @@ +/** + * The composer's decisions, kept out of the component so they can be tested + * without a DOM — and so every app that uses the one composer gets exactly the + * same answer to "may this send?" and "does the draft survive?". + * + * From loki `src/components/composer/composer-logic.ts`, where these were + * written after four composers in one app gave four different answers. + */ +/** A destination the same words can go to (e.g. Ask vs Inject). */ +export type ComposerMode = { + id: string; + label: string; + hint?: string; +}; +/** `false` keeps the draft (the send failed or was refused); anything else + * clears it. A failed send must be retryable from the same box, not retyped. */ +export type ComposerSendResult = void | boolean; +export declare function composerCanSend({ text, attachmentCount, attachmentOnlyText, sending, disabled, blocked, }: { + text: string; + attachmentCount: number; + attachmentOnlyText?: string; + sending: boolean; + disabled: boolean; + blocked: boolean; +}): boolean; +/** The words actually sent: the draft, or the app's stand-in for an + * attachments-only send. */ +export declare function composerOutgoingText(text: string, attachmentCount: number, attachmentOnlyText?: string): string; +export declare function shouldClearDraft(result: ComposerSendResult): boolean; +/** Dictated words join the draft with one space, never glued to the last word. */ +export declare function appendTranscript(draft: string, said: string): string; +/** `75` → `1:15`. The recording timer. */ +export declare function formatElapsed(seconds: number): string; +//# sourceMappingURL=composer.d.ts.map \ No newline at end of file diff --git a/dist/composer.d.ts.map b/dist/composer.d.ts.map new file mode 100644 index 0000000..f37dd34 --- /dev/null +++ b/dist/composer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"composer.d.ts","sourceRoot":"","sources":["../src/composer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,mEAAmE;AACnE,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE;iFACiF;AACjF,MAAM,MAAM,kBAAkB,GAAG,IAAI,GAAG,OAAO,CAAC;AAEhD,wBAAgB,eAAe,CAAC,EAC9B,IAAI,EACJ,eAAe,EACf,kBAAkB,EAClB,OAAO,EACP,QAAQ,EACR,OAAO,GACR,EAAE;IACD,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,EAAE,MAAM,CAAC;IACxB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;CAClB,GAAG,OAAO,CAMV;AAED;6BAC6B;AAC7B,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,EACZ,eAAe,EAAE,MAAM,EACvB,kBAAkB,CAAC,EAAE,MAAM,GAC1B,MAAM,CAIR;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAEpE;AAED,kFAAkF;AAClF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAIpE;AAED,0CAA0C;AAC1C,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGrD"} \ No newline at end of file diff --git a/dist/composer.js b/dist/composer.js new file mode 100644 index 0000000..c879b53 --- /dev/null +++ b/dist/composer.js @@ -0,0 +1,41 @@ +/** + * The composer's decisions, kept out of the component so they can be tested + * without a DOM — and so every app that uses the one composer gets exactly the + * same answer to "may this send?" and "does the draft survive?". + * + * From loki `src/components/composer/composer-logic.ts`, where these were + * written after four composers in one app gave four different answers. + */ +export function composerCanSend({ text, attachmentCount, attachmentOnlyText, sending, disabled, blocked, }) { + if (sending || disabled || blocked) + return false; + if (text.trim().length > 0) + return true; + // A screenshot with no words is still a complete message — but only where + // the app has said what that message means. + return attachmentCount > 0 && Boolean(attachmentOnlyText); +} +/** The words actually sent: the draft, or the app's stand-in for an + * attachments-only send. */ +export function composerOutgoingText(text, attachmentCount, attachmentOnlyText) { + const trimmed = text.trim(); + if (trimmed) + return trimmed; + return attachmentCount > 0 && attachmentOnlyText ? attachmentOnlyText : ""; +} +export function shouldClearDraft(result) { + return result !== false; +} +/** Dictated words join the draft with one space, never glued to the last word. */ +export function appendTranscript(draft, said) { + const t = said.trim(); + if (!t) + return draft; + return draft.trim() ? `${draft.replace(/\s+$/, "")} ${t}` : t; +} +/** `75` → `1:15`. The recording timer. */ +export function formatElapsed(seconds) { + const s = Math.max(0, Math.floor(seconds)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +} +//# sourceMappingURL=composer.js.map \ No newline at end of file diff --git a/dist/composer.js.map b/dist/composer.js.map new file mode 100644 index 0000000..ff7c418 --- /dev/null +++ b/dist/composer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"composer.js","sourceRoot":"","sources":["../src/composer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH,MAAM,UAAU,eAAe,CAAC,EAC9B,IAAI,EACJ,eAAe,EACf,kBAAkB,EAClB,OAAO,EACP,QAAQ,EACR,OAAO,GAQR;IACC,IAAI,OAAO,IAAI,QAAQ,IAAI,OAAO;QAAE,OAAO,KAAK,CAAC;IACjD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACxC,0EAA0E;IAC1E,4CAA4C;IAC5C,OAAO,eAAe,GAAG,CAAC,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAC5D,CAAC;AAED;6BAC6B;AAC7B,MAAM,UAAU,oBAAoB,CAClC,IAAY,EACZ,eAAuB,EACvB,kBAA2B;IAE3B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,OAAO,eAAe,GAAG,CAAC,IAAI,kBAAkB,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,CAAC;AAC7E,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAA0B;IACzD,OAAO,MAAM,KAAK,KAAK,CAAC;AAC1B,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gBAAgB,CAAC,KAAa,EAAE,IAAY;IAC1D,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IACtB,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACrB,OAAO,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,0CAA0C;AAC1C,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3C,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AACpE,CAAC"} \ No newline at end of file diff --git a/dist/dictation.d.ts b/dist/dictation.d.ts new file mode 100644 index 0000000..e52124d --- /dev/null +++ b/dist/dictation.d.ts @@ -0,0 +1,60 @@ +/** + * The decisions behind the microphone, without the microphone. + * + * The shape comes from heidi (`app/[locale]/_components/use-dictation.ts`), + * which is the only chat in the fleet whose mic never goes dead: + * + * - The browser's recogniser is FAST (free, instant, nothing uploaded) but + * sometimes a lie: Chromium builds without Google's speech service accept + * `start()` and then never fire an event — measured on heidi's live site + * 2026-09-12, nine seconds, zero events. So the recogniser is never the only + * path. Missing or silent, the same button RECORDS and a server transcribes. + * - Every failure becomes one of three words the person can act on — the mic + * (permission, hardware), silence (nothing heard), unavailable (nothing here + * can do it) — never a button that does nothing and says nothing. + * + * Kept pure so "never forever" and "which failures the fallback rescues" are + * tested properties rather than behaviour buried in a timeout. + */ +/** Why a dictation produced no text, in terms the person can act on. */ +export type DictationProblem = "mic" | "silence" | "unavailable"; +/** Which path to try first. `browser` is free and instant; `server` is one + * model everywhere (and detects the language by itself). Either falls back to + * the other when it cannot work. */ +export type DictationPreference = "browser" | "server"; +/** + * Which recogniser failures the fallback can rescue: only "unavailable" — the + * recogniser cannot do this (no speech service, network refused, language + * unsupported) and recording locally does not care. "mic" is the person's + * hardware or a permission they denied; "silence" is whether they spoke. + * Recording again would tell them the same thing twice. + */ +export declare function fallbackCanRescue(problem: DictationProblem | null): boolean; +/** Web Speech `error` codes → the three words. Anything unknown is + * `unavailable`, never nothing: a control that fails silently looks broken. */ +export declare function problemFor(error: string | undefined): DictationProblem | null; +/** getUserMedia / MediaRecorder failures → the same three words, so the UI + * never grows a second vocabulary for the same situations. */ +export declare function problemForRecording(error: unknown): DictationProblem; +/** A working recogniser fires `start` well inside this once the mic is allowed. */ +export declare const START_TIMEOUT_MS = 4000; +/** + * How long a pending permission may hold off the fallback. The wait is right — + * someone reading a permission dialog has not failed — but it must be BOUNDED: + * `permissions.query` says "prompt" both while a dialog is open and when none + * will ever appear (heidi, 2026-09-12: twenty-two seconds, nothing). + */ +export declare const PERMISSION_WAIT_MS = 10000; +export declare function mayKeepWaitingForPermission(elapsedMs: number, permissionPending: boolean): boolean; +/** A browser whose recogniser proved dead is remembered for this long, so the + * person does not rediscover it on every press — and not forever, because a + * browser can gain the capability. */ +export declare const DEAD_RECOGNISER_TTL_MS: number; +export declare function deadRecogniserStillTrusted(rememberedAt: number | null, now?: number): boolean; +/** Recording is capped so a forgotten mic does not run for an hour. */ +export declare const MAX_RECORDING_MS = 120000; +/** Candidate containers for MediaRecorder, best first. */ +export declare const RECORDING_MIME_CANDIDATES: readonly ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg"]; +/** The default words for each problem. Override per app (and per language). */ +export declare const DEFAULT_DICTATION_MESSAGES: Record; +//# sourceMappingURL=dictation.d.ts.map \ No newline at end of file diff --git a/dist/dictation.d.ts.map b/dist/dictation.d.ts.map new file mode 100644 index 0000000..41aaa47 --- /dev/null +++ b/dist/dictation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dictation.d.ts","sourceRoot":"","sources":["../src/dictation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,wEAAwE;AACxE,MAAM,MAAM,gBAAgB,GAAG,KAAK,GAAG,SAAS,GAAG,aAAa,CAAC;AAEjE;;qCAEqC;AACrC,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,QAAQ,CAAC;AAEvD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,GAAG,OAAO,CAE3E;AAED;gFACgF;AAChF,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,gBAAgB,GAAG,IAAI,CAa7E;AAED;+DAC+D;AAC/D,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAKpE;AAED,mFAAmF;AACnF,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC,wBAAgB,2BAA2B,CACzC,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,OAAO,GACzB,OAAO,CAET;AAED;;uCAEuC;AACvC,eAAO,MAAM,sBAAsB,QAA2B,CAAC;AAE/D,wBAAgB,0BAA0B,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,SAAa,GAAG,OAAO,CAKjG;AAED,uEAAuE;AACvE,eAAO,MAAM,gBAAgB,SAAU,CAAC;AAExC,0DAA0D;AAC1D,eAAO,MAAM,yBAAyB,6EAK5B,CAAC;AAEX,+EAA+E;AAC/E,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAIvE,CAAC"} \ No newline at end of file diff --git a/dist/dictation.js b/dist/dictation.js new file mode 100644 index 0000000..4034ef0 --- /dev/null +++ b/dist/dictation.js @@ -0,0 +1,93 @@ +/** + * The decisions behind the microphone, without the microphone. + * + * The shape comes from heidi (`app/[locale]/_components/use-dictation.ts`), + * which is the only chat in the fleet whose mic never goes dead: + * + * - The browser's recogniser is FAST (free, instant, nothing uploaded) but + * sometimes a lie: Chromium builds without Google's speech service accept + * `start()` and then never fire an event — measured on heidi's live site + * 2026-09-12, nine seconds, zero events. So the recogniser is never the only + * path. Missing or silent, the same button RECORDS and a server transcribes. + * - Every failure becomes one of three words the person can act on — the mic + * (permission, hardware), silence (nothing heard), unavailable (nothing here + * can do it) — never a button that does nothing and says nothing. + * + * Kept pure so "never forever" and "which failures the fallback rescues" are + * tested properties rather than behaviour buried in a timeout. + */ +/** + * Which recogniser failures the fallback can rescue: only "unavailable" — the + * recogniser cannot do this (no speech service, network refused, language + * unsupported) and recording locally does not care. "mic" is the person's + * hardware or a permission they denied; "silence" is whether they spoke. + * Recording again would tell them the same thing twice. + */ +export function fallbackCanRescue(problem) { + return problem === "unavailable"; +} +/** Web Speech `error` codes → the three words. Anything unknown is + * `unavailable`, never nothing: a control that fails silently looks broken. */ +export function problemFor(error) { + switch (error) { + case "aborted": + return null; + case "not-allowed": + case "service-not-allowed": + case "audio-capture": + return "mic"; + case "no-speech": + return "silence"; + default: + return "unavailable"; + } +} +/** getUserMedia / MediaRecorder failures → the same three words, so the UI + * never grows a second vocabulary for the same situations. */ +export function problemForRecording(error) { + const name = error?.name ?? ""; + if (name === "NotAllowedError" || name === "SecurityError") + return "mic"; + if (name === "NotFoundError" || name === "NotReadableError") + return "mic"; + return "unavailable"; +} +/** A working recogniser fires `start` well inside this once the mic is allowed. */ +export const START_TIMEOUT_MS = 4000; +/** + * How long a pending permission may hold off the fallback. The wait is right — + * someone reading a permission dialog has not failed — but it must be BOUNDED: + * `permissions.query` says "prompt" both while a dialog is open and when none + * will ever appear (heidi, 2026-09-12: twenty-two seconds, nothing). + */ +export const PERMISSION_WAIT_MS = 10_000; +export function mayKeepWaitingForPermission(elapsedMs, permissionPending) { + return permissionPending && elapsedMs < PERMISSION_WAIT_MS; +} +/** A browser whose recogniser proved dead is remembered for this long, so the + * person does not rediscover it on every press — and not forever, because a + * browser can gain the capability. */ +export const DEAD_RECOGNISER_TTL_MS = 30 * 24 * 60 * 60 * 1000; +export function deadRecogniserStillTrusted(rememberedAt, now = Date.now()) { + if (rememberedAt === null || !Number.isFinite(rememberedAt)) + return false; + const age = now - rememberedAt; + // A timestamp from the future is a clock change, not a verdict. + return age >= 0 && age < DEAD_RECOGNISER_TTL_MS; +} +/** Recording is capped so a forgotten mic does not run for an hour. */ +export const MAX_RECORDING_MS = 120_000; +/** Candidate containers for MediaRecorder, best first. */ +export const RECORDING_MIME_CANDIDATES = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/mp4", + "audio/ogg", +]; +/** The default words for each problem. Override per app (and per language). */ +export const DEFAULT_DICTATION_MESSAGES = { + mic: "The microphone is blocked. Allow it for this site and try again.", + silence: "Nothing was heard. Try again, a little closer to the mic.", + unavailable: "Voice input is not available right now. Type instead, or try again later.", +}; +//# sourceMappingURL=dictation.js.map \ No newline at end of file diff --git a/dist/dictation.js.map b/dist/dictation.js.map new file mode 100644 index 0000000..74bc444 --- /dev/null +++ b/dist/dictation.js.map @@ -0,0 +1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AAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IACtF,IAAI,YAAY,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,GAAG,GAAG,GAAG,GAAG,YAAY,CAAC;IAC/B,gEAAgE;IAChE,OAAO,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,sBAAsB,CAAC;AAClD,CAAC;AAED,uEAAuE;AACvE,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC,0DAA0D;AAC1D,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,wBAAwB;IACxB,YAAY;IACZ,WAAW;IACX,WAAW;CACH,CAAC;AAEX,+EAA+E;AAC/E,MAAM,CAAC,MAAM,0BAA0B,GAAqC;IAC1E,GAAG,EAAE,kEAAkE;IACvE,OAAO,EAAE,2DAA2D;IACpE,WAAW,EAAE,2EAA2E;CACzF,CAAC"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..d3b9515 --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,11 @@ +/** + * @bitbaum/chatkit — the framework-free half. Every decision a chat makes, + * testable without a DOM. The React components live in `@bitbaum/chatkit/react`, + * the look in `@bitbaum/chatkit/styles.css`. + */ +export * from "./composer.js"; +export * from "./dictation.js"; +export * from "./markdown.js"; +export * from "./scroll.js"; +export * from "./attachments.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map new file mode 100644 index 0000000..74e3886 --- /dev/null +++ b/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..8ac3242 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,11 @@ +/** + * @bitbaum/chatkit — the framework-free half. Every decision a chat makes, + * testable without a DOM. The React components live in `@bitbaum/chatkit/react`, + * the look in `@bitbaum/chatkit/styles.css`. + */ +export * from "./composer.js"; +export * from "./dictation.js"; +export * from "./markdown.js"; +export * from "./scroll.js"; +export * from "./attachments.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..11e517f --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/markdown.d.ts b/dist/markdown.d.ts new file mode 100644 index 0000000..3f25f01 --- /dev/null +++ b/dist/markdown.d.ts @@ -0,0 +1,62 @@ +/** + * The markdown an LLM actually writes, parsed into blocks and inline spans — + * no dependency, no HTML string, nothing to sanitise because nothing is ever + * rendered as HTML. + * + * From loki's `MarkdownText`, the one renderer in the fleet that four repos + * did NOT have: those rendered model output with the literal `**` still in it. + * Supports what answers use — paragraphs, bullet and numbered lists, headings, + * **bold**, *italic*, `code`, fenced code, [links](url) and `[F1]` citation + * handles — and deliberately nothing else. + */ +export type MarkdownBlock = { + kind: "p"; + text: string; +} | { + kind: "h"; + text: string; +} | { + kind: "ul"; + items: string[]; +} | { + kind: "ol"; + items: string[]; +} | { + kind: "code"; + lang: string; + code: string; +} | { + kind: "quote"; + text: string; +}; +export declare function parseBlocks(text: string): MarkdownBlock[]; +export type InlineSpan = { + kind: "text"; + text: string; +} | { + kind: "code"; + text: string; +} | { + kind: "strong"; + text: string; +} | { + kind: "em"; + text: string; +} | { + kind: "link"; + text: string; + href: string; +} | { + kind: "cite"; + ids: string[]; +}; +export declare function parseInline(text: string): InlineSpan[]; +/** + * Only http(s), mailto and same-site paths become links. A `javascript:` URL in + * model output is text, never a link — the answer is written by a model that + * may have read a hostile page. + */ +export declare function safeHref(href: string): string | null; +/** A same-site path navigates in place; anything else opens a new tab. */ +export declare function isInternalHref(href: string): boolean; +//# sourceMappingURL=markdown.d.ts.map \ No newline at end of file diff --git a/dist/markdown.d.ts.map b/dist/markdown.d.ts.map new file mode 100644 index 0000000..b026e42 --- /dev/null +++ b/dist/markdown.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"markdown.d.ts","sourceRoot":"","sources":["../src/markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAEpC,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,CAkDzD;AAED,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC5B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAKpC,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,CAyBtD;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAYpD;AAED,0EAA0E;AAC1E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEpD"} \ No newline at end of file diff --git a/dist/markdown.js b/dist/markdown.js new file mode 100644 index 0000000..12ca058 --- /dev/null +++ b/dist/markdown.js @@ -0,0 +1,127 @@ +/** + * The markdown an LLM actually writes, parsed into blocks and inline spans — + * no dependency, no HTML string, nothing to sanitise because nothing is ever + * rendered as HTML. + * + * From loki's `MarkdownText`, the one renderer in the fleet that four repos + * did NOT have: those rendered model output with the literal `**` still in it. + * Supports what answers use — paragraphs, bullet and numbered lists, headings, + * **bold**, *italic*, `code`, fenced code, [links](url) and `[F1]` citation + * handles — and deliberately nothing else. + */ +export function parseBlocks(text) { + const blocks = []; + let list = null; + const lines = text.split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const raw = lines[i] ?? ""; + const line = raw.trim(); + // ``` fenced code — verbatim until the closing fence (or the end, while + // it is still streaming in). + if (line.startsWith("```")) { + list = null; + const lang = line.slice(3).trim(); + const code = []; + i++; + while (i < lines.length && !(lines[i] ?? "").trim().startsWith("```")) { + code.push(lines[i] ?? ""); + i++; + } + blocks.push({ kind: "code", lang, code: code.join("\n") }); + continue; + } + if (!line) { + list = null; + continue; + } + const bullet = /^[-*•]\s+(.*)$/.exec(line); + const numbered = /^\d+[.)]\s+(.*)$/.exec(line); + if (bullet || numbered) { + const kind = bullet ? "ul" : "ol"; + if (!list || list.kind !== kind) { + list = { kind, items: [] }; + blocks.push(list); + } + list.items.push((bullet ?? numbered)[1] ?? ""); + continue; + } + list = null; + if (/^#{1,6}\s/.test(line)) { + blocks.push({ kind: "h", text: line.replace(/^#+\s+/, "") }); + } + else if (line.startsWith(">")) { + // A model's `>` leaked into prose was one of orangecat's fixed bugs. + blocks.push({ kind: "quote", text: line.replace(/^>\s?/, "") }); + } + else { + const prev = blocks[blocks.length - 1]; + // A soft line break inside a paragraph continues it. + if (prev && prev.kind === "p" && (lines[i - 1] ?? "").trim()) + prev.text += `\n${line}`; + else + blocks.push({ kind: "p", text: line }); + } + } + return blocks; +} +const INLINE_RE = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*\s][^*]*\*|\[[^\]]+\]\([^)\s]+\)|\[[FD]\d+(?:,\s*[FD]\d+)*\]|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/g; +export function parseInline(text) { + const out = []; + for (const part of text.split(INLINE_RE)) { + if (!part) + continue; + if (/^\[[FD]\d+(?:,\s*[FD]\d+)*\]$/.test(part)) { + out.push({ kind: "cite", ids: part.slice(1, -1).split(/,\s*/) }); + } + else if (part.startsWith("`") && part.endsWith("`") && part.length > 1) { + out.push({ kind: "code", text: part.slice(1, -1) }); + } + else if (part.startsWith("**") && part.endsWith("**") && part.length > 4) { + out.push({ kind: "strong", text: part.slice(2, -2) }); + } + else if (/^\*[^*\s][^*]*\*$/.test(part)) { + out.push({ kind: "em", text: part.slice(1, -1) }); + } + else { + const link = /^\[([^\]]+)\]\(([^)\s]+)\)$/.exec(part); + const href = link + ? safeHref(link[2] ?? "") + : /^https?:\/\//.test(part) + ? safeHref(part) + : null; + if (link && href) + out.push({ kind: "link", text: link[1] ?? href, href }); + else if (!link && href) + out.push({ kind: "link", text: part, href }); + else + out.push({ kind: "text", text: link ? (link[1] ?? part) : part }); + } + } + return out; +} +/** + * Only http(s), mailto and same-site paths become links. A `javascript:` URL in + * model output is text, never a link — the answer is written by a model that + * may have read a hostile page. + */ +export function safeHref(href) { + const h = href.trim(); + if (h.startsWith("/") && !h.startsWith("//")) + return h; + if (h.startsWith("#")) + return h; + try { + const u = new URL(h); + return u.protocol === "https:" || u.protocol === "http:" || u.protocol === "mailto:" + ? u.href + : null; + } + catch { + return null; + } +} +/** A same-site path navigates in place; anything else opens a new tab. */ +export function isInternalHref(href) { + return href.startsWith("/") || href.startsWith("#"); +} +//# sourceMappingURL=markdown.js.map \ No newline at end of file diff --git a/dist/markdown.js.map b/dist/markdown.js.map new file mode 100644 index 0000000..22c8598 --- /dev/null +++ b/dist/markdown.js.map @@ -0,0 +1 @@ +{"version":3,"file":"markdown.js","sourceRoot":"","sources":["../src/markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,MAAM,MAAM,GAAoB,EAAE,CAAC;IACnC,IAAI,IAAI,GAAkD,IAAI,CAAC;IAC/D,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;QACxB,wEAAwE;QACxE,6BAA6B;QAC7B,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3B,IAAI,GAAG,IAAI,CAAC;YACZ,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,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I,CAAC;IACd,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AACtD,CAAC"} \ No newline at end of file diff --git a/dist/react/Composer.d.ts b/dist/react/Composer.d.ts new file mode 100644 index 0000000..e0a7db4 --- /dev/null +++ b/dist/react/Composer.d.ts @@ -0,0 +1,78 @@ +import { type ReactNode, type RefObject } from "react"; +import { type ComposerMode, type ComposerSendResult } from "../composer.js"; +import { type DictationProblem } from "../dictation.js"; +import type { Attachment, AttachmentLimits } from "../attachments.js"; +import { type UseDictationOptions } from "./use-dictation.js"; +export type ComposerLabels = { + send: string; + stop: string; + voice: string; + voiceStop: string; + cancelRecording: string; + confirmRecording: string; + listening: string; + transcribing: string; + attach: string; + remove: (name: string) => string; + dismiss: string; + dictation: Record; +}; +export declare const DEFAULT_COMPOSER_LABELS: ComposerLabels; +export type ComposerVoice = Omit; +export type ComposerProps = { + /** Deliver what was written. Return `false` (or resolve to it) to keep the + * draft — a failed send is retried from the same box, not retyped. */ + onSend: (text: string, attachments: Attachment[]) => ComposerSendResult | Promise; + placeholder: string; + ariaLabel?: string; + disabled?: boolean; + /** Typing is fine, sending is not — shown as the send button's title. */ + sendBlockedReason?: string | null; + sending?: boolean; + /** Given, the send slot becomes Stop while `sending`: a turn you cannot + * cancel is what makes a slow answer feel broken. */ + onStop?: () => void; + /** What an attachments-only send says. Omit and empty text cannot send. */ + attachmentOnlyText?: string; + /** Attachments on, optionally with the app's own limits. Off by default: + * only offer what the app's API accepts. */ + attach?: boolean | Partial; + /** The microphone. On by default. Pass `transcribeUrl` (or `transcribe`) so + * it still works where the browser recogniser does not — that fallback is + * what makes the mic never a dead button. `false` only for a surface that + * truly cannot take speech. */ + voice?: ComposerVoice | false; + modes?: readonly ComposerMode[]; + mode?: string; + onModeChange?: (id: string) => void; + /** "/" typed into an empty composer — open a library instead of typing. */ + onEmptySlash?: () => void; + value?: string; + onValueChange?: (text: string) => void; + defaultValue?: string; + inputRef?: RefObject; + density?: "comfortable" | "compact"; + /** Outside the box, above it (suggestion chips). */ + above?: ReactNode; + /** Inside the box, above the text (scope pills, an error). */ + header?: ReactNode; + /** Extra tools after attach and voice (a model picker, a library). */ + tools?: ReactNode; + /** Just before the send button. */ + trailing?: ReactNode; + /** Inside the box, under the controls. */ + footer?: ReactNode; + hint?: string; + labels?: Partial; + autoFocus?: boolean; +}; +/** + * THE composer: write words — or say them, or paste a screenshot — and send + * them. Enter sends, Shift+Enter breaks the line, an IME composition never + * sends half a word. 16px text, so iOS never zooms the page on focus. + * + * Extracted from loki `components/composer/Composer.tsx` (itself the merge of + * four composers in one app), with heidi's microphone and orangecat's lessons. + */ +export declare function Composer({ onSend, placeholder, ariaLabel, disabled, sendBlockedReason, sending, onStop, attachmentOnlyText, attach, voice, modes, mode, onModeChange, onEmptySlash, value, onValueChange, defaultValue, inputRef, density, above, header, tools, trailing, footer, hint, labels: labelOverrides, autoFocus, }: ComposerProps): import("react").JSX.Element; +//# sourceMappingURL=Composer.d.ts.map \ No newline at end of file diff --git a/dist/react/Composer.d.ts.map b/dist/react/Composer.d.ts.map new file mode 100644 index 0000000..b7d5912 --- /dev/null +++ b/dist/react/Composer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Composer.d.ts","sourceRoot":"","sources":["../../src/react/Composer.tsx"],"names":[],"mappings":"AAEA,OAAO,EAA+B,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AACpF,OAAO,EAML,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAA8B,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACpF,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAgB,KAAK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AM,EAAE,cAAc,EACtB,SAAS,GACV,EAAE,aAAa,+BAsPf"} \ No newline at end of file diff --git a/dist/react/Composer.js b/dist/react/Composer.js new file mode 100644 index 0000000..6a08061 --- /dev/null +++ b/dist/react/Composer.js @@ -0,0 +1,129 @@ +"use client"; +import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; +import { useEffect, useRef, useState } from "react"; +import { appendTranscript, composerCanSend, composerOutgoingText, formatElapsed, shouldClearDraft, } from "../composer.js"; +import { DEFAULT_DICTATION_MESSAGES } from "../dictation.js"; +import { useDictation } from "./use-dictation.js"; +import { useAttachments } from "./use-attachments.js"; +import { useAutoGrow } from "./hooks.js"; +import { IconArrowUp, IconCheck, IconFile, IconMic, IconPaperclip, IconSpinner, IconStop, IconX, } from "./icons.js"; +export const DEFAULT_COMPOSER_LABELS = { + send: "Send", + stop: "Stop generating", + voice: "Speak instead of typing", + voiceStop: "Stop recording", + cancelRecording: "Cancel recording", + confirmRecording: "Done — use what I said", + listening: "Listening…", + transcribing: "Transcribing…", + attach: "Attach a screenshot or file", + remove: (name) => `Remove ${name}`, + dismiss: "Dismiss", + dictation: DEFAULT_DICTATION_MESSAGES, +}; +function AttachmentStrip({ attachments, labels, }) { + if (attachments.attachments.length === 0 && !attachments.note) + return null; + return (_jsxs("div", { className: "ck-attach-strip", children: [attachments.attachments.map((a) => { + const key = attachments.keyOf(a); + return (_jsxs("div", { className: "ck-attach-item", children: [a.kind === "image" && a.previewUrl ? (_jsx("img", { src: a.previewUrl, alt: a.name, className: "ck-attach-thumb" })) : (_jsxs("span", { className: "ck-attach-file", children: [_jsx(IconFile, {}), _jsx("span", { className: "ck-truncate", children: a.name })] })), _jsx("button", { type: "button", className: "ck-attach-remove", onClick: () => attachments.remove(key), "aria-label": labels.remove(a.name), title: labels.remove(a.name), children: _jsx(IconX, {}) })] }, key)); + }), attachments.note && (_jsx("button", { type: "button", className: "ck-note", onClick: attachments.clearNote, children: attachments.note }))] })); +} +function Elapsed({ since }) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (since === null) + return; + const t = setInterval(() => setNow(Date.now()), 250); + return () => clearInterval(t); + }, [since]); + return (_jsx("span", { className: "ck-voice-timer", children: formatElapsed(since === null ? 0 : (now - since) / 1000) })); +} +/** + * THE composer: write words — or say them, or paste a screenshot — and send + * them. Enter sends, Shift+Enter breaks the line, an IME composition never + * sends half a word. 16px text, so iOS never zooms the page on focus. + * + * Extracted from loki `components/composer/Composer.tsx` (itself the merge of + * four composers in one app), with heidi's microphone and orangecat's lessons. + */ +export function Composer({ onSend, placeholder, ariaLabel, disabled = false, sendBlockedReason = null, sending = false, onStop, attachmentOnlyText, attach = false, voice = {}, modes, mode, onModeChange, onEmptySlash, value, onValueChange, defaultValue = "", inputRef, density = "comfortable", above, header, tools, trailing, footer, hint, labels: labelOverrides, autoFocus, }) { + const labels = { + ...DEFAULT_COMPOSER_LABELS, + ...labelOverrides, + dictation: { ...DEFAULT_COMPOSER_LABELS.dictation, ...labelOverrides?.dictation }, + }; + const [ownText, setOwnText] = useState(defaultValue); + const controlled = value !== undefined; + const text = controlled ? value : ownText; + // Mirrored so an async send compares against the CURRENT draft, not the one + // its closure captured. Written in an effect, never during render. + const textRef = useRef(text); + useEffect(() => { + textRef.current = text; + }); + const setText = (next) => { + const resolved = typeof next === "function" ? next(textRef.current) : next; + textRef.current = resolved; + if (!controlled) + setOwnText(resolved); + onValueChange?.(resolved); + }; + const localRef = useRef(null); + const textareaRef = inputRef ?? localRef; + useAutoGrow(textareaRef, text); + const attachOn = attach !== false; + const attachments = useAttachments(typeof attach === "object" ? attach : {}); + const dictation = useDictation({ + ...(voice || {}), + onText: (said) => setText((prev) => appendTranscript(prev, said)), + }); + const voiceOn = voice !== false && dictation.supported; + const listening = dictation.status === "listening"; + const transcribing = dictation.status === "transcribing"; + const attachCount = attachOn ? attachments.attachments.length : 0; + const canSend = composerCanSend({ + text, + attachmentCount: attachCount, + attachmentOnlyText, + sending, + disabled, + blocked: Boolean(sendBlockedReason), + }); + const submit = async () => { + if (!canSend) + return; + const sent = text; + const outgoing = composerOutgoingText(sent, attachCount, attachmentOnlyText); + const result = await onSend(outgoing, attachOn ? attachments.toWire() : []); + if (!shouldClearDraft(result)) + return; + // Only clear what was sent: words typed while a slow send was in flight + // are the next message. + if (textRef.current === sent) + setText(""); + attachments.clear(); + }; + const fileInput = useRef(null); + const showModes = Boolean(modes && modes.length > 1); + return (_jsxs("div", { className: "ck-composer-wrap", children: [above, _jsxs("div", { className: "ck-composer-frame", children: [(listening || transcribing) && (_jsx("div", { className: "ck-voice-bar", role: "status", "aria-live": "polite", children: listening ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "ck-voice-dot", "aria-hidden": true }), _jsx("span", { className: "ck-voice-wave", "aria-hidden": true, children: Array.from({ length: 9 }).map((_, i) => (_jsx("span", {}, i))) }), _jsx(Elapsed, { since: dictation.startedAt }), _jsx("button", { type: "button", className: "ck-icon-btn", onClick: dictation.cancel, "aria-label": labels.cancelRecording, title: labels.cancelRecording, children: _jsx(IconX, {}) }), _jsx("button", { type: "button", className: "ck-voice-confirm", onClick: dictation.stop, "aria-label": labels.confirmRecording, title: labels.confirmRecording, children: _jsx(IconCheck, {}) })] })) : (_jsxs(_Fragment, { children: [_jsx(IconSpinner, {}), _jsx("span", { className: "ck-voice-timer", children: labels.transcribing })] })) })), _jsxs("div", { className: density === "compact" ? "ck-composer ck-composer-compact" : "ck-composer", children: [showModes && (_jsx("div", { className: "ck-modes", role: "group", children: modes.map((m) => (_jsx("button", { type: "button", className: "ck-mode", "aria-pressed": m.id === mode, title: m.hint, onClick: () => onModeChange?.(m.id), children: m.label }, m.id))) })), header, _jsx("textarea", { ref: textareaRef, className: "ck-input", rows: 1, value: text, autoFocus: autoFocus, disabled: disabled || transcribing, placeholder: listening ? labels.listening : placeholder, "aria-label": ariaLabel ?? placeholder, enterKeyHint: "send", onChange: (e) => { + const next = e.target.value; + if (onEmptySlash && next === "/" && text === "") { + onEmptySlash(); + return; + } + setText(next); + }, onPaste: (e) => { + if (attachOn && attachments.addFromPaste(e)) + e.preventDefault(); + }, onKeyDown: (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { + e.preventDefault(); + void submit(); + } + } }), attachOn && _jsx(AttachmentStrip, { attachments: attachments, labels: labels }), _jsxs("div", { className: "ck-actions", children: [_jsxs("div", { className: "ck-tools", children: [attachOn && (_jsxs(_Fragment, { children: [_jsx("input", { ref: fileInput, type: "file", multiple: true, hidden: true, accept: "image/*,text/*,.md,.txt,.json,.csv,.log", onChange: (e) => { + attachments.addFiles(e.target.files); + e.target.value = ""; + } }), _jsx("button", { type: "button", className: "ck-icon-btn", onClick: () => fileInput.current?.click(), disabled: disabled || attachments.full, "aria-label": labels.attach, title: labels.attach, children: _jsx(IconPaperclip, {}) })] })), voiceOn && (_jsx("button", { type: "button", className: listening ? "ck-icon-btn ck-mic ck-mic-on" : "ck-icon-btn ck-mic", onClick: dictation.toggle, disabled: disabled || transcribing, "aria-label": listening ? labels.voiceStop : labels.voice, "aria-pressed": listening, title: listening ? labels.voiceStop : labels.voice, children: transcribing ? _jsx(IconSpinner, {}) : _jsx(IconMic, {}) })), tools, hint && _jsx("span", { className: "ck-hint", children: hint })] }), _jsxs("div", { className: "ck-submit", children: [trailing, sending && onStop ? (_jsx("button", { type: "button", className: "ck-send ck-send-stop", onClick: onStop, "aria-label": labels.stop, title: labels.stop, children: _jsx(IconStop, {}) })) : (!listening && (_jsx("button", { type: "button", className: "ck-send", disabled: !canSend, onClick: () => void submit(), "aria-label": labels.send, title: sendBlockedReason ?? labels.send, children: sending ? _jsx(IconSpinner, {}) : _jsx(IconArrowUp, {}) })))] })] }), footer] })] }), dictation.problem && (_jsxs("p", { className: "ck-problem", role: "status", children: [_jsx("span", { children: labels.dictation[dictation.problem] }), _jsx("button", { type: "button", className: "ck-problem-x", onClick: dictation.clearProblem, "aria-label": labels.dismiss, children: _jsx(IconX, {}) })] }))] })); +} +//# sourceMappingURL=Composer.js.map \ No newline at end of file diff --git a/dist/react/Composer.js.map b/dist/react/Composer.js.map new file mode 100644 index 0000000..15dd957 --- /dev/null +++ b/dist/react/Composer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Composer.js","sourceRoot":"","sources":["../../src/react/Composer.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAkC,MAAM,OAAO,CAAC;AACpF,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,gBAAgB,GAGjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAyB,MAAM,iBAAiB,CAAC;AAEpF,OAAO,EAAE,YAAY,EAA4B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAA8B,MAAM,sBAAsB,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EACL,WAAW,EACX,SAAS,EACT,QAAQ,EACR,OAAO,EACP,aAAa,EACb,WAAW,EACX,QAAQ,EACR,KAAK,GACN,MAAM,YAAY,CAAC;AAiBpB,MAAM,CAAC,MAAM,uBAAuB,GAAmB;IACrD,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,iBAAiB;IACvB,KAAK,EAAE,yBAAyB;IAChC,SAAS,EAAE,gBAAgB;IAC3B,eAAe,EAAE,kBAAkB;IACnC,gBAAgB,EAAE,wBAAwB;IAC1C,SAAS,EAAE,YAAY;IACvB,YAAY,EAAE,eAAe;IAC7B,MAAM,EAAE,6BAA6B;IACrC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,IAAI,EAAE;IAClC,OAAO,EAAE,SAAS;IAClB,SAAS,EAAE,0BAA0B;CACtC,CAAC;AAuDF,SAAS,eAAe,CAAC,EACvB,WAAW,EACX,MAAM,GAIP;IACC,IAAI,WAAW,CAAC,WAA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 0000000..ab7c740 --- /dev/null +++ b/dist/react/Markdown.d.ts @@ -0,0 +1,27 @@ +import type { ReactNode } from "react"; +/** What a grounded answer's `[F8]` / `[D1]` handle refers to. Unknown handles + * are dropped rather than shown bare: a dangling `[F8]` implies a source the + * reader cannot reach. */ +export type CitationMap = Record; +export type RenderLink = (link: { + href: string; + internal: boolean; + className: string; + children: ReactNode; +}) => ReactNode; +/** A plain anchor: same-site paths in place, everything else in a new tab. */ +export declare const defaultRenderLink: RenderLink; +/** + * Model output as readable text: paragraphs, lists, headings, bold, italic, + * code, links and citations. Never HTML — nothing here can inject markup. + */ +export declare function Markdown({ text, citations, renderLink, className, }: { + text: string; + citations?: CitationMap; + renderLink?: RenderLink; + className?: string; +}): import("react").JSX.Element; +//# sourceMappingURL=Markdown.d.ts.map \ No newline at end of file diff --git a/dist/react/Markdown.d.ts.map b/dist/react/Markdown.d.ts.map new file mode 100644 index 0000000..414b541 --- /dev/null +++ b/dist/react/Markdown.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Markdown.d.ts","sourceRoot":"","sources":["../../src/react/Markdown.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGvC;;2BAE2B;AAC3B,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAE5E,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,SAAS,CAAC;CACrB,KAAK,SAAS,CAAC;AAEhB,8EAA8E;AAC9E,eAAO,MAAM,iBAAiB,EAAE,UAS7B,CAAC;AA2DJ;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,EACvB,IAAI,EACJ,SAAS,EACT,UAA8B,EAC9B,SAAS,GACV,EAAE;IACD,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,+BAuCA"} \ No newline at end of file diff --git a/dist/react/Markdown.js b/dist/react/Markdown.js new file mode 100644 index 0000000..152cca3 --- /dev/null +++ b/dist/react/Markdown.js @@ -0,0 +1,58 @@ +import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; +import { isInternalHref, parseBlocks, parseInline } from "../markdown.js"; +/** A plain anchor: same-site paths in place, everything else in a new tab. */ +export const defaultRenderLink = ({ href, internal, className, children }) => internal ? (_jsx("a", { href: href, className: className, children: children })) : (_jsx("a", { href: href, className: className, target: "_blank", rel: "noopener noreferrer", children: children })); +function Inline({ spans, citations, renderLink, }) { + return (_jsx(_Fragment, { children: spans.map((s, i) => { + switch (s.kind) { + case "code": + return (_jsx("code", { className: "ck-code", children: s.text }, i)); + case "strong": + return _jsx("strong", { children: s.text }, i); + case "em": + return _jsx("em", { children: s.text }, i); + case "link": + return (_jsx("span", { children: renderLink({ + href: s.href, + internal: isInternalHref(s.href), + className: "ck-link", + children: s.text, + }) }, i)); + case "cite": { + const known = s.ids.filter((id) => citations?.[id]); + if (known.length === 0) + return null; + return (_jsx("sup", { className: "ck-cite", title: known + .map((id) => `${id} — ${citations[id].label}\n${citations[id].detail}`) + .join("\n\n"), children: known.join(" ") }, i)); + } + default: + return _jsx("span", { children: s.text }, i); + } + }) })); +} +/** + * Model output as readable text: paragraphs, lists, headings, bold, italic, + * code, links and citations. Never HTML — nothing here can inject markup. + */ +export function Markdown({ text, citations, renderLink = defaultRenderLink, className, }) { + const inline = (t) => (_jsx(Inline, { spans: parseInline(t), citations: citations, renderLink: renderLink })); + return (_jsx("div", { className: className ? `ck-md ${className}` : "ck-md", children: parseBlocks(text).map((b, i) => { + switch (b.kind) { + case "code": + return (_jsx("pre", { className: "ck-pre", "data-lang": b.lang || undefined, children: _jsx("code", { children: b.code }) }, i)); + case "ul": + case "ol": { + const List = b.kind; + return (_jsx(List, { children: b.items.map((item, j) => (_jsx("li", { children: inline(item) }, j))) }, i)); + } + case "h": + return (_jsx("p", { className: "ck-md-h", children: inline(b.text) }, i)); + case "quote": + return _jsx("blockquote", { children: inline(b.text) }, i); + default: + return _jsx("p", { children: inline(b.text) }, i); + } + }) })); +} +//# sourceMappingURL=Markdown.js.map \ No newline at end of file diff --git a/dist/react/Markdown.js.map b/dist/react/Markdown.js.map new file mode 100644 index 0000000..804172e --- /dev/null +++ b/dist/react/Markdown.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Markdown.js","sourceRoot":"","sources":["../../src/react/Markdown.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,WAAW,EAAmB,MAAM,gBAAgB,CAAC;AAc3F,8EAA8E;AAC9E,MAAM,CAAC,MAAM,iBAAiB,GAAe,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,EAAE,CACvF,QAAQ,CAAC,CAAC,CAAC,CACT,YAAG,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,YAChC,QAAQ,GACP,CACL,CAAC,CAAC,CAAC,CACF,YAAG,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAC,QAAQ,EAAC,GAAG,EAAC,qBAAqB,YAC3E,QAAQ,GACP,CACL,CAAC;AAEJ,SAAS,MAAM,CAAC,EACd,KAAK,EACL,SAAS,EACT,UAAU,GAKX;IACC,OAAO,CACL,4BACG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YAClB,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;gBACf,KAAK,MAAM;oBACT,OAAO,CACL,eAAc,SAAS,EAAC,SAAS,YAC9B,CAAC,CAAC,I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AAC,IAAlB,CAAC,CAAsB,CAAC;YAC3C,CAAC;QACH,CAAC,CAAC,GACE,CACP,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/react/Thread.d.ts b/dist/react/Thread.d.ts new file mode 100644 index 0000000..4c2b2c9 --- /dev/null +++ b/dist/react/Thread.d.ts @@ -0,0 +1,90 @@ +import type { ReactNode } from "react"; +import { type CitationMap, type RenderLink } from "./Markdown.js"; +export type ChatSpeaker = { + /** Shown above the message when more than one agent can answer. */ + name: string; + /** Stable id for styling (`ck-from-`), e.g. "cat" or "loki". */ + id?: string; +}; +export type ChatMessageData = { + id: string; + role: "user" | "assistant"; + content: string; + speaker?: ChatSpeaker; + citations?: CitationMap; + /** The turn failed: shown as a failure with Retry, never as silence. */ + failed?: boolean; +}; +export type ThreadLabels = { + copy: string; + copied: string; + retry: string; + stop: string; + working: string; + stopped: string; + jump: string; + failed: string; + loading: string; +}; +export declare const DEFAULT_THREAD_LABELS: ThreadLabels; +/** + * One turn. The asymmetry is deliberate: the person's own words get a pill — + * a short aside they already know — and the answer gets the full column with + * no box, because it is the thing being READ. Copy is on every answer; Retry + * only on the last one (retrying an older turn would fork the thread). + */ +export declare function ChatMessage({ message, onRetry, renderLink, showSpeaker, footer, last, labels, }: { + message: ChatMessageData; + /** The latest answer: its actions stay visible (they are what you want next). */ + last?: boolean; + onRetry?: () => void; + renderLink?: RenderLink; + /** Hide the name when only one agent ever speaks. */ + showSpeaker?: boolean; + /** Under the answer: provenance, sources, an action card. */ + footer?: ReactNode; + labels?: ThreadLabels; +}): import("react").JSX.Element; +export type LiveTurn = { + /** What has streamed in so far. */ + text?: string; + /** What it is doing before the first word ("Reading the fleet map"). */ + status?: string; + speaker?: ChatSpeaker; +}; +/** + * The conversation. Follows new tokens only while the reader is at the + * bottom, with a button back down once they are not; a turn in flight can be + * stopped from where it is being written. + */ +export declare function ChatThread({ messages, live, loading, stopped, onStop, onRetry, renderLink, renderFooter, showSpeakers, empty, children, labels: labelOverrides, }: { + messages: ChatMessageData[]; + live?: LiveTurn | null; + loading?: boolean; + /** The person stopped the last turn themselves. */ + stopped?: boolean; + onStop?: () => void; + /** Retry the last answer (offered on it, and on a failed one). */ + onRetry?: () => void; + renderLink?: RenderLink; + /** App-specific content under an answer (sources, an action card). */ + renderFooter?: (m: ChatMessageData) => ReactNode; + /** Default: shown when more than one speaker appears in the thread. */ + showSpeakers?: boolean; + /** Shown instead of the thread before the first message (starters). */ + empty?: ReactNode; + /** After the last turn (a note, a picker). */ + children?: ReactNode; + labels?: Partial; +}): import("react").JSX.Element; +export type Starter = string | { + label: string; + prompt?: string; +}; +/** The empty state that starts a conversation. It disappears once one has. */ +export declare function ChatStarters({ starters, onPick, title, }: { + starters: readonly Starter[]; + onPick: (prompt: string) => void; + title?: ReactNode; +}): import("react").JSX.Element; +//# sourceMappingURL=Thread.d.ts.map \ No newline at end of file diff --git a/dist/react/Thread.d.ts.map b/dist/react/Thread.d.ts.map new file mode 100644 index 0000000..afbdf2b --- /dev/null +++ b/dist/react/Thread.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Thread.d.ts","sourceRoot":"","sources":["../../src/react/Thread.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACvC,OAAO,EAA+B,KAAK,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,eAAe,CAAC;AAI/F,MAAM,MAAM,WAAW,GAAG;IACxB,mEAAmE;IACnE,IAAI,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,EAAE,CAAC,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,wEAAwE;IACxE,MAAM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,EAAE,eAAe,EAAE,CAAC;IAC5B,IAAI,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;IACvB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,mDAAmD;IACnD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;IACpB,kEAAkE;IAClE,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,sEAAsE;IACtE,YAAY,CAAC,EAAE,CAAC,CAAC,EAAE,eAAe,KAAK,SAAS,CAAC;IACjD,uEAAuE;IACvE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uEAAuE;IACvE,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;CAChC,+BAmFA;AAED,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAElE,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,EAC3B,QAAQ,EACR,MAAM,EACN,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IAC7B,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB,+BAiBA"} \ No newline at end of file diff --git a/dist/react/Thread.js b/dist/react/Thread.js new file mode 100644 index 0000000..6e0d581 --- /dev/null +++ b/dist/react/Thread.js @@ -0,0 +1,64 @@ +"use client"; +import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; +import { Markdown, defaultRenderLink } from "./Markdown.js"; +import { useClipboard, useStickToBottom } from "./hooks.js"; +import { IconArrowDown, IconCheck, IconCopy, IconRetry, IconStop } from "./icons.js"; +export const DEFAULT_THREAD_LABELS = { + copy: "Copy", + copied: "Copied", + retry: "Try again", + stop: "Stop", + working: "Working on it", + stopped: "Stopped. Send it again to retry.", + jump: "Jump to the latest message", + failed: "That did not go through.", + loading: "Loading conversation", +}; +/** + * One turn. The asymmetry is deliberate: the person's own words get a pill — + * a short aside they already know — and the answer gets the full column with + * no box, because it is the thing being READ. Copy is on every answer; Retry + * only on the last one (retrying an older turn would fork the thread). + */ +export function ChatMessage({ message, onRetry, renderLink = defaultRenderLink, showSpeaker = true, footer, last = false, labels = DEFAULT_THREAD_LABELS, }) { + const { copied, copy } = useClipboard(); + if (message.role === "user") { + return (_jsx("div", { className: "ck-turn ck-turn-user", children: _jsx("div", { className: "ck-bubble", children: message.content }) })); + } + const cls = ["ck-turn", "ck-turn-answer"]; + if (message.speaker?.id) + cls.push(`ck-from-${message.speaker.id}`); + // A failed turn and the latest answer never hide their buttons: Retry after + // a failure is the one thing the reader needs, and a hover it cannot do on + // a phone must not stand between them. + if (last || message.failed) + cls.push("ck-turn-pinned"); + return (_jsxs("div", { className: cls.join(" "), children: [showSpeaker && message.speaker && _jsx("span", { className: "ck-speaker", children: message.speaker.name }), message.failed ? (_jsx("p", { className: "ck-failed", role: "status", children: message.content || labels.failed })) : (_jsx(Markdown, { text: message.content, citations: message.citations, renderLink: renderLink })), footer, _jsxs("div", { className: "ck-turn-actions", children: [!message.failed && (_jsxs("button", { type: "button", className: "ck-action", onClick: () => copy(message.content), "aria-label": copied ? labels.copied : labels.copy, children: [copied ? _jsx(IconCheck, {}) : _jsx(IconCopy, {}), _jsx("span", { children: copied ? labels.copied : labels.copy })] })), onRetry && (_jsxs("button", { type: "button", className: "ck-action", onClick: onRetry, children: [_jsx(IconRetry, {}), _jsx("span", { children: labels.retry })] }))] })] })); +} +/** + * The conversation. Follows new tokens only while the reader is at the + * bottom, with a button back down once they are not; a turn in flight can be + * stopped from where it is being written. + */ +export function ChatThread({ messages, live = null, loading = false, stopped = false, onStop, onRetry, renderLink = defaultRenderLink, renderFooter, showSpeakers, empty, children, labels: labelOverrides, }) { + const labels = { ...DEFAULT_THREAD_LABELS, ...labelOverrides }; + const { scrollRef, endRef, following, onScroll, jumpToBottom } = useStickToBottom([messages.length, live?.text, live?.status, stopped], messages.length); + if (loading) { + return (_jsx("div", { className: "ck-thread-loading", role: "status", children: labels.loading })); + } + if (messages.length === 0 && !live && !stopped) + return _jsx(_Fragment, { children: empty ?? null }); + const speakers = new Set([...messages.map((m) => m.speaker?.name), live?.speaker?.name].filter(Boolean)); + const named = showSpeakers ?? speakers.size > 1; + const lastAnswer = [...messages].reverse().find((m) => m.role === "assistant"); + return (_jsxs("div", { className: "ck-thread-wrap", children: [_jsx("div", { ref: scrollRef, className: "ck-thread", onScroll: onScroll, children: _jsxs("div", { className: "ck-thread-inner", children: [messages.map((m) => (_jsx(ChatMessage, { message: m, onRetry: onRetry && m.id === lastAnswer?.id && !live ? onRetry : undefined, renderLink: renderLink, showSpeaker: named, footer: renderFooter?.(m), last: m.id === lastAnswer?.id, labels: labels }, m.id))), live && (_jsxs("div", { className: "ck-turn ck-turn-answer", children: [named && live.speaker && _jsx("span", { className: "ck-speaker", children: live.speaker.name }), live.text ? (_jsx(Markdown, { text: live.text, renderLink: renderLink })) : (_jsxs("p", { className: "ck-live", role: "status", "aria-live": "polite", children: [_jsxs("span", { className: "ck-dots", "aria-hidden": true, children: [_jsx("span", {}), _jsx("span", {}), _jsx("span", {})] }), live.status ?? labels.working] })), onStop && (_jsxs("button", { type: "button", className: "ck-stop", onClick: onStop, children: [_jsx(IconStop, {}), labels.stop] }))] })), stopped && !live && (_jsx("p", { className: "ck-stopped", role: "status", children: labels.stopped })), children, _jsx("div", { ref: endRef })] }) }), !following && (_jsx("button", { type: "button", className: "ck-jump", onClick: jumpToBottom, "aria-label": labels.jump, title: labels.jump, children: _jsx(IconArrowDown, {}) }))] })); +} +/** The empty state that starts a conversation. It disappears once one has. */ +export function ChatStarters({ starters, onPick, title, }) { + return (_jsxs("div", { className: "ck-starters", children: [title && _jsx("div", { className: "ck-starters-title", children: title }), _jsx("div", { className: "ck-starters-list", children: starters.map((s, i) => { + const label = typeof s === "string" ? s : s.label; + const prompt = typeof s === "string" ? s : (s.prompt ?? s.label); + return (_jsx("button", { type: "button", className: "ck-starter", onClick: () => onPick(prompt), children: label }, i)); + }) })] })); +} +//# sourceMappingURL=Thread.js.map \ No newline at end of file diff --git a/dist/react/Thread.js.map b/dist/react/Thread.js.map new file mode 100644 index 0000000..84fb19c --- /dev/null +++ b/dist/react/Thread.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Thread.js","sourceRoot":"","sources":["../../src/react/Thread.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAqC,MAAM,eAAe,CAAC;AAC/F,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA+BrF,MAAM,CAAC,MAAM,qBAAqB,GAAiB;IACjD,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,WAAW;IAClB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,eAAe;IACxB,OAAO,EAAE,kCAAkC;IAC3C,IAAI,EAAE,4BAA4B;IAClC,MAAM,EAAE,0BAA0B;IAClC,OAAO,EAAE,sBAAsB;CAChC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,EAC1B,OAAO,EACP,OAAO,EACP,UAAU,GAAG,iBAAiB,EAC9B,WAAW,GAAG,IAAI,EAClB,MAAM,EACN,IAAI,GAAG,KAAK,EACZ,MAAM,GAAG,qBAAqB,GAY/B;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,YAAY,EAAE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B,YAC9B,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;oBACrB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;oBAClD,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC;oBACjE,OAAO,CACL,iBAAgB,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,YAAY,EAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,YAC/E,KAAK,IADK,CAAC,CAEL,CACV,CAAC;gBACJ,CAAC,CAAC,GACE,IACF,CACP,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/react/hooks.d.ts b/dist/react/hooks.d.ts new file mode 100644 index 0000000..4951f92 --- /dev/null +++ b/dist/react/hooks.d.ts @@ -0,0 +1,40 @@ +import { type DependencyList, type RefObject } from "react"; +/** + * Copy + a checkmark that resets. Failures are swallowed on purpose (insecure + * origin, denied permission): the text stays selectable, so a failed copy + * blocks nothing — `copied` simply never flips. + */ +export declare function useClipboard(resetMs?: number): { + copied: boolean; + copy: (text: string) => void; +}; +/** + * Follow the conversation only while the reader is at the bottom, and offer a + * way back once they are not. Pinned in a layout effect so the view settles + * before the new token paints — in a passive effect the content lands first + * and the scroll catches up, which reads as a shudder on every chunk. + * + * `grew` should change when a NEW turn is added (message count): sending is an + * unambiguous "show me the reply", so it re-arms following. + */ +export declare function useStickToBottom(changes: DependencyList, grew: number): { + scrollRef: RefObject; + endRef: RefObject; + following: boolean; + onScroll: () => void; + jumpToBottom: () => void; +}; +/** + * Publishes the VISUAL viewport height as `--ck-viewport-height`. + * + * `100dvh` does not shrink when the Android soft keyboard opens; only + * `visualViewport` does. A chat column sized `100dvh` keeps its height while + * the keyboard covers the bottom of it, so the composer ends up behind the + * keyboard (orangecat `ViewportHeightSync`, #1094). Rounded down: sub-pixel + * heights leave a 1px seam under the composer on some devices. + */ +export declare function useViewportHeight(target?: RefObject): void; +/** Grow a textarea to its content up to `max` px, keyed on the VALUE so a + * prefill, a dictated transcript or the clear after send resize it too. */ +export declare function useAutoGrow(ref: RefObject, value: string, max?: number): void; +//# sourceMappingURL=hooks.d.ts.map \ No newline at end of file diff --git a/dist/react/hooks.d.ts.map b/dist/react/hooks.d.ts.map new file mode 100644 index 0000000..bea9cf0 --- /dev/null +++ b/dist/react/hooks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAGf;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,SAAO;;iBAUhC,MAAM;EAYhB;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM;;;;;;EA0BrE;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,QAoBvE;AAED;4EAC4E;AAC5E,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,CAAC,mBAAmB,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,QAO/F"} \ No newline at end of file diff --git a/dist/react/hooks.js b/dist/react/hooks.js new file mode 100644 index 0000000..3f70eac --- /dev/null +++ b/dist/react/hooks.js @@ -0,0 +1,99 @@ +"use client"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react"; +import { isFollowing } from "../scroll.js"; +/** + * Copy + a checkmark that resets. Failures are swallowed on purpose (insecure + * origin, denied permission): the text stays selectable, so a failed copy + * blocks nothing — `copied` simply never flips. + */ +export function useClipboard(resetMs = 1500) { + const [copied, setCopied] = useState(false); + const timer = useRef(null); + useEffect(() => () => { + if (timer.current) + clearTimeout(timer.current); + }, []); + const copy = useCallback((text) => { + void Promise.resolve(navigator.clipboard?.writeText(text)) + .then(() => { + setCopied(true); + if (timer.current) + clearTimeout(timer.current); + timer.current = setTimeout(() => setCopied(false), resetMs); + }) + .catch(() => { }); + }, [resetMs]); + return { copied, copy }; +} +/** + * Follow the conversation only while the reader is at the bottom, and offer a + * way back once they are not. Pinned in a layout effect so the view settles + * before the new token paints — in a passive effect the content lands first + * and the scroll catches up, which reads as a shudder on every chunk. + * + * `grew` should change when a NEW turn is added (message count): sending is an + * unambiguous "show me the reply", so it re-arms following. + */ +export function useStickToBottom(changes, grew) { + const scrollRef = useRef(null); + const endRef = useRef(null); + const [following, setFollowing] = useState(true); + const onScroll = useCallback(() => { + const el = scrollRef.current; + if (el) + setFollowing(isFollowing(el)); + }, []); + const jumpToBottom = useCallback(() => { + setFollowing(true); + endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" }); + }, []); + useLayoutEffect(() => { + if (following) + endRef.current?.scrollIntoView({ block: "end" }); + }, [following, ...changes]); + const previous = useRef(grew); + useEffect(() => { + if (grew > previous.current) + setFollowing(true); + previous.current = grew; + }, [grew]); + return { scrollRef, endRef, following, onScroll, jumpToBottom }; +} +/** + * Publishes the VISUAL viewport height as `--ck-viewport-height`. + * + * `100dvh` does not shrink when the Android soft keyboard opens; only + * `visualViewport` does. A chat column sized `100dvh` keeps its height while + * the keyboard covers the bottom of it, so the composer ends up behind the + * keyboard (orangecat `ViewportHeightSync`, #1094). Rounded down: sub-pixel + * heights leave a 1px seam under the composer on some devices. + */ +export function useViewportHeight(target) { + useEffect(() => { + const vv = window.visualViewport; + const el = target?.current ?? document.documentElement; + const sync = () => el.style.setProperty("--ck-viewport-height", `${Math.floor(vv?.height ?? window.innerHeight)}px`); + sync(); + vv?.addEventListener("resize", sync); + vv?.addEventListener("scroll", sync); + window.addEventListener("orientationchange", sync); + return () => { + vv?.removeEventListener("resize", sync); + vv?.removeEventListener("scroll", sync); + window.removeEventListener("orientationchange", sync); + el.style.removeProperty("--ck-viewport-height"); + }; + }, [target]); +} +/** Grow a textarea to its content up to `max` px, keyed on the VALUE so a + * prefill, a dictated transcript or the clear after send resize it too. */ +export function useAutoGrow(ref, value, max = 240) { + useLayoutEffect(() => { + const el = ref.current; + if (!el) + return; + el.style.height = "auto"; + el.style.height = `${Math.min(el.scrollHeight, max)}px`; + }, [ref, value, max]); +} +//# sourceMappingURL=hooks.js.map \ No newline at end of file diff --git a/dist/react/hooks.js.map b/dist/react/hooks.js.map new file mode 100644 index 0000000..6d0eae0 --- /dev/null +++ b/dist/react/hooks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EACL,WAAW,EACX,SAAS,EACT,eAAe,EACf,MAAM,EACN,QAAQ,GAGT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,OAAO,GAAG,IAAI;IACzC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,CAAuC,IAAI,CAAC,CAAC;IACjE,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,IAAI,KAAK,CAAC,OAAO;YAAE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC,EACD,EAAE,CACH,CAAC;IACF,MAAM,IAAI,GAAG,WAAW,CACtB,CAAC,IAAY,EAAE,EAAE;QACf,KAAK,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,C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,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAC;YACtD,EAAE,CAAC,KAAK,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;QAClD,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;AACf,CAAC;AAED;4EAC4E;AAC5E,MAAM,UAAU,WAAW,CAAC,GAA0C,EAAE,KAAa,EAAE,GAAG,GAAG,GAAG;IAC9F,eAAe,CAAC,GAAG,EAAE;QACnB,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE;YAAE,OAAO;QAChB,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;QACzB,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC;IAC1D,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;AACxB,CAAC"} \ No newline at end of file diff --git a/dist/react/icons.d.ts b/dist/react/icons.d.ts new file mode 100644 index 0000000..52bdd83 --- /dev/null +++ b/dist/react/icons.d.ts @@ -0,0 +1,12 @@ +export declare const IconArrowUp: () => import("react").JSX.Element; +export declare const IconArrowDown: () => import("react").JSX.Element; +export declare const IconMic: () => import("react").JSX.Element; +export declare const IconCheck: () => import("react").JSX.Element; +export declare const IconX: () => import("react").JSX.Element; +export declare const IconStop: () => import("react").JSX.Element; +export declare const IconSpinner: () => import("react").JSX.Element; +export declare const IconCopy: () => import("react").JSX.Element; +export declare const IconRetry: () => import("react").JSX.Element; +export declare const IconPaperclip: () => import("react").JSX.Element; +export declare const IconFile: () => import("react").JSX.Element; +//# sourceMappingURL=icons.d.ts.map \ No newline at end of file diff --git a/dist/react/icons.d.ts.map b/dist/react/icons.d.ts.map new file mode 100644 index 0000000..132c8ef --- /dev/null +++ b/dist/react/icons.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"icons.d.ts","sourceRoot":"","sources":["../../src/react/icons.tsx"],"names":[],"mappings":"AAyBA,eAAO,MAAM,WAAW,mCAKvB,CAAC;AACF,eAAO,MAAM,aAAa,mCAKzB,CAAC;AACF,eAAO,MAAM,OAAO,mCAMnB,CAAC;AACF,eAAO,MAAM,SAAS,mCAIrB,CAAC;AACF,eAAO,MAAM,KAAK,mCAKjB,CAAC;AACF,eAAO,MAAM,QAAQ,mCAIpB,CAAC;AACF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AACF,eAAO,MAAM,QAAQ,mCAKpB,CAAC;AACF,eAAO,MAAM,SAAS,mCAKrB,CAAC;AACF,eAAO,MAAM,aAAa,mCAIzB,CAAC;AACF,eAAO,MAAM,QAAQ,mCAKpB,CAAC"} \ No newline at end of file diff --git a/dist/react/icons.js b/dist/react/icons.js new file mode 100644 index 0000000..2b4ca6a --- /dev/null +++ b/dist/react/icons.js @@ -0,0 +1,21 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +/** + * The handful of icons a chat needs, inline — so installing chatkit never + * drags an icon library into an app that uses a different one. Paths follow + * Lucide (ISC), stroke = currentColor, so they take the button's colour. + */ +function Svg(props) { + return (_jsx("svg", { viewBox: "0 0 24 24", width: "1em", height: "1em", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", ...props })); +} +export const IconArrowUp = () => (_jsxs(Svg, { children: [_jsx("path", { d: "m5 12 7-7 7 7" }), _jsx("path", { d: "M12 19V5" })] })); +export const IconArrowDown = () => (_jsxs(Svg, { children: [_jsx("path", { d: "M12 5v14" }), _jsx("path", { d: "m19 12-7 7-7-7" })] })); +export const IconMic = () => (_jsxs(Svg, { children: [_jsx("path", { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" }), _jsx("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2" }), _jsx("path", { d: "M12 19v3" })] })); +export const IconCheck = () => (_jsx(Svg, { children: _jsx("path", { d: "M20 6 9 17l-5-5" }) })); +export const IconX = () => (_jsxs(Svg, { children: [_jsx("path", { d: "M18 6 6 18" }), _jsx("path", { d: "m6 6 12 12" })] })); +export const IconStop = () => (_jsx(Svg, { fill: "currentColor", stroke: "none", children: _jsx("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" }) })); +export const IconSpinner = () => (_jsx(Svg, { className: "ck-spin", children: _jsx("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }) })); +export const IconCopy = () => (_jsxs(Svg, { children: [_jsx("rect", { width: "14", height: "14", x: "8", y: "8", rx: "2" }), _jsx("path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" })] })); +export const IconRetry = () => (_jsxs(Svg, { children: [_jsx("path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }), _jsx("path", { d: "M3 3v5h5" })] })); +export const IconPaperclip = () => (_jsx(Svg, { children: _jsx("path", { d: "m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48" }) })); +export const IconFile = () => (_jsxs(Svg, { children: [_jsx("path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }), _jsx("path", { d: "M14 2v4a2 2 0 0 0 2 2h4" })] })); +//# sourceMappingURL=icons.js.map \ No newline at end of file diff --git a/dist/react/icons.js.map b/dist/react/icons.js.map new file mode 100644 index 0000000..f9e46e4 --- /dev/null +++ b/dist/react/icons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"icons.js","sourceRoot":"","sources":["../../src/react/icons.tsx"],"names":[],"mappings":";AAEA;;;;GAIG;AACH,SAAS,GAAG,CAAC,KAA8B;IACzC,O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EAAC,CAAC,EAAC,GAAG,EAAC,KAAK,EAAC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,GAAG,GAC9C,CACP,CAAC;AACF,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,CAC/B,KAAC,GAAG,IAAC,SAAS,EAAC,SAAS,YACtB,eAAM,CAAC,EAAC,6BAA6B,GAAG,GACpC,CACP,CAAC;AACF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,CAC5B,MAAC,GAAG,eACF,eAAM,KAAK,EAAC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,GAAG,EAClD,eAAM,CAAC,EAAC,yDAAyD,GAAG,IAChE,CACP,CAAC;AACF,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,CAC7B,MAAC,GAAG,eACF,eAAM,CAAC,EAAC,mDAAmD,GAAG,EAC9D,eAAM,CAAC,EAAC,UAAU,GAAG,IACjB,CACP,CAAC;AACF,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,EAAE,CAAC,CACjC,KAAC,GAAG,cACF,eAAM,CAAC,EAAC,iHAAiH,GAAG,GACxH,CACP,CAAC;AACF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,CAC5B,MAAC,GAAG,eACF,eAAM,CAAC,EAAC,4DAA4D,GAAG,EACvE,eAAM,CAAC,EAAC,yBAAyB,GAAG,IAChC,CACP,CAAC"} \ No newline at end of file diff --git a/dist/react/index.d.ts b/dist/react/index.d.ts new file mode 100644 index 0000000..63f8b71 --- /dev/null +++ b/dist/react/index.d.ts @@ -0,0 +1,21 @@ +/** + * @bitbaum/chatkit/react — the chat every product uses. + * + * import { Composer, ChatThread, ChatStarters } from "@bitbaum/chatkit/react"; + * import "@bitbaum/chatkit/styles.css"; + * + * Behaviour is fixed here and identical everywhere; the look follows the + * app's tokens through `--ck-*` variables (see styles.css). + */ +export { Composer, DEFAULT_COMPOSER_LABELS } from "./Composer.js"; +export type { ComposerProps, ComposerLabels, ComposerVoice } from "./Composer.js"; +export { ChatThread, ChatMessage, ChatStarters, DEFAULT_THREAD_LABELS } from "./Thread.js"; +export type { ChatMessageData, ChatSpeaker, LiveTurn, Starter, ThreadLabels } from "./Thread.js"; +export { Markdown, defaultRenderLink } from "./Markdown.js"; +export type { CitationMap, RenderLink } from "./Markdown.js"; +export { useDictation } from "./use-dictation.js"; +export type { DictationController, DictationStatus, UseDictationOptions } from "./use-dictation.js"; +export { useAttachments } from "./use-attachments.js"; +export type { AttachmentsController } from "./use-attachments.js"; +export { useClipboard, useStickToBottom, useViewportHeight, useAutoGrow } from "./hooks.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/react/index.d.ts.map b/dist/react/index.d.ts.map new file mode 100644 index 0000000..1bb5d29 --- /dev/null +++ b/dist/react/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,QAAQ,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAClE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAClF,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC3F,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC5D,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACpG,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,YAAY,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/react/index.js b/dist/react/index.js new file mode 100644 index 0000000..791dd1c --- /dev/null +++ b/dist/react/index.js @@ -0,0 +1,16 @@ +/** + * @bitbaum/chatkit/react — the chat every product uses. + * + * import { Composer, ChatThread, ChatStarters } from "@bitbaum/chatkit/react"; + * import "@bitbaum/chatkit/styles.css"; + * + * Behaviour is fixed here and identical everywhere; the look follows the + * app's tokens through `--ck-*` variables (see styles.css). + */ +export { Composer, DEFAULT_COMPOSER_LABELS } from "./Composer.js"; +export { ChatThread, ChatMessage, ChatStarters, DEFAULT_THREAD_LABELS } from "./Thread.js"; +export { Markdown, defaultRenderLink } from "./Markdown.js"; +export { useDictation } from "./use-dictation.js"; +export { useAttachments } from "./use-attachments.js"; +export { useClipboard, useStickToBottom, useViewportHeight, useAutoGrow } from "./hooks.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/react/index.js.map b/dist/react/index.js.map new file mode 100644 index 0000000..3fb6821 --- /dev/null +++ b/dist/react/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,QAAQ,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAElE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAE3F,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/react/use-attachments.d.ts b/dist/react/use-attachments.d.ts new file mode 100644 index 0000000..9fc3259 --- /dev/null +++ b/dist/react/use-attachments.d.ts @@ -0,0 +1,26 @@ +import { type ClipboardEvent } from "react"; +import { type Attachment, type AttachmentLimits, type StagedAttachment } from "../attachments.js"; +export type AttachmentsController = { + attachments: StagedAttachment[]; + /** Why something did not attach (too big, wrong type, too many). Never + * thrown — a rejected file must not lose the draft next to it. */ + note: string | null; + clearNote: () => void; + addFiles: (files: FileList | File[] | null) => void; + /** Consumes the paste only when it carried an image. */ + addFromPaste: (e: ClipboardEvent) => boolean; + remove: (key: string) => void; + clear: () => void; + toWire: () => Attachment[]; + keyOf: (a: Attachment) => string; + full: boolean; + limits: AttachmentLimits; +}; +/** + * Staging screenshots and text files for a composer — paste-to-attach + * included, because on a phone that is how a screenshot arrives. Preview URLs + * are revoked on remove, clear and unmount (a preview never revoked is a leak + * that survives every send). From loki `hooks/use-attachments.ts`. + */ +export declare function useAttachments(limits?: Partial): AttachmentsController; +//# sourceMappingURL=use-attachments.d.ts.map \ No newline at end of file diff --git a/dist/react/use-attachments.d.ts.map b/dist/react/use-attachments.d.ts.map new file mode 100644 index 0000000..06dda7c --- /dev/null +++ b/dist/react/use-attachments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-attachments.d.ts","sourceRoot":"","sources":["../../src/react/use-attachments.ts"],"names":[],"mappings":"AAEA,OAAO,EAA4C,KAAK,cAAc,EAAE,MAAM,OAAO,CAAC;AACtF,OAAO,EAML,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACtB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,MAAM,qBAAqB,GAAG;IAClC,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC;uEACmE;IACnE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,QAAQ,EAAE,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,EAAE,GAAG,IAAI,KAAK,IAAI,CAAC;IACpD,wDAAwD;IACxD,YAAY,EAAE,CAAC,CAAC,EAAE,cAAc,KAAK,OAAO,CAAC;IAC7C,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9B,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,MAAM,EAAE,MAAM,UAAU,EAAE,CAAC;IAC3B,KAAK,EAAE,CAAC,CAAC,EAAE,UAAU,KAAK,MAAM,CAAC;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,gBAAgB,CAAC;CAC1B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,GAAE,OAAO,CAAC,gBAAgB,CAAM,GAAG,qBAAqB,CAiJ5F"} \ No newline at end of file diff --git a/dist/react/use-attachments.js b/dist/react/use-attachments.js new file mode 100644 index 0000000..8e2d6a5 --- /dev/null +++ b/dist/react/use-attachments.js @@ -0,0 +1,139 @@ +"use client"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { DEFAULT_ATTACHMENT_LIMITS, attachmentKey, isImageMime, stripDataUrlBase64, toWire, } from "../attachments.js"; +/** + * Staging screenshots and text files for a composer — paste-to-attach + * included, because on a phone that is how a screenshot arrives. Preview URLs + * are revoked on remove, clear and unmount (a preview never revoked is a leak + * that survives every send). From loki `hooks/use-attachments.ts`. + */ +export function useAttachments(limits = {}) { + const lim = { ...DEFAULT_ATTACHMENT_LIMITS, ...limits }; + const { maxFiles, maxImageBytes, maxTextChars } = lim; + const [attachments, setAttachments] = useState([]); + const [note, setNote] = useState(null); + const previews = useRef(new Set()); + const count = useRef(0); + useEffect(() => { + count.current = attachments.length; + }, [attachments.length]); + useEffect(() => { + const urls = previews.current; + return () => { + for (const url of urls) + URL.revokeObjectURL(url); + urls.clear(); + }; + }, []); + const add = useCallback((item) => setAttachments((prev) => { + if (prev.length >= maxFiles) + return prev; + if (prev.some((p) => attachmentKey(p) === attachmentKey(item))) + return prev; + return [...prev, item]; + }), [maxFiles]); + const stageImage = useCallback((file) => { + if (!isImageMime(file.type)) { + setNote(`${file.name}: use PNG, JPEG, GIF or WebP.`); + return; + } + if (file.size > maxImageBytes) { + setNote(`${file.name} is too large (max ${Math.round(maxImageBytes / 1_000_000)} MB).`); + return; + } + const reader = new FileReader(); + reader.onload = () => { + const previewUrl = URL.createObjectURL(file); + previews.current.add(previewUrl); + add({ + kind: "image", + name: file.name || "screenshot.png", + mimeType: file.type, + dataBase64: stripDataUrlBase64(String(reader.result ?? "")), + previewUrl, + }); + }; + reader.onerror = () => setNote(`Could not read ${file.name}.`); + reader.readAsDataURL(file); + }, [add, maxImageBytes]); + const stageText = useCallback((file) => { + if (file.size > maxTextChars) { + setNote(`${file.name} is too large (max ${Math.round(maxTextChars / 1000)}k characters).`); + return; + } + const reader = new FileReader(); + reader.onload = () => add({ + kind: "text", + name: file.name, + content: String(reader.result ?? "").slice(0, maxTextChars), + }); + reader.onerror = () => setNote(`Could not read ${file.name}.`); + reader.readAsText(file); + }, [add, maxTextChars]); + const addFiles = useCallback((files) => { + if (!files) + return; + setNote(null); + const room = maxFiles - count.current; + if (room <= 0) { + setNote(`Up to ${maxFiles} files.`); + return; + } + for (const file of Array.from(files).slice(0, room)) { + if (isImageMime(file.type)) + stageImage(file); + else + stageText(file); + } + }, [maxFiles, stageImage, stageText]); + const addFromPaste = useCallback((e) => { + const items = e.clipboardData?.items; + if (!items) + return false; + const images = Array.from(items).filter((i) => i.type.startsWith("image/")); + if (images.length === 0) + return false; + setNote(null); + for (const item of images) { + const file = item.getAsFile(); + if (file) + stageImage(file); + } + return true; + }, [stageImage]); + const revoke = (a) => { + if (!a.previewUrl) + return; + URL.revokeObjectURL(a.previewUrl); + previews.current.delete(a.previewUrl); + }; + const remove = useCallback((key) => { + setAttachments((prev) => { + const target = prev.find((a) => attachmentKey(a) === key); + if (target) + revoke(target); + return prev.filter((a) => attachmentKey(a) !== key); + }); + }, []); + const clear = useCallback(() => { + setAttachments((prev) => { + prev.forEach(revoke); + return []; + }); + setNote(null); + }, []); + return { + attachments, + note, + clearNote: () => setNote(null), + addFiles, + addFromPaste, + remove, + clear, + toWire: () => toWire(attachments), + keyOf: attachmentKey, + full: attachments.length >= maxFiles, + limits: lim, + }; +} +//# sourceMappingURL=use-attachments.js.map \ No newline at end of file diff --git a/dist/react/use-attachments.js.map b/dist/react/use-attachments.js.map new file mode 100644 index 0000000..ccc1106 --- /dev/null +++ b/dist/react/use-attachments.js.map @@ -0,0 +1 @@ +{"version":3,"file":"use-attachments.js","sourceRoot":"","sources":["../../src/react/use-attachments.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAuB,MAAM,OAAO,CAAC;AACtF,OAAO,EACL,yBAAyB,EACzB,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,MAAM,GAIP,MAAM,mBAAmB,CAAC;AAmB3B;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,SAAoC,EAAE;IACnE,MAAM,GAAG,GAAqB,EAAE,GAAG,yBAAyB,EAAE,GAAG,MAAM,EAAE,CAAC;IAC1E,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,YAAY,EAAE,GAAG,GAAG,CAAC;IACtD,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAqB,EAAE,CAAC,CAAC;IACvE,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAgB,IAAI,CAAC,CAAC;IACtD,MAAM,QAAQ,GAAG,MAAM,CAAc,IAAI,GAAG,EAAE,CA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CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;QAC9B,QAAQ;QACR,YAAY;QACZ,MAAM;QACN,KAAK;QACL,MAAM,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;QACjC,KAAK,EAAE,aAAa;QACpB,IAAI,EAAE,WAAW,CAAC,MAAM,IAAI,QAAQ;QACpC,MAAM,EAAE,GAAG;KACZ,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/react/use-dictation.d.ts b/dist/react/use-dictation.d.ts new file mode 100644 index 0000000..2474f96 --- /dev/null +++ b/dist/react/use-dictation.d.ts @@ -0,0 +1,49 @@ +import { type DictationPreference, type DictationProblem } from "../dictation.js"; +export type DictationStatus = "idle" | "listening" | "transcribing"; +export type UseDictationOptions = { + /** Receives what was said, once, when the take ends. */ + onText: (text: string) => void; + /** BCP-47 language for the browser recogniser. Defaults to the page's + * ``, then the browser's. The server leg receives its first part + * as `locale` and may detect the language itself. */ + lang?: string; + /** Which path first. Default `browser` (free, instant); `server` for one + * model everywhere. Each falls back to the other when it cannot work. */ + prefer?: DictationPreference; + /** Server leg: POST multipart `{ audio, locale }` → `{ text }`. */ + transcribeUrl?: string; + /** Or bring your own server leg (a widget token, a different body). */ + transcribe?: (audio: Blob, locale: string) => Promise; + maxRecordingMs?: number; + /** Where a dead recogniser is remembered (localStorage). `null` to never + * store anything on the device. */ + rememberKey?: string | null; +}; +export type DictationController = { + /** False only when neither path can work here — the mic is then hidden. */ + supported: boolean; + status: DictationStatus; + /** When the current take began (ms epoch), for the timer. */ + startedAt: number | null; + problem: DictationProblem | null; + clearProblem: () => void; + start: () => void; + /** End the take and deliver what was said. */ + stop: () => void; + /** End the take and throw it away. */ + cancel: () => void; + toggle: () => void; +}; +/** + * Speaking instead of typing — with a microphone that is never a dead button. + * + * Browser recogniser first (unless `prefer: "server"`); when it is missing, or + * accepts `start()` and then says nothing (heidi measured nine silent seconds + * on a real Chromium), the same press RECORDS and the server transcribes. A + * failure always ends as a `problem` the composer shows in words. + * + * Every microphone track is stopped on every exit path. A mic left open on + * someone's device because a request failed is the worst bug a chat can have. + */ +export declare function useDictation(opts: UseDictationOptions): DictationController; +//# sourceMappingURL=use-dictation.d.ts.map \ No newline at end of file diff --git a/dist/react/use-dictation.d.ts.map b/dist/react/use-dictation.d.ts.map new file mode 100644 index 0000000..351b72f --- /dev/null +++ b/dist/react/use-dictation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-dictation.d.ts","sourceRoot":"","sources":["../../src/react/use-dictation.ts"],"names":[],"mappings":"AAGA,OAAO,EASL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACtB,MAAM,iBAAiB,CAAC;AAwCzB,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,WAAW,GAAG,cAAc,CAAC;AAEpE,MAAM,MAAM,mBAAmB,GAAG;IAChC,wDAAwD;IACxD,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/B;;0DAEsD;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;8EAC0E;IAC1E,MAAM,CAAC,EAAE,mBAAmB,CAAC;IAC7B,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC9D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;wCACoC;IACpC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,2EAA2E;IAC3E,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,eAAe,CAAC;IACxB,6DAA6D;IAC7D,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACjC,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,8CAA8C;IAC9C,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,sCAAsC;IACtC,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AA2CF;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,mBAAmB,CAoS3E"} \ No newline at end of file diff --git a/dist/react/use-dictation.js b/dist/react/use-dictation.js new file mode 100644 index 0000000..f4fd365 --- /dev/null +++ b/dist/react/use-dictation.js @@ -0,0 +1,365 @@ +"use client"; +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { MAX_RECORDING_MS, PERMISSION_WAIT_MS, RECORDING_MIME_CANDIDATES, START_TIMEOUT_MS, deadRecogniserStillTrusted, fallbackCanRescue, problemFor, problemForRecording, } from "../dictation.js"; +function recogniser() { + if (typeof window === "undefined") + return undefined; + const w = window; + return w.SpeechRecognition ?? w.webkitSpeechRecognition; +} +function canRecord() { + return (typeof window !== "undefined" && + typeof MediaRecorder !== "undefined" && + !!navigator.mediaDevices?.getUserMedia); +} +const noSubscribe = () => () => { }; +const DEFAULT_REMEMBER_KEY = "chatkit.dictation.recogniser-dead.v1"; +function readDead(key) { + if (!key) + return false; + try { + const raw = window.localStorage.getItem(key); + return deadRecogniserStillTrusted(raw === null ? null : Number(raw)); + } + catch { + return false; + } +} +function rememberDead(key) { + if (!key) + return; + try { + window.localStorage.setItem(key, String(Date.now())); + } + catch { + /* private mode — the person simply waits again next time */ + } +} +async function awaitingPermission() { + try { + const s = await navigator.permissions.query({ name: "microphone" }); + return s.state === "prompt"; + } + catch { + return false; + } +} +async function postAudio(url, audio, locale) { + const body = new FormData(); + const ext = audio.type.includes("mp4") ? "m4a" : audio.type.includes("ogg") ? "ogg" : "webm"; + body.append("audio", new File([audio], `voice.${ext}`, { type: audio.type || "audio/webm" })); + body.append("locale", locale); + const res = await fetch(url, { method: "POST", body }); + if (!res.ok) + throw new Error(`transcription ${res.status}`); + const data = (await res.json().catch(() => ({}))); + return typeof data.text === "string" ? data.text.trim() : ""; +} +/** + * Speaking instead of typing — with a microphone that is never a dead button. + * + * Browser recogniser first (unless `prefer: "server"`); when it is missing, or + * accepts `start()` and then says nothing (heidi measured nine silent seconds + * on a real Chromium), the same press RECORDS and the server transcribes. A + * failure always ends as a `problem` the composer shows in words. + * + * Every microphone track is stopped on every exit path. A mic left open on + * someone's device because a request failed is the worst bug a chat can have. + */ +export function useDictation(opts) { + const { prefer = "browser", maxRecordingMs = MAX_RECORDING_MS } = opts; + const rememberKey = opts.rememberKey === undefined ? DEFAULT_REMEMBER_KEY : opts.rememberKey; + const hasServer = Boolean(opts.transcribe || opts.transcribeUrl); + const supported = useSyncExternalStore(noSubscribe, () => Boolean(recogniser()) || (hasServer && canRecord()), () => false); + const [status, setStatus] = useState("idle"); + const [startedAt, setStartedAt] = useState(null); + const [problem, setProblem] = useState(null); + // Latest options in refs, assigned in an effect (never during render), so a + // take that outlives a re-render calls the current callbacks. + const optsRef = useRef(opts); + useEffect(() => { + optsRef.current = opts; + }); + const recRef = useRef(null); + const recorderRef = useRef(null); + const streamRef = useRef(null); + const cancelledRef = useRef(false); + const capTimer = useRef(null); + const locale = useCallback(() => { + const l = optsRef.current.lang ?? + (typeof document !== "undefined" ? document.documentElement.lang : "") ?? + ""; + return l || (typeof navigator !== "undefined" ? navigator.language : "en") || "en"; + }, []); + const releaseMic = useCallback(() => { + streamRef.current?.getTracks().forEach((t) => t.stop()); + streamRef.current = null; + if (capTimer.current) { + clearTimeout(capTimer.current); + capTimer.current = null; + } + }, []); + const deliver = useCallback((said) => { + const t = said.trim(); + if (t) + optsRef.current.onText(t); + else + setProblem("silence"); + }, []); + const transcribe = useCallback(async (audio) => { + const o = optsRef.current; + const lang = locale().split("-")[0] ?? "en"; + if (o.transcribe) + return o.transcribe(audio, lang); + if (o.transcribeUrl) + return postAudio(o.transcribeUrl, audio, lang); + throw new Error("no server leg"); + }, [locale]); + /** The server leg: record, then transcribe. */ + const record = useCallback(async () => { + if (!canRecord() || !(optsRef.current.transcribe || optsRef.current.transcribeUrl)) { + setProblem("unavailable"); + setStatus("idle"); + return; + } + setProblem(null); + cancelledRef.current = false; + let stream; + try { + stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + } + catch (e) { + setProblem(problemForRecording(e)); + setStatus("idle"); + return; + } + streamRef.current = stream; + let rec; + try { + const mime = RECORDING_MIME_CANDIDATES.find((m) => MediaRecorder.isTypeSupported?.(m)); + rec = mime ? new MediaRecorder(stream, { mimeType: mime }) : new MediaRecorder(stream); + } + catch (e) { + releaseMic(); + setProblem(problemForRecording(e)); + setStatus("idle"); + return; + } + const chunks = []; + rec.ondataavailable = (e) => { + if (e.data && e.data.size > 0) + chunks.push(e.data); + }; + rec.onstop = async () => { + releaseMic(); + recorderRef.current = null; + setStartedAt(null); + if (cancelledRef.current) { + setStatus("idle"); + return; + } + const audio = new Blob(chunks, { type: rec.mimeType || "audio/webm" }); + if (audio.size === 0) { + setProblem("silence"); + setStatus("idle"); + return; + } + setStatus("transcribing"); + try { + deliver(await transcribe(audio)); + } + catch { + setProblem("unavailable"); + } + finally { + setStatus("idle"); + } + }; + recorderRef.current = rec; + rec.start(); + setStatus("listening"); + setStartedAt(Date.now()); + capTimer.current = setTimeout(() => { + if (recorderRef.current?.state === "recording") + recorderRef.current.stop(); + }, maxRecordingMs); + }, [deliver, maxRecordingMs, releaseMic, transcribe]); + /** The browser leg, with the silent-recogniser watchdog. */ + const listen = useCallback((Ctor) => { + setProblem(null); + cancelledRef.current = false; + const rec = new Ctor(); + rec.lang = locale(); + // Whole thoughts, not one breath: a take ends when the person presses + // confirm (or the cap), not at the first pause. + rec.continuous = true; + rec.interimResults = false; + const current = () => recRef.current === rec; + const heard = []; + let started = false; + let handedOff = false; + const finish = (next) => { + if (!current()) + return; + recRef.current = null; + if (capTimer.current) { + clearTimeout(capTimer.current); + capTimer.current = null; + } + setStatus("idle"); + setStartedAt(null); + if (next) + setProblem(next); + }; + const handOff = () => { + // The recogniser cannot do this here — record instead, and do not make + // the person rediscover that on the next press. + handedOff = true; + rememberDead(rememberKey); + finish(null); + try { + rec.abort(); + } + catch { + /* already gone */ + } + void record(); + }; + rec.onstart = () => { + started = true; + }; + rec.onresult = (event) => { + for (let i = event.resultIndex; i < event.results.length; i++) { + const r = event.results[i]; + if (r && r.isFinal !== false) + heard.push(r[0]?.transcript ?? ""); + } + }; + rec.onerror = (event) => { + const why = problemFor(event?.error); + if (fallbackCanRescue(why) && canRecord() && hasServer && !cancelledRef.current) { + handOff(); + return; + } + finish(why); + }; + rec.onend = () => { + if (!current() || handedOff) + return; + const said = heard.join(" "); + finish(null); + if (!cancelledRef.current) + deliver(said); + }; + recRef.current = rec; + try { + rec.start(); + } + catch { + if (canRecord() && hasServer) + handOff(); + else + finish("unavailable"); + return; + } + setStatus("listening"); + setStartedAt(Date.now()); + capTimer.current = setTimeout(() => { + if (current()) + rec.stop(); + }, maxRecordingMs); + const giveUpAt = Date.now() + PERMISSION_WAIT_MS; + const watch = () => { + setTimeout(async () => { + if (started || !current()) + return; + if (Date.now() < giveUpAt && (await awaitingPermission())) { + watch(); + return; + } + if (started || !current()) + return; + if (canRecord() && hasServer) + handOff(); + else + finish("unavailable"); + }, START_TIMEOUT_MS); + }; + watch(); + }, [deliver, hasServer, locale, maxRecordingMs, record, rememberKey]); + const start = useCallback(() => { + if (status !== "idle") + return; + const Ctor = recogniser(); + const serverFirst = prefer === "server" && canRecord() && hasServer; + if (Ctor && !serverFirst && !readDead(rememberKey)) + listen(Ctor); + else if (canRecord() && hasServer) + void record(); + else if (Ctor) + listen(Ctor); + else + setProblem("unavailable"); + }, [hasServer, listen, prefer, record, rememberKey, status]); + const stop = useCallback(() => { + const rec = recRef.current; + if (rec) + rec.stop(); + const rc = recorderRef.current; + if (rc && rc.state !== "inactive") + rc.stop(); + }, []); + const cancel = useCallback(() => { + cancelledRef.current = true; + const rec = recRef.current; + recRef.current = null; + try { + rec?.abort(); + } + catch { + /* already gone */ + } + const rc = recorderRef.current; + if (rc && rc.state !== "inactive") + rc.stop(); + releaseMic(); + setStatus("idle"); + setStartedAt(null); + }, [releaseMic]); + const toggle = useCallback(() => { + // A press while the server is answering is ignored: a second take would + // race the first one's words into the box. + if (status === "transcribing") + return; + if (status === "listening") + stop(); + else + start(); + }, [start, status, stop]); + // A live microphone must not outlive the component that opened it. + useEffect(() => () => { + cancelledRef.current = true; + try { + recRef.current?.abort(); + } + catch { + /* gone */ + } + const rc = recorderRef.current; + if (rc && rc.state !== "inactive") + rc.stop(); + streamRef.current?.getTracks().forEach((t) => t.stop()); + }, []); + return { + supported, + status, + startedAt, + problem, + clearProblem: () => setProblem(null), + start, + stop, + cancel, + toggle, + }; +} +//# sourceMappingURL=use-dictation.js.map \ No newline at end of file diff --git a/dist/react/use-dictation.js.map b/dist/react/use-dictation.js.map new file mode 100644 index 0000000..c345f42 --- /dev/null +++ b/dist/react/use-dictation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"use-dictation.js","sourceRoot":"","sources":["../../src/react/use-dictation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AACvF,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,yBAAyB,EACzB,gBAAgB,EAChB,0BAA0B,EAC1B,iBAAiB,EACjB,UAAU,EACV,mBAAmB,GAGpB,MAAM,iBAAiB,CAAC;AAqBzB,SAAS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AC;YACH,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC;QAC1B,CAAC;QAAC,MAAM,CAAC;YACP,UAAU;QACZ,CAAC;QACD,MAAM,EAAE,GAAG,WAAW,CAAC,OAAO,CAAC;QAC/B,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,KAAK,UAAU;YAAE,EAAE,CAAC,IAAI,EAAE,CAAC;QAC7C,SAAS,CAAC,OAAO,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC,EACD,EAAE,CACH,CAAC;IAEF,OAAO;QACL,SAAS;QACT,MAAM;QACN,SAAS;QACT,OAAO;QACP,YAAY,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;QACpC,KAAK;QACL,IAAI;QACJ,MAAM;QACN,MAAM;KACP,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/scroll.d.ts b/dist/scroll.d.ts new file mode 100644 index 0000000..6d7f541 --- /dev/null +++ b/dist/scroll.d.ts @@ -0,0 +1,13 @@ +/** + * How close to the bottom still counts as "following the conversation". Above + * this, the reader is reading something older and must not be yanked back + * every time a token arrives — the bug in every chat here except loki's and + * orangecat's. + */ +export declare const FOLLOW_THRESHOLD_PX = 120; +export declare function isFollowing(el: { + scrollHeight: number; + scrollTop: number; + clientHeight: number; +}, threshold?: number): boolean; +//# sourceMappingURL=scroll.d.ts.map \ No newline at end of file diff --git a/dist/scroll.d.ts.map b/dist/scroll.d.ts.map new file mode 100644 index 0000000..bf88dcd --- /dev/null +++ b/dist/scroll.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scroll.d.ts","sourceRoot":"","sources":["../src/scroll.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAEvC,wBAAgB,WAAW,CACzB,EAAE,EAAE;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,EACrE,SAAS,SAAsB,GAC9B,OAAO,CAET"} \ No newline at end of file diff --git a/dist/scroll.js b/dist/scroll.js new file mode 100644 index 0000000..cd096fd --- /dev/null +++ b/dist/scroll.js @@ -0,0 +1,11 @@ +/** + * How close to the bottom still counts as "following the conversation". Above + * this, the reader is reading something older and must not be yanked back + * every time a token arrives — the bug in every chat here except loki's and + * orangecat's. + */ +export const FOLLOW_THRESHOLD_PX = 120; +export function isFollowing(el, threshold = FOLLOW_THRESHOLD_PX) { + return el.scrollHeight - el.scrollTop - el.clientHeight < threshold; +} +//# sourceMappingURL=scroll.js.map \ No newline at end of file diff --git a/dist/scroll.js.map b/dist/scroll.js.map new file mode 100644 index 0000000..3378c31 --- /dev/null +++ b/dist/scroll.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scroll.js","sourceRoot":"","sources":["../src/scroll.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEvC,MAAM,UAAU,WAAW,CACzB,EAAqE,EACrE,SAAS,GAAG,mBAAmB;IAE/B,OAAO,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,SAAS,GAAG,EAAE,CAAC,YAAY,GAAG,SAAS,CAAC;AACtE,CAAC"} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..b529a80 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,27 @@ +// Flat config. Recommended presets only: a bespoke rule set would be a second +// opinion to maintain for no benefit. The floor is "lint runs and can fail", not "lint encodes +// taste". +import js from "@eslint/js"; +import globals from "globals"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { + // dist/ is generated by `tsc`; demo/dist/ by esbuild for the visual check. + ignores: ["dist/**", "demo/dist/**", "node_modules/**"], + }, + js.configs.recommended, + ...tseslint.configs.recommended, + { + files: ["**/*.ts", "**/*.tsx"], + // Client islands touch browser APIs; the parser and server components + // run under Node. Both global sets, one config. + languageOptions: { globals: { ...globals.node, ...globals.browser } }, + }, + { + // Tests are plain Node running under `node --test`. + files: ["test/**/*.js", "test/**/*.mjs"], + // browser.mjs is Node driving a browser: page.evaluate bodies run there. + languageOptions: { globals: { ...globals.node, ...globals.nodeBuiltin, ...globals.browser } }, + }, +); diff --git a/package.json b/package.json new file mode 100644 index 0000000..a4bcb59 --- /dev/null +++ b/package.json @@ -0,0 +1,83 @@ +{ + "name": "@bitbaum/chatkit", + "version": "0.1.0", + "description": "One chat for every product: a composer with a microphone that always works, a thread that does not fight the reader, messages with copy and retry, and LLM markdown \u2014 the fleet's chat standard as a package.", + "license": "MIT", + "author": "Cato", + "homepage": "https://github.com/bitbaum/chatkit#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/bitbaum/chatkit.git" + }, + "bugs": { + "url": "https://github.com/bitbaum/chatkit/issues" + }, + "keywords": [ + "chat", + "composer", + "voice", + "dictation", + "speech-to-text", + "markdown", + "react", + "ai" + ], + "type": "module", + "sideEffects": [ + "*.css" + ], + "packageManager": "pnpm@11.25.0", + "engines": { + "node": ">=20" + }, + "publishConfig": { + "access": "public", + "provenance": true + }, + "files": [ + "dist", + "styles.css" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./react": { + "types": "./dist/react/index.d.ts", + "default": "./dist/react/index.js" + }, + "./styles.css": "./styles.css" + }, + "scripts": { + "build": "rm -rf dist && tsc -p tsconfig.json", + "lint": "eslint .", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "node --test test/*.test.js", + "check:dist": "git diff --exit-code --stat -- dist", + "verify": "pnpm run format:check && pnpm run lint && pnpm run typecheck && pnpm run build && pnpm test && pnpm run test:browser", + "format": "prettier --write .", + "format:check": "prettier --check .", + "demo": "esbuild demo/demo.tsx --bundle --jsx=automatic --format=iife --define:process.env.NODE_ENV='\"production\"' --outfile=demo/dist/demo.js --log-level=warning", + "test:browser": "pnpm run demo && node test/browser.mjs" + }, + "devDependencies": { + "@bitbaum/design-tokens": "^1.1.0", + "@eslint/js": "^10.0.1", + "@types/node": "^26.4.0", + "@types/react": "^19.2.18", + "@types/react-dom": "^19.2.3", + "esbuild": "^0.28.2", + "eslint": "^10.9.1", + "globals": "^17.11.0", + "playwright": "1.63.0", + "prettier": "^3.9.6", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "typescript": "^6.0.3", + "typescript-eslint": "^8.68.0" + }, + "peerDependencies": { + "react": ">=18" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..3069a67 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1254 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@bitbaum/design-tokens': + specifier: ^1.1.0 + version: 1.1.0 + '@eslint/js': + specifier: ^10.0.1 + version: 10.0.1(eslint@10.11.0) + '@types/node': + specifier: ^26.4.0 + version: 26.6.2 + '@types/react': + specifier: ^19.2.18 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.3.0(@types/react@19.3.0) + esbuild: + specifier: ^0.28.2 + version: 0.28.2 + eslint: + specifier: ^10.9.1 + version: 10.11.0 + globals: + specifier: ^17.11.0 + version: 17.12.0 + playwright: + specifier: 1.63.0 + version: 1.63.0 + prettier: + specifier: ^3.9.6 + version: 3.9.9 + react: + specifier: ^19.2.8 + version: 19.3.0 + react-dom: + specifier: ^19.2.8 + version: 19.3.0(react@19.3.0) + typescript: + specifier: ^6.0.3 + version: 6.0.3 + typescript-eslint: + specifier: ^8.68.0 + version: 8.70.1(eslint@10.11.0)(typescript@6.0.3) + +packages: + + '@bitbaum/design-tokens@1.1.0': + resolution: {integrity: sha512-sDVplKP4jKe0WHCOnW7xk75RC46JsAYqUngcVlctyAs9f1TQqZqbYTfbmyYipYCOaCIHMflnzAneQTbqrQbtBw==} + engines: {node: '>=20'} + + '@cacheable/memory@2.2.0': + resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==} + + '@cacheable/utils@2.5.0': + resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.5': + resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.7.0': + resolution: {integrity: sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/js@10.0.1': + resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.3': + resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@keyv/bigmap@1.3.1': + resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==} + engines: {node: '>= 18'} + peerDependencies: + keyv: ^5.6.0 + + '@keyv/serialize@1.1.1': + resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/node@26.6.2': + resolution: {integrity: sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g==} + + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + + '@typescript-eslint/eslint-plugin@8.70.1': + resolution: {integrity: sha512-nDNrUQ/4ruSNYbu749TRY7cfrzPtoLHEXSNBI8aaNY32LlZCajixqRf3FqcKC4p5Cam4VOHYx/t+i5+nKXvrqA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.70.1 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.70.1': + resolution: {integrity: sha512-nO974WLllwhSFWQXnMLj6nDGa8f0khKEz1JzpPJ1u7Vm/4X1X6ZHajpoknU4bb41vJyMB0HHVyS2GqdhWfIXZw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.70.1': + resolution: {integrity: sha512-62xOgboPfwc3/IgPSX/W6oQR3ZbF04194FPGUGH8HL8iLFHbt/456/8Ph1wLNUgVF+s94FlHoipBsz+v7+LMnA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.70.1': + resolution: {integrity: sha512-Pa0EeSeAusQc1WbjQMac+YfenewYTBu0KjgYvkUKwhXaHUKbFog23Dm/rp0DX/6tyYOQ3Xl1a+3EcFNZynGHCw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.70.1': + resolution: {integrity: sha512-jumze1fPI+sDOaM2TWGQdn39PDxTr7TZGeuyLkAbNyx2vtMT3uRnVKChN0hfht5V2TugphJzF6bYXvBcE09qqg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.70.1': + resolution: {integrity: sha512-7zKTnyvaVWqzLZHPFQtX1hVHqgkMC+WebPWakNCSyrQVbIP1AM0L0TlBZtACldIRb6PptI8Odk+jyZ5kP3B1VA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.70.1': + resolution: {integrity: sha512-Dm1ypdhhrGCTyyehxElhgJ6kgk8MVCv5qXdoOVqPr1uqk42jX8KjrZqhROvdShczA8qrDoYiOWn1ykWlx2k81Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.70.1': + resolution: {integrity: sha512-TU8PwyGN0PQJUcE96mw8eCQ44SmxGdQlJmlWakHaHQ15eIuuvye5yNtmh/i6oS88jzXVQB71xdNkbkB/fMwL0g==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.70.1': + resolution: {integrity: sha512-Esgul8MsnKnRLdYU2Eb2cRV9bS5HJYtKj1ByJnOzzG2M58DGdSUQ1jUuILxipqcpB2h9WLrbD5GijIWUjX/Tqw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.70.1': + resolution: {integrity: sha512-Vwj9lUIW5Xq3wQ9w6gv3R86g1hMK8f2zNOdGTAgeXUMMXFK78G9ruCjjqutHMNJc0+CH7LYRnHeUB9IT8wFmcw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + brace-expansion@5.0.12: + resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} + engines: {node: 20 || >=22} + + cacheable@2.5.0: + resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.11.0: + resolution: {integrity: sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-entry-cache@11.1.5: + resolution: {integrity: sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@6.1.23: + resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + globals@17.12.0: + resolution: {integrity: sha512-cezEd/DTyyht9cvSSURyygXPfy04GtWO/5e6ZPvH7fCtjKz9PYOmuawphw1Ctd1f6C+5JypXfGD7ahNMXvevBA==} + engines: {node: '>=18'} + + hashery@1.5.1: + resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} + engines: {node: '>=20'} + + hookified@1.15.1: + resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} + + hookified@2.2.0: + resolution: {integrity: sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.10: + resolution: {integrity: sha512-HpbUakT7xp5miBUywCHf36ZEuAJNklBJDDsGpUIjMzOSmM8ELSfA9Sa/QDPeNeqeoN31u+UTCkL4klCOVvRm4Q==} + engines: {node: '>= 4'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + keyv@5.6.0: + resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.63.0: + resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==} + engines: {node: '>=20'} + hasBin: true + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@3.9.9: + resolution: {integrity: sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==} + engines: {node: '>=14'} + hasBin: true + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + qified@0.10.1: + resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} + engines: {node: '>=20'} + + react-dom@19.3.0: + resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} + peerDependencies: + react: ^19.3.0 + + react@19.3.0: + resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} + engines: {node: '>=0.10.0'} + + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + typescript-eslint@8.70.1: + resolution: {integrity: sha512-AcWG7KDjZ2THNXsgwttMaGmzVi0VFRlFYfqFHYQRbDpF3owuYbuiL8c7UUrd2k8s3PoSfIQrWfrGXfcElrWLYA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + +snapshots: + + '@bitbaum/design-tokens@1.1.0': {} + + '@cacheable/memory@2.2.0': + dependencies: + '@cacheable/utils': 2.5.0 + '@keyv/bigmap': 1.3.1(keyv@5.6.0) + hookified: 1.15.1 + keyv: 5.6.0 + + '@cacheable/utils@2.5.0': + dependencies: + hashery: 1.5.1 + keyv: 5.6.0 + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@eslint-community/eslint-utils@4.10.1(eslint@10.11.0)': + dependencies: + eslint: 10.11.0 + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.23.5': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3 + minimatch: 10.2.6 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.7.0': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/js@10.0.1(eslint@10.11.0)': + optionalDependencies: + eslint: 10.11.0 + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.3': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + + '@keyv/bigmap@1.3.1(keyv@5.6.0)': + dependencies: + hashery: 1.5.1 + hookified: 1.15.1 + keyv: 5.6.0 + + '@keyv/serialize@1.1.1': {} + + '@types/esrecurse@4.3.1': {} + + '@types/estree@1.0.9': {} + + '@types/json-schema@7.0.15': {} + + '@types/node@26.6.2': + dependencies: + undici-types: 8.9.0 + + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + + '@typescript-eslint/eslint-plugin@8.70.1(@typescript-eslint/parser@8.70.1(eslint@10.11.0)(typescript@6.0.3))(eslint@10.11.0)(typescript@6.0.3)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + '@typescript-eslint/scope-manager': 8.70.1 + '@typescript-eslint/type-utils': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + '@typescript-eslint/utils': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.70.1 + eslint: 10.11.0 + ignore: 7.0.10 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.70.1(eslint@10.11.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.70.1 + '@typescript-eslint/types': 8.70.1 + '@typescript-eslint/typescript-estree': 8.70.1(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.70.1 + debug: 4.4.3 + eslint: 10.11.0 + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.70.1(typescript@6.0.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.70.1(typescript@6.0.3) + '@typescript-eslint/types': 8.70.1 + debug: 4.4.3 + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.70.1': + dependencies: + '@typescript-eslint/types': 8.70.1 + '@typescript-eslint/visitor-keys': 8.70.1 + + '@typescript-eslint/tsconfig-utils@8.70.1(typescript@6.0.3)': + dependencies: + typescript: 6.0.3 + + '@typescript-eslint/type-utils@8.70.1(eslint@10.11.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/types': 8.70.1 + '@typescript-eslint/typescript-estree': 8.70.1(typescript@6.0.3) + '@typescript-eslint/utils': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + debug: 4.4.3 + eslint: 10.11.0 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.70.1': {} + + '@typescript-eslint/typescript-estree@8.70.1(typescript@6.0.3)': + dependencies: + '@typescript-eslint/project-service': 8.70.1(typescript@6.0.3) + '@typescript-eslint/tsconfig-utils': 8.70.1(typescript@6.0.3) + '@typescript-eslint/types': 8.70.1 + '@typescript-eslint/visitor-keys': 8.70.1 + debug: 4.4.3 + minimatch: 10.2.6 + semver: 7.8.5 + tinyglobby: 0.2.17 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.70.1(eslint@10.11.0)(typescript@6.0.3)': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.11.0) + '@typescript-eslint/scope-manager': 8.70.1 + '@typescript-eslint/types': 8.70.1 + '@typescript-eslint/typescript-estree': 8.70.1(typescript@6.0.3) + eslint: 10.11.0 + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.70.1': + dependencies: + '@typescript-eslint/types': 8.70.1 + eslint-visitor-keys: 5.0.1 + + acorn-jsx@5.3.2(acorn@8.18.0): + dependencies: + acorn: 8.18.0 + + acorn@8.18.0: {} + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + balanced-match@4.0.4: {} + + brace-expansion@5.0.12: + dependencies: + balanced-match: 4.0.4 + + cacheable@2.5.0: + dependencies: + '@cacheable/memory': 2.2.0 + '@cacheable/utils': 2.5.0 + hookified: 1.15.1 + keyv: 5.6.0 + qified: 0.10.1 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + csstype@3.2.3: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-is@0.1.4: {} + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + + escape-string-regexp@4.0.0: {} + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.9 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.11.0: + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.11.0) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.23.5 + '@eslint/config-helpers': 0.7.0 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.3 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.9 + ajv: 6.15.0 + cross-spawn: 7.0.6 + debug: 4.4.3 + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 11.1.5 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 10.2.6 + natural-compare: 1.4.0 + optionator: 0.9.4 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.18.0 + acorn-jsx: 5.3.2(acorn@8.18.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + esutils@2.0.3: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + file-entry-cache@11.1.5: + dependencies: + flat-cache: 6.1.23 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@6.1.23: + dependencies: + cacheable: 2.5.0 + flatted: 3.4.4 + hookified: 1.15.1 + + flatted@3.4.4: {} + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + globals@17.12.0: {} + + hashery@1.5.1: + dependencies: + hookified: 1.15.1 + + hookified@1.15.1: {} + + hookified@2.2.0: {} + + ignore@5.3.2: {} + + ignore@7.0.10: {} + + imurmurhash@0.1.4: {} + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + isexe@2.0.0: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + keyv@5.6.0: + dependencies: + '@keyv/serialize': 1.1.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.12 + + ms@2.1.3: {} + + natural-compare@1.4.0: {} + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + picomatch@4.0.7: {} + + playwright-core@1.63.0: {} + + playwright@1.63.0: + dependencies: + playwright-core: 1.63.0 + + prelude-ls@1.2.1: {} + + prettier@3.9.9: {} + + punycode@2.3.1: {} + + qified@0.10.1: + dependencies: + hookified: 2.2.0 + + react-dom@19.3.0(react@19.3.0): + dependencies: + react: 19.3.0 + scheduler: 0.28.0 + + react@19.3.0: {} + + scheduler@0.28.0: {} + + semver@7.8.5: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + ts-api-utils@2.5.0(typescript@6.0.3): + dependencies: + typescript: 6.0.3 + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + typescript-eslint@8.70.1(eslint@10.11.0)(typescript@6.0.3): + dependencies: + '@typescript-eslint/eslint-plugin': 8.70.1(@typescript-eslint/parser@8.70.1(eslint@10.11.0)(typescript@6.0.3))(eslint@10.11.0)(typescript@6.0.3) + '@typescript-eslint/parser': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.70.1(typescript@6.0.3) + '@typescript-eslint/utils': 8.70.1(eslint@10.11.0)(typescript@6.0.3) + eslint: 10.11.0 + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + typescript@6.0.3: {} + + undici-types@8.9.0: {} + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + word-wrap@1.2.5: {} + + yocto-queue@0.1.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..894f12c --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +# esbuild only builds demo/ (the visual check); nothing it produces ships. +allowBuilds: + esbuild: true diff --git a/src/attachments.ts b/src/attachments.ts new file mode 100644 index 0000000..01b2f7f --- /dev/null +++ b/src/attachments.ts @@ -0,0 +1,63 @@ +/** + * What a composer can attach, and the wire shape an app's API receives. + * + * From loki `lib/loki/attachments.ts`. The limits are defaults, not law — an + * app passes its own to `useAttachments` when its model or API differs. + */ + +export type TextAttachment = { kind: "text"; name: string; content: string }; +export type ImageAttachment = { + kind: "image"; + name: string; + mimeType: string; + dataBase64: string; +}; +export type Attachment = TextAttachment | ImageAttachment; + +/** Client-only preview URL — never sent to the API. */ +export type StagedAttachment = Attachment & { previewUrl?: string }; + +export type AttachmentLimits = { + /** Files per message. */ + maxFiles: number; + /** Characters per text file (it is inlined into a prompt). */ + maxTextChars: number; + /** Raw image bytes before base64. */ + maxImageBytes: number; +}; + +export const DEFAULT_ATTACHMENT_LIMITS: AttachmentLimits = { + maxFiles: 5, + maxTextChars: 100_000, + maxImageBytes: 2_800_000, +}; + +const IMAGE_MIME = /^image\/(jpeg|jpg|png|gif|webp)$/i; + +export function isImageMime(mime: string): boolean { + return IMAGE_MIME.test(mime); +} + +/** `data:image/png;base64,AAAA` → `AAAA`: FileReader hands back a data URL, + * the wire carries raw base64. */ +export function stripDataUrlBase64(dataUrl: string): string { + const i = dataUrl.indexOf(","); + return i >= 0 ? dataUrl.slice(i + 1) : dataUrl; +} + +/** Identity for dedupe and removal: the same name and bytes are the same + * attachment however they arrived (picker, paste, drop). */ +export function attachmentKey(a: Attachment): string { + return a.kind === "image" + ? `image:${a.name}:${a.dataBase64.length}` + : `text:${a.name}:${a.content.length}`; +} + +/** Strip client-only fields: what the API validates. */ +export function toWire(staged: StagedAttachment[]): Attachment[] { + return staged.map((a) => { + const { previewUrl: _preview, ...rest } = a; + void _preview; + return rest as Attachment; + }); +} diff --git a/src/composer.ts b/src/composer.ts new file mode 100644 index 0000000..2abb802 --- /dev/null +++ b/src/composer.ts @@ -0,0 +1,66 @@ +/** + * The composer's decisions, kept out of the component so they can be tested + * without a DOM — and so every app that uses the one composer gets exactly the + * same answer to "may this send?" and "does the draft survive?". + * + * From loki `src/components/composer/composer-logic.ts`, where these were + * written after four composers in one app gave four different answers. + */ + +/** A destination the same words can go to (e.g. Ask vs Inject). */ +export type ComposerMode = { id: string; label: string; hint?: string }; + +/** `false` keeps the draft (the send failed or was refused); anything else + * clears it. A failed send must be retryable from the same box, not retyped. */ +export type ComposerSendResult = void | boolean; + +export function composerCanSend({ + text, + attachmentCount, + attachmentOnlyText, + sending, + disabled, + blocked, +}: { + text: string; + attachmentCount: number; + attachmentOnlyText?: string; + sending: boolean; + disabled: boolean; + blocked: boolean; +}): boolean { + if (sending || disabled || blocked) return false; + if (text.trim().length > 0) return true; + // A screenshot with no words is still a complete message — but only where + // the app has said what that message means. + return attachmentCount > 0 && Boolean(attachmentOnlyText); +} + +/** The words actually sent: the draft, or the app's stand-in for an + * attachments-only send. */ +export function composerOutgoingText( + text: string, + attachmentCount: number, + attachmentOnlyText?: string, +): string { + const trimmed = text.trim(); + if (trimmed) return trimmed; + return attachmentCount > 0 && attachmentOnlyText ? attachmentOnlyText : ""; +} + +export function shouldClearDraft(result: ComposerSendResult): boolean { + return result !== false; +} + +/** Dictated words join the draft with one space, never glued to the last word. */ +export function appendTranscript(draft: string, said: string): string { + const t = said.trim(); + if (!t) return draft; + return draft.trim() ? `${draft.replace(/\s+$/, "")} ${t}` : t; +} + +/** `75` → `1:15`. The recording timer. */ +export function formatElapsed(seconds: number): string { + const s = Math.max(0, Math.floor(seconds)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +} diff --git a/src/dictation.ts b/src/dictation.ts new file mode 100644 index 0000000..7a5c057 --- /dev/null +++ b/src/dictation.ts @@ -0,0 +1,111 @@ +/** + * The decisions behind the microphone, without the microphone. + * + * The shape comes from heidi (`app/[locale]/_components/use-dictation.ts`), + * which is the only chat in the fleet whose mic never goes dead: + * + * - The browser's recogniser is FAST (free, instant, nothing uploaded) but + * sometimes a lie: Chromium builds without Google's speech service accept + * `start()` and then never fire an event — measured on heidi's live site + * 2026-09-12, nine seconds, zero events. So the recogniser is never the only + * path. Missing or silent, the same button RECORDS and a server transcribes. + * - Every failure becomes one of three words the person can act on — the mic + * (permission, hardware), silence (nothing heard), unavailable (nothing here + * can do it) — never a button that does nothing and says nothing. + * + * Kept pure so "never forever" and "which failures the fallback rescues" are + * tested properties rather than behaviour buried in a timeout. + */ + +/** Why a dictation produced no text, in terms the person can act on. */ +export type DictationProblem = "mic" | "silence" | "unavailable"; + +/** Which path to try first. `browser` is free and instant; `server` is one + * model everywhere (and detects the language by itself). Either falls back to + * the other when it cannot work. */ +export type DictationPreference = "browser" | "server"; + +/** + * Which recogniser failures the fallback can rescue: only "unavailable" — the + * recogniser cannot do this (no speech service, network refused, language + * unsupported) and recording locally does not care. "mic" is the person's + * hardware or a permission they denied; "silence" is whether they spoke. + * Recording again would tell them the same thing twice. + */ +export function fallbackCanRescue(problem: DictationProblem | null): boolean { + return problem === "unavailable"; +} + +/** Web Speech `error` codes → the three words. Anything unknown is + * `unavailable`, never nothing: a control that fails silently looks broken. */ +export function problemFor(error: string | undefined): DictationProblem | null { + switch (error) { + case "aborted": + return null; + case "not-allowed": + case "service-not-allowed": + case "audio-capture": + return "mic"; + case "no-speech": + return "silence"; + default: + return "unavailable"; + } +} + +/** getUserMedia / MediaRecorder failures → the same three words, so the UI + * never grows a second vocabulary for the same situations. */ +export function problemForRecording(error: unknown): DictationProblem { + const name = (error as { name?: string } | null)?.name ?? ""; + if (name === "NotAllowedError" || name === "SecurityError") return "mic"; + if (name === "NotFoundError" || name === "NotReadableError") return "mic"; + return "unavailable"; +} + +/** A working recogniser fires `start` well inside this once the mic is allowed. */ +export const START_TIMEOUT_MS = 4000; + +/** + * How long a pending permission may hold off the fallback. The wait is right — + * someone reading a permission dialog has not failed — but it must be BOUNDED: + * `permissions.query` says "prompt" both while a dialog is open and when none + * will ever appear (heidi, 2026-09-12: twenty-two seconds, nothing). + */ +export const PERMISSION_WAIT_MS = 10_000; + +export function mayKeepWaitingForPermission( + elapsedMs: number, + permissionPending: boolean, +): boolean { + return permissionPending && elapsedMs < PERMISSION_WAIT_MS; +} + +/** A browser whose recogniser proved dead is remembered for this long, so the + * person does not rediscover it on every press — and not forever, because a + * browser can gain the capability. */ +export const DEAD_RECOGNISER_TTL_MS = 30 * 24 * 60 * 60 * 1000; + +export function deadRecogniserStillTrusted(rememberedAt: number | null, now = Date.now()): boolean { + if (rememberedAt === null || !Number.isFinite(rememberedAt)) return false; + const age = now - rememberedAt; + // A timestamp from the future is a clock change, not a verdict. + return age >= 0 && age < DEAD_RECOGNISER_TTL_MS; +} + +/** Recording is capped so a forgotten mic does not run for an hour. */ +export const MAX_RECORDING_MS = 120_000; + +/** Candidate containers for MediaRecorder, best first. */ +export const RECORDING_MIME_CANDIDATES = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/mp4", + "audio/ogg", +] as const; + +/** The default words for each problem. Override per app (and per language). */ +export const DEFAULT_DICTATION_MESSAGES: Record = { + mic: "The microphone is blocked. Allow it for this site and try again.", + silence: "Nothing was heard. Try again, a little closer to the mic.", + unavailable: "Voice input is not available right now. Type instead, or try again later.", +}; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..88cc766 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,10 @@ +/** + * @bitbaum/chatkit — the framework-free half. Every decision a chat makes, + * testable without a DOM. The React components live in `@bitbaum/chatkit/react`, + * the look in `@bitbaum/chatkit/styles.css`. + */ +export * from "./composer.js"; +export * from "./dictation.js"; +export * from "./markdown.js"; +export * from "./scroll.js"; +export * from "./attachments.js"; diff --git a/src/markdown.ts b/src/markdown.ts new file mode 100644 index 0000000..eaee9b9 --- /dev/null +++ b/src/markdown.ts @@ -0,0 +1,133 @@ +/** + * The markdown an LLM actually writes, parsed into blocks and inline spans — + * no dependency, no HTML string, nothing to sanitise because nothing is ever + * rendered as HTML. + * + * From loki's `MarkdownText`, the one renderer in the fleet that four repos + * did NOT have: those rendered model output with the literal `**` still in it. + * Supports what answers use — paragraphs, bullet and numbered lists, headings, + * **bold**, *italic*, `code`, fenced code, [links](url) and `[F1]` citation + * handles — and deliberately nothing else. + */ + +export type MarkdownBlock = + | { kind: "p"; text: string } + | { kind: "h"; text: string } + | { kind: "ul"; items: string[] } + | { kind: "ol"; items: string[] } + | { kind: "code"; lang: string; code: string } + | { kind: "quote"; text: string }; + +export function parseBlocks(text: string): MarkdownBlock[] { + const blocks: MarkdownBlock[] = []; + let list: { kind: "ul" | "ol"; items: string[] } | null = null; + const lines = text.split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const raw = lines[i] ?? ""; + const line = raw.trim(); + // ``` fenced code — verbatim until the closing fence (or the end, while + // it is still streaming in). + if (line.startsWith("```")) { + list = null; + const lang = line.slice(3).trim(); + const code: string[] = []; + i++; + while (i < lines.length && !(lines[i] ?? "").trim().startsWith("```")) { + code.push(lines[i] ?? ""); + i++; + } + blocks.push({ kind: "code", lang, code: code.join("\n") }); + continue; + } + if (!line) { + list = null; + continue; + } + const bullet = /^[-*•]\s+(.*)$/.exec(line); + const numbered = /^\d+[.)]\s+(.*)$/.exec(line); + if (bullet || numbered) { + const kind = bullet ? "ul" : "ol"; + if (!list || list.kind !== kind) { + list = { kind, items: [] }; + blocks.push(list); + } + list.items.push((bullet ?? numbered)![1] ?? ""); + continue; + } + list = null; + if (/^#{1,6}\s/.test(line)) { + blocks.push({ kind: "h", text: line.replace(/^#+\s+/, "") }); + } else if (line.startsWith(">")) { + // A model's `>` leaked into prose was one of orangecat's fixed bugs. + blocks.push({ kind: "quote", text: line.replace(/^>\s?/, "") }); + } else { + const prev = blocks[blocks.length - 1]; + // A soft line break inside a paragraph continues it. + if (prev && prev.kind === "p" && (lines[i - 1] ?? "").trim()) prev.text += `\n${line}`; + else blocks.push({ kind: "p", text: line }); + } + } + return blocks; +} + +export type InlineSpan = + | { kind: "text"; text: string } + | { kind: "code"; text: string } + | { kind: "strong"; text: string } + | { kind: "em"; text: string } + | { kind: "link"; text: string; href: string } + | { kind: "cite"; ids: string[] }; + +const INLINE_RE = + /(`[^`]+`|\*\*[^*]+\*\*|\*[^*\s][^*]*\*|\[[^\]]+\]\([^)\s]+\)|\[[FD]\d+(?:,\s*[FD]\d+)*\]|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/g; + +export function parseInline(text: string): InlineSpan[] { + const out: InlineSpan[] = []; + for (const part of text.split(INLINE_RE)) { + if (!part) continue; + if (/^\[[FD]\d+(?:,\s*[FD]\d+)*\]$/.test(part)) { + out.push({ kind: "cite", ids: part.slice(1, -1).split(/,\s*/) }); + } else if (part.startsWith("`") && part.endsWith("`") && part.length > 1) { + out.push({ kind: "code", text: part.slice(1, -1) }); + } else if (part.startsWith("**") && part.endsWith("**") && part.length > 4) { + out.push({ kind: "strong", text: part.slice(2, -2) }); + } else if (/^\*[^*\s][^*]*\*$/.test(part)) { + out.push({ kind: "em", text: part.slice(1, -1) }); + } else { + const link = /^\[([^\]]+)\]\(([^)\s]+)\)$/.exec(part); + const href = link + ? safeHref(link[2] ?? "") + : /^https?:\/\//.test(part) + ? safeHref(part) + : null; + if (link && href) out.push({ kind: "link", text: link[1] ?? href, href }); + else if (!link && href) out.push({ kind: "link", text: part, href }); + else out.push({ kind: "text", text: link ? (link[1] ?? part) : part }); + } + } + return out; +} + +/** + * Only http(s), mailto and same-site paths become links. A `javascript:` URL in + * model output is text, never a link — the answer is written by a model that + * may have read a hostile page. + */ +export function safeHref(href: string): string | null { + const h = href.trim(); + if (h.startsWith("/") && !h.startsWith("//")) return h; + if (h.startsWith("#")) return h; + try { + const u = new URL(h); + return u.protocol === "https:" || u.protocol === "http:" || u.protocol === "mailto:" + ? u.href + : null; + } catch { + return null; + } +} + +/** A same-site path navigates in place; anything else opens a new tab. */ +export function isInternalHref(href: string): boolean { + return href.startsWith("/") || href.startsWith("#"); +} diff --git a/src/react/Composer.tsx b/src/react/Composer.tsx new file mode 100644 index 0000000..bbea5c8 --- /dev/null +++ b/src/react/Composer.tsx @@ -0,0 +1,451 @@ +"use client"; + +import { useEffect, useRef, useState, type ReactNode, type RefObject } from "react"; +import { + appendTranscript, + composerCanSend, + composerOutgoingText, + formatElapsed, + shouldClearDraft, + type ComposerMode, + type ComposerSendResult, +} from "../composer.js"; +import { DEFAULT_DICTATION_MESSAGES, type DictationProblem } from "../dictation.js"; +import type { Attachment, AttachmentLimits } from "../attachments.js"; +import { useDictation, type UseDictationOptions } from "./use-dictation.js"; +import { useAttachments, type AttachmentsController } from "./use-attachments.js"; +import { useAutoGrow } from "./hooks.js"; +import { + IconArrowUp, + IconCheck, + IconFile, + IconMic, + IconPaperclip, + IconSpinner, + IconStop, + IconX, +} from "./icons.js"; + +export type ComposerLabels = { + send: string; + stop: string; + voice: string; + voiceStop: string; + cancelRecording: string; + confirmRecording: string; + listening: string; + transcribing: string; + attach: string; + remove: (name: string) => string; + dismiss: string; + dictation: Record; +}; + +export const DEFAULT_COMPOSER_LABELS: ComposerLabels = { + send: "Send", + stop: "Stop generating", + voice: "Speak instead of typing", + voiceStop: "Stop recording", + cancelRecording: "Cancel recording", + confirmRecording: "Done — use what I said", + listening: "Listening…", + transcribing: "Transcribing…", + attach: "Attach a screenshot or file", + remove: (name) => `Remove ${name}`, + dismiss: "Dismiss", + dictation: DEFAULT_DICTATION_MESSAGES, +}; + +export type ComposerVoice = Omit; + +export type ComposerProps = { + /** Deliver what was written. Return `false` (or resolve to it) to keep the + * draft — a failed send is retried from the same box, not retyped. */ + onSend: ( + text: string, + attachments: Attachment[], + ) => ComposerSendResult | Promise; + placeholder: string; + ariaLabel?: string; + disabled?: boolean; + /** Typing is fine, sending is not — shown as the send button's title. */ + sendBlockedReason?: string | null; + sending?: boolean; + /** Given, the send slot becomes Stop while `sending`: a turn you cannot + * cancel is what makes a slow answer feel broken. */ + onStop?: () => void; + /** What an attachments-only send says. Omit and empty text cannot send. */ + attachmentOnlyText?: string; + /** Attachments on, optionally with the app's own limits. Off by default: + * only offer what the app's API accepts. */ + attach?: boolean | Partial; + /** The microphone. On by default. Pass `transcribeUrl` (or `transcribe`) so + * it still works where the browser recogniser does not — that fallback is + * what makes the mic never a dead button. `false` only for a surface that + * truly cannot take speech. */ + voice?: ComposerVoice | false; + modes?: readonly ComposerMode[]; + mode?: string; + onModeChange?: (id: string) => void; + /** "/" typed into an empty composer — open a library instead of typing. */ + onEmptySlash?: () => void; + value?: string; + onValueChange?: (text: string) => void; + defaultValue?: string; + inputRef?: RefObject; + density?: "comfortable" | "compact"; + /** Outside the box, above it (suggestion chips). */ + above?: ReactNode; + /** Inside the box, above the text (scope pills, an error). */ + header?: ReactNode; + /** Extra tools after attach and voice (a model picker, a library). */ + tools?: ReactNode; + /** Just before the send button. */ + trailing?: ReactNode; + /** Inside the box, under the controls. */ + footer?: ReactNode; + hint?: string; + labels?: Partial; + autoFocus?: boolean; +}; + +function AttachmentStrip({ + attachments, + labels, +}: { + attachments: AttachmentsController; + labels: ComposerLabels; +}) { + if (attachments.attachments.length === 0 && !attachments.note) return null; + return ( +
+ {attachments.attachments.map((a) => { + const key = attachments.keyOf(a); + return ( +
+ {a.kind === "image" && a.previewUrl ? ( + {a.name} + ) : ( + + + {a.name} + + )} + +
+ ); + })} + {attachments.note && ( + + )} +
+ ); +} + +function Elapsed({ since }: { since: number | null }) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (since === null) return; + const t = setInterval(() => setNow(Date.now()), 250); + return () => clearInterval(t); + }, [since]); + return ( + + {formatElapsed(since === null ? 0 : (now - since) / 1000)} + + ); +} + +/** + * THE composer: write words — or say them, or paste a screenshot — and send + * them. Enter sends, Shift+Enter breaks the line, an IME composition never + * sends half a word. 16px text, so iOS never zooms the page on focus. + * + * Extracted from loki `components/composer/Composer.tsx` (itself the merge of + * four composers in one app), with heidi's microphone and orangecat's lessons. + */ +export function Composer({ + onSend, + placeholder, + ariaLabel, + disabled = false, + sendBlockedReason = null, + sending = false, + onStop, + attachmentOnlyText, + attach = false, + voice = {}, + modes, + mode, + onModeChange, + onEmptySlash, + value, + onValueChange, + defaultValue = "", + inputRef, + density = "comfortable", + above, + header, + tools, + trailing, + footer, + hint, + labels: labelOverrides, + autoFocus, +}: ComposerProps) { + const labels: ComposerLabels = { + ...DEFAULT_COMPOSER_LABELS, + ...labelOverrides, + dictation: { ...DEFAULT_COMPOSER_LABELS.dictation, ...labelOverrides?.dictation }, + }; + const [ownText, setOwnText] = useState(defaultValue); + const controlled = value !== undefined; + const text = controlled ? value : ownText; + // Mirrored so an async send compares against the CURRENT draft, not the one + // its closure captured. Written in an effect, never during render. + const textRef = useRef(text); + useEffect(() => { + textRef.current = text; + }); + const setText = (next: string | ((prev: string) => string)) => { + const resolved = typeof next === "function" ? next(textRef.current) : next; + textRef.current = resolved; + if (!controlled) setOwnText(resolved); + onValueChange?.(resolved); + }; + + const localRef = useRef(null); + const textareaRef = inputRef ?? localRef; + useAutoGrow(textareaRef, text); + + const attachOn = attach !== false; + const attachments = useAttachments(typeof attach === "object" ? attach : {}); + + const dictation = useDictation({ + ...(voice || {}), + onText: (said) => setText((prev) => appendTranscript(prev, said)), + }); + const voiceOn = voice !== false && dictation.supported; + const listening = dictation.status === "listening"; + const transcribing = dictation.status === "transcribing"; + + const attachCount = attachOn ? attachments.attachments.length : 0; + const canSend = composerCanSend({ + text, + attachmentCount: attachCount, + attachmentOnlyText, + sending, + disabled, + blocked: Boolean(sendBlockedReason), + }); + + const submit = async () => { + if (!canSend) return; + const sent = text; + const outgoing = composerOutgoingText(sent, attachCount, attachmentOnlyText); + const result = await onSend(outgoing, attachOn ? attachments.toWire() : []); + if (!shouldClearDraft(result)) return; + // Only clear what was sent: words typed while a slow send was in flight + // are the next message. + if (textRef.current === sent) setText(""); + attachments.clear(); + }; + + const fileInput = useRef(null); + const showModes = Boolean(modes && modes.length > 1); + + return ( +
+ {above} +
+ {(listening || transcribing) && ( +
+ {listening ? ( + <> + + + {Array.from({ length: 9 }).map((_, i) => ( + + ))} + + + + + + ) : ( + <> + + {labels.transcribing} + + )} +
+ )} + +
+ {showModes && ( +
+ {modes!.map((m) => ( + + ))} +
+ )} + {header} + +