@kiosko/sdk 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/format.ts ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Times and lengths of time, written the same way by every widget:
3
+ * `ctx.fmt.time(at)`, `ctx.fmt.ago(at)` and `ctx.fmt.duration(ms)`.
4
+ *
5
+ * They follow the panel's language (English and Spanish words; any other
6
+ * language gets the English ones) and the config's `timeFormat`. Hand-written
7
+ * rather than `Intl.RelativeTimeFormat`: its short forms differ between ICU
8
+ * versions (Node, Chromium, WebKit), and a panel must paint the same thing in
9
+ * the editor, the browser demo and on the glass.
10
+ */
11
+
12
+ /** How clock times are written: `auto` follows the language (24 h in Spanish, 12 h in US English). */
13
+ export type TimeFormat = 'auto' | '24h' | '12h';
14
+ export const TIME_FORMATS: readonly TimeFormat[] = ['auto', '24h', '12h'];
15
+
16
+ export interface Formatters {
17
+ /** True when clock times are written on a 12-hour clock. */
18
+ readonly hour12: boolean;
19
+ /**
20
+ * A clock time: `"09:05"` on a 24-hour clock, `"9:05 AM"` (`"9:05 a. m."`)
21
+ * on a 12-hour one. `seconds` adds `":07"`; `ampm: false` leaves out
22
+ * AM/PM (a big clock that paints it apart).
23
+ */
24
+ time(at: number | Date, o?: { seconds?: boolean; ampm?: boolean }): string;
25
+ /**
26
+ * How long ago `at` (epoch ms, a Date or an ISO string) was, from `ctx.now`:
27
+ * `"just now"`, `"5 min ago"`, `"3 h ago"`, `"4 d ago"`, `"2 wk ago"`,
28
+ * `"1 yr ago"` (`"hace 5 min"`…). `suffix: false` gives the bare age for
29
+ * a meta line: `"now"`, `"5 min"`, `"3 h"`. A future `at` is "now".
30
+ */
31
+ ago(at: number | Date | string, o?: { suffix?: boolean; now?: number }): string;
32
+ /**
33
+ * A length of time: `"45 s"` (only with `seconds`), `"12 min"`,
34
+ * `"1 h 05"`, `"2 d 3 h"`. Rounded down by default; `round: 'up'` for
35
+ * countdowns ("in 0 min" would be a lie until it starts). `compact`
36
+ * drops a zero remainder: `"1 h"` rather than `"1 h 00"`, `"2 d"` rather
37
+ * than `"2 d 0 h"` (a span such as "the last 1 h", not a running timer).
38
+ */
39
+ duration(ms: number, o?: { seconds?: boolean; round?: 'down' | 'up' | 'nearest'; compact?: boolean }): string;
40
+ }
41
+
42
+ interface Words {
43
+ now: string;
44
+ justNow: string;
45
+ ago: (v: string) => string;
46
+ wk: string;
47
+ yr: (n: number) => string;
48
+ am: string;
49
+ pm: string;
50
+ }
51
+
52
+ const WORDS: Record<string, Words> = {
53
+ en: { now: 'now', justNow: 'just now', ago: (v) => `${v} ago`, wk: 'wk', yr: () => 'yr', am: 'AM', pm: 'PM' },
54
+ es: { now: 'ahora', justNow: 'ahora mismo', ago: (v) => `hace ${v}`, wk: 'sem', yr: (n) => (n === 1 ? 'año' : 'años'), am: 'a. m.', pm: 'p. m.' },
55
+ };
56
+
57
+ const langOf = (locale: string) => locale.toLowerCase().split(/[-_]/)[0] ?? 'en';
58
+ const wordsFor = (locale: string): Words => WORDS[langOf(locale)] ?? WORDS.en!;
59
+ const pad2 = (n: number) => String(n).padStart(2, '0');
60
+
61
+ const cycles = new Map<string, boolean>();
62
+
63
+ /** Whether `locale` writes times on a 12-hour clock, per `timeFormat`. */
64
+ export function usesHour12(locale: string, timeFormat: TimeFormat = 'auto'): boolean {
65
+ if (timeFormat !== 'auto') return timeFormat === '12h';
66
+ let h12 = cycles.get(locale);
67
+ if (h12 === undefined) {
68
+ try {
69
+ const cycle = new Intl.DateTimeFormat(locale, { hour: 'numeric' }).resolvedOptions().hourCycle;
70
+ h12 = cycle === 'h11' || cycle === 'h12';
71
+ } catch {
72
+ h12 = false;
73
+ }
74
+ cycles.set(locale, h12);
75
+ }
76
+ return h12;
77
+ }
78
+
79
+ function toMs(at: number | Date | string): number {
80
+ if (typeof at === 'number') return at;
81
+ if (typeof at === 'string') return Date.parse(at);
82
+ return at.getTime();
83
+ }
84
+
85
+ /**
86
+ * The formatters of a context. Kiosko builds them for every plugin context;
87
+ * plugin tests can build their own: `createFormatters({ locale: 'es', now })`.
88
+ */
89
+ export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; now: number }): Formatters {
90
+ const w = wordsFor(o.locale);
91
+ const hour12 = usesHour12(o.locale, o.timeFormat);
92
+ return {
93
+ hour12,
94
+ time(at, opts = {}) {
95
+ const d = new Date(toMs(at));
96
+ const h = d.getHours();
97
+ const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ''}`;
98
+ if (!hour12) return `${pad2(h)}${rest}`;
99
+ const base = `${h % 12 || 12}${rest}`;
100
+ return opts.ampm === false ? base : `${base} ${h < 12 ? w.am : w.pm}`;
101
+ },
102
+ ago(at, opts = {}) {
103
+ const suffix = opts.suffix !== false;
104
+ const ms = (opts.now ?? o.now) - toMs(at);
105
+ const min = Math.floor(ms / 60_000);
106
+ if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
107
+ const h = Math.floor(min / 60);
108
+ const d = Math.floor(h / 24);
109
+ const v = min < 60 ? `${min} min` : h < 24 ? `${h} h` : d < 14 ? `${d} d` : d < 365 ? `${Math.floor(d / 7)} ${w.wk}` : `${Math.floor(d / 365)} ${w.yr(Math.floor(d / 365))}`;
110
+ return suffix ? w.ago(v) : v;
111
+ },
112
+ duration(ms, opts = {}) {
113
+ const round = opts.round === 'up' ? Math.ceil : opts.round === 'nearest' ? Math.round : Math.floor;
114
+ const safe = Number.isFinite(ms) ? Math.max(0, ms) : 0;
115
+ if (opts.seconds && safe < 60_000) return `${round(safe / 1000)} s`;
116
+ const min = round(safe / 60_000);
117
+ if (min < 60) return `${min} min`;
118
+ const h = Math.floor(min / 60);
119
+ if (h < 24) return opts.compact && min % 60 === 0 ? `${h} h` : `${h} h ${pad2(min % 60)}`;
120
+ return opts.compact && h % 24 === 0 ? `${h / 24} d` : `${Math.floor(h / 24)} d ${h % 24} h`;
121
+ },
122
+ };
123
+ }
package/src/i18n.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Plugin texts can be a plain string (shown as is) or a map by language.
3
+ * The editor and the panel pick the user's locale, then English, then the
4
+ * first one available.
5
+ */
6
+ export type Localized = string | ({ en: string } & Partial<Record<string, string>>);
7
+
8
+ export function localize(text: Localized | undefined, locale = 'en'): string {
9
+ if (text === undefined) return '';
10
+ if (typeof text === 'string') return text;
11
+ const lang = locale.toLowerCase().split(/[-_]/)[0]!;
12
+ return text[locale] ?? text[lang] ?? text.en ?? Object.values(text).find((v) => typeof v === 'string') ?? '';
13
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export * from './plugin.ts';
2
+ export * from './schema.ts';
3
+ export * from './theme.ts';
4
+ export * from './i18n.ts';
5
+ export * from './format.ts';
6
+ export * from './workday.ts';
7
+ export * from './list.ts';
8
+ export * from './filter.ts';
9
+ export * from './context.ts';
10
+ export * from './location.ts';
11
+ export * from './system.ts';
package/src/list.ts ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Lists, the same in every widget: two shared options (`rows`, `layout`),
3
+ * one layout helper that decides how many rows fit and how tall they are,
4
+ * and one "+N more" line.
5
+ *
6
+ * options: t.object({
7
+ * ...listOptions({ layouts: ['one-line', 'detailed'] }), // rows, layout
8
+ * projects: t.filter({ label: 'Projects' }),
9
+ * }),
10
+ * render(g, ctx) {
11
+ * const items = …;
12
+ * if (!items.length) return drawEmpty(g, ctx, ctx.t({ en: 'Nothing to review', es: 'Nada que revisar' }));
13
+ * const plan = listLayout(ctx.box, items.length, ctx.options, {
14
+ * sizes: { 'one-line': { min: 22, max: 46 }, detailed: { min: 50, max: 80 } },
15
+ * auto: (box, n) => (box.h >= box.w * 0.7 && box.h / n >= 50 ? 'detailed' : 'one-line'),
16
+ * });
17
+ * plan.rows.forEach((row, i) => drawItem(items[i], row, plan.layout, plan.textSize));
18
+ * drawMore(g, ctx, plan);
19
+ * },
20
+ *
21
+ * `rows` = 0 fits as many rows as the box holds, each between the layout's
22
+ * `min` and `max` px. `rows` = N shows N items, in rows of the box's height
23
+ * divided by N but never taller than `max` (the rest of the box stays empty,
24
+ * below them) nor shorter than `min` (then fewer rows). Items left out are
25
+ * counted in "+N more", a compact line under the last row.
26
+ */
27
+ import type { Localized } from './i18n.ts';
28
+ import type { Box, Graphics, RenderContext } from './plugin.ts';
29
+ import { t, type EnumField, type NumberField } from './schema.ts';
30
+
31
+ /** How a list row is drawn: one line per item, or a title with details under it. */
32
+ export type ListLayout = 'one-line' | 'detailed';
33
+ /** The `layout` option: a fixed layout, or `auto` (the widget's own rule). */
34
+ export type ListLayoutChoice = 'auto' | ListLayout;
35
+
36
+ const LAYOUT_LABELS: Record<ListLayoutChoice, Localized> = {
37
+ auto: { en: 'Automatic', es: 'Automático' },
38
+ 'one-line': { en: 'One line', es: 'Una línea' },
39
+ detailed: { en: 'Detailed', es: 'Detallado' },
40
+ };
41
+
42
+ const rowsField = (def: number): NumberField =>
43
+ t.integer({
44
+ default: def,
45
+ min: 0,
46
+ max: 30,
47
+ label: { en: 'Rows', es: 'Filas' },
48
+ help: {
49
+ en: '0 = as many as fit. A number shows that many, in rows of a readable size (fewer when the tile is too small for them); the rest are counted in "+N more".',
50
+ es: '0 = las que quepan. Con un número se ven esas, en filas de un tamaño legible (menos si la tesela no da para ellas); el resto se cuenta en «+N más».',
51
+ },
52
+ });
53
+
54
+ /**
55
+ * The shared list options, to spread into the widget's `t.object({...})`:
56
+ * `rows` (0 = auto, up to 30) and, when the widget draws two layouts,
57
+ * `layout` (`auto` plus those). `rows` is the default of `rows`: 0 unless
58
+ * the widget had a fixed count before.
59
+ */
60
+ export function listOptions(o?: { rows?: number }): { rows: NumberField };
61
+ export function listOptions<L extends ListLayout>(o: { rows?: number; layouts: readonly [L, L, ...L[]]; layout?: 'auto' | L }): { rows: NumberField; layout: EnumField<'auto' | L> };
62
+ export function listOptions(o: { rows?: number; layouts?: readonly ListLayout[]; layout?: ListLayoutChoice } = {}): { rows: NumberField; layout?: EnumField<ListLayoutChoice> } {
63
+ const rows = rowsField(o.rows ?? 0);
64
+ if (!o.layouts || o.layouts.length < 2) return { rows };
65
+ const values = ['auto', ...o.layouts] as ListLayoutChoice[];
66
+ return {
67
+ rows,
68
+ layout: t.enum(values, {
69
+ default: o.layout ?? 'auto',
70
+ label: { en: 'Row layout', es: 'Formato de fila' },
71
+ labels: Object.fromEntries(values.map((v) => [v, LAYOUT_LABELS[v]])),
72
+ help: { en: 'Automatic: the widget picks by the tile\'s shape.', es: 'Automático: el widget elige según la forma de la tesela.' },
73
+ }),
74
+ };
75
+ }
76
+
77
+ /** Row heights of one layout, in px of the widget's box. */
78
+ export interface RowSize {
79
+ /** Smallest row that can still be read. */
80
+ min: number;
81
+ /** Tallest row: rows never grow past it, however few they are (the rest of the box stays empty). */
82
+ max: number;
83
+ }
84
+
85
+ export interface ListSpec<L extends ListLayout = ListLayout> {
86
+ /** One entry per layout the widget draws: its row heights. */
87
+ sizes: { [K in L]: RowSize };
88
+ /**
89
+ * The layout `auto` picks: the widget's own rule (e.g. two lines on tall
90
+ * tiles). `count` is how many rows the box is sized for: `rows` when the
91
+ * user set it (and there are that many items), otherwise every item.
92
+ * Default: the first layout in `sizes`.
93
+ */
94
+ auto?: (box: Box, count: number) => L;
95
+ /** In auto mode, size rows as if there were at least this many items, so one item doesn't get a giant row. Default 1. */
96
+ minRows?: number;
97
+ /** Height of the "+N more" line, in px. Default: `moreHeight(rowH)`. Never more than a row. */
98
+ moreH?: number;
99
+ }
100
+
101
+ export interface ListPlan<L extends ListLayout = ListLayout> {
102
+ /** The layout to draw (`auto` already resolved). */
103
+ layout: L;
104
+ /** Height of every row, in px: between the layout's `min` and `max` (less only in a box shorter than one row). */
105
+ rowH: number;
106
+ /** One box per row to draw, top to bottom from the top of the box: item i goes in `rows[i]`. */
107
+ rows: Box[];
108
+ /** Items drawn (`rows.length`). */
109
+ shown: number;
110
+ /** Items left out, counted in "+N more". */
111
+ hidden: number;
112
+ /** Where "+N more" goes, right under the last row; null when everything fits (or a tiny box leaves no room for it). */
113
+ more: Box | null;
114
+ /** Suggested size of a row's main text, px: 60 % of a one-line row, 42 % of a detailed one (its first line). */
115
+ textSize: number;
116
+ /** Suggested size of the secondary text: a detailed row's second line (30 % of the row), or the smaller bits of a one-line row (80 % of `textSize`). */
117
+ detailSize: number;
118
+ }
119
+
120
+ /** Rows may overflow the box by this fraction of a row (the descenders of the last one), as widgets always did. */
121
+ const TOLERANCE = 0.1;
122
+ /** A "+N more" line shorter than this is left out (its text would be under 8 px). */
123
+ const MIN_MORE_H = 12;
124
+ const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
125
+
126
+ /** Height of the "+N more" line under rows of `rowH` px: 60 % of a row, between 18 and 28 px, never more than a row. */
127
+ export function moreHeight(rowH: number): number {
128
+ return Math.min(clamp(Math.round(rowH * 0.6), 18, 28), rowH);
129
+ }
130
+
131
+ /**
132
+ * Plans a list of `count` items in `box` from the shared options (`rows`,
133
+ * `layout`) and the widget's row heights. Pure: no drawing, no canvas.
134
+ *
135
+ * - `rows` 0: rows of `box.h / count` (at least `minRows`), clamped to the
136
+ * layout's `min`–`max`; as many as fit.
137
+ * - `rows` N: N items in rows of `box.h / N` clamped the same way, so they
138
+ * never balloon; fewer when N rows don't fit at `min`.
139
+ * - Items left out: a compact "+N more" line (`more`) right under the last
140
+ * row, reserved only then. A box with room for one row but not for the row
141
+ * and that line still gets the row, with the line squeezed or left out.
142
+ */
143
+ export function listLayout<L extends ListLayout>(box: Box, count: number, options: { rows?: number; layout?: string }, spec: ListSpec<L>): ListPlan<L> {
144
+ const declared = Object.keys(spec.sizes) as L[];
145
+ const n = Math.max(0, Math.floor(count));
146
+ const fixed = Math.max(0, Math.round(options.rows ?? 0));
147
+ const want = options.layout as L | 'auto' | undefined;
148
+ const layout: L = want && want !== 'auto' && declared.includes(want) ? want : (spec.auto?.(box, fixed > 0 ? Math.min(fixed, n) : n) ?? declared[0]!);
149
+ const size = spec.sizes[layout] ?? spec.sizes[declared[0]!];
150
+ const min = Math.max(1, size.min);
151
+ const max = Math.max(min, size.max);
152
+ const h = Math.max(0, box.h);
153
+ const text = (rowH: number) => {
154
+ const textSize = Math.round(rowH * (layout === 'detailed' ? 0.42 : 0.6));
155
+ return { textSize, detailSize: Math.round(layout === 'detailed' ? rowH * 0.3 : textSize * 0.8) };
156
+ };
157
+ if (h <= 0) return { layout, rowH: 0, rows: [], shown: 0, hidden: n, more: null, ...text(0) };
158
+
159
+ // Items to show and the rows the height is divided by.
160
+ const target = fixed > 0 ? Math.min(fixed, n) : n;
161
+ const divisor = fixed > 0 ? fixed : Math.max(n, spec.minRows ?? 1, 1);
162
+ const fits = (space: number, rowH: number) => Math.floor(space / rowH + TOLERANCE);
163
+ let rowH = clamp(h / divisor, min, max);
164
+ let shown = Math.min(target, fits(h, rowH));
165
+ let more: Box | null = null;
166
+ if (shown < n) {
167
+ // Items left out: the same rows over a compact "+N more" line.
168
+ let moreH = Math.min(spec.moreH ?? moreHeight(rowH), rowH);
169
+ rowH = clamp((h - moreH) / divisor, min, max);
170
+ shown = Math.min(target, fits(h - moreH, rowH));
171
+ if (shown < 1) {
172
+ // Room for a row but not for the row and the line: the row first (squeezed in a box shorter than one), the line in what's left.
173
+ shown = Math.min(1, n);
174
+ rowH = Math.min(h, min);
175
+ moreH = Math.min(moreH, h - rowH);
176
+ }
177
+ if (moreH >= MIN_MORE_H) more = { x: box.x, y: box.y + shown * rowH, w: box.w, h: moreH };
178
+ }
179
+ const rows = Array.from({ length: shown }, (_, i) => ({ x: box.x, y: box.y + i * rowH, w: box.w, h: rowH }));
180
+ return { layout, rowH, rows, shown, hidden: n - shown, more, ...text(rowH) };
181
+ }
182
+
183
+ /** `"+3 more"` / `"+3 más"`. */
184
+ export function moreLabel(n: number, tr: (text: Localized) => string): string {
185
+ return tr({ en: `+${n} more`, es: `+${n} más` });
186
+ }
187
+
188
+ type DrawCtx = Pick<RenderContext<unknown, unknown>, 'kit' | 'theme' | 't'>;
189
+
190
+ /**
191
+ * Paints "+N more" in the plan's `more` box, dim, the same in every list.
192
+ * `indent` lines it up with the rows' text (after a status dot, say);
193
+ * `align: 'right'` puts it at the right edge instead.
194
+ */
195
+ export function drawMore(g: Graphics, ctx: DrawCtx, plan: Pick<ListPlan, 'hidden' | 'more'>, o: { indent?: number; align?: 'left' | 'right' } = {}): void {
196
+ const m = plan.more;
197
+ if (!m || plan.hidden <= 0) return;
198
+ const size = Math.max(8, Math.round(m.h * 0.62));
199
+ const indent = o.indent ?? 0;
200
+ const font = { size, family: ctx.theme.fonts.sans, color: ctx.theme.colors.inkDim };
201
+ const text = ctx.kit.truncate(g, moreLabel(plan.hidden, ctx.t), Math.max(1, m.w - indent), font);
202
+ const y = m.y + (m.h + size * 0.7) / 2;
203
+ if (o.align === 'right') ctx.kit.drawTracked(g, text, m.x + m.w, y, { ...font, align: 'right' });
204
+ else ctx.kit.drawTracked(g, text, m.x + indent, y, font);
205
+ }
206
+
207
+ /**
208
+ * The message of an empty list ("Nothing to review"), dim, at the top left
209
+ * of the box, the same in every list. Paint it unless the user asked to hide
210
+ * the widget when it's empty (see `WidgetDefinition.empty`).
211
+ */
212
+ export function drawEmpty(g: Graphics, ctx: DrawCtx & { box: Box }, message: string): void {
213
+ const { box, kit, theme } = ctx;
214
+ const size = Math.max(10, Math.round(Math.min(32, box.h * 0.3)));
215
+ const font = { size, family: theme.fonts.sans, color: theme.colors.inkDim };
216
+ kit.drawTracked(g, kit.truncate(g, message, box.w, font), box.x, box.y + size * 1.1, font);
217
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The user's place is set once, in Settings, and reaches every plugin as
3
+ * `ctx.location`. A widget or source that can look somewhere else (the
4
+ * weather of another city) offers `locationOptions()`, advanced, and picks
5
+ * with `placeOf`: its own place when both coordinates are set, otherwise the
6
+ * user's.
7
+ */
8
+ import type { Location } from './plugin.ts';
9
+ import { t, type NumberField, type StringField } from './schema.ts';
10
+
11
+ /** Advanced latitude, longitude and name fields; 0, 0 means "the place in Settings". */
12
+ export function locationOptions(): { latitude: NumberField; longitude: NumberField; placeName: StringField } {
13
+ return {
14
+ latitude: t.number({
15
+ default: 0,
16
+ min: -90,
17
+ max: 90,
18
+ step: 0.0001,
19
+ unit: '°',
20
+ advanced: true,
21
+ label: { en: 'Latitude', es: 'Latitud' },
22
+ help: { en: 'Leave latitude and longitude at 0 to use the place in Settings.', es: 'Con latitud y longitud a 0 se usa el lugar de los ajustes.' },
23
+ }),
24
+ longitude: t.number({ default: 0, min: -180, max: 180, step: 0.0001, unit: '°', advanced: true, label: { en: 'Longitude', es: 'Longitud' } }),
25
+ placeName: t.string({ advanced: true, placeholder: 'Madrid', label: { en: 'Place name', es: 'Nombre del lugar' }, help: { en: 'Empty: the one in Settings.', es: 'Vacío: el de los ajustes.' } }),
26
+ };
27
+ }
28
+
29
+ /**
30
+ * The place to use: `own` when it has both coordinates (not 0, 0), with its
31
+ * name or the user's; otherwise the user's (`ctx.location`), which may be
32
+ * unset.
33
+ */
34
+ export function placeOf(own: { latitude?: number; longitude?: number; placeName?: string; name?: string } | undefined, user: Location | undefined): Location | undefined {
35
+ const lat = own?.latitude ?? 0;
36
+ const lon = own?.longitude ?? 0;
37
+ const name = (own?.placeName ?? own?.name ?? '').trim();
38
+ if (Number.isFinite(lat) && Number.isFinite(lon) && (lat !== 0 || lon !== 0)) return { latitude: lat, longitude: lon, ...(name ? { name } : {}) };
39
+ if (!user) return undefined;
40
+ return name ? { ...user, name } : user;
41
+ }