Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/book/layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,21 @@ describe("the wrap cache while a paragraph grows", () => {
});
});

describe("when a paragraph takes no drop cap", () => {
const drop = { lines: 3, width: 4 };
it("sets a paragraph shorter than the drop cap without one", () => {
const lines = wrapParagraph({ text: "One short line.", measure, width: 60, drop });
expect(lines.map((l) => [l.drop, l.besideDrop, l.text])).toEqual([[undefined, false, "One short line."]]);
});
it("sets none before an apostrophe or on a mark that is not a letter", () => {
const long = " look at the existing code first, then the conventions, then write the change and say why it fits the rest of the file.";
for (const text of [`I'll${long}`, `I’ve${long}`, `"Quoted${long}`]) {
expect(wrapParagraph({ text, measure, width: 60, drop }).some((l) => l.drop || l.besideDrop)).toBe(false);
}
expect(wrapParagraph({ text: `It${long}`, measure, width: 60, drop })[0].drop).toBe("I");
});
});

describe("lines beside the drop cap", () => {
it("leave the cap's width and the page's gap beside it", () => {
expect(DROP_GAP).toBe(8);
Expand Down Expand Up @@ -420,7 +435,8 @@ describe("reasoning in a part still streaming", () => {
expect(paginateChapter(chapter(text), opts).flatMap((page) => page.lines)).toEqual([]);
}
const tag = paginateChapter(chapter("<b> is bold"), opts).flatMap((page) => page.lines);
expect(tag.map((l) => [l.drop, l.text])).toEqual([["<", "b> is bold"]]);
// Shown as sent; a tag is no letter for a drop cap.
expect(tag.map((l) => [l.drop, l.text])).toEqual([[undefined, "<b> is bold"]]);
});
});

Expand Down
8 changes: 8 additions & 0 deletions src/book/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ describe("footnotes for opencode 2.0 tools", () => {
expect(footnoteSentence({ ...edit, status: "running" }).text).toBe("Editing src/greet.ts…");
});

it("words code mode's execute call as a script", () => {
expect(footnoteSentence({ tool: "execute", status: "running", input: { code: "await tools.read({})" } }).text).toBe("Running a script…");
expect(footnoteSentence({ tool: "execute", status: "completed", input: { code: "text(1)" } }).text).toBe("Ran a script.");
expect(footnoteSentence({ tool: "execute", status: "error", error: "Unknown tool 'shell'." }).text).toBe(
"The script failed: Unknown tool 'shell'.",
);
});

it("reads path as well as filePath", () => {
expect(footnoteSentence({ tool: "read", input: { path: "src/greet.ts" }, status: "completed" }).text).toBe(
"Read src/greet.ts.",
Expand Down
7 changes: 7 additions & 0 deletions src/book/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ export function footnoteSentence(
return { text: asked ? `Asked a question: ${sentence(asked)}` : "Asked a question.", opensPlate: false };
}

if (name === "execute") {
// opencode's code mode: a short script that calls other tools.
if (tool.status === "running" || tool.status === "pending") return { text: "Running a script…", opensPlate: false };
if (tool.status === "error") return { text: sentence(`The script failed${reason(tool.error)}`), opensPlate: false };
return { text: "Ran a script.", opensPlate: false };
}

if (name === "webfetch") {
const url = firstString(tool.input, ["url"]) ?? "a page";
if (tool.status === "running" || tool.status === "pending") return { text: `Fetching ${url}…`, opensPlate: false };
Expand Down
8 changes: 7 additions & 1 deletion src/book/wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export function wrapParagraph(opts: {
const source = opts.text.replace(/\s+/g, " ").trim();
if (!source) return [];

const drop = opts.drop;
// A drop cap is a letter or a figure, and never one before an apostrophe: "I'll" would be
// set as a lone "I" beside "'ll".
const drop = opts.drop && /^[\p{L}\p{N}](?!['’])/u.test(source) ? opts.drop : undefined;
const dropChar = drop ? source.slice(0, 1) : "";
const body = drop ? source.slice(1).trimStart() : source;
const bodyShift = source.length - body.length;
Expand All @@ -57,6 +59,10 @@ export function wrapParagraph(opts: {
index += count;
}

// A paragraph shorter than the drop cap would leave the letter cut off at its line's foot;
// it is set without one.
if (drop && draft.length > 0 && draft.length < drop.lines) return wrapParagraph({ ...opts, drop: undefined });

const lines: WrappedLine[] = draft.map((line, lineNo) => ({
text: line.text,
justify: lineNo < draft.length - 1 && line.text.includes(" "),
Expand Down
7 changes: 7 additions & 0 deletions src/engine/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ describe("EngineClient against the replay press", () => {
expect(requests.at(-1)?.body).toEqual({ title: "Untitled", location: { directory: "/book" }, permissions: rules });
});

it("leaves the title out when none is given, so the press can name the session", async () => {
const { url, requests } = await press();
const client = new EngineClient(url, { password: "pw" });
await client.createSession({ directory: "/book" });
expect(requests.at(-1)?.body).toEqual({ location: { directory: "/book" } });
});

it("returns the user message id from a prompt and streams the turn unfiltered", async () => {
const { url, requests } = await press();
const client = new EngineClient(url, { password: "pw" });
Expand Down
6 changes: 4 additions & 2 deletions src/engine/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,15 @@ export class EngineClient {
}

async createSession(input: {
title: string;
/** Left out, the press names the session from its first turn. */
title?: string;
directory: string;
agent?: string;
model?: ModelRef;
permissions?: PermissionRule[];
}): Promise<SessionInfo> {
const body: Record<string, unknown> = { title: input.title, location: { directory: input.directory } };
const body: Record<string, unknown> = { location: { directory: input.directory } };
if (input.title) body.title = input.title;
if (input.agent) body.agent = input.agent;
if (input.model) body.model = { providerID: input.model.providerID, id: input.model.id };
if (input.permissions) body.permissions = input.permissions;
Expand Down
2 changes: 1 addition & 1 deletion src/state/press.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,8 @@ export async function openChapter(
directory: string,
opts: { askBeforeWrite: boolean; model?: ModelRef | null } & Notices,
): Promise<SessionInfo> {
// No title: a session made with one is never named by the press, so every chapter stayed "Untitled".
const session = await client.createSession({
title: "Untitled",
directory,
permissions: opts.askBeforeWrite ? ASK_RULES : undefined,
model: opts.model ?? undefined,
Expand Down
4 changes: 4 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@ button:focus-visible, textarea:focus-visible, input:focus-visible {
}
.line.justify { text-align: justify; text-align-last: justify; }
.line.ragged, .ragged .line.justify { text-align: left; text-align-last: auto; }
/* Handwriting is never spaced out to the margin. */
.line.ink.justify { text-align: left; text-align-last: auto; }
.line.ink, .quill, .ink-line, .chip {
font-family: Caveat, cursive;
color: var(--quill);
Expand All @@ -280,6 +282,8 @@ button:focus-visible, textarea:focus-visible, input:focus-visible {
.em { font-style: italic; }
.hl { background: linear-gradient(var(--highlight), var(--highlight)); }
.fn-mark, .fn-num { color: var(--terra); font-size: 0.72em; margin-left: 1px; }
/* Raised without growing the line box, so a line with marks keeps its baseline. */
.fn-mark { line-height: 0; vertical-align: baseline; position: relative; top: -0.5em; }
.fn-num { margin-right: 8px; font-style: normal; }

.foot { flex: none; }
Expand Down
20 changes: 20 additions & 0 deletions src/ui/Forms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,26 @@ const question: Form = {
};

describe("FormView", () => {
it("sets the press's Markdown in italics rather than showing it raw", () => {
const html = render({
id: "frm",
title: "Questions",
fields: [
{
key: "q0",
title: "Greeting language",
description: "Which language should `greet` use?",
type: "string",
options: [{ value: "Keep", label: "Keep English", description: "Matches the *existing* `shout` helper." }],
},
],
});
expect(html).not.toContain("`");
expect(html).not.toContain("*existing*");
expect(html).toContain("Which language should <em>greet</em> use?");
expect(html).toContain("Matches the <em>existing</em> <em>shout</em> helper.");
});

it("sets each option's description as a quiet line beneath it", () => {
const html = render(question);
expect(html).toContain('class="form-options described"');
Expand Down
33 changes: 27 additions & 6 deletions src/ui/Forms.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useId, useState } from "react";
import { useId, useState, type ReactNode } from "react";
import { toProse } from "../book/emphasis";
import { formAnswer, type FormReply, type FormValue, type FormValues } from "../book/forms";
import type { Form, FormField } from "../book/model";

Expand All @@ -24,8 +25,14 @@ export function FormView({ form, onSend, onSkip }: { form: Form; onSend: (answer
>
{form.fields.map((field) => (
<fieldset key={field.key} className="form-field">
<legend>{field.title}</legend>
{field.description ? <p className="form-desc">{field.description}</p> : null}
<legend>
<Inline text={field.title} />
</legend>
{field.description ? (
<p className="form-desc">
<Inline text={field.description} />
</p>
) : null}
<FieldInput field={field} value={values[field.key]} onChange={(value) => set(field.key, value)} />
</fieldset>
))}
Expand All @@ -42,6 +49,20 @@ export function FormView({ form, onSend, onSkip }: { form: Form; onSend: (answer
);
}

/** The press writes Markdown: `code` and *emphasis* are set in italics, as on the page, never shown raw. */
function Inline({ text }: { text: string }) {
const { text: plain, italics } = toProse(text);
const out: ReactNode[] = [];
let at = 0;
for (const [from, to] of italics) {
if (from > at) out.push(plain.slice(at, from));
out.push(<em key={from}>{plain.slice(from, to)}</em>);
at = to;
}
if (at < plain.length) out.push(plain.slice(at));
return <>{out}</>;
}

function FieldInput({ field, value, onChange }: { field: FormField; value: FormValue; onChange: (value: FormValue) => void }) {
const descBase = useId();
// With any option described, the options stand one above another, each with its quiet line beneath.
Expand All @@ -51,7 +72,7 @@ function FieldInput({ field, value, onChange }: { field: FormField; value: FormV
const desc = (description: string | undefined, index: number) =>
description ? (
<span className="form-option-desc" id={descId(index)}>
{description}
<Inline text={description} />
</span>
) : null;
if (field.type === "boolean") {
Expand Down Expand Up @@ -80,7 +101,7 @@ function FieldInput({ field, value, onChange }: { field: FormField; value: FormV
onChange(event.target.checked ? [...picked, option.value] : picked.filter((item) => item !== option.value))
}
/>
{option.label}
<Inline text={option.label} />
</label>
{desc(option.description, index)}
</span>
Expand Down Expand Up @@ -117,7 +138,7 @@ function FieldInput({ field, value, onChange }: { field: FormField; value: FormV
aria-describedby={option.description ? descId(index) : undefined}
onClick={() => onChange(option.value)}
>
{option.label}
<Inline text={option.label} />
</button>
{desc(option.description, index)}
</span>
Expand Down
12 changes: 12 additions & 0 deletions src/ui/lines.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { describe, expect, it } from "vitest";
import { markLabel } from "./lines";

describe("footnote marks on a line", () => {
it("never let a run read as one number", () => {
expect(markLabel([4])).toBe("4");
expect(markLabel([1, 2])).toBe("1,2");
expect(markLabel([3, 4, 5, 6, 7])).toBe("3–7");
expect(markLabel([12, 8, 9, 10])).toBe("8–10,12");
expect(markLabel([12, 13])).toBe("12,13");
});
});
20 changes: 15 additions & 5 deletions src/ui/lines.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ export function LineView({ line, marks }: { line: LaidLine; marks: Range[] }) {
{piece.text}
</span>
))}
{line.notes.map((n) => (
<sup key={n} className="fn-mark">
{n}
</sup>
))}
{line.notes.length ? <sup className="fn-mark">{markLabel(line.notes)}</sup> : null}
</span>
);
return (
Expand All @@ -35,6 +31,20 @@ export function LineView({ line, marks }: { line: LaidLine; marks: Range[] }) {
);
}

/** Footnote marks as one superscript: "1,2", "3–7", "8–10,12", so a run never reads as one number. */
export function markLabel(notes: number[]): string {
const sorted = [...new Set(notes)].sort((a, b) => a - b);
const runs: [number, number][] = [];
for (const n of sorted) {
const run = runs[runs.length - 1];
if (run && n === run[1] + 1) run[1] = n;
else runs.push([n, n]);
}
return runs
.flatMap(([from, to]) => (to - from >= 2 ? [`${from}\u2013${to}`] : from === to ? [`${from}`] : [`${from}`, `${to}`]))
.join(",");
}

function pieceClass(piece: { italic: boolean; mark: boolean }): string {
return [piece.italic ? "em" : "", piece.mark ? "hl" : ""].filter(Boolean).join(" ");
}
Expand Down
Loading