@sdeck/plugin 0.1.0 → 0.3.0

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/plugin.ts CHANGED
@@ -2,12 +2,14 @@ import type { SlotInfo } from "@sdeck/app";
2
2
  import type { ExecSource, StateValueType } from "@sdeck/engine";
3
3
  import type { Look, NavigateTarget } from "@sdeck/schema";
4
4
  import type { ComponentType } from "react";
5
+ import { PERMISSIONS, type Permission } from "./permissions.ts";
5
6
  import {
6
7
  checkSchema,
7
8
  type InferSettings,
8
9
  type SelectOption,
9
10
  type SettingsSchema,
10
11
  } from "./settings.ts";
12
+ import type { TextRow } from "./text.ts";
11
13
 
12
14
  /** Bumped when the plugin contract changes incompatibly. Hosts refuse plugins built for another. */
13
15
  export const PLUGIN_API_VERSION = 2;
@@ -15,29 +17,6 @@ export const PLUGIN_API_VERSION = 2;
15
17
  /** Where an action can be placed. */
16
18
  export type SlotKind = "key" | "sensor" | "window";
17
19
 
18
- /**
19
- * What a plugin declares it does. Shown to the user before enabling it. Plugins run in the host
20
- * process, so this is information, not a sandbox.
21
- */
22
- export type Permission =
23
- | "shell"
24
- | "process"
25
- | "filesystem"
26
- | "network"
27
- | "input"
28
- | "audio"
29
- | "clipboard";
30
-
31
- export const PERMISSIONS: readonly Permission[] = [
32
- "shell",
33
- "process",
34
- "filesystem",
35
- "network",
36
- "input",
37
- "audio",
38
- "clipboard",
39
- ];
40
-
41
20
  /** Given to a plugin's `activate`, its actions, state providers and triggers. */
