mirror of
https://github.com/bitbaum/chatkit.git
synced 2026-12-04 20:07:45 +01:00
feat: chatkit v0.1 — one chat for every product (#1)
* feat: chatkit v0.1 — one chat for every product The fleet had 13 chats in 10 repos, each written fresh, each missing what another had fixed. This extracts loki /loki (composer, thread, messages, markdown, attachments) and adds heidi's microphone and orangecat's keyboard fix: - Composer: auto-growing 16px textarea, Enter/Shift+Enter/IME, Send and Stop in one slot, attachments with paste, mic always present, every label translatable, app-specific controls in slots. - useDictation: browser recogniser first; missing or SILENT (4 s watchdog, bounded permission wait) -> record and transcribe on the server; a dead recogniser remembered 30 days; every failure shown in words. - ChatThread/ChatMessage: stick-to-bottom + jump button, speaker names once two agents speak, Copy on answers, Retry on the last one, failed turns visible. - Markdown with no HTML path; javascript: links stay text. - styles.css: --ck-* variables defaulting to @bitbaum/design-tokens. - verify = format, lint, types, build, 18 unit/render tests and 21 browser checks (390px + desktop, light + dark, a sentence through a fake mic past a silent recogniser). Browser checks mutation-tested (14px input, 60 s watchdog) — both fail as they should. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(styles): --ck-* defaults at zero specificity on :root, so an app's own values win Declared on the chat's elements they overrode any app setting --ck-* at the root — the opposite of what the README promised. Found preparing loki, whose colour variables are full OKLCH colours under the design-token names and so must map them. New browser check: a :root --ck-accent reaches the chat. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
dcc8c61cd2
commit
ed759a8516
87 files changed
+6758
-1
No files matched your search
@@ -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 }}
|
||||
@@ -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
|
||||
@@ -1,3 +1,5 @@
|
||||
node_modules/
|
||||
.DS_Store
|
||||
*.log
|
||||
.claude/
|
||||
demo/dist/
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
<ChatThread
|
||||
messages={messages} // { id, role, content, speaker?, citations?, failed? }
|
||||
live={streaming ? { text: partial } : null}
|
||||
onStop={stop}
|
||||
onRetry={retryLast}
|
||||
empty={<ChatStarters starters={["What can you build for me?"]} onPick={send} />}
|
||||
/>
|
||||
<Composer
|
||||
onSend={(text, attachments) => 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={<ModelPicker />} // 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<string>` 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<version> origin/main && git push origin v<version>`.
|
||||
|
||||
## Develop
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
pnpm run demo # builds demo/dist; open demo/index.html
|
||||
pnpm run verify # everything CI runs
|
||||
```
|
||||
|
||||
MIT © Cato
|
||||
@@ -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<ChatMessageData[]>(
|
||||
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 (
|
||||
<div className="demo-chat">
|
||||
<ChatThread
|
||||
messages={messages}
|
||||
live={sending ? { status: "Reading the catalogue" } : null}
|
||||
onStop={() => setSending(false)}
|
||||
onRetry={() => {}}
|
||||
empty={
|
||||
<ChatStarters
|
||||
title="Ask about any project — the Cat and Loki are both in here."
|
||||
starters={[
|
||||
"What can you build for me?",
|
||||
"I want to earn in Bitcoin",
|
||||
"How do I run AI agents on my code?",
|
||||
]}
|
||||
onPick={send}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Composer
|
||||
onSend={(t) => send(t)}
|
||||
placeholder="Ask about any project…"
|
||||
sending={sending}
|
||||
onStop={() => setSending(false)}
|
||||
attach
|
||||
voice={{ transcribeUrl: "/api/transcribe" }}
|
||||
hint="Enter sends · Shift+Enter new line"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
for (const [id, props] of [
|
||||
["conversation", {}],
|
||||
["empty", { empty: true }],
|
||||
["failed", { failed: true }],
|
||||
] as const) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) createRoot(el).render(<Demo {...props} />);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, interactive-widget=resizes-content"
|
||||
/>
|
||||
<title>chatkit demo</title>
|
||||
<link rel="stylesheet" href="../node_modules/@bitbaum/design-tokens/tokens.css" />
|
||||
<link rel="stylesheet" href="../styles.css" />
|
||||
<style>
|
||||
/* Page chrome only — the chat's look comes from styles.css + tokens. */
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
.theme {
|
||||
padding: 24px 16px;
|
||||
background: hsl(var(--surface-page, 0 0% 98%));
|
||||
color: hsl(var(--text-primary, 0 0% 10%));
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 24px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.demo-chat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
height: 560px;
|
||||
}
|
||||
h2 {
|
||||
font-size: 14px;
|
||||
margin: 0 0 8px;
|
||||
opacity: 0.6;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<section class="theme">
|
||||
<div class="grid">
|
||||
<div>
|
||||
<h2>Conversation — two agents</h2>
|
||||
<div id="conversation"></div>
|
||||
</div>
|
||||
<div>
|
||||
<h2>Empty — starters</h2>
|
||||
<div id="empty"></div>
|
||||
</div>
|
||||
<div>
|
||||
<h2>Failed turn — retry</h2>
|
||||
<div id="failed"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<script src="./dist/demo.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+41
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+37
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+34
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+41
@@ -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
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"composer.js","sourceRoot":"","sources":["../src/composer.ts"],"names":[],"mappings":"AAAA;;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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"}
|
||||
Vendored
+60
@@ -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<DictationProblem, string>;
|
||||
//# sourceMappingURL=dictation.d.ts.map
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+93
@@ -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
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"dictation.js","sourceRoot":"","sources":["../src/dictation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAUH;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAgC;IAChE,OAAO,OAAO,KAAK,aAAa,CAAC;AACnC,CAAC;AAED;gFACgF;AAChF,MAAM,UAAU,UAAU,CAAC,KAAyB;IAClD,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,SAAS;YACZ,O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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"}
|
||||
Vendored
+11
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+11
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+62
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+127
@@ -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
|
||||
Vendored
+1
@@ -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,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AChC,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC;QACrB,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS;YAClF,CAAC,CAAC,CAAC,CAAC,IAAI;YACR,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,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"}
|
||||
Vendored
+78
@@ -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<DictationProblem, string>;
|
||||
};
|
||||
export declare const DEFAULT_COMPOSER_LABELS: ComposerLabels;
|
||||
export type ComposerVoice = Omit<UseDictationOptions, "onText">;
|
||||
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<ComposerSendResult>;
|
||||
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<AttachmentLimits>;
|
||||
/** 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<HTMLTextAreaElement | null>;
|
||||
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<ComposerLabels>;
|
||||
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
|
||||
Vendored
+1
@@ -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,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAc5E,MAAM,MAAM,cAAc,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;CAC7C,CAAC;AAEF,eAAO,MAAM,uBAAuB,EAAE,cAarC,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,IAAI,CA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,CAAC;IACnB,sEAAsE;IACtE,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,mCAAmC;IACnC,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,0CAA0C;IAC1C,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IACjC,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC;AA2DF;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,EACvB,MAAM,EACN,WAAW,EACX,SAAS,EACT,QAAgB,EAChB,iBAAwB,EACxB,OAAe,EACf,MAAM,EACN,kBAAkB,EAClB,MAAc,EACd,KAAU,EACV,KAAK,EACL,IAAI,EACJ,YAAY,EACZ,YAAY,EACZ,KAAK,EACL,aAAa,EACb,YAAiB,EACjB,QAAQ,EACR,OAAuB,EACvB,KAAK,EACL,MAAM,EACN,KAAK,EACL,QAAQ,EACR,MAAM,EACN,IAAI,EACJ,MAAM,EAAE,cAAc,EACtB,SAAS,GACV,EAAE,aAAa,+BAsPf"}
|
||||
Vendored
+129
@@ -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
|
||||
Vendored
+1
@@ -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,WAAW,CAAC,MA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IAAI,EAAE,IAAI,CAAC,CAAC;KAClE,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,KAAK,KAAK,KAAK,IAAI,SAAS,CAAC,SAAS,CAAC;IACvD,MAAM,SAAS,GAAG,SAAS,CAAC,MAAM,KAAK,WAAW,CAAC;IACnD,MAAM,YAAY,GAAG,SAAS,CAAC,MAAM,KAAK,cAAc,CAAC;IAEzD,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAClE,MAAM,OAAO,GAAG,eAAe,CAAC;QAC9B,IAAI;QACJ,eAAe,EAAE,WAAW;QAC5B,kBAAkB;QAClB,OAAO;QACP,QAAQ;QACR,OAAO,EAAE,OAAO,CAAC,iBAAiB,CAAC;KACpC,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE;QACxB,IAAI,CAAC,OAAO;YAAE,OAAO;QACrB,MAAM,IAAI,GAAG,IAAI,CAAC;QAClB,MAAM,QAAQ,GAAG,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,kBAAkB,CAAC,CAAC;QAC7E,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC5E,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC;YAAE,OAAO;QACtC,wEAAwE;QACxE,wBAAwB;QACxB,IAAI,OAAO,CAAC,OAAO,KAAK,IAAI;YAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QAC1C,WAAW,Line truncated
|
||||
Vendored
+27
@@ -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<string, {
|
||||
label: string;
|
||||
detail: string;
|
||||
}>;
|
||||
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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+58
@@ -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
|
||||
Vendored
+1
@@ -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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oBACE,OAAO,sBAAY,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAlB,CAAC,CAAsB,CAAC;YAC3C,CAAC;QACH,CAAC,CAAC,GACE,CACP,CAAC;AACJ,CAAC"}
|
||||
Vendored
+90
@@ -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-<id>`), 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<ThreadLabels>;
|
||||
}): 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
|
||||
Vendored
+1
@@ -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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EAAE,CAAC;IAC7B,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB,+BAiBA"}
|
||||
Vendored
+64
@@ -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
|
||||
Vendored
+1
@@ -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,EAA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IAAI,IAAI,CACnB,YAAG,SAAS,EAAC,YAAY,EAAC,IAAI,EAAC,QAAQ,YACpC,MAAM,CAAC,OAAO,GACb,CACL,EACA,QAAQ,EACT,cAAK,GAAG,EAAE,MAAM,GAAI,IAChB,GACF,EACL,CAAC,SAAS,IAAI,CACb,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,SAAS,EACnB,OAAO,EAAE,YAAY,gBACT,MAAM,CAAC,IAAI,EACvB,KAAK,EAAE,MAAM,CAAC,IAAI,YAElB,KAAC,aAAa,KAAG,GACV,CACV,IACG,CACP,CAAC;AACJ,CAAC;AAID,8EAA8E;AAC9E,MAAM,UAAU,YAAY,CAAC,EAC3B,QAAQ,EACR,MAAM,EACN,KAAK,GAKN;IACC,OAAO,CACL,eAAK,SAAS,EAAC,aAAa,aACzB,KAAK,IAAI,cAAK,SAAS,EAAC,mBAAmB,YAAE,KAAK,GAAO,EAC1D,cAAK,SAAS,EAAC,kBAAkB,YAC9B,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;oBACrB,MALine truncated
|
||||
Vendored
+40
@@ -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<HTMLDivElement | null>;
|
||||
endRef: RefObject<HTMLDivElement | null>;
|
||||
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<HTMLElement | null>): 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<HTMLTextAreaElement | null>, value: string, max?: number): void;
|
||||
//# sourceMappingURL=hooks.d.ts.map
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+99
@@ -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
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/react/hooks.ts"],"names":[],"mappings":"AAAA,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AC,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;AACxB,CAAC"}
|
||||
Vendored
+12
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+21
@@ -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
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"icons.js","sourceRoot":"","sources":["../../src/react/icons.tsx"],"names":[],"mappings":";AAEA;;;;GAIG;AACH,SAAS,GAAG,CAAC,KAA8B;IACzC,OAAO,CACL,cACE,OAAO,EAAC,WAAW,EACnB,KAAK,EAAC,KAAK,EACX,MAAM,EAAC,KAAK,EACZ,IAAI,EAAC,MAAM,EACX,MAAM,EAAC,cAAc,EACrB,WAAW,EAAE,CAAC,EACd,aAAa,EAAC,OAAO,EACrB,cAAc,EAAC,OAAO,iBACV,MAAM,EAClB,SAAS,EAAC,OAAO,KACb,KAAK,GACT,CACH,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,CAC/B,MAAC,GAAG,eACF,eAAM,CAAC,EAAC,eAAe,GAAG,EAC1B,eAAM,CAAC,EAAC,UAAU,GAAG,IACjB,CACP,CAAC;AACF,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,EAAE,CAAC,CACjC,MAAC,GAAG,eACF,eAAM,CAAC,EAAC,UAAU,GAAG,EACrB,eAAM,CAAC,EAAC,gBAAgB,GAAG,IACvB,CACP,CAAC;AACF,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAC3B,MAAC,GAAG,eACF,eAAM,CAAC,EAAC,sDAAsD,GAAG,EACjE,eA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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"}
|
||||
Vendored
+21
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+16
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+26
@@ -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<AttachmentLimits>): AttachmentsController;
|
||||
//# sourceMappingURL=use-attachments.d.ts.map
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+139
@@ -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
|
||||
Vendored
+1
@@ -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,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IAExB,SAAS,CAAC,GAAG,EAAE;QACb,KAAK,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;IACrC,CAAC,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;IAEzB,SAAS,CAAC,GA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
@@ -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
|
||||
* `<html lang>`, 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<string>;
|
||||
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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+365
@@ -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
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"use-dictation.js","sourceRoot":"","sources":["../../src/react/use-dictation.ts"],"names":[],"mapp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OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;;YAC5B,UAAU,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,UAAU,GAAG,WAAW,CAC5B,KAAK,EAAE,KAAW,EAAE,EAAE;QACpB,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;QAC1B,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;QAC5C,IAAI,CAAC,CAAC,UAAU;YAAE,OAAO,CAAC,CAAC,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACnD,IAAI,CAAC,CAAC,aAAa;YAAE,OAAO,SAAS,CAAC,CAAC,CAAC,aAAa,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;QACpE,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC,EACD,CAAC,MAAM,CAAC,CACT,CAAC;IAEF,+CAA+C;IAC/C,MAAM,MAAM,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACpC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;YACnF,UAAU,CAAC,aAAaLine truncated
|
||||
Vendored
+13
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
Vendored
+11
@@ -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
|
||||
Vendored
+1
@@ -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"}
|
||||
@@ -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 } },
|
||||
},
|
||||
);
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
Generated
+1254
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
# esbuild only builds demo/ (the visual check); nothing it produces ships.
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
@@ -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")}`;
|
||||
}
|
||||
@@ -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<DictationProblem, string> = {
|
||||
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.",
|
||||
};
|
||||
@@ -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";
|
||||
+133
@@ -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("#");
|
||||
}
|
||||
@@ -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<DictationProblem, string>;
|
||||
};
|
||||
|
||||
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<UseDictationOptions, "onText">;
|
||||
|
||||
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<ComposerSendResult>;
|
||||
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<AttachmentLimits>;
|
||||
/** 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<HTMLTextAreaElement | null>;
|
||||
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<ComposerLabels>;
|
||||
autoFocus?: boolean;
|
||||
};
|
||||
|
||||
function AttachmentStrip({
|
||||
attachments,
|
||||
labels,
|
||||
}: {
|
||||
attachments: AttachmentsController;
|
||||
labels: ComposerLabels;
|
||||
}) {
|
||||
if (attachments.attachments.length === 0 && !attachments.note) return null;
|
||||
return (
|
||||
<div className="ck-attach-strip">
|
||||
{attachments.attachments.map((a) => {
|
||||
const key = attachments.keyOf(a);
|
||||
return (
|
||||
<div key={key} className="ck-attach-item">
|
||||
{a.kind === "image" && a.previewUrl ? (
|
||||
<img src={a.previewUrl} alt={a.name} className="ck-attach-thumb" />
|
||||
) : (
|
||||
<span className="ck-attach-file">
|
||||
<IconFile />
|
||||
<span className="ck-truncate">{a.name}</span>
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="ck-attach-remove"
|
||||
onClick={() => attachments.remove(key)}
|
||||
aria-label={labels.remove(a.name)}
|
||||
title={labels.remove(a.name)}
|
||||
>
|
||||
<IconX />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{attachments.note && (
|
||||
<button type="button" className="ck-note" onClick={attachments.clearNote}>
|
||||
{attachments.note}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<span className="ck-voice-timer">
|
||||
{formatElapsed(since === null ? 0 : (now - since) / 1000)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<HTMLTextAreaElement | null>(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<HTMLInputElement>(null);
|
||||
const showModes = Boolean(modes && modes.length > 1);
|
||||
|
||||
return (
|
||||
<div className="ck-composer-wrap">
|
||||
{above}
|
||||
<div className="ck-composer-frame">
|
||||
{(listening || transcribing) && (
|
||||
<div className="ck-voice-bar" role="status" aria-live="polite">
|
||||
{listening ? (
|
||||
<>
|
||||
<span className="ck-voice-dot" aria-hidden />
|
||||
<span className="ck-voice-wave" aria-hidden>
|
||||
{Array.from({ length: 9 }).map((_, i) => (
|
||||
<span key={i} />
|
||||
))}
|
||||
</span>
|
||||
<Elapsed since={dictation.startedAt} />
|
||||
<button
|
||||
type="button"
|
||||
className="ck-icon-btn"
|
||||
onClick={dictation.cancel}
|
||||
aria-label={labels.cancelRecording}
|
||||
title={labels.cancelRecording}
|
||||
>
|
||||
<IconX />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="ck-voice-confirm"
|
||||
onClick={dictation.stop}
|
||||
aria-label={labels.confirmRecording}
|
||||
title={labels.confirmRecording}
|
||||
>
|
||||
<IconCheck />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<IconSpinner />
|
||||
<span className="ck-voice-timer">{labels.transcribing}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={density === "compact" ? "ck-composer ck-composer-compact" : "ck-composer"}>
|
||||
{showModes && (
|
||||
<div className="ck-modes" role="group">
|
||||
{modes!.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
type="button"
|
||||
className="ck-mode"
|
||||
aria-pressed={m.id === mode}
|
||||
title={m.hint}
|
||||
onClick={() => onModeChange?.(m.id)}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{header}
|
||||
|
||||
<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 && <AttachmentStrip attachments={attachments} labels={labels} />}
|
||||
|
||||
<div className="ck-actions">
|
||||
<div className="ck-tools">
|
||||
{attachOn && (
|
||||
<>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
accept="image/*,text/*,.md,.txt,.json,.csv,.log"
|
||||
onChange={(e) => {
|
||||
attachments.addFiles(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="ck-icon-btn"
|
||||
onClick={() => fileInput.current?.click()}
|
||||
disabled={disabled || attachments.full}
|
||||
aria-label={labels.attach}
|
||||
title={labels.attach}
|
||||
>
|
||||
<IconPaperclip />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{voiceOn && (
|
||||
<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}
|
||||
>
|
||||
{transcribing ? <IconSpinner /> : <IconMic />}
|
||||
</button>
|
||||
)}
|
||||
{tools}
|
||||
{hint && <span className="ck-hint">{hint}</span>}
|
||||
</div>
|
||||
<div className="ck-submit">
|
||||
{trailing}
|
||||
{/* Send and Stop share ONE slot, so the button you want never
|
||||
moves depending on state. */}
|
||||
{sending && onStop ? (
|
||||
<button
|
||||
type="button"
|
||||
className="ck-send ck-send-stop"
|
||||
onClick={onStop}
|
||||
aria-label={labels.stop}
|
||||
title={labels.stop}
|
||||
>
|
||||
<IconStop />
|
||||
</button>
|
||||
) : (
|
||||
!listening && (
|
||||
<button
|
||||
type="button"
|
||||
className="ck-send"
|
||||
disabled={!canSend}
|
||||
onClick={() => void submit()}
|
||||
aria-label={labels.send}
|
||||
title={sendBlockedReason ?? labels.send}
|
||||
>
|
||||
{sending ? <IconSpinner /> : <IconArrowUp />}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{footer}
|
||||
</div>
|
||||
</div>
|
||||
{dictation.problem && (
|
||||
<p className="ck-problem" role="status">
|
||||
<span>{labels.dictation[dictation.problem]}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="ck-problem-x"
|
||||
onClick={dictation.clearProblem}
|
||||
aria-label={labels.dismiss}
|
||||
>
|
||||
<IconX />
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { isInternalHref, parseBlocks, parseInline, type InlineSpan } from "../markdown.js";
|
||||
|
||||
/** 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<string, { label: string; detail: string }>;
|
||||
|
||||
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 const defaultRenderLink: RenderLink = ({ href, internal, className, children }) =>
|
||||
internal ? (
|
||||
<a href={href} className={className}>
|
||||
{children}
|
||||
</a>
|
||||
) : (
|
||||
<a href={href} className={className} target="_blank" rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
|
||||
function Inline({
|
||||
spans,
|
||||
citations,
|
||||
renderLink,
|
||||
}: {
|
||||
spans: InlineSpan[];
|
||||
citations?: CitationMap;
|
||||
renderLink: RenderLink;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{spans.map((s, i) => {
|
||||
switch (s.kind) {
|
||||
case "code":
|
||||
return (
|
||||
<code key={i} className="ck-code">
|
||||
{s.text}
|
||||
</code>
|
||||
);
|
||||
case "strong":
|
||||
return <strong key={i}>{s.text}</strong>;
|
||||
case "em":
|
||||
return <em key={i}>{s.text}</em>;
|
||||
case "link":
|
||||
return (
|
||||
<span key={i}>
|
||||
{renderLink({
|
||||
href: s.href,
|
||||
internal: isInternalHref(s.href),
|
||||
className: "ck-link",
|
||||
children: s.text,
|
||||
})}
|
||||
</span>
|
||||
);
|
||||
case "cite": {
|
||||
const known = s.ids.filter((id) => citations?.[id]);
|
||||
if (known.length === 0) return null;
|
||||
return (
|
||||
<sup
|
||||
key={i}
|
||||
className="ck-cite"
|
||||
title={known
|
||||
.map((id) => `${id} — ${citations![id]!.label}\n${citations![id]!.detail}`)
|
||||
.join("\n\n")}
|
||||
>
|
||||
{known.join(" ")}
|
||||
</sup>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return <span key={i}>{s.text}</span>;
|
||||
}
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
}: {
|
||||
text: string;
|
||||
citations?: CitationMap;
|
||||
renderLink?: RenderLink;
|
||||
className?: string;
|
||||
}) {
|
||||
const inline = (t: string) => (
|
||||
<Inline spans={parseInline(t)} citations={citations} renderLink={renderLink} />
|
||||
);
|
||||
return (
|
||||
<div className={className ? `ck-md ${className}` : "ck-md"}>
|
||||
{parseBlocks(text).map((b, i) => {
|
||||
switch (b.kind) {
|
||||
case "code":
|
||||
return (
|
||||
<pre key={i} className="ck-pre" data-lang={b.lang || undefined}>
|
||||
<code>{b.code}</code>
|
||||
</pre>
|
||||
);
|
||||
case "ul":
|
||||
case "ol": {
|
||||
const List = b.kind;
|
||||
return (
|
||||
<List key={i}>
|
||||
{b.items.map((item, j) => (
|
||||
<li key={j}>{inline(item)}</li>
|
||||
))}
|
||||
</List>
|
||||
);
|
||||
}
|
||||
case "h":
|
||||
return (
|
||||
<p key={i} className="ck-md-h">
|
||||
{inline(b.text)}
|
||||
</p>
|
||||
);
|
||||
case "quote":
|
||||
return <blockquote key={i}>{inline(b.text)}</blockquote>;
|
||||
default:
|
||||
return <p key={i}>{inline(b.text)}</p>;
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Markdown, defaultRenderLink, type CitationMap, type RenderLink } from "./Markdown.js";
|
||||
import { useClipboard, useStickToBottom } from "./hooks.js";
|
||||
import { IconArrowDown, IconCheck, IconCopy, IconRetry, IconStop } from "./icons.js";
|
||||
|
||||
export type ChatSpeaker = {
|
||||
/** Shown above the message when more than one agent can answer. */
|
||||
name: string;
|
||||
/** Stable id for styling (`ck-from-<id>`), 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 const DEFAULT_THREAD_LABELS: ThreadLabels = {
|
||||
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,
|
||||
}: {
|
||||
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;
|
||||
}) {
|
||||
const { copied, copy } = useClipboard();
|
||||
|
||||
if (message.role === "user") {
|
||||
return (
|
||||
<div className="ck-turn ck-turn-user">
|
||||
<div className="ck-bubble">{message.content}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className={cls.join(" ")}>
|
||||
{showSpeaker && message.speaker && <span className="ck-speaker">{message.speaker.name}</span>}
|
||||
{message.failed ? (
|
||||
<p className="ck-failed" role="status">
|
||||
{message.content || labels.failed}
|
||||
</p>
|
||||
) : (
|
||||
<Markdown text={message.content} citations={message.citations} renderLink={renderLink} />
|
||||
)}
|
||||
{footer}
|
||||
<div className="ck-turn-actions">
|
||||
{!message.failed && (
|
||||
<button
|
||||
type="button"
|
||||
className="ck-action"
|
||||
onClick={() => copy(message.content)}
|
||||
aria-label={copied ? labels.copied : labels.copy}
|
||||
>
|
||||
{copied ? <IconCheck /> : <IconCopy />}
|
||||
<span>{copied ? labels.copied : labels.copy}</span>
|
||||
</button>
|
||||
)}
|
||||
{onRetry && (
|
||||
<button type="button" className="ck-action" onClick={onRetry}>
|
||||
<IconRetry />
|
||||
<span>{labels.retry}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 function ChatThread({
|
||||
messages,
|
||||
live = null,
|
||||
loading = false,
|
||||
stopped = false,
|
||||
onStop,
|
||||
onRetry,
|
||||
renderLink = defaultRenderLink,
|
||||
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<ThreadLabels>;
|
||||
}) {
|
||||
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 (
|
||||
<div className="ck-thread-loading" role="status">
|
||||
{labels.loading}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (messages.length === 0 && !live && !stopped) return <>{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 (
|
||||
<div className="ck-thread-wrap">
|
||||
<div ref={scrollRef} className="ck-thread" onScroll={onScroll}>
|
||||
<div className="ck-thread-inner">
|
||||
{messages.map((m) => (
|
||||
<ChatMessage
|
||||
key={m.id}
|
||||
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}
|
||||
/>
|
||||
))}
|
||||
{live && (
|
||||
<div className="ck-turn ck-turn-answer">
|
||||
{named && live.speaker && <span className="ck-speaker">{live.speaker.name}</span>}
|
||||
{live.text ? (
|
||||
<Markdown text={live.text} renderLink={renderLink} />
|
||||
) : (
|
||||
<p className="ck-live" role="status" aria-live="polite">
|
||||
<span className="ck-dots" aria-hidden>
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</span>
|
||||
{live.status ?? labels.working}
|
||||
</p>
|
||||
)}
|
||||
{onStop && (
|
||||
<button type="button" className="ck-stop" onClick={onStop}>
|
||||
<IconStop />
|
||||
{labels.stop}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{stopped && !live && (
|
||||
<p className="ck-stopped" role="status">
|
||||
{labels.stopped}
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
</div>
|
||||
{!following && (
|
||||
<button
|
||||
type="button"
|
||||
className="ck-jump"
|
||||
onClick={jumpToBottom}
|
||||
aria-label={labels.jump}
|
||||
title={labels.jump}
|
||||
>
|
||||
<IconArrowDown />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type Starter = string | { label: string; prompt?: string };
|
||||
|
||||
/** The empty state that starts a conversation. It disappears once one has. */
|
||||
export function ChatStarters({
|
||||
starters,
|
||||
onPick,
|
||||
title,
|
||||
}: {
|
||||
starters: readonly Starter[];
|
||||
onPick: (prompt: string) => void;
|
||||
title?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="ck-starters">
|
||||
{title && <div className="ck-starters-title">{title}</div>}
|
||||
<div className="ck-starters-list">
|
||||
{starters.map((s, i) => {
|
||||
const label = typeof s === "string" ? s : s.label;
|
||||
const prompt = typeof s === "string" ? s : (s.prompt ?? s.label);
|
||||
return (
|
||||
<button key={i} type="button" className="ck-starter" onClick={() => onPick(prompt)}>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type DependencyList,
|
||||
type RefObject,
|
||||
} 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<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const copy = useCallback(
|
||||
(text: string) => {
|
||||
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: DependencyList, grew: number) {
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const endRef = useRef<HTMLDivElement | null>(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?: RefObject<HTMLElement | null>) {
|
||||
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: RefObject<HTMLTextAreaElement | null>, value: string, 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]);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
/**
|
||||
* 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: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<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 = () => (
|
||||
<Svg>
|
||||
<path d="m5 12 7-7 7 7" />
|
||||
<path d="M12 19V5" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconArrowDown = () => (
|
||||
<Svg>
|
||||
<path d="M12 5v14" />
|
||||
<path d="m19 12-7 7-7-7" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconMic = () => (
|
||||
<Svg>
|
||||
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
|
||||
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
|
||||
<path d="M12 19v3" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconCheck = () => (
|
||||
<Svg>
|
||||
<path d="M20 6 9 17l-5-5" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconX = () => (
|
||||
<Svg>
|
||||
<path d="M18 6 6 18" />
|
||||
<path d="m6 6 12 12" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconStop = () => (
|
||||
<Svg fill="currentColor" stroke="none">
|
||||
<rect x="6" y="6" width="12" height="12" rx="2" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconSpinner = () => (
|
||||
<Svg className="ck-spin">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconCopy = () => (
|
||||
<Svg>
|
||||
<rect width="14" height="14" x="8" y="8" rx="2" />
|
||||
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconRetry = () => (
|
||||
<Svg>
|
||||
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||
<path d="M3 3v5h5" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconPaperclip = () => (
|
||||
<Svg>
|
||||
<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" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconFile = () => (
|
||||
<Svg>
|
||||
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
|
||||
<path d="M14 2v4a2 2 0 0 0 2 2h4" />
|
||||
</Svg>
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* @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";
|
||||
@@ -0,0 +1,183 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, type ClipboardEvent } from "react";
|
||||
import {
|
||||
DEFAULT_ATTACHMENT_LIMITS,
|
||||
attachmentKey,
|
||||
isImageMime,
|
||||
stripDataUrlBase64,
|
||||
toWire,
|
||||
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 function useAttachments(limits: Partial<AttachmentLimits> = {}): AttachmentsController {
|
||||
const lim: AttachmentLimits = { ...DEFAULT_ATTACHMENT_LIMITS, ...limits };
|
||||
const { maxFiles, maxImageBytes, maxTextChars } = lim;
|
||||
const [attachments, setAttachments] = useState<StagedAttachment[]>([]);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const previews = useRef<Set<string>>(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: StagedAttachment) =>
|
||||
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: 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: 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: FileList | File[] | null) => {
|
||||
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: ClipboardEvent) => {
|
||||
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: StagedAttachment) => {
|
||||
if (!a.previewUrl) return;
|
||||
URL.revokeObjectURL(a.previewUrl);
|
||||
previews.current.delete(a.previewUrl);
|
||||
};
|
||||
|
||||
const remove = useCallback((key: string) => {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
"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,
|
||||
type DictationPreference,
|
||||
type DictationProblem,
|
||||
} from "../dictation.js";
|
||||
|
||||
type RecognitionLike = {
|
||||
lang: string;
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
abort: () => void;
|
||||
onstart: (() => void) | null;
|
||||
onresult:
|
||||
| ((event: {
|
||||
resultIndex: number;
|
||||
results: ArrayLike<{ isFinal?: boolean } & ArrayLike<{ transcript: string }>>;
|
||||
}) => void)
|
||||
| null;
|
||||
onerror: ((event: { error?: string }) => void) | null;
|
||||
onend: (() => void) | null;
|
||||
};
|
||||
type RecognitionCtor = new () => RecognitionLike;
|
||||
|
||||
function recogniser(): RecognitionCtor | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
const w = window as unknown as {
|
||||
SpeechRecognition?: RecognitionCtor;
|
||||
webkitSpeechRecognition?: RecognitionCtor;
|
||||
};
|
||||
return w.SpeechRecognition ?? w.webkitSpeechRecognition;
|
||||
}
|
||||
|
||||
function canRecord(): boolean {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
typeof MediaRecorder !== "undefined" &&
|
||||
!!navigator.mediaDevices?.getUserMedia
|
||||
);
|
||||
}
|
||||
|
||||
const noSubscribe = () => () => {};
|
||||
|
||||
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
|
||||
* `<html lang>`, 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<string>;
|
||||
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;
|
||||
};
|
||||
|
||||
const DEFAULT_REMEMBER_KEY = "chatkit.dictation.recogniser-dead.v1";
|
||||
|
||||
function readDead(key: string | null): boolean {
|
||||
if (!key) return false;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(key);
|
||||
return deadRecogniserStillTrusted(raw === null ? null : Number(raw));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberDead(key: string | null): void {
|
||||
if (!key) return;
|
||||
try {
|
||||
window.localStorage.setItem(key, String(Date.now()));
|
||||
} catch {
|
||||
/* private mode — the person simply waits again next time */
|
||||
}
|
||||
}
|
||||
|
||||
async function awaitingPermission(): Promise<boolean> {
|
||||
try {
|
||||
const s = await navigator.permissions.query({ name: "microphone" as PermissionName });
|
||||
return s.state === "prompt";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function postAudio(url: string, audio: Blob, locale: string): Promise<string> {
|
||||
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(() => ({}))) as { text?: unknown };
|
||||
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: UseDictationOptions): DictationController {
|
||||
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<DictationStatus>("idle");
|
||||
const [startedAt, setStartedAt] = useState<number | null>(null);
|
||||
const [problem, setProblem] = useState<DictationProblem | null>(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<RecognitionLike | null>(null);
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const cancelledRef = useRef(false);
|
||||
const capTimer = useRef<ReturnType<typeof setTimeout> | null>(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: string) => {
|
||||
const t = said.trim();
|
||||
if (t) optsRef.current.onText(t);
|
||||
else setProblem("silence");
|
||||
}, []);
|
||||
|
||||
const transcribe = useCallback(
|
||||
async (audio: Blob) => {
|
||||
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: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
} catch (e) {
|
||||
setProblem(problemForRecording(e));
|
||||
setStatus("idle");
|
||||
return;
|
||||
}
|
||||
streamRef.current = stream;
|
||||
let rec: MediaRecorder;
|
||||
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: Blob[] = [];
|
||||
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: RecognitionCtor) => {
|
||||
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: string[] = [];
|
||||
let started = false;
|
||||
let handedOff = false;
|
||||
|
||||
const finish = (next: DictationProblem | null) => {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* 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: { scrollHeight: number; scrollTop: number; clientHeight: number },
|
||||
threshold = FOLLOW_THRESHOLD_PX,
|
||||
): boolean {
|
||||
return el.scrollHeight - el.scrollTop - el.clientHeight < threshold;
|
||||
}
|
||||
+689
@@ -0,0 +1,689 @@
|
||||
/*
|
||||
* @bitbaum/chatkit — the look of the one chat.
|
||||
*
|
||||
* Every colour, radius and face is a --ck-* variable. By default they read
|
||||
* @bitbaum/design-tokens' HSL-triplet variables, so apps on those tokens match
|
||||
* without doing anything. An app whose variables are full colours (loki's are
|
||||
* OKLCH under the same names) maps them once — `:root { --ck-bg:
|
||||
* var(--surface-base); … }` — and any other app sets --ck-* to keep its own
|
||||
* look. The BEHAVIOUR is what is shared, and it is not configurable.
|
||||
*
|
||||
* Non-negotiable, and why:
|
||||
* - 16px text in the input and the messages: under 16px iOS zooms the whole
|
||||
* page when the input is focused (loki globals.css).
|
||||
* - 44px touch targets on every control (WCAG 2.5.8, loki's audit).
|
||||
* - Nothing wider than its container at 320px (min-width: 0 on flex rows —
|
||||
* heidi composer.tsx).
|
||||
*/
|
||||
|
||||
:where(:root) {
|
||||
/* Defaults at ZERO specificity on the root: an app's own :root (or any
|
||||
container) rule setting a --ck-* variable always wins. Declaring these on
|
||||
the chat's elements instead would silently override the app. */
|
||||
--ck-bg: hsl(var(--surface-base, 0 0% 100%));
|
||||
--ck-raised: hsl(var(--surface-raised, 0 0% 96%));
|
||||
--ck-overlay: hsl(var(--surface-overlay, 0 0% 98%));
|
||||
--ck-fg: hsl(var(--text-primary, 0 0% 10%));
|
||||
--ck-fg-2: hsl(var(--text-secondary, 0 0% 30%));
|
||||
--ck-fg-3: hsl(var(--text-tertiary, 0 0% 42%));
|
||||
--ck-muted: hsl(var(--text-muted, 0 0% 50%));
|
||||
--ck-line: hsl(var(--border-subtle, 0 0% 90%));
|
||||
--ck-line-2: hsl(var(--border-default, 0 0% 82%));
|
||||
--ck-accent: var(--accent-primary, #ff5c00);
|
||||
--ck-on-accent: hsl(var(--on-accent, 0 0% 8%));
|
||||
--ck-accent-soft: color-mix(in srgb, var(--ck-accent) 14%, transparent);
|
||||
--ck-danger: hsl(var(--status-negative, 0 65% 50%));
|
||||
--ck-danger-soft: color-mix(in srgb, var(--ck-danger) 12%, transparent);
|
||||
--ck-on-danger: #fff;
|
||||
--ck-warning: hsl(var(--status-warning, 38 92% 45%));
|
||||
--ck-radius: 1rem;
|
||||
--ck-radius-sm: var(--radius-control, 0.5rem);
|
||||
--ck-font: var(--font-sans, system-ui, -apple-system, "Segoe UI", sans-serif);
|
||||
--ck-mono: var(--font-mono, ui-monospace, "SF Mono", Menlo, monospace);
|
||||
--ck-text: 1rem;
|
||||
--ck-leading: 1.6;
|
||||
--ck-target: 2.75rem;
|
||||
}
|
||||
|
||||
.ck-composer-wrap,
|
||||
.ck-thread-wrap,
|
||||
.ck-starters {
|
||||
font-family: var(--ck-font);
|
||||
color: var(--ck-fg);
|
||||
}
|
||||
|
||||
.ck-composer-wrap *,
|
||||
.ck-thread-wrap *,
|
||||
.ck-starters * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* ── composer ───────────────────────────────────────────────────────────── */
|
||||
.ck-composer-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-composer-frame {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-composer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
padding: 0.75rem 0.75rem 0.625rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: var(--ck-radius);
|
||||
background: var(--ck-bg);
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
.ck-composer:focus-within {
|
||||
border-color: var(--ck-line-2);
|
||||
}
|
||||
.ck-composer-compact {
|
||||
gap: 0.375rem;
|
||||
padding: 0.5rem;
|
||||
border-radius: calc(var(--ck-radius) * 0.75);
|
||||
}
|
||||
.ck-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 2.5rem;
|
||||
max-height: 15rem;
|
||||
resize: none;
|
||||
overflow-y: auto;
|
||||
padding: 0.375rem 0.25rem;
|
||||
border: 0;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--ck-fg);
|
||||
font: inherit;
|
||||
font-size: max(16px, var(--ck-text));
|
||||
line-height: var(--ck-leading);
|
||||
}
|
||||
.ck-input::placeholder {
|
||||
color: var(--ck-muted);
|
||||
}
|
||||
.ck-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-tools {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-submit {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ck-hint {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--ck-muted);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.ck-hint {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
.ck-icon-btn,
|
||||
.ck-send {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
min-width: var(--ck-target);
|
||||
min-height: var(--ck-target);
|
||||
padding: 0;
|
||||
border-radius: 999px;
|
||||
font-size: 1.125rem;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
color 0.15s ease,
|
||||
border-color 0.15s ease,
|
||||
opacity 0.15s ease;
|
||||
}
|
||||
.ck-icon-btn {
|
||||
border: 1px solid var(--ck-line);
|
||||
background: var(--ck-raised);
|
||||
color: var(--ck-fg-2);
|
||||
}
|
||||
.ck-icon-btn:hover:not(:disabled) {
|
||||
border-color: var(--ck-line-2);
|
||||
color: var(--ck-fg);
|
||||
}
|
||||
.ck-mic-on {
|
||||
border-color: var(--ck-danger);
|
||||
background: var(--ck-danger-soft);
|
||||
color: var(--ck-danger);
|
||||
}
|
||||
.ck-send {
|
||||
border: 0;
|
||||
background: var(--ck-accent);
|
||||
color: var(--ck-on-accent);
|
||||
}
|
||||
.ck-send:hover:not(:disabled) {
|
||||
opacity: 0.9;
|
||||
}
|
||||
.ck-send:disabled,
|
||||
.ck-icon-btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.45;
|
||||
}
|
||||
.ck-send:disabled {
|
||||
background: var(--ck-raised);
|
||||
color: var(--ck-muted);
|
||||
opacity: 1;
|
||||
}
|
||||
.ck-send-stop {
|
||||
background: var(--ck-raised);
|
||||
color: var(--ck-fg);
|
||||
border: 1px solid var(--ck-line-2);
|
||||
}
|
||||
:where(.ck-composer-wrap, .ck-thread-wrap, .ck-starters) button:focus-visible,
|
||||
.ck-input:focus-visible {
|
||||
outline: 2px solid var(--ck-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.ck-input:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
.ck-modes {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.ck-mode {
|
||||
min-height: 2rem;
|
||||
padding: 0 0.75rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--ck-fg-2);
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-mode[aria-pressed="true"] {
|
||||
border-color: var(--ck-accent);
|
||||
background: var(--ck-accent-soft);
|
||||
color: var(--ck-fg);
|
||||
}
|
||||
|
||||
/* voice: the bar covers the box while a take is live, so what is happening —
|
||||
and how to keep or throw it away — is unmissable */
|
||||
.ck-voice-bar {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0 0.75rem;
|
||||
border: 1px solid var(--ck-line-2);
|
||||
border-radius: var(--ck-radius);
|
||||
background: var(--ck-bg);
|
||||
color: var(--ck-fg-2);
|
||||
}
|
||||
.ck-voice-dot {
|
||||
width: 0.625rem;
|
||||
height: 0.625rem;
|
||||
flex-shrink: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--ck-danger);
|
||||
animation: ck-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
.ck-voice-wave {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.25rem;
|
||||
height: 1.75rem;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.ck-voice-wave > span {
|
||||
width: 0.25rem;
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: var(--ck-accent);
|
||||
transform: scaleY(0.3);
|
||||
animation: ck-wave 1s ease-in-out infinite;
|
||||
}
|
||||
.ck-voice-wave > span:nth-child(2n) {
|
||||
animation-delay: -0.3s;
|
||||
}
|
||||
.ck-voice-wave > span:nth-child(3n) {
|
||||
animation-delay: -0.6s;
|
||||
}
|
||||
.ck-voice-wave > span:nth-child(5n) {
|
||||
animation-delay: -0.8s;
|
||||
}
|
||||
.ck-voice-timer {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.9375rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.ck-voice-confirm {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: var(--ck-target);
|
||||
min-height: var(--ck-target);
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--ck-danger);
|
||||
color: var(--ck-on-danger);
|
||||
font-size: 1.125rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-problem {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0.5rem 0.625rem;
|
||||
border: 1px solid color-mix(in srgb, var(--ck-warning) 40%, transparent);
|
||||
border-radius: var(--ck-radius-sm);
|
||||
color: var(--ck-fg-2);
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.ck-problem > span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-problem-x {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
padding: 0.125rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ck-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* attachments */
|
||||
.ck-attach-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.ck-attach-item {
|
||||
position: relative;
|
||||
}
|
||||
.ck-attach-thumb {
|
||||
display: block;
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: var(--ck-radius-sm);
|
||||
}
|
||||
.ck-attach-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
max-width: 11rem;
|
||||
height: 3.5rem;
|
||||
padding: 0 0.5rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: var(--ck-radius-sm);
|
||||
background: var(--ck-raised);
|
||||
color: var(--ck-fg-2);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.ck-attach-remove {
|
||||
position: absolute;
|
||||
top: -0.5rem;
|
||||
right: -0.5rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
border: 1px solid var(--ck-line-2);
|
||||
border-radius: 999px;
|
||||
background: var(--ck-overlay);
|
||||
color: var(--ck-fg-2);
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-attach-remove::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -0.625rem;
|
||||
}
|
||||
.ck-note {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ck-warning);
|
||||
font: inherit;
|
||||
font-size: 0.8125rem;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-truncate {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ── thread ─────────────────────────────────────────────────────────────── */
|
||||
.ck-thread-wrap {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-thread {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
.ck-thread-inner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
margin-top: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-thread-loading {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--ck-muted);
|
||||
}
|
||||
.ck-turn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-turn-user {
|
||||
align-items: flex-end;
|
||||
}
|
||||
.ck-bubble {
|
||||
max-width: min(85%, 42rem);
|
||||
padding: 0.625rem 1rem;
|
||||
border-radius: calc(var(--ck-radius) * 1.25);
|
||||
background: var(--ck-accent-soft);
|
||||
color: var(--ck-fg);
|
||||
font-size: var(--ck-text);
|
||||
line-height: var(--ck-leading);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.ck-speaker {
|
||||
margin-bottom: 0.25rem;
|
||||
color: var(--ck-fg-3);
|
||||
font-family: var(--ck-mono);
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.ck-turn-actions {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.ck-action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
min-height: 2.25rem;
|
||||
padding: 0 0.5rem;
|
||||
border: 0;
|
||||
border-radius: var(--ck-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--ck-muted);
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-action:hover {
|
||||
background: var(--ck-raised);
|
||||
color: var(--ck-fg-2);
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.ck-turn-answer .ck-turn-actions {
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
.ck-turn-answer:hover .ck-turn-actions,
|
||||
.ck-turn-answer:focus-within .ck-turn-actions,
|
||||
.ck-turn-pinned .ck-turn-actions {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.ck-failed {
|
||||
margin: 0;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border: 1px solid color-mix(in srgb, var(--ck-danger) 35%, transparent);
|
||||
border-radius: var(--ck-radius-sm);
|
||||
background: var(--ck-danger-soft);
|
||||
color: var(--ck-fg);
|
||||
font-size: var(--ck-text);
|
||||
}
|
||||
.ck-live {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
color: var(--ck-fg-3);
|
||||
font-size: var(--ck-text);
|
||||
}
|
||||
.ck-dots {
|
||||
display: inline-flex;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.ck-dots > span {
|
||||
width: 0.375rem;
|
||||
height: 0.375rem;
|
||||
border-radius: 999px;
|
||||
background: var(--ck-muted);
|
||||
animation: ck-dot 1.2s ease-in-out infinite;
|
||||
}
|
||||
.ck-dots > span:nth-child(2) {
|
||||
animation-delay: 0.15s;
|
||||
}
|
||||
.ck-dots > span:nth-child(3) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
.ck-stop {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
align-self: flex-start;
|
||||
min-height: 2.25rem;
|
||||
margin-top: 0.5rem;
|
||||
padding: 0 0.875rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--ck-fg-3);
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-stopped {
|
||||
margin: 0;
|
||||
color: var(--ck-muted);
|
||||
}
|
||||
.ck-jump {
|
||||
position: absolute;
|
||||
bottom: 0.75rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--ck-target);
|
||||
height: var(--ck-target);
|
||||
border: 1px solid var(--ck-line-2);
|
||||
border-radius: 999px;
|
||||
background: var(--ck-overlay);
|
||||
color: var(--ck-fg-2);
|
||||
font-size: 1.125rem;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 6px 20px -8px rgb(0 0 0 / 0.35);
|
||||
}
|
||||
|
||||
/* markdown: 16px, readable measure, no leaked ** or > */
|
||||
.ck-md {
|
||||
min-width: 0;
|
||||
color: var(--ck-fg);
|
||||
font-size: var(--ck-text);
|
||||
line-height: var(--ck-leading);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.ck-md > * {
|
||||
margin: 0;
|
||||
}
|
||||
.ck-md > * + * {
|
||||
margin-top: 0.75em;
|
||||
}
|
||||
.ck-md ul,
|
||||
.ck-md ol {
|
||||
padding-left: 1.25em;
|
||||
}
|
||||
.ck-md li + li {
|
||||
margin-top: 0.25em;
|
||||
}
|
||||
.ck-md-h {
|
||||
font-weight: 650;
|
||||
}
|
||||
.ck-md blockquote {
|
||||
padding-left: 0.875em;
|
||||
border-left: 3px solid var(--ck-line-2);
|
||||
color: var(--ck-fg-2);
|
||||
}
|
||||
.ck-md strong {
|
||||
font-weight: 650;
|
||||
}
|
||||
.ck-code {
|
||||
padding: 0.1em 0.35em;
|
||||
border-radius: 0.3em;
|
||||
background: var(--ck-raised);
|
||||
font-family: var(--ck-mono);
|
||||
font-size: 0.875em;
|
||||
}
|
||||
.ck-pre {
|
||||
overflow-x: auto;
|
||||
padding: 0.75rem 0.875rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: var(--ck-radius-sm);
|
||||
background: var(--ck-raised);
|
||||
font-family: var(--ck-mono);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.ck-pre code {
|
||||
white-space: pre;
|
||||
}
|
||||
.ck-link {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--ck-accent);
|
||||
text-underline-offset: 0.18em;
|
||||
}
|
||||
.ck-cite {
|
||||
margin-left: 0.15em;
|
||||
color: var(--ck-muted);
|
||||
font-size: 0.7em;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* starters */
|
||||
.ck-starters {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.ck-starters-title {
|
||||
color: var(--ck-fg-2);
|
||||
font-size: var(--ck-text);
|
||||
}
|
||||
.ck-starters-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.ck-starter {
|
||||
min-height: var(--ck-target);
|
||||
padding: 0.5rem 0.875rem;
|
||||
border: 1px solid var(--ck-line);
|
||||
border-radius: calc(var(--ck-radius) * 0.75);
|
||||
background: var(--ck-bg);
|
||||
color: var(--ck-fg-2);
|
||||
font: inherit;
|
||||
font-size: 0.9375rem;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ck-starter:hover {
|
||||
border-color: var(--ck-accent);
|
||||
color: var(--ck-fg);
|
||||
}
|
||||
|
||||
.ck-spin {
|
||||
animation: ck-spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes ck-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@keyframes ck-pulse {
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
@keyframes ck-wave {
|
||||
50% {
|
||||
transform: scaleY(1);
|
||||
}
|
||||
}
|
||||
@keyframes ck-dot {
|
||||
0%,
|
||||
80%,
|
||||
100% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
40% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ck-spin,
|
||||
.ck-voice-dot,
|
||||
.ck-voice-wave > span,
|
||||
.ck-dots > span {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// The standard, checked in a real browser — the part no unit test can see.
|
||||
//
|
||||
// pnpm run demo && node test/browser.mjs
|
||||
//
|
||||
// Each check is something that shipped broken in at least one fleet chat:
|
||||
// - text and input at 16px (below it iOS zooms the page on focus)
|
||||
// - a microphone in every composer
|
||||
// - every control at least 44px (a thumb has to land on it)
|
||||
// - no horizontal scroll at 390px, light and dark
|
||||
// - the mic still works where the browser's recogniser is silent: headless
|
||||
// Chromium exposes webkitSpeechRecognition with no speech service behind it
|
||||
// — exactly heidi's measured failure — so the press must fall back to
|
||||
// recording, post the audio, and put the words in the box.
|
||||
import { createServer } from "node:http";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { extname, join, normalize } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const types = {
|
||||
".html": "text/html",
|
||||
".js": "text/javascript",
|
||||
".css": "text/css",
|
||||
".woff2": "font/woff2",
|
||||
};
|
||||
const server = createServer(async (req, res) => {
|
||||
const path = normalize(join(root, decodeURIComponent(new URL(req.url, "http://x").pathname)));
|
||||
if (!path.startsWith(root)) return res.writeHead(403).end();
|
||||
try {
|
||||
const body = await readFile(path);
|
||||
res
|
||||
.writeHead(200, { "content-type": types[extname(path)] ?? "application/octet-stream" })
|
||||
.end(body);
|
||||
} catch {
|
||||
res.writeHead(404).end();
|
||||
}
|
||||
}).listen(0);
|
||||
const base = `http://localhost:${server.address().port}/demo/index.html`;
|
||||
|
||||
let failures = 0;
|
||||
const check = (ok, what) => {
|
||||
console.log(`${ok ? "PASS" : "FAIL"} ${what}`);
|
||||
if (!ok) failures++;
|
||||
};
|
||||
|
||||
const browser = await chromium.launch({
|
||||
args: ["--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream"],
|
||||
});
|
||||
try {
|
||||
for (const [name, width, height, dark] of [
|
||||
["desktop light", 1280, 800, false],
|
||||
["desktop dark", 1280, 800, true],
|
||||
["phone dark", 390, 844, true],
|
||||
]) {
|
||||
const page = await browser.newPage({ viewport: { width, height } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.goto(base);
|
||||
if (dark) await page.evaluate(() => document.documentElement.classList.add("dark"));
|
||||
await page.waitForSelector(".ck-input");
|
||||
const m = await page.evaluate(() => {
|
||||
const px = (sel) =>
|
||||
[...document.querySelectorAll(sel)].map((e) => parseFloat(getComputedStyle(e).fontSize));
|
||||
return {
|
||||
overflow: document.documentElement.scrollWidth - window.innerWidth,
|
||||
input: Math.min(...px(".ck-input")),
|
||||
text: Math.min(...px(".ck-md, .ck-bubble")),
|
||||
composers: document.querySelectorAll(".ck-composer").length,
|
||||
mics: document.querySelectorAll(".ck-composer .ck-mic").length,
|
||||
small: [
|
||||
...document.querySelectorAll(".ck-icon-btn, .ck-send, .ck-starter, .ck-voice-confirm"),
|
||||
]
|
||||
.map((e) => e.getBoundingClientRect())
|
||||
.filter((r) => r.width > 0 && (r.width < 44 || r.height < 44)).length,
|
||||
};
|
||||
});
|
||||
check(m.overflow <= 0, `${name}: no horizontal scroll (${m.overflow}px over)`);
|
||||
check(m.input >= 16, `${name}: input text >= 16px (${m.input}px)`);
|
||||
check(m.text >= 16, `${name}: message text >= 16px (${m.text}px)`);
|
||||
check(
|
||||
m.composers > 0 && m.mics === m.composers,
|
||||
`${name}: a mic in every composer (${m.mics}/${m.composers})`,
|
||||
);
|
||||
check(m.small === 0, `${name}: every control >= 44px (${m.small} smaller)`);
|
||||
check(errors.length === 0, `${name}: no page errors ${errors.join(" | ")}`);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
// An app's own variables win: a --ck-* set on :root must reach the chat
|
||||
// (the defaults are declared at zero specificity for exactly this).
|
||||
{
|
||||
const page = await browser.newPage();
|
||||
await page.goto(base);
|
||||
await page.waitForSelector("#conversation .ck-link");
|
||||
const bg = await page.evaluate(() => {
|
||||
document.documentElement.style.setProperty("--ck-accent", "rgb(0, 128, 0)");
|
||||
return getComputedStyle(document.querySelector("#conversation .ck-link")).textDecorationColor;
|
||||
});
|
||||
check(bg === "rgb(0, 128, 0)", `an app's :root --ck-accent reaches the chat (${bg})`);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
const context = await browser.newContext({ permissions: ["microphone"] });
|
||||
const page = await context.newPage();
|
||||
let posted = 0;
|
||||
await page.route("**/api/transcribe", async (route) => {
|
||||
posted = route.request().postDataBuffer()?.length ?? 0;
|
||||
await route.fulfill({
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ text: "hello from the mic" }),
|
||||
});
|
||||
});
|
||||
await page.goto(base);
|
||||
const box = page.locator("#empty");
|
||||
await box.locator(".ck-mic").click();
|
||||
check(await box.locator(".ck-voice-bar").isVisible(), "mic: pressing it shows the recording bar");
|
||||
// Past the silent-recogniser watchdog (4 s): it must now be recording.
|
||||
await page.waitForTimeout(5500);
|
||||
await box.locator(".ck-voice-confirm").click();
|
||||
await page
|
||||
.waitForFunction(() => document.querySelector("#empty .ck-input")?.value !== "", null, {
|
||||
timeout: 5000,
|
||||
})
|
||||
.catch(() => {});
|
||||
check(
|
||||
posted > 0,
|
||||
`mic: a silent recogniser falls back to recording and posts the audio (${posted} bytes)`,
|
||||
);
|
||||
check(
|
||||
(await box.locator(".ck-input").inputValue()) === "hello from the mic",
|
||||
"mic: the spoken sentence lands in the input",
|
||||
);
|
||||
await context.close();
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
if (failures) {
|
||||
console.log(`\n${failures} browser check(s) failed`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("\nall browser checks passed");
|
||||
@@ -0,0 +1,129 @@
|
||||
// The decisions every chat must make the same way. Each case is a bug that
|
||||
// already shipped somewhere in the fleet.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
appendTranscript,
|
||||
composerCanSend,
|
||||
composerOutgoingText,
|
||||
deadRecogniserStillTrusted,
|
||||
fallbackCanRescue,
|
||||
formatElapsed,
|
||||
isFollowing,
|
||||
mayKeepWaitingForPermission,
|
||||
parseBlocks,
|
||||
parseInline,
|
||||
problemFor,
|
||||
problemForRecording,
|
||||
safeHref,
|
||||
shouldClearDraft,
|
||||
toWire,
|
||||
DEAD_RECOGNISER_TTL_MS,
|
||||
PERMISSION_WAIT_MS,
|
||||
} from "../dist/index.js";
|
||||
|
||||
test("send: empty text cannot send; a screenshot alone only where the app said what it means", () => {
|
||||
const base = { attachmentCount: 0, sending: false, disabled: false, blocked: false };
|
||||
assert.equal(composerCanSend({ ...base, text: " " }), false);
|
||||
assert.equal(composerCanSend({ ...base, text: "hi" }), true);
|
||||
assert.equal(composerCanSend({ ...base, text: "", attachmentCount: 1 }), false);
|
||||
assert.equal(
|
||||
composerCanSend({ ...base, text: "", attachmentCount: 1, attachmentOnlyText: "See image" }),
|
||||
true,
|
||||
);
|
||||
assert.equal(composerCanSend({ ...base, text: "hi", sending: true }), false);
|
||||
assert.equal(composerOutgoingText("", 1, "See image"), "See image");
|
||||
assert.equal(composerOutgoingText(" hi ", 0), "hi");
|
||||
});
|
||||
|
||||
test("a failed send keeps the draft", () => {
|
||||
assert.equal(shouldClearDraft(false), false);
|
||||
assert.equal(shouldClearDraft(undefined), true);
|
||||
assert.equal(shouldClearDraft(true), true);
|
||||
});
|
||||
|
||||
test("dictated words join the draft with one space", () => {
|
||||
assert.equal(appendTranscript("", " hello "), "hello");
|
||||
assert.equal(appendTranscript("I want", "to earn"), "I want to earn");
|
||||
assert.equal(appendTranscript("I want ", "to earn"), "I want to earn");
|
||||
assert.equal(appendTranscript("keep", " "), "keep");
|
||||
assert.equal(formatElapsed(75.9), "1:15");
|
||||
assert.equal(formatElapsed(-3), "0:00");
|
||||
});
|
||||
|
||||
test("mic: only 'unavailable' is rescued by recording; mic and silence are real answers", () => {
|
||||
assert.equal(fallbackCanRescue("unavailable"), true);
|
||||
assert.equal(fallbackCanRescue("mic"), false);
|
||||
assert.equal(fallbackCanRescue("silence"), false);
|
||||
assert.equal(problemFor("not-allowed"), "mic");
|
||||
assert.equal(problemFor("no-speech"), "silence");
|
||||
assert.equal(problemFor("network"), "unavailable");
|
||||
assert.equal(problemFor("something-new"), "unavailable", "unknown is never nothing");
|
||||
assert.equal(problemFor("aborted"), null);
|
||||
assert.equal(problemForRecording({ name: "NotAllowedError" }), "mic");
|
||||
assert.equal(problemForRecording({ name: "NotFoundError" }), "mic");
|
||||
assert.equal(problemForRecording(new Error("x")), "unavailable");
|
||||
});
|
||||
|
||||
test("mic: a pending permission never holds the fallback forever (heidi: 22 s, nothing)", () => {
|
||||
assert.equal(mayKeepWaitingForPermission(0, true), true);
|
||||
assert.equal(mayKeepWaitingForPermission(PERMISSION_WAIT_MS, true), false);
|
||||
assert.equal(mayKeepWaitingForPermission(10, false), false);
|
||||
});
|
||||
|
||||
test("mic: a dead recogniser is remembered for a while, not forever, not from the future", () => {
|
||||
const now = 1_000_000_000_000;
|
||||
assert.equal(deadRecogniserStillTrusted(null, now), false);
|
||||
assert.equal(deadRecogniserStillTrusted(now - 1000, now), true);
|
||||
assert.equal(deadRecogniserStillTrusted(now - DEAD_RECOGNISER_TTL_MS, now), false);
|
||||
assert.equal(deadRecogniserStillTrusted(now + 5000, now), false);
|
||||
assert.equal(deadRecogniserStillTrusted(Number.NaN, now), false);
|
||||
});
|
||||
|
||||
test("scroll: follow only while at the bottom", () => {
|
||||
assert.equal(isFollowing({ scrollHeight: 1000, scrollTop: 900, clientHeight: 90 }), true);
|
||||
assert.equal(isFollowing({ scrollHeight: 1000, scrollTop: 200, clientHeight: 90 }), false);
|
||||
});
|
||||
|
||||
test("markdown: no literal ** or > leaks; lists, code and headings parse", () => {
|
||||
const blocks = parseBlocks(
|
||||
"# Title\nSome **bold** text\n\n- one\n- two\n1. first\n> quoted\n```js\nconst a = 1;\n```",
|
||||
);
|
||||
assert.deepEqual(
|
||||
blocks.map((b) => b.kind),
|
||||
["h", "p", "ul", "ol", "quote", "code"],
|
||||
);
|
||||
const inline = parseInline("Some **bold** and *em* and `code` [site](https://x.ch) [F1]");
|
||||
assert.deepEqual(
|
||||
inline.filter((s) => s.kind !== "text").map((s) => s.kind),
|
||||
["strong", "em", "code", "link", "cite"],
|
||||
);
|
||||
assert.ok(!inline.some((s) => s.kind === "text" && s.text.includes("**")));
|
||||
});
|
||||
|
||||
test("markdown: a streaming, unclosed code fence still renders as code", () => {
|
||||
const blocks = parseBlocks("Here:\n```\nnpm i");
|
||||
assert.equal(blocks.at(-1).kind, "code");
|
||||
});
|
||||
|
||||
test("links: javascript: from a model is text, never a link", () => {
|
||||
assert.equal(safeHref("javascript:alert(1)"), null);
|
||||
assert.equal(safeHref("//evil.example"), null);
|
||||
assert.equal(safeHref("/work/"), "/work/");
|
||||
assert.equal(safeHref("https://orangecat.ch"), "https://orangecat.ch/");
|
||||
const spans = parseInline("[click](javascript:alert(1))");
|
||||
assert.ok(spans.every((s) => s.kind !== "link"));
|
||||
});
|
||||
|
||||
test("bare https URLs in an answer become links, without trailing punctuation", () => {
|
||||
const spans = parseInline("See https://heidi.orangecat.ch.");
|
||||
const link = spans.find((s) => s.kind === "link");
|
||||
assert.equal(link?.href, "https://heidi.orangecat.ch/");
|
||||
});
|
||||
|
||||
test("attachments: the wire never carries a preview URL", () => {
|
||||
const wire = toWire([
|
||||
{ kind: "image", name: "a.png", mimeType: "image/png", dataBase64: "AA", previewUrl: "blob:x" },
|
||||
]);
|
||||
assert.equal("previewUrl" in wire[0], false);
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
// The components render on the server (Next RSC/SSR) and carry the parts the
|
||||
// standard requires. Rendered to a string: a chat that cannot even render
|
||||
// without a browser is a chat that breaks every Next page it is put on.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createElement as h } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { Composer, ChatThread, ChatStarters, Markdown } from "../dist/react/index.js";
|
||||
|
||||
test("composer: textarea, send, and 16px guaranteed by the stylesheet", () => {
|
||||
const html = renderToStaticMarkup(h(Composer, { onSend: () => {}, placeholder: "Ask" }));
|
||||
assert.match(html, /<textarea[^>]*class="ck-input"/);
|
||||
assert.match(html, /aria-label="Send"/);
|
||||
const css = readFileSync(new URL("../styles.css", import.meta.url), "utf8");
|
||||
assert.match(
|
||||
css,
|
||||
/\.ck-input\s*\{[^}]*font-size:\s*max\(16px/,
|
||||
"input must be >= 16px (iOS zoom)",
|
||||
);
|
||||
assert.match(css, /\.ck-md\s*\{[^}]*font-size:\s*var\(--ck-text\)/);
|
||||
assert.match(css, /--ck-text:\s*1rem/);
|
||||
});
|
||||
|
||||
test("composer: labels are translatable (heidi is not in English)", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
h(Composer, { onSend: () => {}, placeholder: "Frag", labels: { send: "Senden" } }),
|
||||
);
|
||||
assert.match(html, /aria-label="Senden"/);
|
||||
});
|
||||
|
||||
test("thread: names who speaks once two agents answer, and offers retry on the last answer", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
h(ChatThread, {
|
||||
messages: [
|
||||
{ id: "1", role: "user", content: "I want to earn" },
|
||||
{
|
||||
id: "2",
|
||||
role: "assistant",
|
||||
content: "Use **OrangeCat**.",
|
||||
speaker: { name: "Cat", id: "cat" },
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
role: "assistant",
|
||||
content: "I can build it.",
|
||||
speaker: { name: "Loki", id: "loki" },
|
||||
},
|
||||
],
|
||||
onRetry: () => {},
|
||||
}),
|
||||
);
|
||||
assert.match(html, /ck-speaker">Cat</);
|
||||
assert.match(html, /ck-speaker">Loki</);
|
||||
assert.match(html, /<strong>OrangeCat<\/strong>/);
|
||||
assert.equal((html.match(/Try again/g) ?? []).length, 1, "retry only on the last answer");
|
||||
assert.match(html, /ck-from-cat/);
|
||||
});
|
||||
|
||||
test("thread: a failed turn says so, with retry — never silence", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
h(ChatThread, {
|
||||
messages: [
|
||||
{ id: "1", role: "user", content: "hi" },
|
||||
{ id: "2", role: "assistant", content: "", failed: true },
|
||||
],
|
||||
onRetry: () => {},
|
||||
}),
|
||||
);
|
||||
assert.match(html, /ck-failed/);
|
||||
assert.match(html, /ck-turn-pinned/, "a failed turn never hides its Retry behind a hover");
|
||||
assert.match(html, /Try again/);
|
||||
});
|
||||
|
||||
test("thread: empty shows the starters, live shows stop", () => {
|
||||
const empty = renderToStaticMarkup(
|
||||
h(ChatThread, {
|
||||
messages: [],
|
||||
empty: h(ChatStarters, { starters: ["What can you build?"], onPick: () => {} }),
|
||||
}),
|
||||
);
|
||||
assert.match(empty, /What can you build\?/);
|
||||
const live = renderToStaticMarkup(
|
||||
h(ChatThread, {
|
||||
messages: [{ id: "1", role: "user", content: "x" }],
|
||||
live: {},
|
||||
onStop: () => {},
|
||||
}),
|
||||
);
|
||||
assert.match(live, /ck-stop/);
|
||||
});
|
||||
|
||||
test("markdown never renders model text as HTML", () => {
|
||||
const html = renderToStaticMarkup(h(Markdown, { text: "<img src=x onerror=alert(1)> **ok**" }));
|
||||
assert.ok(!html.includes("<img"), "raw HTML must be escaped");
|
||||
assert.match(html, /<img/);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"types": ["node"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
Reference in new issue
Block a user