Add daily page date-picker to Roam app

This commit is contained in:
James Babcock committed 2026-10-14 01:32:21 -07:00
1 parent 132b90c21d
commit 08094a3be9
5 files changed
+481 -6

No files matched your search

+1
View File
@@ -9,6 +9,7 @@
* Add configuration options to the glanceboard system card and music player
* Glanceboard compass shows calibration-accuracy indicator
* Status-bar widgets (nightscout, weather) are selectable
* Roam app: Add a date-picker for navigating to a daily page
### Bug fixes
+9
View File
@@ -37,6 +37,15 @@ export function dailyPageUid(date: Date): string {
return `${month}-${day}-${date.getFullYear()}`;
}
/** The date a daily-note page uid names, or null for any other uid. */
export function dailyPageDate(uid: string): Date | null {
const match = /^(\d{2})-(\d{2})-(\d{4})$/.exec(uid);
if (!match) return null;
const date = new Date(Number(match[3]), Number(match[1]) - 1, Number(match[2]));
// Rejects out-of-range fields such as 02-31, which Date would roll over.
return dailyPageUid(date) === uid ? date : null;
}
/** Daily-note page title for a date, e.g. "August 3rd, 2026". */
export function dailyPageTitle(date: Date): string {
const months = [
+28 -6
View File
@@ -2,7 +2,8 @@
* 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
* pages then yields focus. The context menu jumps to today's or a picked
* date's daily note. Edits (check/uncheck, add todo, edit block) go
* through the Roam backend API and are also exposed as assistant tools.
* The graph name and API token are configured here too, from the context
* menu, via the phone app's text editor.
@@ -19,6 +20,7 @@ import { getActiveDisplay } from "../../native/active-display";
import { onSettingsStoreChanged } from "../../native/settings-store";
import type { MenuItem } from "../../ui/menu";
import { WindowMenu } from "../../ui/window-menu";
import { DatePickerLayer } from "../../ui/date-picker";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
@@ -32,6 +34,7 @@ import { docNodePageLink, type DocNode } from "../../ui/document/document-model"
import {
createBlock,
createPage,
dailyPageDate,
dailyPageTitle,
dailyPageUid,
fetchPageByUid,
@@ -280,9 +283,12 @@ function inferForeground(focused: boolean): void {
// ---------------------------------------------------------------------------
// Page loading
function dailyRef(date: Date): PageRef {
return { uid: dailyPageUid(date), title: dailyPageTitle(date) };
}
function todayRef(): PageRef {
const now = new Date();
return { uid: dailyPageUid(now), title: dailyPageTitle(now) };
return dailyRef(new Date());
}
async function loadPage(ref: PageRef, options: { resetStack?: boolean; pushCurrent?: boolean } = {}): Promise<void> {
@@ -311,8 +317,8 @@ async function loadPage(ref: PageRef, options: { resetStack?: boolean; pushCurre
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.
} else if (dailyPageDate(uid)) {
// A daily note isn't created until something is written to it.
currentPage = { uid, title: ref.title, children: [] };
pageMissing = true;
} else {
@@ -371,6 +377,22 @@ function menuItems(): MenuItem[] {
},
});
}
items.push({
label: "Go to date",
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(new DatePickerLayer({
title: "Go to date",
initial: (currentRef?.uid ? dailyPageDate(currentRef.uid) : null) ?? new Date(),
confirmLabel: "open",
onPick: (date) => {
const ref = dailyRef(date);
if (ref.uid === currentRef?.uid) void reloadCurrentPage();
else void loadPage(ref, { pushCurrent: true });
},
}));
},
});
items.push({
label: "Refresh",
onSelect: (ctx) => {
@@ -515,7 +537,7 @@ async function toggleTodo(node: DocNode): Promise<void> {
}
}
/** Create today's daily page if it only exists locally. */
/** Create the shown daily page if it only exists locally. */
async function ensureCurrentPageExists(): Promise<void> {
if (!currentPage || !pageMissing) return;
await createPage(currentPage.title, currentPage.uid);
+294
View File
@@ -0,0 +1,294 @@
import { GrayImage, type UiFont } from "../graphics/image";
import { truncateText } from "../graphics/textwrap";
import { getDefaultMediumFont, getDefaultSmallFont } from "../graphics/ui-fonts";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, gestureHints, type InputEvent } from "./gestures";
import type { Layer, LayerContext, PaintBelow } from "./layers";
import { CONTEXT_MENU_DIM } from "./menu";
import { centeredTextY } from "./metrics";
/** A calendar day with no time or zone attached; month is 0-11, as in Date. */
export type CalendarDay = { year: number; month: number; day: number };
/** The picker's fields, in display and click order. */
export const DATE_FIELDS = ["day", "month", "year"] as const;
export type DateField = (typeof DATE_FIELDS)[number];
const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const WEEKDAY_HEADERS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
/** Year bounds: four digits, and clear of Date's 0-99 => 1900s mapping. */
const MIN_YEAR = 1000;
const MAX_YEAR = 9999;
const DAY_MS = 86_400_000;
const PADDING = 12;
const COLUMN_GAP = 24;
const FIELD_GAP = 8;
const FIELD_PAD_X = 6;
/** Fill and outline of the active field and the selected day (the Timers pickers' field style). */
const ACTIVE_FILL = 35;
const ACTIVE_STROKE = 130;
const TODAY_STROKE = 60;
export function calendarDayOf(date: Date): CalendarDay {
return { year: date.getFullYear(), month: date.getMonth(), day: date.getDate() };
}
/** Local midnight on the given day. */
export function calendarDayToDate({ year, month, day }: CalendarDay): Date {
return new Date(year, month, day);
}
export function daysInMonth(year: number, month: number): number {
return new Date(year, month + 1, 0).getDate();
}
/** Whole days from `from` to `to` (negative when `to` is earlier). */
export function daysBetween(from: CalendarDay, to: CalendarDay): number {
return Math.round((Date.UTC(to.year, to.month, to.day) - Date.UTC(from.year, from.month, from.day)) / DAY_MS);
}
/**
* Step a day by `delta` of a field's unit. Day steps are date arithmetic,
* rolling into neighboring months and years. Month and year steps keep the
* day of month, clamped to the target month's length; they aim for
* `preferredDay` (the day last picked) so stepping from Jan 31 through
* February lands on Mar 31 again. A step past the year bounds is refused.
*/
export function stepCalendarDay(date: CalendarDay, field: DateField, delta: number, preferredDay = date.day): CalendarDay {
let next: CalendarDay;
if (field === "day") {
next = calendarDayOf(new Date(date.year, date.month, date.day + delta));
} else {
const months = date.year * 12 + date.month + (field === "month" ? delta : delta * 12);
const year = Math.floor(months / 12);
const month = months - year * 12;
next = { year, month, day: Math.min(preferredDay, daysInMonth(year, month)) };
}
return next.year < MIN_YEAR || next.year > MAX_YEAR ? date : next;
}
/** "today", "yesterday", "in 3 days"... for a day relative to today. */
export function relativeDayLabel(date: CalendarDay, today: CalendarDay): string {
const days = daysBetween(today, date);
if (days === 0) return "today";
if (days === -1) return "yesterday";
if (days === 1) return "tomorrow";
return days < 0 ? `${-days} days ago` : `in ${days} days`;
}
export type DatePickerOptions = {
title: string;
/** The day to start on (its local calendar day). Default: today. */
initial?: Date;
/** Hint for the final click, e.g. "open". Default "done". */
confirmLabel?: string;
/** Called with the picked day, as local midnight, after the picker has closed. */
onPick: (date: Date) => void;
/** Called when the picker closes without a pick: cancelled, or cleared away by its host. */
onCancel?: () => void;
};
/**
* A modal date picker: day, month and year fields beside a month calendar,
* in a dialog centered on its stack's base (an app window, or the shell
* surface) with the content beneath dimmed like a context menu's. Pushed on
* a LayerStack, it works in in-process apps and in worker apps alike (a
* worker pushes it from a WindowMenu item, whose stack then hosts it).
*
* Input follows the Timers app's field pickers: scroll adjusts the active
* field (up is later), click moves to the next field and on the last one
* picks the date, double-click steps back a field and on the first one
* cancels. A watch's swipes move between fields (left / right) and adjust
* (up / down). Steps are date arithmetic rather than per-field wrapping (see
* stepCalendarDay), so a nearby day needs only the day field.
*/
export class DatePickerLayer implements Layer {
readonly acceptsDirectional = true;
readonly dimUnderneath = CONTEXT_MENU_DIM;
private date: CalendarDay;
/** The day of month to aim for when month or year steps pass through shorter months. */
private preferredDay: number;
private field = 0;
/** Picked or cancelled: onRemoved must not report a cancel. */
private finished = false;
constructor(private readonly options: DatePickerOptions) {
this.date = calendarDayOf(options.initial ?? new Date());
this.preferredDay = this.date.day;
}
/** The day currently shown. */
get value(): CalendarDay {
return { ...this.date };
}
get activeField(): DateField {
return DATE_FIELDS[this.field]!;
}
onRemoved(): void {
if (this.finished) return;
this.finished = true;
this.options.onCancel?.();
}
handleInput(event: InputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
case "swipe-up":
this.adjust(1);
return;
case "scroll-down":
case "swipe-down":
this.adjust(-1);
return;
case "swipe-right":
this.field = Math.min(DATE_FIELDS.length - 1, this.field + 1);
return;
case "swipe-left":
this.field = Math.max(0, this.field - 1);
return;
case "click":
if (this.field < DATE_FIELDS.length - 1) {
this.field++;
} else {
this.finished = true;
ctx.stack.pop();
this.options.onPick(calendarDayToDate(this.date));
}
return;
case "double-click":
if (this.field > 0) this.field--;
else ctx.stack.pop();
return;
default:
return;
}
}
private adjust(delta: number): void {
const field = this.activeField;
this.date = stepCalendarDay(this.date, field, delta, this.preferredDay);
if (field === "day") this.preferredDay = this.date.day;
}
private hints(field: number): string {
return gestureHints([
[GESTURE_SCROLL, "adjust"],
[GESTURE_CLICK, field < DATE_FIELDS.length - 1 ? "next" : this.options.confirmLabel ?? "done"],
[GESTURE_DOUBLE_CLICK, field > 0 ? "back" : "cancel"],
]);
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const image = paintBelow();
const small = getDefaultSmallFont();
const medium = getDefaultMediumFont();
const focused = ctx.stack.isFocused();
const base = ctx.stack.getBaseSize();
// Sized for the widest value each field and line can show, so the dialog
// holds still while the date changes.
const fieldWidths = [
medium.measureText("00"),
Math.max(...MONTH_NAMES.map((name) => medium.measureText(name))),
medium.measureText("0000"),
].map((width, index) => Math.max(width, small.measureText(DATE_FIELDS[index]!)) + 2 * FIELD_PAD_X);
const fieldsWidth = fieldWidths.reduce((sum, width) => sum + width, 0) + FIELD_GAP * (fieldWidths.length - 1);
const boxHeight = medium.lineHeight + 6;
const leftWidth = Math.max(fieldsWidth, small.measureText("Wednesday · 999 days ago"));
const leftHeight = boxHeight + 2 + small.lineHeight + 12 + small.lineHeight;
const cellWidth = Math.max(small.measureText("00"), ...WEEKDAY_HEADERS.map((name) => small.measureText(name))) + 8;
const cellHeight = small.lineHeight + 4;
const gridWidth = 7 * cellWidth;
// A header row plus six weeks, the most a month spans.
const gridHeight = 7 * cellHeight;
const hintsWidth = Math.max(...DATE_FIELDS.map((_, index) => small.measureText(this.hints(index))));
const chrome = (bodyWidth: number) => Math.max(bodyWidth, hintsWidth, small.measureText(this.options.title)) + 2 * PADDING;
const titleHeight = small.lineHeight + 12;
const footerHeight = 12 + small.lineHeight + 10;
const chromeHeight = 8 + titleHeight + footerHeight;
// Drop the calendar when the dialog would not fit beside it.
let width = chrome(leftWidth + COLUMN_GAP + gridWidth);
let bodyHeight = Math.max(leftHeight, gridHeight);
const showGrid = width <= base.width - 16 && chromeHeight + bodyHeight <= base.height - 8;
if (!showGrid) {
width = Math.min(chrome(leftWidth), base.width);
bodyHeight = leftHeight;
}
const height = Math.min(chromeHeight + bodyHeight, base.height);
const x = Math.max(0, Math.floor((base.width - width) / 2));
const y = Math.max(0, Math.floor((base.height - height) / 2));
// Fill 1, not 0: 0 is the transparent color key on the shell surface.
image.fillRoundedRect(x, y, width, height, 1);
image.drawRoundedRect(x, y, width, height, 72);
image.drawText(small, x + PADDING, y + 8, truncateText(small, this.options.title, width - 2 * PADDING), 220);
const bodyTop = y + 8 + titleHeight;
const leftX = x + PADDING;
const leftTop = bodyTop + Math.floor((bodyHeight - leftHeight) / 2);
this.paintFields(image, medium, small, leftX, leftTop, fieldWidths, boxHeight, focused);
const today = calendarDayOf(new Date());
const weekday = calendarDayToDate(this.date).getDay();
const summary = `${WEEKDAY_NAMES[weekday]} · ${relativeDayLabel(this.date, today)}`;
image.drawText(small, leftX, leftTop + leftHeight - small.lineHeight,
truncateText(small, summary, showGrid ? leftWidth : width - 2 * PADDING), 190);
if (showGrid) {
this.paintMonth(image, small, x + width - PADDING - gridWidth, bodyTop, cellWidth, cellHeight, today, focused);
}
image.drawText(small, x + PADDING, y + height - 10 - small.lineHeight, this.hints(this.field), 110);
return image;
}
/** The three fields as boxes with captions beneath; the active one highlighted. */
private paintFields(image: GrayImage, font: UiFont, captionFont: UiFont, x: number, y: number,
widths: number[], boxHeight: number, focused: boolean): void {
const values = [String(this.date.day), MONTH_NAMES[this.date.month]!, String(this.date.year)];
for (let index = 0; index < DATE_FIELDS.length; index++) {
const width = widths[index]!;
const active = index === this.field;
if (active) {
if (focused) image.fillRoundedRect(x, y, width, boxHeight, ACTIVE_FILL, 6);
image.drawRoundedRect(x, y, width, boxHeight, ACTIVE_STROKE, 6);
}
const value = values[index]!;
image.drawText(font, x + Math.floor((width - font.measureText(value)) / 2), centeredTextY(font, y, boxHeight),
value, active ? 250 : 170);
const caption = DATE_FIELDS[index]!;
image.drawText(captionFont, x + Math.floor((width - captionFont.measureText(caption)) / 2), y + boxHeight + 2,
caption, 110);
x += width + FIELD_GAP;
}
}
/** The shown month as a Sunday-first grid: the picked day highlighted, today outlined. */
private paintMonth(image: GrayImage, font: UiFont, x: number, y: number, cellWidth: number, cellHeight: number,
today: CalendarDay, focused: boolean): void {
const { year, month, day: picked } = this.date;
for (let column = 0; column < 7; column++) {
const header = WEEKDAY_HEADERS[column]!;
image.drawText(font, x + column * cellWidth + Math.floor((cellWidth - font.measureText(header)) / 2),
centeredTextY(font, y, cellHeight), header, 110);
}
const firstWeekday = new Date(year, month, 1).getDay();
const todayInMonth = today.year === year && today.month === month ? today.day : 0;
for (let day = 1, count = daysInMonth(year, month); day <= count; day++) {
const slot = firstWeekday + day - 1;
const cellX = x + (slot % 7) * cellWidth;
const cellY = y + (1 + Math.floor(slot / 7)) * cellHeight;
const selected = day === picked;
if (selected) {
if (focused) image.fillRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, ACTIVE_FILL, 4);
image.drawRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, ACTIVE_STROKE, 4);
} else if (day === todayInMonth) {
image.drawRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, TODAY_STROKE, 4);
}
const text = String(day);
image.drawText(font, cellX + Math.floor((cellWidth - font.measureText(text)) / 2),
centeredTextY(font, cellY, cellHeight), text, selected ? 255 : day === todayInMonth ? 220 : 170);
}
}
}
+149
View File
@@ -0,0 +1,149 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules = {}) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, require: (name) => modules[name] ?? {}, console, Date };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context, { filename: file });
return context.exports;
}
const textwrap = load('app/graphics/textwrap.ts');
const graphics = require('../.test-build/app/graphics/image.js');
const plane = load('app/graphics/plane.ts', { './image': graphics });
const gestures = load('app/ui/gestures.ts');
const { BdfFont } = load('app/graphics/bdffont.ts');
const font = (name) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/${name}.bdf`), 'utf8'));
const fonts = { getDefaultSmallFont: () => font('ter-u12n'), getDefaultMediumFont: () => font('ter-u16n') };
const layers = load('app/ui/layers.ts', {
'../graphics/image': graphics, '../graphics/plane': plane, './gestures': gestures,
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
});
const picker = load('app/ui/date-picker.ts', {
'../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts, './gestures': gestures,
'./menu': { CONTEXT_MENU_DIM: 0.25 }, './metrics': load('app/ui/metrics.ts'),
});
const day = (year, month, date) => ({ year, month: month - 1, day: date });
// Copied into this realm: the module's objects carry the vm context's prototypes.
const step = (...args) => ({ ...picker.stepCalendarDay(...args) });
function fixture(initial = new Date(2026, 9, 14), size = { width: 576, height: 260 }) {
const picks = [];
let cancels = 0;
const base = { paint: () => new graphics.GrayImage(size.width, size.height, 0), handleInput() {} };
const stack = new layers.LayerStack(base, layers.noopLayerActions, size);
const layer = new picker.DatePickerLayer({
title: 'Go to date', initial, onPick: (date) => picks.push(date), onCancel: () => cancels++,
});
stack.push(layer);
return {
stack, layer, picks, cancels: () => cancels,
input: async (...types) => {
for (const type of types) await stack.handleInput(gestures.makeInputEvent({ type, source: 'ring' }));
},
};
}
test('day steps roll across months and years', () => {
assert.deepEqual(step(day(2026, 10, 31), 'day', 1), day(2026, 11, 1));
assert.deepEqual(step(day(2026, 1, 1), 'day', -1), day(2025, 12, 31));
assert.deepEqual(step(day(2024, 2, 28), 'day', 1), day(2024, 2, 29));
});
test('month and year steps clamp to short months but return to the preferred day', () => {
const feb = step(day(2026, 1, 31), 'month', 1, 31);
assert.deepEqual(feb, day(2026, 2, 28));
assert.deepEqual(step(feb, 'month', 1, 31), day(2026, 3, 31));
assert.deepEqual(step(day(2026, 1, 15), 'month', -1), day(2025, 12, 15));
assert.deepEqual(step(day(2024, 2, 29), 'year', 1, 29), day(2025, 2, 28));
assert.deepEqual(step(day(9999, 12, 31), 'day', 1), day(9999, 12, 31));
assert.deepEqual(step(day(1000, 3, 1), 'year', -1), day(1000, 3, 1));
});
test('relative labels count whole days', () => {
const today = day(2026, 10, 14);
assert.equal(picker.relativeDayLabel(today, today), 'today');
assert.equal(picker.relativeDayLabel(day(2026, 10, 13), today), 'yesterday');
assert.equal(picker.relativeDayLabel(day(2026, 10, 15), today), 'tomorrow');
assert.equal(picker.relativeDayLabel(day(2026, 10, 4), today), '10 days ago');
// Across the US DST change on Nov 1.
assert.equal(picker.relativeDayLabel(day(2026, 11, 20), today), 'in 37 days');
});
test('scroll adjusts the active field; clicks walk the fields and the last one picks', async () => {
const f = fixture();
await f.input('scroll-down', 'scroll-down', 'scroll-down');
assert.deepEqual({ ...f.layer.value }, day(2026, 10, 11));
await f.input('click');
assert.equal(f.layer.activeField, 'month');
await f.input('scroll-up');
assert.deepEqual({ ...f.layer.value }, day(2026, 11, 11));
await f.input('click', 'scroll-down', 'click');
assert.ok(f.stack.isAtBase());
assert.equal(f.picks.length, 1);
assert.equal(f.picks[0].getTime(), new Date(2025, 10, 11).getTime());
assert.equal(f.cancels(), 0);
});
test('double-click steps back a field, then cancels from the first', async () => {
const f = fixture();
await f.input('click', 'click');
assert.equal(f.layer.activeField, 'year');
await f.input('double-click', 'double-click');
assert.equal(f.layer.activeField, 'day');
assert.ok(!f.stack.isAtBase());
await f.input('double-click');
assert.ok(f.stack.isAtBase());
assert.equal(f.cancels(), 1);
assert.equal(f.picks.length, 0);
});
test('a host clearing the stack reports a cancel', () => {
const f = fixture();
f.stack.clearToBase();
assert.equal(f.cancels(), 1);
});
test('watch swipes move between fields without picking or cancelling', async () => {
const f = fixture();
await f.input('swipe-left');
assert.ok(!f.stack.isAtBase());
await f.input('swipe-right', 'swipe-right', 'swipe-right', 'swipe-up');
assert.equal(f.layer.activeField, 'year');
assert.deepEqual({ ...f.layer.value }, day(2027, 10, 14));
assert.ok(!f.stack.isAtBase());
});
test('the dialog is centered over the dimmed window, dropping the calendar when it does not fit', () => {
const widths = [];
for (const size of [{ width: 576, height: 260 }, { width: 576, height: 160 }, { width: 300, height: 260 }]) {
const f = fixture(new Date(2026, 9, 14), size);
const planes = f.stack.paint();
assert.equal(planes.length, 2);
assert.equal(planes.at(-1).dimUnderneath, 0.25);
// The dialog's backdrop is the only value-1 fill.
const image = planes.at(-1).image.withDrawsBaked();
let left = Infinity, right = -1, top = Infinity, bottom = -1;
for (let y = 0; y < image.height; y++) {
for (let x = 0; x < image.width; x++) {
if (image.getPixel(x, y) !== 1) continue;
left = Math.min(left, x); right = Math.max(right, x);
top = Math.min(top, y); bottom = Math.max(bottom, y);
}
}
assert.ok(left > 0 && top > 0 && right < size.width - 1 && bottom < size.height - 1);
assert.ok(Math.abs(left - (size.width - 1 - right)) <= 1);
assert.ok(Math.abs(top - (size.height - 1 - bottom)) <= 1);
widths.push(right - left);
}
// Only the roomy window has the calendar beside the fields.
assert.ok(widths[0] > widths[1] + 100);
assert.equal(widths[1], widths[2]);
});