42
21
  export interface PluginContext {
43
22
  readonly pluginId: string;
@@ -61,26 +40,78 @@ export interface PluginContext {
61
40
  /** Live state: `set` publishes `<namespace>.<id>`, `get` reads any key (`system.cpu`). */
62
41
  readonly state: {
63
42
  set(id: string, value: unknown): void;
43
+ /** Keys of other plugins need the `state` permission. */
64
44
  get(key: string): unknown;
45
+ /**
46
+ * Calls `listener` whenever one of `keys` changes, and keeps them up to date meanwhile (`get`
47
+ * alone does not). Returns a function that stops. Same permission as `get`.
48
+ */
49
+ watch(keys: readonly string[], listener: () => void): () => void;
50
+ };
51
+ /** Pictures and text on top of the user's buttons. Needs the `overlay` permission. */
52
+ readonly overlays: {
53
+ /** Shows `overlay` on every deck, replacing this plugin's overlay called `id`. */
54
+ show(id: string, overlay: Overlay): void;
55
+ hide(id: string): void;
65
56
  };
66
57
  /** Emits `<namespace>:<event>` on the event bus (workflows can trigger on it). */
67
58
  emit(event: string, payload?: unknown): void;
68
- /** Global user variables. */
59
+ /** Global user variables. Needs the `variables` permission. */
69
60
  readonly vars: {
70
61
  get(name: string): unknown;
71
62
  set(name: string, value: unknown): void;
72
63
  };
73
64
  }
74
65
 
66
+ /** Something drawn as one picture across several slots. The last one shown is on top. */
67
+ export interface Overlay {
68
+ /**
69
+ * The slots it covers: `key:0`, `sensor:1`, `window` (as a `slots` setting gives them). Leaving
70
+ * it out, or an empty list, covers the entire deck. Slots a deck does not have are skipped, and
71
+ * touch sensors show no text.
72
+ */
73
+ slots?: readonly string[];
74
+ /** Shown on this page only (default: every page). */
75
+ page?: string;
76
+ /**
77
+ * What happens between slots, where a deck shows nothing. `keep`: the picture runs on behind
78
+ * the gaps, as through a window. `close`: slots are drawn as if they touched, so nothing is
79
+ * lost, which suits text. Default `keep`.
80
+ */
81
+ gaps?: "keep" | "close";
82
+ /**
83
+ * Draws it, at the size of the whole overlay. Every slot draws all of it and shows its own
84
+ * part, so it must look the same in each: keep state outside, or in `@sdeck/plugin` hooks.
85
+ * Transparent parts show the buttons; `null` draws nothing.
86
+ */
87
+ content: ComponentType<OverlayProps>;
88
+ }
89
+
90
+ export interface OverlayProps {
91
+ /** The size of the whole overlay. On a Neo these are pixels, and a key is 96×96. */
92
+ width: number;
93
+ height: number;
94
+ /**
95
+ * The rows of keys, or the window, it lies over, from the top, and how wide each is. Text reads best when no line is cut by the gap
96
+ * between two of them: `layoutText` places it so.
97
+ */
98
+ rows: readonly TextRow[];
99
+ }
100
+
75
101
  /** How a plugin's status reads: fine, needing attention, or failing. */
76
102
  export type StatusLevel = "ok" | "info" | "error";
77
103
 
78
- /** Something the user can run from the plugin's page (sign in, reconnect). */
104
+ /** Something the user can run from the plugin's settings (sign in, reconnect). */
79
105
  export interface PluginCommand {
80
106
  /** Unique within the plugin. */
81
107
  id: string;
82
108
  name: string;
83
109
  description?: string;
110
+ /**
111
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
112
+ * Without them it is refused.
113
+ */
114
+ permissions?: readonly Permission[];
84
115
  /** What it returns, if a string, is opened in the user's browser. Throw to fail. */
85
116
  run(context: PluginContext): unknown | Promise<unknown>;
86
117
  }
@@ -200,9 +231,19 @@ export interface ActionDef<S extends SettingsSchema = SettingsSchema> {
200
231
  slots?: readonly SlotKind[];
201
232
  /** Settings shown in the UI, as a form. */
202
233
  settings?: S;
234
+ /**
235
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
236
+ * Without them it cannot run or draw itself.
237
+ */
238
+ permissions?: readonly Permission[];
239
+ /**
240
+ * It only shows something. It is offered for buttons, but not as a step of a workflow or
241
+ * gesture, and needs no `run`.
242
+ */
243
+ display?: boolean;
203
244
  /**
204
245
  * Does the work, without drawing anything: it can run from a key, a trigger or a workflow.
205
- * Throw to fail. An action needs `run`, `component`, or both.
246
+ * Throw to fail. An action needs `run`, `component`, or both, unless it is `display`.
206
247
  */
207
248
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `run` simply not return anything.
208
249
  run?(context: RunContext<S>): RunResult | void | Promise<RunResult | void>;
@@ -227,6 +268,8 @@ export interface Action {
227
268
  readonly icon?: string;
228
269
  readonly slots: readonly SlotKind[];
229
270
  readonly settings: SettingsSchema;
271
+ readonly permissions?: readonly Permission[];
272
+ readonly display?: boolean;
230
273
  readonly run?: RunFn;
231
274
  readonly component?: ComponentType<ActionProps>;
232
275
  readonly look?: (settings: Record<string, unknown>) => Look;
@@ -240,6 +283,11 @@ export interface StateDef {
240
283
  type: StateValueType;
241
284
  unit?: string;
242
285
  description?: string;
286
+ /**
287
+ * What reading it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
288
+ * Without them it has no value.
289
+ */
290
+ permissions?: readonly Permission[];
243
291
  /** Read every `everyMs` while something shows or waits on the value. */
244
292
  poll?: { everyMs: number; read(context: PluginContext): unknown | Promise<unknown> };
245
293
  /** Push updates while watched; return a stop function. */
@@ -261,6 +309,11 @@ export interface TriggerDef<S extends SettingsSchema = SettingsSchema> {
261
309
  name: string;
262
310
  description?: string;
263
311
  settings?: S;
312
+ /**
313
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
314
+ * Without them it never fires.
315
+ */
316
+ permissions?: readonly Permission[];
264
317
  /** Starts watching; returns a function that stops. */
265
318
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `subscribe` simply not return anything.
266
319
  subscribe(context: TriggerContext<S>): (() => void) | void;
@@ -271,6 +324,7 @@ export interface Trigger {
271
324
  readonly name: string;
272
325
  readonly description?: string;
273
326
  readonly settings: SettingsSchema;
327
+ readonly permissions?: readonly Permission[];
274
328
  readonly subscribe: (context: TriggerContext) => (() => void) | undefined;
275
329
  }
276
330
 
@@ -301,10 +355,14 @@ export interface PluginDef {
301
355
  state?: readonly StateDef[];
302
356
  triggers?: readonly Trigger[];
303
357
  optionSources?: Readonly<Record<string, OptionSource>>;
358
+ /**
359
+ * Everything the plugin asks to be allowed to do. The user decides about each one, and can
360
+ * change their mind at any time: handle being refused. What is not listed is never allowed.
361
+ */
304
362
  permissions?: readonly Permission[];
305
363
  /** The plugin's own settings (a server address, a token), shown on its page. */
306
364
  settings?: SettingsSchema;
307
- /** Buttons on the plugin's page. */
365
+ /** Buttons in the plugin's settings. */
308
366
  commands?: readonly PluginCommand[];
309
367
  /**
310
368
  * How to set the plugin up, step by step, shown after it is installed. Without it, Studio asks
@@ -370,6 +428,16 @@ export function definePlugin(def: PluginDef): PluginDef {
370
428
  return def;
371
429
  }
372
430
 
431
+ /** Problems with the `permissions` of one of a plugin's parts. */
432
+ function checkNeeds(part: string, needs: unknown, asked: unknown): string[] {
433
+ if (needs === undefined) return [];
434
+ if (!Array.isArray(needs)) return [`${part}: permissions must be an array`];
435
+ const missing = needs.filter((p) => !Array.isArray(asked) || !asked.includes(p));
436
+ return missing.map(
437
+ (p) => `${part}: permission "${String(p)}" is not in the plugin's permissions`,
438
+ );
439
+ }
440
+
373
441
  function checkLocalIds(
374
442
  kind: string,
375
443
  items: readonly { id?: unknown }[],
@@ -423,6 +491,7 @@ export function checkPlugin(value: unknown): string[] {
423
491
  const name = typeof c?.id === "string" ? c.id : "?";
424
492
  if (typeof c?.name !== "string") problems.push(`command "${name}": name is required`);
425
493
  if (typeof c?.run !== "function") problems.push(`command "${name}": run is required`);
494
+ problems.push(...checkNeeds(`command "${name}"`, c?.permissions, def.permissions));
426
495
  }
427
496
  }
428
497
  }
@@ -441,7 +510,10 @@ export function checkPlugin(value: unknown): string[] {
441
510
  const hasComponent =
442
511
  typeof action?.component === "function" || typeof action?.component === "object";
443
512
  const hasRun = typeof action?.run === "function";
444
- if (!hasComponent && !hasRun) problems.push(`action "${name}": needs run or component`);
513
+ if (!hasComponent && !hasRun && !action?.display) {
514
+ problems.push(`action "${name}": needs run or component`);
515
+ }
516
+ problems.push(...checkNeeds(`action "${name}"`, action?.permissions, def.permissions));
445
517
  if (action?.look !== undefined && typeof action.look !== "function") {
446
518
  problems.push(`action "${name}": look must be a function`);
447
519
  }
@@ -461,6 +533,9 @@ export function checkPlugin(value: unknown): string[] {
461
533
  if (field?.type === "secret") {
462
534
  problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
463
535
  }
536
+ if (field?.type === "groups") {
537
+ problems.push(`action "${name}": setting "${key}": groups belong in the plugin settings`);
538
+ }
464
539
  }
465
540
  }
466
541
 
@@ -474,6 +549,7 @@ export function checkPlugin(value: unknown): string[] {
474
549
  if (!["number", "string", "boolean", "json"].includes(s?.type as string)) {
475
550
  problems.push(`state "${name}": type must be number, string, boolean or json`);
476
551
  }
552
+ problems.push(...checkNeeds(`state "${name}"`, s?.permissions, def.permissions));
477
553
  if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
478
554
  problems.push(`state "${name}": poll needs read() and everyMs > 0`);
479
555
  }
@@ -494,6 +570,7 @@ export function checkPlugin(value: unknown): string[] {
494
570
  if (typeof t?.subscribe !== "function") {
495
571
  problems.push(`trigger "${name}": subscribe is required`);
496
572
  }
573
+ problems.push(...checkNeeds(`trigger "${name}"`, t?.permissions, def.permissions));
497
574
  for (const p of checkSchema(t?.settings ?? {}, sources)) {
498
575
  problems.push(`trigger "${name}": ${p}`);
499
576
  }
package/src/settings.ts CHANGED
@@ -10,6 +10,11 @@ interface FieldBase {
10
10
  label: string;
11
11
  /** Help text under the field. */
12
12
  description?: string;
13
+ /**
14
+ * It only changes how the button looks. It is asked for on a button, but not in a step of a
15
+ * workflow or gesture, where nothing is drawn.
16
+ */
17
+ appearance?: boolean;
13
18
  /**
14
19
  * Shown only while other fields have these values: `{ to: "page" }` or
15
20
  * `{ mode: ["a", "b"] }`. Hidden fields keep their value.
@@ -26,6 +31,11 @@ export interface TextField extends FieldBase {
26
31
  source?: string;
27
32
  /** Other fields the suggestions depend on, passed to the source. */
28
33
  dependsOn?: readonly string[];
34
+ /**
35
+ * `{{templates}}` in it reach `run` as they were written, for drawing with `useTemplate` so the
36
+ * text follows their values. Ones that read the run itself (`event`, `loop`…) are filled in.
37
+ */
38
+ live?: boolean;
29
39
  }
30
40
 
31
41
  export interface NumberField extends FieldBase {
@@ -83,12 +93,44 @@ export interface SelectField extends FieldBase {
83
93
  export interface PageField extends FieldBase {
84
94
  type: "page";
85
95
  default?: string;
96
+ /** Offers choosing no page (an empty value), under this name: `Every page`. */
97
+ none?: string;
98
+ }
99
+
100
+ /**
101
+ * Keys, touch sensors and the window, picked on a picture of the deck: `key:0`, `sensor:1`,
102
+ * `window`. An empty list stands for the entire deck.
103
+ */
104
+ export interface SlotsField extends FieldBase {
105
+ type: "slots";
106
+ default?: readonly string[];
86
107
  }
87
108
 
88
109
  /** An image: an `http(s)` URL or a `data:` URI (the UI accepts a URL or a file). */
89
110
  export interface ImageField extends FieldBase {
90
111
  type: "image";
91
112
  default?: string;
113
+ /** As on a text field: `{{spotify.art}}` reaches `run` as written. */
114
+ live?: boolean;
115
+ }
116
+
117
+ /** A named set the user made of options, from a `groups` field. */
118
+ export interface OptionGroup {
119
+ /** Stays the same when the group is renamed; refer to the group by it. */
120
+ id: string;
121
+ name: string;
122
+ /** The chosen options' values. */
123
+ members: readonly string[];
124
+ }
125
+
126
+ /** Named sets of options the user puts together (rooms of lights), only for a plugin's own settings. */
127
+ export interface GroupsField extends FieldBase {
128
+ type: "groups";
129
+ /** The plugin's `optionSources` entry that lists what a group can contain. */
130
+ source: string;
131
+ /** What a group contains, for the form, e.g. `lights` (default: `items`). */
132
+ noun?: string;
133
+ default?: readonly OptionGroup[];
92
134
  }
93
135
 
94
136
  export type SettingField =
@@ -98,7 +140,9 @@ export type SettingField =
98
140
  | ColorField
99
141
  | SelectField
100
142
  | PageField
143
+ | SlotsField
101
144
  | ImageField
145
+ | GroupsField
102
146
  | SecretField;
103
147
 
104
148
  export type SettingsSchema = Readonly<Record<string, SettingField>>;
@@ -108,11 +152,18 @@ export type FieldValue<F extends SettingField> = F extends NumberField
108
152
  ? number
109
153
  : F extends BooleanField
110
154
  ? boolean
111
- : F extends SelectField
112
- ? F extends { source: string }
113
- ? string
114
- : F["options"][number]["value"]
115
- : string;
155
+ : F extends GroupsField
156
+ ? readonly OptionGroup[]
157
+ : F extends SlotsField
158
+ ? readonly string[]
159
+ : F extends SelectField
160
+ ? F extends { source: string }
161
+ ? string
162
+ : F["options"][number]["value"]
163
+ : string;
164
+
165
+ /** A value of any field. */
166
+ export type SettingValue = Primitive | readonly OptionGroup[] | readonly string[];
116
167
 
117
168
  /** The settings object an action receives for a schema. */
118
169
  export type InferSettings<S extends SettingsSchema> = {
@@ -122,7 +173,7 @@ export type InferSettings<S extends SettingsSchema> = {
122
173
  const HEX = /^#[0-9a-f]{6}$/i;
123
174
 
124
175
  /** The value a field takes when nothing (valid) is stored. */
125
- export function defaultValue(field: SettingField): string | number | boolean {
176
+ export function defaultValue(field: SettingField): SettingValue {
126
177
  switch (field.type) {
127
178
  case "number":
128
179
  return field.default ?? field.min ?? 0;
@@ -130,6 +181,9 @@ export function defaultValue(field: SettingField): string | number | boolean {
130
181
  return field.default ?? false;
131
182
  case "color":
132
183
  return field.default ?? "#000000";
184
+ case "groups":
185
+ case "slots":
186
+ return field.default ?? [];
133
187
  case "select":
134
188
  return field.default ?? field.options[0]?.value ?? "";
135
189
  default:
@@ -137,7 +191,33 @@ export function defaultValue(field: SettingField): string | number | boolean {
137
191
  }
138
192
  }
139
193
 
140
- function coerce(field: SettingField, value: unknown): string | number | boolean {
194
+ /** The valid groups in a stored value, or `undefined` if it isn't a list. */
195
+ export function optionGroups(value: unknown): OptionGroup[] | undefined {
196
+ if (!Array.isArray(value)) return undefined;
197
+ const ids = new Set<string>();
198
+ return value.flatMap((group: Partial<OptionGroup> | null) => {
199
+ if (typeof group?.id !== "string" || !group.id || ids.has(group.id)) return [];
200
+ ids.add(group.id);
201
+ const members = Array.isArray(group.members) ? group.members : [];
202
+ return [
203
+ {
204
+ id: group.id,
205
+ name: typeof group.name === "string" ? group.name : "",
206
+ members: [...new Set(members.filter((m) => typeof m === "string"))],
207
+ },
208
+ ];
209
+ });
210
+ }
211
+
212
+ const SLOT = /^(window|(key|sensor):\d{1,3})$/;
213
+
214
+ /** The slots in a stored value, or `undefined` if it isn't a list. */
215
+ export function slotList(value: unknown): string[] | undefined {
216
+ if (!Array.isArray(value)) return undefined;
217
+ return [...new Set(value.filter((v): v is string => typeof v === "string" && SLOT.test(v)))];
218
+ }
219
+
220
+ function coerce(field: SettingField, value: unknown): SettingValue {
141
221
  switch (field.type) {
142
222
  case "number": {
143
223
  const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
@@ -150,6 +230,10 @@ function coerce(field: SettingField, value: unknown): string | number | boolean
150
230
  return typeof value === "string" && HEX.test(value)
151
231
  ? value.toLowerCase()
152
232
  : defaultValue(field);
233
+ case "groups":
234
+ return optionGroups(value) ?? defaultValue(field);
235
+ case "slots":
236
+ return slotList(value) ?? defaultValue(field);
153
237
  case "select":
154
238
  if (typeof value !== "string") return defaultValue(field);
155
239
  if (field.source !== undefined) return value;
@@ -172,6 +256,18 @@ export function resolveSettings<S extends SettingsSchema>(
172
256
  return out as InferSettings<S>;
173
257
  }
174
258
 
259
+ /** The fields that change what an action does, without those for how its button looks. */
260
+ export function behaviorFields(schema: SettingsSchema): SettingsSchema {
261
+ return Object.fromEntries(Object.entries(schema).filter(([, field]) => !field.appearance));
262
+ }
263
+
264
+ /** The settings whose templates are left for the action to keep up to date. */
265
+ export function liveSettings(schema: SettingsSchema): string[] {
266
+ return Object.entries(schema).flatMap(([key, field]) =>
267
+ "live" in field && field.live ? [key] : [],
268
+ );
269
+ }
270
+
175
271
  /** Whether `field` is shown for these (resolved) settings. */
176
272
  export function isFieldVisible(
177
273
  field: SettingField,
@@ -200,7 +296,9 @@ export function checkSchema(
200
296
  "color",
201
297
  "select",
202
298
  "page",
299
+ "slots",
203
300
  "image",
301
+ "groups",
204
302
  "secret",
205
303
  ]);
206
304
  for (const [key, field] of Object.entries(schema)) {
@@ -210,6 +308,9 @@ export function checkSchema(
210
308
  }
211
309
  if (typeof field.label !== "string") problems.push(`setting "${key}" needs a label`);
212
310
  const source = "source" in field ? field.source : undefined;
311
+ if (field.type === "groups" && source === undefined) {
312
+ problems.push(`setting "${key}" needs a source`);
313
+ }
213
314
  if (source !== undefined && !(source in sources)) {
214
315
  problems.push(`setting "${key}" uses unknown option source "${source}"`);
215
316
  }
package/src/text.ts ADDED
@@ -0,0 +1,192 @@
1
+ /** Choosing a text size without laying the text out. */
2
+
3
+ /** How wide characters are in the built-in font, in ems. A little generous, so text fits. */
4
+ function emWidth(char: string): number {
5
+ if (/[ᄀ-ᇿ⺀-鿿가-힯豈-﫿＀-⦆]/.test(char)) return 1;
6
+ if (/\p{Extended_Pictographic}/u.test(char)) return 1.25;
7
+ if (/\p{Mark}/u.test(char)) return 0;
8
+ if (char === " ") return 0.27;
9
+ if (/[ijl.,:;'|!’‘·]/.test(char)) return 0.29;
10
+ if (/[Ifrt()[\]{}/\\"“”-]/.test(char)) return 0.41;
11
+ if (/[mwMW@%—]/.test(char)) return 0.93;
12
+ if (/[\p{Lu}\d]/u.test(char)) return 0.69;
13
+ return 0.6;
14
+ }
15
+
16
+ const textWidth = (text: string) => [...text].reduce((sum, c) => sum + emWidth(c), 0);
17
+
18
+ /** Chinese, Japanese and Korean characters, between which a line can break. */
19
+ const CJK = "\\u2e80-\\u9fff\\uac00-\\ud7af\\uff00-\\uff60";
20
+ const TOKENS = new RegExp(`\\n|[^\\S\\n]+|[${CJK}]|[^\\s${CJK}]+`, "g");
21
+
22
+ interface Range {
23
+ start: number;
24
+ end: number;
25
+ }
26
+
27
+ /**
28
+ * Breaks text into lines, each at most as many ems wide as `room` says for its number.
29
+ * `undefined` when a word is too long for its line.
30
+ */
31
+ function wrap(text: string, room: (line: number) => number): Range[] | undefined {
32
+ const lines: Range[] = [];
33
+ let line: Range | undefined;
34
+ let used = 0;
35
+ for (const match of text.matchAll(TOKENS)) {
36
+ const [token] = match;
37
+ const start = match.index;
38
+ const end = start + token.length;
39
+ if (token === "\n") {
40
+ lines.push(line ?? { start, end: start });
41
+ line = undefined;
42
+ continue;
43
+ }
44
+ const width = textWidth(token);
45
+ if (token.trim() === "") {
46
+ used += width;
47
+ continue;
48
+ }
49
+ if (line && used + width > room(lines.length)) {
50
+ lines.push(line);
51
+ line = undefined;
52
+ }
53
+ if (line) {
54
+ line.end = end;
55
+ used += width;
56
+ } else {
57
+ if (width > room(lines.length)) return undefined;
58
+ line = { start, end };
59
+ used = width;
60
+ }
61
+ }
62
+ if (line) lines.push(line);
63
+ return lines;
64
+ }
65
+
66
+ /** A stretch of height text can be in, such as one row of keys. */
67
+ export interface TextRow {
68
+ top: number;
69
+ height: number;
70
+ /** Where it starts and how wide it is, when that is not all of the width. */
71
+ left?: number;
72
+ width?: number;
73
+ }
74
+
75
+ export interface TextLayoutOptions {
76
+ width: number;
77
+ /** Each line goes into one of these, whole: pass an overlay's `rows`. */
78
+ rows: readonly TextRow[];
79
+ /** The smallest size to go down to, even if the text then does not fit (default 8). */
80
+ min?: number;
81
+ /** The largest size (default: whatever fits). */
82
+ max?: number;
83
+ /** Line height, as a multiple of the size (default 1.2). */
84
+ lineHeight?: number;
85
+ /** Where lines go when there is room to spare (default `middle`). */
86
+ position?: "top" | "middle" | "bottom";
87
+ }
88
+
89
+ export interface TextLayout {
90
+ size: number;
91
+ /** The lines: where they are in the text, and the place each one has. */
92
+ lines: {
93
+ text: string;
94
+ start: number;
95
+ end: number;
96
+ top: number;
97
+ left: number;
98
+ width: number;
99
+ }[];
100
+ }
101
+
102
+ /**
103
+ * Breaks text into lines and finds the largest font size at which they fit. It goes by how wide
104
+ * characters of the built-in font usually are, so leave a little room at the sides.
105
+ */
106
+ export function layoutText(text: string, options: TextLayoutOptions): TextLayout {
107
+ const { width, rows, min = 8, lineHeight = 1.2, position = "middle" } = options;
108
+ const tallest = Math.max(0, ...rows.map((r) => r.height));
109
+ const max = Math.max(min, Math.floor(options.max ?? tallest / lineHeight));
110
+ /** The places for lines, by row. */
111
+ const slots = (size: number) =>
112
+ rows.flatMap((row, index) => {
113
+ const count = Math.floor((row.height + 0.01) / (size * lineHeight));
114
+ return Array.from({ length: count }, () => ({
115
+ index,
116
+ left: row.left ?? 0,
117
+ width: row.width ?? width,
118
+ }));
119
+ });
120
+ /** The lines from the `skip`th place on, if they fit. */
121
+ const fill = (size: number, skip = 0) => {
122
+ const places = slots(size).slice(skip);
123
+ const lines = wrap(text, (i) => (places[i]?.width ?? 0) / size);
124
+ return lines && lines.length <= places.length ? lines : undefined;
125
+ };
126
+
127
+ let size = max;
128
+ if (!fill(max)) {
129
+ size = min;
130
+ for (let high = max; high - size > 1; ) {
131
+ const middle = Math.floor((size + high) / 2);
132
+ if (fill(middle)) size = middle;
133
+ else high = middle;
134
+ }
135
+ }
136
+
137
+ const places = slots(size);
138
+ const last = rows.at(-1);
139
+ if (last && rows.length > 1 && places.length === 0) {
140
+ // Taller than any row, as asked: then it has to run across them.
141
+ const top = rows[0]?.top ?? 0;
142
+ const whole = { top, height: last.top + last.height - top };
143
+ return layoutText(text, { ...options, rows: [whole] });
144
+ }
145
+
146
+ let skip = 0;
147
+ let lines = fill(size);
148
+ if (lines && position !== "top") {
149
+ const spare = places.length - lines.length;
150
+ // Further down the rows can be narrower, and need more lines.
151
+ for (let wanted = position === "bottom" ? spare : Math.floor(spare / 2); wanted > 0; wanted--) {
152
+ const moved = fill(size, wanted);
153
+ if (!moved) continue;
154
+ lines = moved;
155
+ skip = wanted;
156
+ break;
157
+ }
158
+ }
159
+ // What does not fit even at the smallest size runs out at the bottom and the sides.
160
+ lines ??=
161
+ wrap(text, (i) => (places[i]?.width ?? width) / size) ?? wrap(text, () => Infinity) ?? [];
162
+
163
+ const height = size * lineHeight;
164
+ const used = places.slice(skip, skip + lines.length);
165
+ const placed: TextLayout["lines"] = [];
166
+ for (const [i, line] of lines.entries()) {
167
+ const place = used[i];
168
+ const row = place && rows[place.index];
169
+ const before = placed.at(-1);
170
+ let top = before ? before.top + height : (rows[0]?.top ?? 0);
171
+ if (row && used[i - 1]?.index !== place.index) {
172
+ const free = row.height - used.filter((p) => p.index === place.index).length * height;
173
+ top = row.top + (position === "top" ? 0 : position === "bottom" ? free : free / 2);
174
+ }
175
+ placed.push({
176
+ ...line,
177
+ text: text.slice(line.start, line.end),
178
+ top,
179
+ left: place?.left ?? 0,
180
+ width: place?.width ?? width,
181
+ });
182
+ }
183
+ return { size, lines: placed };
184
+ }
185
+
186
+ /** The largest font size at which `text`, wrapped between words, fits a box. */
187
+ export function fitText(
188
+ text: string,
189
+ { height, ...options }: Omit<TextLayoutOptions, "rows" | "position"> & { height: number },
190
+ ): number {
191
+ return layoutText(text, { ...options, rows: [{ top: 0, height }] }).size;
192
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The parts that are plain data and functions, for UIs: no React, engine or runtime behind them. */
2
+ export * from "./permissions.ts";
3
+ export * from "./settings.ts";