Build an integration with Roam Research
This commit is contained in:
1 parent
63f515b8a6
commit
4022f06d49
12 files changed
+1575
No files matched your search
@@ -10,6 +10,7 @@ import notificationsApp from "./notifications";
|
||||
import calendarApp from "./calendar";
|
||||
import weatherApp from "./weather";
|
||||
import navigateApp from "./navigate";
|
||||
import roamApp from "./roam";
|
||||
import blocksApp from "./blocks";
|
||||
import minesweeperApp from "./minesweeper";
|
||||
import freecellApp from "./freecell";
|
||||
@@ -34,6 +35,7 @@ export const ALL_APPS: readonly AppDefinition[] = [
|
||||
calendarApp,
|
||||
weatherApp,
|
||||
navigateApp,
|
||||
roamApp,
|
||||
blocksApp,
|
||||
minesweeperApp,
|
||||
freecellApp,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
|
||||
|
||||
const roamApp: AppDefinition = {
|
||||
appId: "roam",
|
||||
title: "Roam",
|
||||
icon: "roam",
|
||||
launch: (ctx) =>
|
||||
launchWorkerAppWindow(ctx, {
|
||||
createWorker: () => new Worker("./roam-app.worker"),
|
||||
windowId: "roam:main",
|
||||
title: "Roam",
|
||||
iconLetter: "R",
|
||||
icon: "roam",
|
||||
}),
|
||||
};
|
||||
|
||||
export default roamApp;
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Minimal client for the Roam Research backend API
|
||||
* (https://roamresearch.com/#/app/developer-documentation): pull a page's
|
||||
* block tree, run datalog queries, and apply block writes. Configured by the
|
||||
* Roam graph/token settings; all calls are plain JSON POSTs from the app
|
||||
* worker via fetch.
|
||||
*/
|
||||
import { roamApiTokenSetting, roamGraphNameSetting } from "../../ui/dashboard-settings";
|
||||
|
||||
const API_BASE = "https://api.roamresearch.com";
|
||||
const FETCH_TIMEOUT_MS = 12_000;
|
||||
|
||||
export type RoamBlock = {
|
||||
uid: string;
|
||||
string: string;
|
||||
order: number;
|
||||
/** Roam heading level 1-3, when set on the block. */
|
||||
heading?: number;
|
||||
children: RoamBlock[];
|
||||
};
|
||||
|
||||
export type RoamPage = {
|
||||
uid: string;
|
||||
title: string;
|
||||
children: RoamBlock[];
|
||||
};
|
||||
|
||||
export function isRoamConfigured(): boolean {
|
||||
return roamGraphNameSetting.get().length > 0 && roamApiTokenSetting.get().length > 0;
|
||||
}
|
||||
|
||||
/** Daily-note page uid for a date (Roam's fixed MM-DD-YYYY convention). */
|
||||
export function dailyPageUid(date: Date): string {
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${month}-${day}-${date.getFullYear()}`;
|
||||
}
|
||||
|
||||
/** Daily-note page title for a date, e.g. "August 3rd, 2026". */
|
||||
export function dailyPageTitle(date: Date): string {
|
||||
const months = [
|
||||
"January", "February", "March", "April", "May", "June",
|
||||
"July", "August", "September", "October", "November", "December",
|
||||
];
|
||||
const day = date.getDate();
|
||||
const teens = day % 100 >= 11 && day % 100 <= 13;
|
||||
const suffix = teens ? "th" : day % 10 === 1 ? "st" : day % 10 === 2 ? "nd" : day % 10 === 3 ? "rd" : "th";
|
||||
return `${months[date.getMonth()]} ${day}${suffix}, ${date.getFullYear()}`;
|
||||
}
|
||||
|
||||
/** Pull a page (or block) and its whole subtree; null when the uid doesn't exist. */
|
||||
export async function fetchPageByUid(uid: string): Promise<RoamPage | null> {
|
||||
const selector = "[:block/uid :node/title :block/string :block/order :block/heading {:block/children ...}]";
|
||||
const response = await roamPost("pull", { eid: `[:block/uid "${uid.replace(/["\\]/g, "")}"]`, selector });
|
||||
const pulled = response?.result;
|
||||
if (!pulled) return null;
|
||||
return {
|
||||
uid: pulled[":block/uid"] ?? uid,
|
||||
title: pulled[":node/title"] ?? pulled[":block/string"] ?? "",
|
||||
children: pulledChildren(pulled),
|
||||
};
|
||||
}
|
||||
|
||||
/** Look up a page's uid by exact title; null when no such page exists. */
|
||||
export async function findPageUidByTitle(title: string): Promise<string | null> {
|
||||
const response = await roamPost("q", {
|
||||
query: "[:find ?uid :in $ ?title :where [?p :node/title ?title] [?p :block/uid ?uid]]",
|
||||
args: [title],
|
||||
});
|
||||
const rows = response?.result;
|
||||
return Array.isArray(rows) && rows.length > 0 ? String(rows[0][0]) : null;
|
||||
}
|
||||
|
||||
export async function updateBlockString(uid: string, text: string): Promise<void> {
|
||||
await roamPost("write", { action: "update-block", block: { uid, string: text } });
|
||||
}
|
||||
|
||||
export async function createBlock(parentUid: string, order: number | "last", text: string): Promise<void> {
|
||||
await roamPost("write", {
|
||||
action: "create-block",
|
||||
location: { "parent-uid": parentUid, order },
|
||||
block: { string: text },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPage(title: string, uid?: string): Promise<void> {
|
||||
const page: Record<string, string> = { title };
|
||||
if (uid) page.uid = uid;
|
||||
await roamPost("write", { action: "create-page", page });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Transport
|
||||
|
||||
// The API 308-redirects each request to a per-graph peer host. Whether the
|
||||
// HTTP stack replays the POST across hosts varies, so on a redirect status we
|
||||
// follow the Location header ourselves and remember the peer for next time.
|
||||
// The token rides in x-authorization as well, because Authorization is what
|
||||
// redirect-following stacks are most likely to strip.
|
||||
let cachedPeerBase: string | null = null;
|
||||
|
||||
async function roamPost(endpoint: "q" | "pull" | "write", body: object): Promise<any> {
|
||||
const graph = roamGraphNameSetting.get();
|
||||
const token = roamApiTokenSetting.get();
|
||||
if (!graph || !token) {
|
||||
throw new Error("Set the Roam graph name and API token in Settings > Roam.");
|
||||
}
|
||||
const path = `/api/graph/${encodeURIComponent(graph)}/${endpoint}`;
|
||||
const payload = JSON.stringify(body);
|
||||
|
||||
let base = cachedPeerBase ?? API_BASE;
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchWithTimeout(`${base}${path}`, payload, token);
|
||||
} catch (error) {
|
||||
if (base !== API_BASE) {
|
||||
// A stale peer host is the likely cause; retry once from the top.
|
||||
cachedPeerBase = null;
|
||||
base = API_BASE;
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Roam API request failed: ${(error as Error)?.message ?? error}`);
|
||||
}
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
const location = response.headers?.get?.("Location") ?? response.headers?.get?.("location");
|
||||
if (!location) throw new Error(`Roam API redirected without a Location header (HTTP ${response.status}).`);
|
||||
const match = /^(https:\/\/[^/]+)/.exec(location);
|
||||
if (!match) throw new Error(`Roam API redirect target not understood: ${location}`);
|
||||
cachedPeerBase = match[1]!;
|
||||
base = cachedPeerBase;
|
||||
continue;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(await describeHttpError(response));
|
||||
}
|
||||
try {
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null; // Writes may return an empty body.
|
||||
}
|
||||
}
|
||||
throw new Error("Roam API request failed: too many redirects.");
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, payload: string, token: string): Promise<Response> {
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
const request = fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
Authorization: `Bearer ${token}`,
|
||||
"x-authorization": `Bearer ${token}`,
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
timeoutHandle = setTimeout(() => reject(new Error("timed out")), FETCH_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([request, timeout]);
|
||||
} finally {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
|
||||
async function describeHttpError(response: Response): Promise<string> {
|
||||
if (response.status === 401) return "Roam API rejected the token (check Settings > Roam).";
|
||||
if (response.status === 404) return "Roam graph not found (check the graph name in Settings > Roam).";
|
||||
if (response.status === 429) return "Roam API rate limit hit; try again shortly.";
|
||||
if (response.status === 503) return "Roam graph is not ready yet; try again shortly.";
|
||||
let detail = "";
|
||||
try {
|
||||
const body = await response.json();
|
||||
detail = body?.message ? `: ${body.message}` : "";
|
||||
} catch {
|
||||
// Body wasn't JSON; the status alone will do.
|
||||
}
|
||||
return `Roam API error (HTTP ${response.status})${detail}`;
|
||||
}
|
||||
|
||||
function pulledChildren(pulled: any): RoamBlock[] {
|
||||
const children = pulled?.[":block/children"];
|
||||
if (!Array.isArray(children)) return [];
|
||||
const blocks = children.map(pulledBlock);
|
||||
blocks.sort((a, b) => a.order - b.order);
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function pulledBlock(pulled: any): RoamBlock {
|
||||
const block: RoamBlock = {
|
||||
uid: String(pulled?.[":block/uid"] ?? ""),
|
||||
string: String(pulled?.[":block/string"] ?? ""),
|
||||
order: Number(pulled?.[":block/order"] ?? 0),
|
||||
children: pulledChildren(pulled),
|
||||
};
|
||||
const heading = Number(pulled?.[":block/heading"] ?? 0);
|
||||
if (heading >= 1 && heading <= 3) block.heading = heading;
|
||||
return block;
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
/**
|
||||
* Roam app worker. Shows a Roam Research page (today's daily note by default)
|
||||
* as a selectable outline: ring scroll moves the selection, click toggles a
|
||||
* todo or follows a [[page]] link, double-click walks back through visited
|
||||
* pages then yields focus. Edits (check/uncheck, add todo, edit block) go
|
||||
* through the Roam backend API and are also exposed as assistant tools.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { getDefaultSmallFont } from "../../graphics/bdffont";
|
||||
import { truncateText, wrapText } from "../../graphics/textwrap";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import type { DashboardInputEvent } from "../../ui/layers";
|
||||
import type { MenuItem } from "../../ui/menu";
|
||||
import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
|
||||
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
|
||||
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
|
||||
import {
|
||||
GESTURE_CLICK,
|
||||
GESTURE_DOUBLE_CLICK,
|
||||
GESTURE_LONG_PRESS,
|
||||
GESTURE_SCROLL,
|
||||
gestureHints,
|
||||
} from "../../ui/gestures";
|
||||
import { DocumentView } from "../../ui/document/document-view";
|
||||
import { docNodePageLink, type DocNode } from "../../ui/document/document-model";
|
||||
import {
|
||||
createBlock,
|
||||
createPage,
|
||||
dailyPageTitle,
|
||||
dailyPageUid,
|
||||
fetchPageByUid,
|
||||
findPageUidByTitle,
|
||||
isRoamConfigured,
|
||||
updateBlockString,
|
||||
type RoamPage,
|
||||
} from "./roam-api";
|
||||
import {
|
||||
findBlockMatching,
|
||||
findTodoParentUid,
|
||||
flattenBlocks,
|
||||
isTodoBlock,
|
||||
pageToDocument,
|
||||
pageToToolText,
|
||||
plainBlockText,
|
||||
setTodoMarker,
|
||||
} from "./roam-doc";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const HEADER_HEIGHT = 26;
|
||||
const FOOTER_HEIGHT = 18;
|
||||
const DOC_MARGIN = 6;
|
||||
/** Reload the shown page when it is foregrounded and older than this. */
|
||||
const STALE_AFTER_MS = 60_000;
|
||||
|
||||
const smallFont = getDefaultSmallFont();
|
||||
|
||||
type RoamWindow = {
|
||||
windowId: string;
|
||||
surfaceId: string;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
foreground: boolean;
|
||||
focused: boolean;
|
||||
menu: WindowMenu | null;
|
||||
view: DocumentView;
|
||||
lastSubmittedFingerprint: string;
|
||||
};
|
||||
|
||||
type PageRef = { uid: string | null; title: string };
|
||||
|
||||
const ROAM_TOOLS: ToolSpec[] = [
|
||||
{
|
||||
name: "read_page",
|
||||
description:
|
||||
"Read the Roam page currently shown on the glasses (today's daily note by default), as an indented outline. Todo items are marked [ ] (open) or [x] (done).",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
availability: "open",
|
||||
timeoutMs: 14_000,
|
||||
},
|
||||
{
|
||||
name: "add_todo",
|
||||
description: "Add a new TODO item to today's Roam daily page (under its Todo section when one exists).",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { text: { type: "string", description: "The todo item's text." } },
|
||||
required: ["text"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
timeoutMs: 14_000,
|
||||
},
|
||||
{
|
||||
name: "set_todo_done",
|
||||
description:
|
||||
"Check off (or uncheck) a todo item on the Roam page currently shown, found by matching its text. Returns the item's new state.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
match: { type: "string", description: "Text of the todo to change (partial matches allowed)." },
|
||||
done: { type: "boolean", description: "True to mark done (default), false to reopen." },
|
||||
},
|
||||
required: ["match"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
timeoutMs: 14_000,
|
||||
},
|
||||
{
|
||||
name: "edit_block",
|
||||
description:
|
||||
"Rewrite the text of a block on the Roam page currently shown, found by matching its current text. A todo block keeps its todo status.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
match: { type: "string", description: "Current text of the block to edit (partial matches allowed)." },
|
||||
new_text: { type: "string", description: "Replacement text for the block." },
|
||||
},
|
||||
required: ["match", "new_text"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
timeoutMs: 14_000,
|
||||
},
|
||||
];
|
||||
|
||||
let window: RoamWindow | null = null;
|
||||
let screenOn = true;
|
||||
|
||||
let currentPage: RoamPage | null = null;
|
||||
let currentRef: PageRef | null = null;
|
||||
/** The current page exists only locally (an empty daily note not yet in Roam). */
|
||||
let pageMissing = false;
|
||||
let backStack: PageRef[] = [];
|
||||
let loading = false;
|
||||
let errorMessage = "";
|
||||
let lastFetchMs = 0;
|
||||
let loadSerial = 0;
|
||||
|
||||
function post(message: WorkerAppReply): void {
|
||||
global.postMessage(message);
|
||||
}
|
||||
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
surfaceId: message.surfaceId,
|
||||
viewportWidth: message.viewport.width,
|
||||
viewportHeight: message.viewport.height,
|
||||
foreground: false,
|
||||
focused: false,
|
||||
menu: null,
|
||||
view: new DocumentView(
|
||||
message.viewport.width - DOC_MARGIN * 2,
|
||||
message.viewport.height - HEADER_HEIGHT - FOOTER_HEIGHT,
|
||||
),
|
||||
lastSubmittedFingerprint: "",
|
||||
};
|
||||
post({ type: "set-tools", windowId: message.windowId, tools: ROAM_TOOLS });
|
||||
void loadPage(todayRef(), { resetStack: true });
|
||||
break;
|
||||
case "close-window":
|
||||
window = null;
|
||||
break;
|
||||
case "input":
|
||||
if (!window || window.windowId !== message.windowId) {
|
||||
frameTimings.finishFrame(message.frameId, "discarded: unknown roam window");
|
||||
break;
|
||||
}
|
||||
window.focused = message.focused;
|
||||
inferForeground(message.focused);
|
||||
handleInput(window, message.event as DashboardInputEvent, message.frameId);
|
||||
break;
|
||||
case "text-input":
|
||||
// Voice input / typed text becomes a new todo on the shown page.
|
||||
if (message.text.trim()) {
|
||||
void addTodoFromText(message.text.trim());
|
||||
}
|
||||
break;
|
||||
case "render":
|
||||
if (!window) break;
|
||||
window.focused = message.focused;
|
||||
inferForeground(message.focused);
|
||||
render();
|
||||
break;
|
||||
case "foreground":
|
||||
if (!window) break;
|
||||
window.foreground = message.foreground;
|
||||
window.focused = message.focused;
|
||||
if (window.foreground) {
|
||||
maybeRefreshStalePage();
|
||||
render();
|
||||
}
|
||||
break;
|
||||
case "screen":
|
||||
screenOn = message.on;
|
||||
break;
|
||||
case "tool-call": {
|
||||
const callId = message.callId;
|
||||
Promise.resolve(handleRoamTool(message.name, message.args))
|
||||
.then((result) => post({ type: "tool-result", callId, result }))
|
||||
.catch((error) =>
|
||||
post({
|
||||
type: "tool-result",
|
||||
callId,
|
||||
result: { ok: false, error: String((error as Error)?.message ?? error) },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Input and render messages only target the foreground window, so a focused
|
||||
* message proves foreground; backstops a "foreground" message lost while the
|
||||
* freshly spawned worker was still evaluating its bundle.
|
||||
*/
|
||||
function inferForeground(focused: boolean): void {
|
||||
if (!focused || !window || window.foreground) return;
|
||||
window.foreground = true;
|
||||
maybeRefreshStalePage();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Page loading
|
||||
|
||||
function todayRef(): PageRef {
|
||||
const now = new Date();
|
||||
return { uid: dailyPageUid(now), title: dailyPageTitle(now) };
|
||||
}
|
||||
|
||||
async function loadPage(ref: PageRef, options: { resetStack?: boolean; pushCurrent?: boolean } = {}): Promise<void> {
|
||||
if (!isRoamConfigured()) {
|
||||
errorMessage = "";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
const serial = ++loadSerial;
|
||||
if (options.resetStack) backStack = [];
|
||||
if (options.pushCurrent && currentRef) backStack.push(currentRef);
|
||||
currentRef = ref;
|
||||
loading = true;
|
||||
errorMessage = "";
|
||||
render();
|
||||
try {
|
||||
let uid = ref.uid;
|
||||
if (!uid) {
|
||||
uid = await findPageUidByTitle(ref.title);
|
||||
if (serial !== loadSerial) return;
|
||||
if (!uid) throw new Error(`No page named "${ref.title}" in the graph.`);
|
||||
ref.uid = uid;
|
||||
}
|
||||
const page = await fetchPageByUid(uid);
|
||||
if (serial !== loadSerial) return;
|
||||
if (page) {
|
||||
currentPage = page;
|
||||
pageMissing = false;
|
||||
} else if (uid === dailyPageUid(new Date())) {
|
||||
// Today's daily note isn't created until something is written to it.
|
||||
currentPage = { uid, title: ref.title, children: [] };
|
||||
pageMissing = true;
|
||||
} else {
|
||||
throw new Error(`Page "${ref.title}" no longer exists.`);
|
||||
}
|
||||
lastFetchMs = Date.now();
|
||||
window?.view.setDocument(pageToDocument(currentPage));
|
||||
} catch (error) {
|
||||
if (serial !== loadSerial) return;
|
||||
errorMessage = String((error as Error)?.message ?? error);
|
||||
} finally {
|
||||
if (serial === loadSerial) {
|
||||
loading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadCurrentPage(): Promise<void> {
|
||||
if (currentRef) await loadPage({ ...currentRef }, {});
|
||||
}
|
||||
|
||||
function maybeRefreshStalePage(): void {
|
||||
if (loading || !currentRef || !isRoamConfigured()) return;
|
||||
if (Date.now() - lastFetchMs < STALE_AFTER_MS) return;
|
||||
void reloadCurrentPage();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Input
|
||||
|
||||
function windowMenu(win: RoamWindow): WindowMenu {
|
||||
if (!win.menu) {
|
||||
win.menu = new WindowMenu({
|
||||
size: { width: win.viewportWidth, height: win.viewportHeight },
|
||||
paintBase: () => paintContent(win),
|
||||
isFocused: () => win.focused,
|
||||
});
|
||||
}
|
||||
return win.menu;
|
||||
}
|
||||
|
||||
function menuItems(win: RoamWindow): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
const today = todayRef();
|
||||
if (currentRef?.uid !== today.uid) {
|
||||
items.push({
|
||||
label: "Today's page",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
void loadPage(today, { resetStack: true });
|
||||
},
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
label: "Refresh",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
void reloadCurrentPage();
|
||||
},
|
||||
});
|
||||
if (backStack.length > 0) {
|
||||
items.push({
|
||||
label: "Back",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
goBack();
|
||||
},
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
label: "Roam settings",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
post({ type: "open-settings", section: "Roam" });
|
||||
},
|
||||
});
|
||||
return [...items, ...defaultWindowMenuItems(win.windowId, post)];
|
||||
}
|
||||
|
||||
function handleInput(win: RoamWindow, event: DashboardInputEvent, frameId: number): void {
|
||||
if (win.menu?.isOpen()) {
|
||||
win.menu
|
||||
.handleInput(event)
|
||||
.catch((error) => console.error(`roam menu input failed: ${error}`))
|
||||
.then(() => renderAndSubmit(win, frameId));
|
||||
return;
|
||||
}
|
||||
if (event.type === "long-press") {
|
||||
windowMenu(win).open(menuItems(win));
|
||||
renderAndSubmit(win, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type === "double-click") {
|
||||
if (backStack.length > 0) {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam back navigation");
|
||||
goBack();
|
||||
} else {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam yielded focus");
|
||||
post({ type: "yield-focus", windowId: win.windowId });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
win.view.moveSelection(event.type === "scroll-down" ? 1 : -1);
|
||||
renderAndSubmit(win, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type === "click") {
|
||||
if (errorMessage) {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam retry");
|
||||
void reloadCurrentPage();
|
||||
return;
|
||||
}
|
||||
const node = win.view.selectedNode();
|
||||
if (node?.kind === "todo") {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam todo toggle renders async");
|
||||
void toggleTodo(node);
|
||||
return;
|
||||
}
|
||||
const link = node ? docNodePageLink(node) : null;
|
||||
if (link) {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam link follow renders async");
|
||||
void loadPage({ uid: null, title: link }, { pushCurrent: true });
|
||||
return;
|
||||
}
|
||||
frameTimings.finishFrame(frameId, "discarded: roam ignored click");
|
||||
return;
|
||||
}
|
||||
frameTimings.finishFrame(frameId, "discarded: roam ignored input");
|
||||
}
|
||||
|
||||
function goBack(): void {
|
||||
const previous = backStack.pop();
|
||||
if (previous) void loadPage(previous, {});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Edits
|
||||
|
||||
async function toggleTodo(node: DocNode): Promise<void> {
|
||||
if (!currentPage) return;
|
||||
const flat = flattenBlocks(currentPage);
|
||||
const entry = flat.find(({ block }) => block.uid === node.id);
|
||||
if (!entry) return;
|
||||
const block = entry.block;
|
||||
const previousText = block.string;
|
||||
const nowDone = !node.checked;
|
||||
block.string = setTodoMarker(previousText, nowDone);
|
||||
window?.view.setDocument(pageToDocument(currentPage));
|
||||
render();
|
||||
try {
|
||||
await updateBlockString(block.uid, block.string);
|
||||
} catch (error) {
|
||||
block.string = previousText;
|
||||
errorMessage = `Sync failed: ${(error as Error)?.message ?? error}`;
|
||||
window?.view.setDocument(pageToDocument(currentPage));
|
||||
if (window) post({ type: "set-attention", windowId: window.windowId, attention: true });
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
/** Create today's daily page if it only exists locally. */
|
||||
async function ensureCurrentPageExists(): Promise<void> {
|
||||
if (!currentPage || !pageMissing) return;
|
||||
await createPage(currentPage.title, currentPage.uid);
|
||||
pageMissing = false;
|
||||
}
|
||||
|
||||
async function addTodoToPage(page: RoamPage, text: string): Promise<void> {
|
||||
await createBlock(findTodoParentUid(page), "last", `{{[[TODO]]}} ${text}`);
|
||||
}
|
||||
|
||||
async function addTodoFromText(text: string): Promise<void> {
|
||||
try {
|
||||
if (!currentPage) throw new Error("No page is loaded.");
|
||||
await ensureCurrentPageExists();
|
||||
await addTodoToPage(currentPage, text);
|
||||
await reloadCurrentPage();
|
||||
} catch (error) {
|
||||
errorMessage = `Add failed: ${(error as Error)?.message ?? error}`;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tools
|
||||
|
||||
async function handleRoamTool(name: string, args: any): Promise<ToolResult> {
|
||||
if (!isRoamConfigured()) {
|
||||
return { ok: false, error: "Roam is not configured; set the graph name and API token in Settings > Roam." };
|
||||
}
|
||||
switch (name) {
|
||||
case "read_page": {
|
||||
if (currentRef) await reloadCurrentPage();
|
||||
else await loadPage(todayRef(), { resetStack: true });
|
||||
if (errorMessage) return { ok: false, error: errorMessage };
|
||||
if (!currentPage) return { ok: false, error: "No page is loaded." };
|
||||
return { ok: true, content: pageToToolText(currentPage) };
|
||||
}
|
||||
case "add_todo": {
|
||||
const text = String(args?.text ?? "").trim();
|
||||
if (!text) return { ok: false, error: "add_todo requires text." };
|
||||
const today = todayRef();
|
||||
let page = currentPage && currentPage.uid === today.uid ? currentPage : await fetchPageByUid(today.uid!);
|
||||
if (!page) {
|
||||
await createPage(today.title, today.uid!);
|
||||
page = { uid: today.uid!, title: today.title, children: [] };
|
||||
} else if (page === currentPage) {
|
||||
await ensureCurrentPageExists();
|
||||
}
|
||||
await addTodoToPage(page, text);
|
||||
if (currentRef?.uid === today.uid) await reloadCurrentPage();
|
||||
return { ok: true, content: `Added todo: ${text}` };
|
||||
}
|
||||
case "set_todo_done": {
|
||||
const match = String(args?.match ?? "").trim();
|
||||
if (!match) return { ok: false, error: "set_todo_done requires match text." };
|
||||
if (!currentPage) return { ok: false, error: "No page is loaded." };
|
||||
const done = args?.done !== false;
|
||||
const block = findBlockMatching(currentPage, match, (candidate) => isTodoBlock(candidate.string));
|
||||
if (!block) return { ok: false, error: `No todo matching "${match}" on ${currentPage.title}.` };
|
||||
await updateBlockString(block.uid, setTodoMarker(block.string, done));
|
||||
await reloadCurrentPage();
|
||||
return {
|
||||
ok: true,
|
||||
content: `Marked "${plainBlockText(block.string).trim()}" as ${done ? "done" : "not done"}.`,
|
||||
};
|
||||
}
|
||||
case "edit_block": {
|
||||
const match = String(args?.match ?? "").trim();
|
||||
const newText = String(args?.new_text ?? "").trim();
|
||||
if (!match || !newText) return { ok: false, error: "edit_block requires match and new_text." };
|
||||
if (!currentPage) return { ok: false, error: "No page is loaded." };
|
||||
const block = findBlockMatching(currentPage, match);
|
||||
if (!block) return { ok: false, error: `No block matching "${match}" on ${currentPage.title}.` };
|
||||
const marker = /^\s*\{\{(?:\[\[)?DONE/.test(block.string) ? true : isTodoBlock(block.string) ? false : null;
|
||||
const replacement = marker === null || isTodoBlock(newText) ? newText : setTodoMarker(newText, marker);
|
||||
await updateBlockString(block.uid, replacement);
|
||||
await reloadCurrentPage();
|
||||
return { ok: true, content: `Rewrote block to: ${plainBlockText(replacement).trim()}` };
|
||||
}
|
||||
default:
|
||||
return { ok: false, error: `Unknown roam tool: ${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Painting
|
||||
|
||||
function paint(win: RoamWindow): GrayImage {
|
||||
if (win.menu?.isOpen()) return win.menu.paint();
|
||||
return paintContent(win);
|
||||
}
|
||||
|
||||
function paintContent(win: RoamWindow): GrayImage {
|
||||
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
|
||||
const title = currentRef?.title ?? "Roam";
|
||||
const status = loading ? "Loading..." : pageMissing ? "(new page)" : "";
|
||||
const statusWidth = status ? smallFont.measureText(status) + 12 : 0;
|
||||
image.drawText(
|
||||
smallFont,
|
||||
DOC_MARGIN + 2,
|
||||
6,
|
||||
truncateText(smallFont, title, win.viewportWidth - DOC_MARGIN * 2 - statusWidth - 4),
|
||||
225,
|
||||
);
|
||||
if (status) {
|
||||
image.drawText(smallFont, win.viewportWidth - DOC_MARGIN - smallFont.measureText(status), 6, status, 130);
|
||||
}
|
||||
image.drawLine(DOC_MARGIN, HEADER_HEIGHT - 4, win.viewportWidth - DOC_MARGIN, HEADER_HEIGHT - 4, 40);
|
||||
|
||||
if (!isRoamConfigured()) {
|
||||
drawBodyMessage(image, win, "Set the Roam graph name and API token in Settings > Roam. Long-press for the menu, then pick Roam settings.");
|
||||
} else if (errorMessage) {
|
||||
drawBodyMessage(image, win, `${errorMessage}\n\n${GESTURE_CLICK} retry`);
|
||||
} else if (currentPage && currentPage.children.length === 0 && !loading) {
|
||||
drawBodyMessage(image, win, "Nothing here yet. Use voice input to add a todo.");
|
||||
} else {
|
||||
win.view.paint(image, DOC_MARGIN, HEADER_HEIGHT, win.focused);
|
||||
}
|
||||
|
||||
const footer = gestureHints([
|
||||
[GESTURE_SCROLL, "move"],
|
||||
[GESTURE_CLICK, "toggle/open"],
|
||||
[GESTURE_DOUBLE_CLICK, backStack.length > 0 ? "back" : "leave"],
|
||||
[GESTURE_LONG_PRESS, "menu"],
|
||||
]);
|
||||
image.drawText(
|
||||
smallFont,
|
||||
Math.max(DOC_MARGIN, Math.round((win.viewportWidth - smallFont.measureText(footer)) / 2)),
|
||||
win.viewportHeight - FOOTER_HEIGHT + 3,
|
||||
footer,
|
||||
110,
|
||||
);
|
||||
return image;
|
||||
}
|
||||
|
||||
function drawBodyMessage(image: GrayImage, win: RoamWindow, message: string): void {
|
||||
const lines = wrapText(smallFont, message, win.viewportWidth - DOC_MARGIN * 2 - 24);
|
||||
let y = HEADER_HEIGHT + 16;
|
||||
for (const line of lines) {
|
||||
image.drawText(smallFont, DOC_MARGIN + 12, y, line, 190);
|
||||
y += smallFont.lineHeight + 2;
|
||||
}
|
||||
}
|
||||
|
||||
function render(): void {
|
||||
if (window && window.foreground && screenOn) renderAndSubmit(window, 0);
|
||||
}
|
||||
|
||||
function renderAndSubmit(win: RoamWindow, inputFrameId: number): void {
|
||||
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
|
||||
try {
|
||||
const paintStartedAtMs = Date.now();
|
||||
const image = frameTimings.span(frameId, "paint", () =>
|
||||
frameTimings.runWithFrame(frameId, () => paint(win)),
|
||||
);
|
||||
const paintMs = Date.now() - paintStartedAtMs;
|
||||
const fingerprint = image.fingerprint();
|
||||
if (fingerprint === win.lastSubmittedFingerprint) {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam content unchanged");
|
||||
return;
|
||||
}
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) {
|
||||
frameTimings.finishFrame(frameId, "discarded: no active communicator");
|
||||
return;
|
||||
}
|
||||
const buffer = image.to8bppBuffer();
|
||||
communicator.submitSurfaceFrame(
|
||||
buffer.buffer,
|
||||
win.surfaceId,
|
||||
0,
|
||||
0,
|
||||
image.width,
|
||||
image.height,
|
||||
fingerprint,
|
||||
paintMs,
|
||||
frameId,
|
||||
);
|
||||
win.lastSubmittedFingerprint = fingerprint;
|
||||
} catch (error) {
|
||||
frameTimings.finishFrame(frameId, "discarded: roam render failed");
|
||||
console.error(`roam worker render failed: ${error}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Maps Roam block trees (roam-api.ts) into the shared document model
|
||||
* (ui/document): parses the subset of Roam markup the glasses can render —
|
||||
* {{[[TODO]]}} / {{[[DONE]]}} markers, [[page]] / #tag / [text](url) links,
|
||||
* `inline code` and ```code blocks``` — and strips emphasis markers it can't.
|
||||
* Also the block-lookup helpers the voice tools use.
|
||||
*/
|
||||
import type { DocInline, DocNode, DocumentRoot } from "../../ui/document/document-model";
|
||||
import type { RoamBlock, RoamPage } from "./roam-api";
|
||||
|
||||
const TODO_MARKER = /^\s*\{\{(?:\[\[)?(TODO|DONE)(?:\]\])?\}\}\s*/;
|
||||
const CODE_BLOCK = /^```([^\n`]*)\n?([\s\S]*?)```\s*$/;
|
||||
|
||||
export function pageToDocument(page: RoamPage): DocumentRoot {
|
||||
return { title: page.title, nodes: page.children.map(blockToNode) };
|
||||
}
|
||||
|
||||
function blockToNode(block: RoamBlock): DocNode {
|
||||
const children = block.children.map(blockToNode);
|
||||
const text = block.string;
|
||||
|
||||
const codeMatch = CODE_BLOCK.exec(text.trim());
|
||||
if (codeMatch) {
|
||||
return { id: block.uid, kind: "code", inlines: [], codeText: codeMatch[2] ?? "", children };
|
||||
}
|
||||
|
||||
const todoMatch = TODO_MARKER.exec(text);
|
||||
if (todoMatch) {
|
||||
return {
|
||||
id: block.uid,
|
||||
kind: "todo",
|
||||
checked: todoMatch[1] === "DONE",
|
||||
inlines: parseInlineMarkup(text.slice(todoMatch[0].length)),
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
if (block.heading) {
|
||||
return { id: block.uid, kind: "heading", level: block.heading, inlines: parseInlineMarkup(text), children };
|
||||
}
|
||||
|
||||
return { id: block.uid, kind: "text", bullet: true, inlines: parseInlineMarkup(text), children };
|
||||
}
|
||||
|
||||
/** Flip a block string's {{[[TODO]]}} / {{[[DONE]]}} marker (adding one if absent). */
|
||||
export function setTodoMarker(text: string, done: boolean): string {
|
||||
const marker = done ? "{{[[DONE]]}}" : "{{[[TODO]]}}";
|
||||
const match = TODO_MARKER.exec(text);
|
||||
if (match) return `${marker} ${text.slice(match[0].length)}`;
|
||||
return `${marker} ${text}`;
|
||||
}
|
||||
|
||||
export function isTodoBlock(text: string): boolean {
|
||||
return TODO_MARKER.test(text);
|
||||
}
|
||||
|
||||
/** The block's text with todo marker and inline markup stripped. */
|
||||
export function plainBlockText(text: string): string {
|
||||
const withoutMarker = text.replace(TODO_MARKER, "");
|
||||
const codeMatch = CODE_BLOCK.exec(withoutMarker.trim());
|
||||
if (codeMatch) return codeMatch[2] ?? "";
|
||||
return parseInlineMarkup(withoutMarker)
|
||||
.map((inline) => inline.text)
|
||||
.join("");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inline markup
|
||||
|
||||
export function parseInlineMarkup(text: string): DocInline[] {
|
||||
// Emphasis renders no differently on the glasses; drop the markers.
|
||||
const source = text.replace(/\*\*|__|\^\^|~~/g, "");
|
||||
const inlines: DocInline[] = [];
|
||||
let plain = "";
|
||||
const flush = (): void => {
|
||||
if (plain.length > 0) inlines.push({ kind: "text", text: plain });
|
||||
plain = "";
|
||||
};
|
||||
|
||||
let index = 0;
|
||||
while (index < source.length) {
|
||||
if (source.startsWith("[[", index) || source.startsWith("#[[", index)) {
|
||||
const open = source[index] === "#" ? index + 3 : index + 2;
|
||||
const close = matchDoubleBracket(source, open);
|
||||
if (close >= 0) {
|
||||
const target = source.slice(open, close);
|
||||
flush();
|
||||
inlines.push({ kind: "link", text: target.replace(/\[\[|\]\]/g, ""), target });
|
||||
index = close + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (source[index] === "#" && /[\w/]/.test(source[index + 1] ?? "")) {
|
||||
const tagMatch = /^[\w/-]+/.exec(source.slice(index + 1));
|
||||
if (tagMatch) {
|
||||
flush();
|
||||
inlines.push({ kind: "link", text: tagMatch[0], target: tagMatch[0] });
|
||||
index += 1 + tagMatch[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (source[index] === "`") {
|
||||
const close = source.indexOf("`", index + 1);
|
||||
if (close >= 0) {
|
||||
flush();
|
||||
inlines.push({ kind: "code", text: source.slice(index + 1, close) });
|
||||
index = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (source[index] === "[" && !source.startsWith("[[", index)) {
|
||||
const labelEnd = source.indexOf("](", index + 1);
|
||||
const urlEnd = labelEnd >= 0 ? source.indexOf(")", labelEnd + 2) : -1;
|
||||
if (labelEnd >= 0 && urlEnd >= 0) {
|
||||
flush();
|
||||
inlines.push({
|
||||
kind: "link",
|
||||
text: source.slice(index + 1, labelEnd),
|
||||
target: source.slice(labelEnd + 2, urlEnd),
|
||||
external: true,
|
||||
});
|
||||
index = urlEnd + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
plain += source[index];
|
||||
index++;
|
||||
}
|
||||
flush();
|
||||
return inlines;
|
||||
}
|
||||
|
||||
/** Offset of the "]]" closing a "[[" whose contents start at `start`, honoring nesting. */
|
||||
function matchDoubleBracket(source: string, start: number): number {
|
||||
let depth = 1;
|
||||
for (let index = start; index < source.length - 1; index++) {
|
||||
if (source.startsWith("[[", index)) {
|
||||
depth++;
|
||||
index++;
|
||||
} else if (source.startsWith("]]", index)) {
|
||||
depth--;
|
||||
if (depth === 0) return index;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Block lookup helpers (voice tools)
|
||||
|
||||
export type FlatBlock = { block: RoamBlock; depth: number };
|
||||
|
||||
export function flattenBlocks(page: RoamPage): FlatBlock[] {
|
||||
const out: FlatBlock[] = [];
|
||||
const visit = (block: RoamBlock, depth: number): void => {
|
||||
out.push({ block, depth });
|
||||
for (const child of block.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const block of page.children) visit(block, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The uid new todos should be created under: the first block that reads like
|
||||
* a todo-section header ("Todo", "Todos", "TODO:"), else the page itself.
|
||||
*/
|
||||
export function findTodoParentUid(page: RoamPage): string {
|
||||
for (const { block } of flattenBlocks(page)) {
|
||||
if (/^todos?:?$/i.test(plainBlockText(block.string).trim())) return block.uid;
|
||||
}
|
||||
return page.uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the block best matching a spoken/typed query: exact plain-text match
|
||||
* first, then prefix, then substring, all case-insensitive, in document order.
|
||||
*/
|
||||
export function findBlockMatching(
|
||||
page: RoamPage,
|
||||
query: string,
|
||||
filter?: (block: RoamBlock) => boolean,
|
||||
): RoamBlock | null {
|
||||
const needle = query.trim().toLowerCase();
|
||||
if (!needle) return null;
|
||||
let prefix: RoamBlock | null = null;
|
||||
let substring: RoamBlock | null = null;
|
||||
for (const { block } of flattenBlocks(page)) {
|
||||
if (filter && !filter(block)) continue;
|
||||
const plain = plainBlockText(block.string).trim().toLowerCase();
|
||||
if (plain === needle) return block;
|
||||
if (!prefix && plain.startsWith(needle)) prefix = block;
|
||||
if (!substring && plain.includes(needle)) substring = block;
|
||||
}
|
||||
return prefix ?? substring;
|
||||
}
|
||||
|
||||
/** Render the page as indented text with [ ]/[x] markers, for the assistant. */
|
||||
export function pageToToolText(page: RoamPage): string {
|
||||
const lines: string[] = [];
|
||||
for (const { block, depth } of flattenBlocks(page)) {
|
||||
const indent = " ".repeat(depth);
|
||||
const text = plainBlockText(block.string).trim();
|
||||
if (!text) continue;
|
||||
if (isTodoBlock(block.string)) {
|
||||
const done = /^\s*\{\{(?:\[\[)?DONE/.test(block.string);
|
||||
lines.push(`${indent}- [${done ? "x" : " "}] ${text}`);
|
||||
} else {
|
||||
lines.push(`${indent}- ${text}`);
|
||||
}
|
||||
}
|
||||
return lines.length > 0 ? `${page.title}\n${lines.join("\n")}` : `${page.title}\n(page is empty)`;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Shell-side roam.* assistant tools. The Roam app's own tools are
|
||||
* window-scoped ("open" tier), but "add milk to my todo list" should work
|
||||
* with the app closed — so these always-available wrappers launch the app,
|
||||
* wait for its tools to register, and forward the call.
|
||||
*/
|
||||
import { roamApiTokenSetting, roamGraphNameSetting } from "../ui/dashboard-settings";
|
||||
import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
|
||||
|
||||
const APP_TOOL_PREFIX = "app.roam.";
|
||||
const TOOL_APPEAR_TIMEOUT_MS = 5_000;
|
||||
const TOOL_APPEAR_POLL_MS = 150;
|
||||
|
||||
let registered = false;
|
||||
|
||||
export function registerRoamTools(
|
||||
launchApp: (appId: string) => Promise<void>,
|
||||
registry: ToolRegistry = toolRegistry,
|
||||
): void {
|
||||
if (registered) return;
|
||||
registered = true;
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "roam.add_todo",
|
||||
description:
|
||||
"Add a TODO item to the user's Roam Research daily notes page (their main todo list). Opens the Roam app on the glasses.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { text: { type: "string", description: "The todo item's text." } },
|
||||
required: ["text"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
timeoutMs: 25_000,
|
||||
},
|
||||
async (args) => {
|
||||
const text = String(args?.text ?? "").trim();
|
||||
if (!text) return err("roam.add_todo requires text");
|
||||
return callAppTool(launchApp, registry, "add_todo", { text });
|
||||
},
|
||||
);
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "roam.read_todos",
|
||||
description:
|
||||
"Read the user's Roam Research daily notes page, including their todo list with each item's done/open state. Opens the Roam app on the glasses.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
timeoutMs: 25_000,
|
||||
},
|
||||
async () => callAppTool(launchApp, registry, "read_page", {}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Launch the Roam app if needed, wait for its tool, and forward the call. */
|
||||
async function callAppTool(
|
||||
launchApp: (appId: string) => Promise<void>,
|
||||
registry: ToolRegistry,
|
||||
unprefixedName: string,
|
||||
args: unknown,
|
||||
): Promise<ToolResult> {
|
||||
if (roamGraphNameSetting.get().length === 0 || roamApiTokenSetting.get().length === 0) {
|
||||
return err("Roam is not configured; the user must set the graph name and API token in Settings > Roam.");
|
||||
}
|
||||
const fullName = `${APP_TOOL_PREFIX}${unprefixedName}`;
|
||||
if (!registry.listTools().some((tool) => tool.name === fullName)) {
|
||||
await launchApp("roam");
|
||||
const deadline = Date.now() + TOOL_APPEAR_TIMEOUT_MS;
|
||||
while (!registry.listTools().some((tool) => tool.name === fullName)) {
|
||||
if (Date.now() > deadline) {
|
||||
return err("The Roam app did not start in time.");
|
||||
}
|
||||
await sleep(TOOL_APPEAR_POLL_MS);
|
||||
}
|
||||
}
|
||||
return registry.callTool(fullName, args);
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function err(error: string): ToolResult {
|
||||
return { ok: false, error };
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { wrapText } from "../graphics/textwrap";
|
||||
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
|
||||
import { registerSystemTools } from "../assistant/system-tools";
|
||||
import { registerNavigateTools } from "../assistant/navigate-tools";
|
||||
import { registerRoamTools } from "../assistant/roam-tools";
|
||||
import { assistantBridge } from "../assistant/bridge-client";
|
||||
import { registerWindowTools } from "../assistant/window-tools";
|
||||
import { WorkerAppHost } from "../ui/shell/worker-window";
|
||||
@@ -215,6 +216,8 @@ class DashboardController {
|
||||
registerSystemTools();
|
||||
// nav.* tools launch the Navigate app on demand, so they need launchApp.
|
||||
registerNavigateTools((appId) => this.launchApp(appId));
|
||||
// roam.* tools launch the Roam app on demand likewise.
|
||||
registerRoamTools((appId) => this.launchApp(appId));
|
||||
// apps.* tools mirror the launcher grid and sidebar (launch, focus, close).
|
||||
registerWindowTools({
|
||||
apps: LAUNCHABLE_APPS,
|
||||
|
||||
@@ -68,6 +68,10 @@ export const ICON_SVGS = {
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12 19v3"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect x="9" y="2" width="6" height="13" rx="3"/></svg>',
|
||||
map:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z"/><path d="M15 5.764v15"/><path d="M9 3.236v15"/></svg>',
|
||||
// The Roam Research logo, potrace-traced from the official PNG (no
|
||||
// fill="none", so the renderer fills it; hole contours wind opposite).
|
||||
roam:
|
||||
'<svg viewBox="0 0 24 24"><path d="M11.2 24C11.1 24 10.7 23.9 10.5 23.9C4.5 23.1 0 18.1 0 12C0 4.1 7.4 -1.6 15.1 0.4C18.9 1.4 22.1 4.4 23.4 8.2C25.7 15.3 21.1 22.7 13.7 23.9C13.2 23.9 11.5 24 11.2 24ZM18.9 19.1C19.9 18.2 20.5 17.4 21.1 16.3C21.4 15.7 21.8 14.5 21.7 14.4C21.7 14.4 21.6 14.3 21.4 14.3C21.2 14.3 21.1 14.2 21.1 14.1C21.1 14 21 13.9 21 13.7C20.9 13.4 20.9 13.4 20.6 13.1C20.2 12.9 20.2 12.9 19.7 12.9L19.1 12.9L19.1 12.7L19.1 12.4L16.6 12.4L14 12.4L13.7 12.8C13.5 13.1 12.9 13.6 12.6 13.7C12.5 13.8 12.5 13.8 12.5 14.7L12.5 15.6L12.8 15.8L13 16.1L13 16.4C12.9 17.1 13.1 17.3 14.1 17.1C14.9 17 15.3 17.1 15.3 17.5C15.3 17.7 15 18.1 14.7 18.4C14.4 18.6 14.4 18.7 14.7 18.9C15.1 19.1 15.5 19.1 16.2 18.7C17.1 18.2 17.5 18.2 17.7 18.8C17.8 19 17.8 19.9 17.7 20.1C17.7 20.3 18.3 19.7 18.9 19.1ZM6.2 19.9C6 19.2 6.2 18.6 6.5 18.4C6.9 18.2 7.2 18.3 7.9 18.8C8.3 19.1 8.6 19.1 9.1 18.9C9.3 18.8 9.5 18.7 9.5 18.7C9.5 18.6 9.4 18.5 9.2 18.4C8.8 17.9 8.6 17.4 8.9 17.1C9 17 9 17 9.5 17.1C10.7 17.2 10.8 17.2 10.9 17C11 16.8 11 16.8 10.9 16.4L10.8 16.1L11.1 15.8L11.4 15.5L11.4 14.8C11.4 14.1 11.4 14.1 11.3 14.1C11.2 14.1 9.9 14.9 8.3 15.8C6.7 16.7 5.4 17.4 5.4 17.4C5.3 17.4 5.3 17.3 5.3 17.2C5.3 17.1 5.3 17 5.3 17C5.2 17 3.8 17.6 3.8 17.7C3.7 17.8 4.8 19 5.7 19.7C6 19.9 6.2 20.1 6.2 20.1C6.2 20.1 6.2 20 6.2 19.9ZM6.1 15.6C7.5 14.6 8.6 13.9 8.6 13.9C8.6 13.8 8.4 13.5 8.2 13.1L7.8 12.5L6.4 12.4L4.9 12.4L4.9 12.7L4.9 12.9L4.3 12.9L3.7 12.9L3.3 13.5C2.9 14 2.8 14.1 2.6 14.2L2.3 14.4L2.3 14.6C2.4 15.3 3.3 17.2 3.5 17.2C3.5 17.2 4.6 16.5 6.1 15.6ZM9.7 13.3C9.9 13.1 10.1 13 10.1 13C10.1 13 10.1 12.8 10 12.7L9.9 12.4L9.2 12.4L8.4 12.4L8.5 12.6C8.5 12.7 8.7 12.9 8.8 13.1C9 13.4 9.1 13.6 9.2 13.6C9.2 13.6 9.4 13.4 9.7 13.3ZM10.3 11.1C10.5 10.8 11 10.3 11.3 10.2L11.4 10.1L11.4 7.4L11.4 4.7L11.3 4.7L11.1 4.7L11.1 4.2C11.1 3.2 10.7 2.8 9.8 2.8C9.6 2.8 9.3 2.8 9.2 2.9C9.1 2.9 9 2.9 8.9 2.7C8.8 2.4 8.8 2.4 8.3 2.6C6 3.5 4.1 5.2 3 7.4C2.7 8.1 2.3 9 2.3 9.2C2.3 9.3 2.4 9.4 2.6 9.6C2.9 9.7 3 9.9 3.4 10.4L3.8 10.9L4.3 10.9L4.9 10.9L4.9 11.1L4.9 11.3L7.5 11.3L10.1 11.3L10.3 11.1ZM15.9 11.3C15.9 11.3 15.4 10.5 15.1 10.1L15 9.9L14.4 10.2C14.1 10.4 13.8 10.6 13.8 10.6C13.8 10.7 13.8 10.8 14.1 11.1L14.2 11.3L15.1 11.3C15.5 11.3 15.9 11.3 15.9 11.3ZM19.1 11.1L19.1 10.9L19.7 10.9L20.2 10.9L20.6 10.6C20.9 10.3 21 10.2 21 10C21 9.7 21.1 9.7 21.4 9.5C21.6 9.4 21.7 9.3 21.7 9.3C21.8 9.3 20.9 7.2 20.6 6.8C20.5 6.7 20.4 6.8 18.2 8.1C16.9 8.9 15.8 9.6 15.8 9.6C15.8 9.6 15.9 9.8 16.1 10L16.4 10.4L16.4 10.9L16.4 11.3L17.8 11.3L19.1 11.3L19.1 11.1ZM13.6 9.2L14.4 8.8L14.4 8.6C14.4 8.4 14.4 8.3 14.5 8.2C14.6 8.1 14.7 8.1 14.8 8.3L15 8.5L16.7 7.4C17.6 6.9 18.3 6.4 18.4 6.4C18.4 6.4 18.4 6.5 18.4 6.6C18.4 6.8 18.4 6.9 18.5 6.9C18.6 6.9 20.1 6.3 20.2 6.2C20.3 6.1 19.7 5.4 19 4.7C18.1 3.8 17.1 3.1 15.9 2.7C15 2.3 15 2.3 14.8 2.6L14.7 2.8L14.1 2.8C13.4 2.8 13.2 2.9 13 3.2C12.9 3.4 12.8 3.9 12.8 4.3C12.8 4.6 12.8 4.7 12.6 4.7L12.5 4.7L12.5 7.2L12.5 9.8L12.7 9.7C12.7 9.7 13.2 9.4 13.6 9.2Z"/></svg>',
|
||||
nightscout:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="70.29 0 371.43 512"><g fill="#fff"><path d="M245.67.33c-26.83 1.88-48.51 7.53-71.01 18.48-12.93 6.31-23.82 13.24-35.58 22.6-6.52 5.14-22.75 21.43-28 27.95C89.04 97 76.06 127.65 71.22 163.38c-1.12 8.6-1.27 37.06-.25 47.85 3.46 35.53 12.16 69.02 27.33 105.37 18.83 45.25 49.17 93.31 88.52 140.44 12.17 14.56 33.39 37.72 39.76 43.47 15.17 13.54 36.19 15.27 52.94 4.33 4.38-2.85 10.44-8.76 23.62-23.06 31.2-33.75 58.18-69.33 78.8-103.84 25.1-42 40.72-78.7 50.8-119.37 8.91-35.89 11.35-74.52 6.57-103.08-3.16-18.94-7.99-33.7-17-51.92C401.59 61.68 366.77 29.76 323 12.5 300.04 3.49 269.34-1.35 245.67.33m21.99 29.42c12.83.66 31.61 4.94 45.2 10.28 35.99 14.15 65.87 41.64 82.97 76.25 8.76 17.71 13.34 33.24 15.58 52.69.66 5.9.76 10.38.56 22.14-.25 14.81-.51 18.17-2.44 31.82-8.35 58.95-36.6 121.71-83.08 184.27-21.38 28.71-57.93 70.3-65 73.86-3 1.53-7.99 1.58-10.94.2-7.13-3.41-42.56-43.62-64.65-73.3-33.09-44.39-55.79-86.33-70.3-129.81-11.5-34.61-16.59-65.16-15.83-95.9.41-17.36 2.44-29.52 7.53-45.15 18.43-56.71 68.87-98.65 127.77-106.39 7.18-.92 19.6-1.68 24.13-1.43 1.68.12 5.5.32 8.5.47"/><path d="M247.05 58.51c-11.56.97-23.31 3.41-33.49 6.87-6.36 2.19-18.94 8.2-24.89 11.96-13.49 8.4-26.27 20.26-36.35 33.7l-1.43 1.93 3.31-1.27c8.65-3.26 18.73-4.84 30.7-4.84 13.03 0 22.5 1.73 33.7 6.21 6.67 2.65 12.78 6.11 18.78 10.64 5.09 3.87 13.64 12.52 16.44 16.65.97 1.43 1.88 2.6 2.04 2.6s1.17-1.27 2.29-2.85c5.14-7.18 14.86-16.14 22.91-21.02 21.18-12.98 50.34-16.09 74.68-7.94l4.94 1.68-1.58-2.29c-7.33-10.69-22.25-24.48-35.28-32.78-14.86-9.42-32.93-15.93-51.26-18.48-7.04-.97-18.74-1.33-25.51-.77"/><path d="M178.07 133.9c-20.46 2.39-36.04 13.44-44.64 31.66-3.41 7.13-4.89 13.44-5.19 21.99-.71 18.68 4.99 41.39 14.91 59.41 20.46 37.16 57.27 62 98.55 66.53 11.5 1.27 28.56.46 40.37-1.99 22.7-4.63 44.29-15.88 61.39-31.97 6.82-6.41 16.29-17.97 21.18-25.81 15.17-24.38 22.55-57.88 17.26-78.29-1.43-5.65-4.73-12.98-7.99-17.71-3.41-5.04-9.88-11.45-14.91-14.76-5.14-3.41-12.78-6.57-19.14-7.89-5.29-1.17-19.9-1.32-24.69-.31-19.7 4.28-34.61 16.75-41.03 34.31-3.82 10.33-3.67 8.55-3.87 51.57-.15 42.2-.1 41.08-3 42.45-.81.36-5.09.56-11.66.56h-10.44l-1.63-1.48-1.68-1.48-.31-39.4c-.31-42.76-.2-41.44-3.31-50.7-3.56-10.69-11.61-21.23-21.02-27.59-10.9-7.32-25.41-10.68-39.15-9.1m12.22 6.06c10.74 1.22 20.31 5.85 28.61 13.74 6.67 6.36 11 13.54 13.64 22.65 1.02 3.61 1.17 5.14 1.12 12.98 0 8.2-.1 9.26-1.37 13.39-4.17 13.49-12.73 23.82-25.04 30.24-11.05 5.7-23.62 7.02-35.79 3.72-13.69-3.77-25.76-14.15-31.87-27.59-6.11-13.29-5.5-30.29 1.53-43.12 7.94-14.61 21.94-24.08 38.33-26.01 4.88-.56 5.95-.56 10.84 0m141.66 0c23.57 2.7 41.39 20.41 44.13 43.88 2.44 20.72-9.52 41.54-28.86 50.34-13.08 5.9-29.17 5.65-41.74-.66-13.18-6.62-22.55-18.17-26.52-32.73-1.48-5.5-1.37-18.33.2-24.18 1.48-5.4 4.48-11.86 7.43-15.93 2.49-3.56 9.06-10.03 12.62-12.47 6.01-4.12 14.91-7.43 22.04-8.2 5.82-.61 5.66-.61 10.7-.05"/><path d="M180.62 168.47c-11.2 2.39-18.58 13.39-16.39 24.54 3.26 16.59 23.42 22.81 35.33 10.89 10.28-10.33 7.28-27.44-5.96-33.7-4.08-1.89-9.01-2.55-12.98-1.73m141.92.2c-8.4 1.83-14.91 8.81-16.29 17.41-1.02 6.26 1.37 13.29 6.11 17.92 13.69 13.49 36.8 2.9 35.48-16.29a21.05 21.05 0 0 0-17.1-19.24c-3.37-.61-4.64-.61-8.2.2M163.15 318.02c8.4 16.8 18.12 33.55 28.71 49.48 7.18 10.84 9.01 13.29 9.52 12.98 1.37-.87 26.32-39.81 25.81-40.27-.05-.05-3.05-.81-6.72-1.63-19.9-4.58-39.35-13.44-55.89-25.45-2.19-1.63-4.43-3.21-4.99-3.61-.71-.51.41 2.14 3.56 8.5m183.57-4.68c-13.39 9.82-30.9 18.48-46.98 23.11-10.33 2.95-23.47 5.19-35.63 6.01l-5.75.36-3.82 6.82c-8.5 15.22-21.69 35.99-31.05 48.97-2.34 3.26-4.28 6.06-4.28 6.21 0 1.27 23.21 28.4 33.49 39.2l3.26 3.41 3.46-3.67c37.01-39.71 67.55-82.62 88.42-124.31 4.17-8.3 4.89-9.98 4.33-9.93-.21 0-2.65 1.73-5.45 3.82"/></g></svg>',
|
||||
} as const;
|
||||
|
||||
@@ -516,6 +516,30 @@ export const terminalWakeOnBellSetting = new ConfigSettingBoolean({
|
||||
"When a terminal rings its bell while the glasses are asleep, wake them and focus that terminal's window (or the terminals list if it has no window open).",
|
||||
});
|
||||
|
||||
export const roamGraphNameSetting = new ConfigSettingString({
|
||||
id: "roam-graph-name",
|
||||
label: "Roam graph name",
|
||||
storageKey: "integrations.roam.graphName",
|
||||
defaultValue: "",
|
||||
editorTitle: "Roam graph name",
|
||||
glassesEditTitle: "Edit Roam graph",
|
||||
normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(),
|
||||
formatValue: emptySettingDisplay,
|
||||
description: "Name of the Roam Research graph the Roam app reads and writes (as shown in Roam's graph switcher).",
|
||||
});
|
||||
|
||||
export const roamApiTokenSetting = new ConfigSettingString({
|
||||
id: "roam-api-token",
|
||||
label: "Roam API token",
|
||||
storageKey: "integrations.roam.apiToken",
|
||||
defaultValue: "",
|
||||
editorTitle: "Roam API token (roam-graph-token-...)",
|
||||
glassesEditTitle: "Edit Roam token",
|
||||
normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(),
|
||||
formatValue: maskToken,
|
||||
description: "API token for the graph, created in Roam under Settings > Graph > API tokens. Needs edit access for checking off todos.",
|
||||
});
|
||||
|
||||
export const nightscoutSiteUrlSetting = new ConfigSettingString({
|
||||
id: "nightscout-site-url",
|
||||
label: "Nightscout site URL",
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
elevenLabsApiKeySetting,
|
||||
mapboxApiKeySetting,
|
||||
openAiApiKeySetting,
|
||||
roamApiTokenSetting,
|
||||
roamGraphNameSetting,
|
||||
enumSettingMenuItem,
|
||||
firmwareDebugFlagsSetting,
|
||||
lockScreenEnabledSetting,
|
||||
@@ -112,6 +114,13 @@ function settingsSections(): SettingsSection[] {
|
||||
toggleSettingMenuItem(terminalWakeOnBellSetting),
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Roam",
|
||||
items: [
|
||||
textSettingMenuItem(roamGraphNameSetting),
|
||||
textSettingMenuItem(roamApiTokenSetting),
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Developer",
|
||||
items: [
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Source-agnostic document tree for rendering structured text (outlines,
|
||||
* todo lists, notes) on the glasses. Integrations (Roam, and later markdown /
|
||||
* Notion / Obsidian) map their native formats into this structure; the
|
||||
* DocumentView in document-view.ts renders it with a selection and scroll
|
||||
* position. Deliberately much smaller than HTML: block nodes nest to give
|
||||
* indent levels, and inline spans cover only the formatting the glasses can
|
||||
* usefully draw (links, inline code).
|
||||
*/
|
||||
|
||||
export type DocInline =
|
||||
| { kind: "text"; text: string }
|
||||
| {
|
||||
kind: "link";
|
||||
text: string;
|
||||
/** Page title or URL the link points at. */
|
||||
target: string;
|
||||
/** True for web URLs (not followable on the glasses); false for in-graph pages. */
|
||||
external?: boolean;
|
||||
}
|
||||
| { kind: "code"; text: string };
|
||||
|
||||
export type DocNodeKind = "text" | "todo" | "heading" | "code";
|
||||
|
||||
export type DocNode = {
|
||||
/** Stable id from the source (e.g. the Roam block uid); keys selection and edits. */
|
||||
id: string;
|
||||
kind: DocNodeKind;
|
||||
/** Todo nodes: whether the item is checked off. */
|
||||
checked?: boolean;
|
||||
/** Heading nodes: 1 (largest) to 3. */
|
||||
level?: number;
|
||||
/** Draw a bullet marker (outline/list item). Ignored for todo nodes. */
|
||||
bullet?: boolean;
|
||||
/** Inline content for text/todo/heading nodes. */
|
||||
inlines: DocInline[];
|
||||
/** Code nodes: preformatted text, possibly multi-line. */
|
||||
codeText?: string;
|
||||
children: DocNode[];
|
||||
};
|
||||
|
||||
export type DocumentRoot = {
|
||||
title: string;
|
||||
nodes: DocNode[];
|
||||
};
|
||||
|
||||
/** The node's text with inline markup dropped (for matching and tool output). */
|
||||
export function docNodePlainText(node: DocNode): string {
|
||||
if (node.kind === "code") return node.codeText ?? "";
|
||||
return node.inlines.map((inline) => inline.text).join("");
|
||||
}
|
||||
|
||||
/** The node's first in-graph page link, if any (the click-to-follow target). */
|
||||
export function docNodePageLink(node: DocNode): string | null {
|
||||
for (const inline of node.inlines) {
|
||||
if (inline.kind === "link" && !inline.external) return inline.target;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Depth-first flatten of a node tree. */
|
||||
export function flattenDocNodes(nodes: readonly DocNode[]): DocNode[] {
|
||||
const out: DocNode[] = [];
|
||||
const visit = (node: DocNode): void => {
|
||||
out.push(node);
|
||||
for (const child of node.children) visit(child);
|
||||
};
|
||||
for (const node of nodes) visit(node);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
/**
|
||||
* Renders a DocumentRoot (document-model.ts) into a scrollable, selectable
|
||||
* region: nested nodes indent, todo nodes get checkboxes, links underline,
|
||||
* code blocks get a shaded box. Selection moves over nodes (a node's wrapped
|
||||
* lines highlight as one unit) and the scroll position follows it, matching
|
||||
* the house list style in ui/menu.ts.
|
||||
*/
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { getDefaultMediumFont, getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
|
||||
import { wrapText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { drawListScrollbar, drawSelectionHighlight } from "../menu";
|
||||
import {
|
||||
docNodePlainText,
|
||||
type DocInline,
|
||||
type DocNode,
|
||||
type DocumentRoot,
|
||||
} from "./document-model";
|
||||
|
||||
const INDENT_STEP = 18;
|
||||
const MARKER_GUTTER = 16;
|
||||
const RIGHT_PAD = 10;
|
||||
const CODE_INSET = 6;
|
||||
|
||||
type SegmentStyle = "plain" | "link" | "code";
|
||||
|
||||
type Segment = { text: string; x: number; style: SegmentStyle };
|
||||
|
||||
type LayoutLine = {
|
||||
node: DocNode;
|
||||
/** Index into the selectable-node list, or -1 for unselectable filler. */
|
||||
selectableIndex: number;
|
||||
/** First wrapped line of its node (draws the bullet/checkbox marker). */
|
||||
firstOfNode: boolean;
|
||||
indentX: number;
|
||||
textX: number;
|
||||
height: number;
|
||||
font: BdfFont;
|
||||
/** Line belongs to a code block (shaded background). */
|
||||
codeBlock: boolean;
|
||||
segments: Segment[];
|
||||
};
|
||||
|
||||
export class DocumentView {
|
||||
private root: DocumentRoot | null = null;
|
||||
private lines: LayoutLine[] = [];
|
||||
private selectable: DocNode[] = [];
|
||||
private selectedIndex = 0;
|
||||
private scrollLine = 0;
|
||||
|
||||
constructor(
|
||||
private readonly width: number,
|
||||
private readonly height: number,
|
||||
) {}
|
||||
|
||||
setDocument(root: DocumentRoot): void {
|
||||
const previousId = this.selectedNode()?.id;
|
||||
this.root = root;
|
||||
this.layout();
|
||||
if (previousId) {
|
||||
const index = this.selectable.findIndex((node) => node.id === previousId);
|
||||
if (index >= 0) this.selectedIndex = index;
|
||||
}
|
||||
this.selectedIndex = clamp(this.selectedIndex, 0, Math.max(0, this.selectable.length - 1));
|
||||
this.scrollLine = clamp(this.scrollLine, 0, this.maxScrollLine());
|
||||
this.ensureSelectionVisible();
|
||||
}
|
||||
|
||||
selectedNode(): DocNode | null {
|
||||
return this.selectable[this.selectedIndex] ?? null;
|
||||
}
|
||||
|
||||
/** Move the selection (or just scroll, in a document with nothing selectable). */
|
||||
moveSelection(delta: number): boolean {
|
||||
if (this.selectable.length === 0) {
|
||||
return this.scrollBy(delta * 3);
|
||||
}
|
||||
const next = clamp(this.selectedIndex + delta, 0, this.selectable.length - 1);
|
||||
if (next === this.selectedIndex) return false;
|
||||
this.selectedIndex = next;
|
||||
this.ensureSelectionVisible();
|
||||
return true;
|
||||
}
|
||||
|
||||
scrollBy(deltaLines: number): boolean {
|
||||
const next = clamp(this.scrollLine + deltaLines, 0, this.maxScrollLine());
|
||||
if (next === this.scrollLine) return false;
|
||||
this.scrollLine = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Draw the document region onto `target` with its top-left at (x, y). */
|
||||
paint(target: GrayImage, x: number, y: number, focused: boolean): void {
|
||||
const image = new GrayImage(this.width, this.height, 0);
|
||||
const selected = this.selectedNode();
|
||||
const visibleCount = this.visibleCountFrom(this.scrollLine);
|
||||
const lastVisible = Math.min(this.lines.length, this.scrollLine + visibleCount);
|
||||
|
||||
// Selection highlight behind the selected node's visible lines.
|
||||
if (selected) {
|
||||
let top: number | null = null;
|
||||
let bottom = 0;
|
||||
let indentX = 0;
|
||||
let lineY = 0;
|
||||
for (let index = this.scrollLine; index < lastVisible; index++) {
|
||||
const line = this.lines[index]!;
|
||||
if (line.node === selected) {
|
||||
if (top === null) {
|
||||
top = lineY;
|
||||
indentX = line.indentX;
|
||||
}
|
||||
bottom = lineY + line.height;
|
||||
}
|
||||
lineY += line.height;
|
||||
}
|
||||
if (top !== null) {
|
||||
const highlightX = Math.max(0, indentX - 4);
|
||||
drawSelectionHighlight(image, highlightX, top, this.width - highlightX - RIGHT_PAD + 4, bottom - top, focused, 4);
|
||||
}
|
||||
}
|
||||
|
||||
let lineY = 0;
|
||||
for (let index = this.scrollLine; index < lastVisible; index++) {
|
||||
const line = this.lines[index]!;
|
||||
const isSelected = line.node === selected;
|
||||
if (line.codeBlock) {
|
||||
image.fillRect(line.textX - CODE_INSET, lineY, this.width - line.textX - RIGHT_PAD + CODE_INSET, line.height, 16);
|
||||
image.drawLine(line.textX - CODE_INSET, lineY, line.textX - CODE_INSET, lineY + line.height - 1, 70);
|
||||
}
|
||||
if (line.firstOfNode) this.drawMarker(image, line, lineY);
|
||||
for (const segment of line.segments) {
|
||||
this.drawSegment(image, line, segment, lineY, isSelected);
|
||||
}
|
||||
lineY += line.height;
|
||||
}
|
||||
|
||||
if (this.lines.length > visibleCount) {
|
||||
drawListScrollbar(image, this.width - 3, 0, this.height, this.scrollLine, visibleCount, this.lines.length);
|
||||
}
|
||||
target.bitBlt(image, x, y);
|
||||
}
|
||||
|
||||
private drawMarker(image: GrayImage, line: LayoutLine, lineY: number): void {
|
||||
const node = line.node;
|
||||
if (node.kind === "todo") {
|
||||
const boxY = lineY + Math.max(0, Math.floor((line.height - 10) / 2)) - 1;
|
||||
image.drawRect(line.indentX, boxY, 10, 10, 170);
|
||||
if (node.checked) {
|
||||
image.drawLine(line.indentX + 2, boxY + 5, line.indentX + 4, boxY + 7, 220);
|
||||
image.drawLine(line.indentX + 4, boxY + 7, line.indentX + 8, boxY + 2, 220);
|
||||
}
|
||||
} else if (node.kind !== "heading" && node.kind !== "code" && node.bullet) {
|
||||
const dotY = lineY + Math.floor(line.height / 2) - 1;
|
||||
image.fillRect(line.indentX + 4, dotY, 3, 3, 130);
|
||||
}
|
||||
}
|
||||
|
||||
private drawSegment(image: GrayImage, line: LayoutLine, segment: Segment, lineY: number, selected: boolean): void {
|
||||
const node = line.node;
|
||||
const width = line.font.measureText(segment.text);
|
||||
let value: number;
|
||||
if (node.kind === "heading") {
|
||||
value = 225;
|
||||
} else if (node.kind === "todo" && node.checked) {
|
||||
value = 110;
|
||||
} else if (line.codeBlock) {
|
||||
value = 185;
|
||||
} else if (segment.style === "link") {
|
||||
value = 220;
|
||||
} else {
|
||||
value = 195;
|
||||
}
|
||||
if (selected) value = Math.min(250, value + 40);
|
||||
if (segment.style === "code" && !line.codeBlock) {
|
||||
image.fillRect(segment.x - 1, lineY, width + 2, line.height, 25);
|
||||
}
|
||||
image.drawText(line.font, segment.x, lineY + 1, segment.text, value);
|
||||
if (segment.style === "link" && width > 0) {
|
||||
image.drawLine(segment.x, lineY + line.height - 2, segment.x + width - 1, lineY + line.height - 2, node.kind === "todo" && node.checked ? 70 : 120);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Layout
|
||||
|
||||
private layout(): void {
|
||||
this.lines = [];
|
||||
this.selectable = [];
|
||||
if (!this.root) return;
|
||||
for (const node of this.root.nodes) this.layoutNode(node, 0);
|
||||
}
|
||||
|
||||
private layoutNode(node: DocNode, depth: number): void {
|
||||
const font = node.kind === "heading" ? getDefaultMediumFont() : getDefaultSmallFont();
|
||||
const lineHeight = font.lineHeight + 2;
|
||||
const indentX = 4 + depth * INDENT_STEP;
|
||||
const textX = indentX + MARKER_GUTTER;
|
||||
const textWidth = Math.max(40, this.width - textX - RIGHT_PAD);
|
||||
const plainText = docNodePlainText(node);
|
||||
const selectableIndex = plainText.trim().length > 0 ? this.selectable.length : -1;
|
||||
if (selectableIndex >= 0) this.selectable.push(node);
|
||||
|
||||
const base = {
|
||||
node,
|
||||
selectableIndex,
|
||||
indentX,
|
||||
textX,
|
||||
height: lineHeight,
|
||||
font,
|
||||
codeBlock: node.kind === "code",
|
||||
};
|
||||
|
||||
if (node.kind === "code") {
|
||||
const codeLines = wrapText(font, node.codeText ?? "", textWidth - CODE_INSET, {
|
||||
preserveLeadingWhitespace: true,
|
||||
breakLongWords: true,
|
||||
});
|
||||
codeLines.forEach((text, index) => {
|
||||
this.lines.push({
|
||||
...base,
|
||||
firstOfNode: index === 0,
|
||||
segments: [{ text, x: textX, style: "plain" }],
|
||||
});
|
||||
});
|
||||
} else if (plainText.length === 0) {
|
||||
this.lines.push({ ...base, firstOfNode: true, segments: [] });
|
||||
} else {
|
||||
const wrapped = wrapText(font, plainText, textWidth, { breakLongWords: true });
|
||||
const spans = inlineSpans(node.inlines);
|
||||
let cursor = 0;
|
||||
wrapped.forEach((text, index) => {
|
||||
let start = cursor;
|
||||
if (text.length > 0) {
|
||||
const found = plainText.indexOf(text, cursor);
|
||||
start = found >= 0 ? found : cursor;
|
||||
cursor = start + text.length;
|
||||
}
|
||||
this.lines.push({
|
||||
...base,
|
||||
firstOfNode: index === 0,
|
||||
segments: segmentLine(font, text, start, spans, textX),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for (const child of node.children) this.layoutNode(child, depth + 1);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Scrolling
|
||||
|
||||
private visibleCountFrom(start: number): number {
|
||||
let used = 0;
|
||||
let count = 0;
|
||||
for (let index = start; index < this.lines.length; index++) {
|
||||
used += this.lines[index]!.height;
|
||||
if (used > this.height) break;
|
||||
count++;
|
||||
}
|
||||
return Math.max(1, count);
|
||||
}
|
||||
|
||||
private maxScrollLine(): number {
|
||||
let used = 0;
|
||||
for (let index = this.lines.length - 1; index >= 0; index--) {
|
||||
used += this.lines[index]!.height;
|
||||
if (used > this.height) return index + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private ensureSelectionVisible(): void {
|
||||
const selected = this.selectedNode();
|
||||
if (!selected) return;
|
||||
let first = -1;
|
||||
let last = -1;
|
||||
for (let index = 0; index < this.lines.length; index++) {
|
||||
if (this.lines[index]!.node === selected) {
|
||||
if (first < 0) first = index;
|
||||
last = index;
|
||||
}
|
||||
}
|
||||
if (first < 0) return;
|
||||
let scroll = this.scrollLine;
|
||||
// Scroll down the minimum needed; a node taller than the view pins its top.
|
||||
while (last >= scroll + this.visibleCountFrom(scroll) && scroll < first) scroll++;
|
||||
if (first < scroll) scroll = first;
|
||||
this.scrollLine = clamp(scroll, 0, this.maxScrollLine());
|
||||
}
|
||||
}
|
||||
|
||||
type InlineSpan = { start: number; end: number; style: SegmentStyle };
|
||||
|
||||
function inlineSpans(inlines: readonly DocInline[]): InlineSpan[] {
|
||||
const spans: InlineSpan[] = [];
|
||||
let offset = 0;
|
||||
for (const inline of inlines) {
|
||||
const end = offset + inline.text.length;
|
||||
const style: SegmentStyle = inline.kind === "link" ? "link" : inline.kind === "code" ? "code" : "plain";
|
||||
if (inline.text.length > 0) spans.push({ start: offset, end, style });
|
||||
offset = end;
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/** Split one wrapped line (plainText[start..start+text.length)) at span boundaries. */
|
||||
function segmentLine(
|
||||
font: BdfFont,
|
||||
text: string,
|
||||
start: number,
|
||||
spans: readonly InlineSpan[],
|
||||
textX: number,
|
||||
): Segment[] {
|
||||
if (text.length === 0) return [];
|
||||
const end = start + text.length;
|
||||
const segments: Segment[] = [];
|
||||
let x = textX;
|
||||
let cursor = start;
|
||||
while (cursor < end) {
|
||||
const span = spans.find((candidate) => candidate.start <= cursor && cursor < candidate.end);
|
||||
const spanEnd = span ? Math.min(span.end, end) : nextSpanStart(spans, cursor, end);
|
||||
const piece = text.slice(cursor - start, spanEnd - start);
|
||||
segments.push({ text: piece, x, style: span?.style ?? "plain" });
|
||||
x += font.measureText(piece);
|
||||
cursor = spanEnd;
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function nextSpanStart(spans: readonly InlineSpan[], cursor: number, end: number): number {
|
||||
let next = end;
|
||||
for (const span of spans) {
|
||||
if (span.start > cursor && span.start < next) next = span.start;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
Reference in new issue
Block a user