@impro.social/impro-plugin 0.0.19 → 0.0.21

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.
Files changed (2) hide show
  1. package/main.js +897 -110
  2. package/package.json +10 -2
package/main.js CHANGED
@@ -1,9 +1,26 @@
1
+ /**
2
+ * @typedef {Record<string, unknown>} PostView
3
+ * Hydrated `app.bsky.feed.defs#postView` shape.
4
+ * @typedef {Record<string, unknown>} ProfileView
5
+ * Basic `app.bsky.actor.defs#profileView` shape.
6
+ * @typedef {Record<string, unknown>} DetailedProfileView
7
+ * Detailed profile view with viewer relationship fields.
8
+ * @typedef {Record<string, unknown>} KnownFollowersResponse
9
+ * Paginated response from `getKnownFollowers`: `{ followers, cursor }`.
10
+ * @typedef {Record<string, unknown>} RepoRecord
11
+ * A raw repo record: `{ uri, cid, value }`.
12
+ * @typedef {Record<string, unknown>} FeedItem
13
+ * A `app.bsky.feed.defs#feedViewPost` (post + reply/repost context).
14
+ * @typedef {Record<string, unknown>} RichTextToken
15
+ * One token in a rich-text stream — `text`, `facet`, `inline`, or `block`.
16
+ * @typedef {VirtualEl | null | undefined} RenderResult
17
+ * What a render callback may return: a tree to render, or nothing.
18
+ */
19
+
1
20
  export class SimpleUUID {
2
- constructor() {
3
- this._id = 0;
4
- }
21
+ #id = 0;
5
22
  create() {
6
- return this._id++;
23
+ return this.#id++;
7
24
  }
8
25
  }
9
26
 
@@ -75,36 +92,70 @@ function addEventListener(event, listener) {
75
92
  }
76
93
  }
77
94
 
95
+ /**
96
+ * A single item in a {@link Menu}. Configure with the chained setters and
97
+ * an `onClick` handler. Not constructed directly — obtained via
98
+ * `Menu.addItem(builder)`.
99
+ */
78
100
  export class MenuItem {
79
101
  constructor() {
80
102
  this.title = "";
81
103
  this.icon = null;
104
+ /** @internal */
82
105
  this._callback = () => {};
83
106
  }
107
+ /**
108
+ * Set the menu item's label.
109
+ * @param {string} title
110
+ * @returns {this}
111
+ */
84
112
  setTitle(title) {
85
113
  this.title = title;
86
114
  return this;
87
115
  }
116
+ /**
117
+ * Set the leading icon. Either a named icon (string) or a {@link VirtualEl}
118
+ * to render as the icon.
119
+ * @param {string | VirtualEl} icon
120
+ * @returns {this}
121
+ */
88
122
  setIcon(icon) {
89
123
  this.icon = icon;
90
124
  return this;
91
125
  }
126
+ /**
127
+ * Called when the user activates the item.
128
+ * @param {() => void} callback
129
+ * @returns {this}
130
+ */
92
131
  onClick(callback) {
93
132
  this._callback = callback;
94
133
  return this;
95
134
  }
96
135
  }
97
136
 
137
+ /**
138
+ * A context-menu builder passed as the first argument to
139
+ * `post-context-menu` and `profile-context-menu` event listeners. Call
140
+ * `addItem` to append menu entries.
141
+ */
98
142
  export class Menu {
99
143
  constructor() {
144
+ /** @type {MenuItem[]} */
100
145
  this.items = [];
101
146
  }
147
+ /**
148
+ * Append a menu item. The builder receives a {@link MenuItem} to configure.
149
+ * @param {(item: MenuItem) => void} builder
150
+ * @returns {this}
151
+ */
102
152
  addItem(builder) {
103
153
  const item = new MenuItem();
104
154
  builder(item);
105
155
  this.items.push(item);
106
156
  return this;
107
157
  }
158
+ /** @internal */
108
159
  _serialize() {
109
160
  return this.items.map((item) => {
110
161
  const handlerId = uuid.create();
@@ -116,95 +167,224 @@ export class Menu {
116
167
  }
117
168
  }
118
169
 
170
+ /**
171
+ * Builder passed as the first argument to `post-composer-open` event
172
+ * listeners. Queues text operations that the host applies to the composer once
173
+ * all listeners have run. operations from multiple plugins are applied in order.
174
+ */
119
175
  export class Composer {
120
- constructor() {
121
- this._ops = [];
122
- this._cursor = null;
123
- }
176
+ #ops = [];
177
+ /** @type {number | null} */
178
+ #cursor = null;
179
+ /**
180
+ * Replace the composer's current text.
181
+ * @param {string} text
182
+ * @returns {this}
183
+ */
124
184
  setText(text) {
125
- this._ops.push({ op: "set", text: String(text) });
185
+ this.#ops.push({ op: "set", text: String(text) });
126
186
  return this;
127
187
  }
188
+ /**
189
+ * Append text to the end of the composer.
190
+ * @param {string} text
191
+ * @returns {this}
192
+ */
128
193
  appendText(text) {
129
- this._ops.push({ op: "append", text: String(text) });
194
+ this.#ops.push({ op: "append", text: String(text) });
130
195
  return this;
131
196
  }
197
+ /**
198
+ * Prepend text to the start of the composer.
199
+ * @param {string} text
200
+ * @returns {this}
201
+ */
132
202
  prependText(text) {
133
- this._ops.push({ op: "prepend", text: String(text) });
203
+ this.#ops.push({ op: "prepend", text: String(text) });
134
204
  return this;
135
205
  }
206
+ /**
207
+ * Move the caret to the given character index in the final text.
208
+ * @param {number} index
209
+ * @returns {this}
210
+ */
136
211
  setCursor(index) {
137
- this._cursor = index;
212
+ this.#cursor = index;
138
213
  return this;
139
214
  }
215
+ /** @internal */
140
216
  _serialize() {
141
- return { ops: this._ops, cursor: this._cursor };
217
+ return { ops: this.#ops, cursor: this.#cursor };
142
218
  }
143
219
  }
144
220
 
145
- class PluginData {
221
+ /**
222
+ * Read-only accessors for appview data with the current user as the viewer.
223
+ * Reached via {@link App.data} on the plugin's {@link App} instance.
224
+ */
225
+ export class PluginData {
226
+ /**
227
+ * Fetch a hydrated post view by AT-URI, as seen by the current user.
228
+ * @param {string} uri
229
+ * @returns {Promise<PostView>}
230
+ */
146
231
  getPost(uri) {
147
232
  return hostCall("getPost", { uri });
148
233
  }
234
+ /**
235
+ * Fetch the basic profile view for a DID.
236
+ * @param {string} did
237
+ * @returns {Promise<ProfileView>}
238
+ */
149
239
  getProfile(did) {
150
240
  return hostCall("getProfile", { did });
151
241
  }
152
- // Like getProfile, but includes viewer relationship details not present
153
- // on the basic profile view: viewer.following, viewer.followedBy, and
154
- // viewer.knownFollowers (a summary of mutual followers).
242
+ /**
243
+ * Like {@link PluginData.getProfile}, but includes viewer relationship
244
+ * details not present on the basic profile view: `viewer.following`,
245
+ * `viewer.followedBy`, and `viewer.knownFollowers` (a summary of mutual
246
+ * followers).
247
+ * @param {string} did
248
+ * @returns {Promise<DetailedProfileView>}
249
+ */
155
250
  getDetailedProfile(did) {
156
251
  return hostCall("getDetailedProfile", { did });
157
252
  }
158
- // The full known-followers list for did (the summary on
159
- // getDetailedProfile's viewer.knownFollowers is capped to a handful).
253
+ /**
254
+ * The full known-followers list for `did`. The summary on
255
+ * {@link PluginData.getDetailedProfile}'s `viewer.knownFollowers` is
256
+ * capped to a handful; use this to paginate the complete list.
257
+ * @param {string} did
258
+ * @returns {Promise<KnownFollowersResponse>}
259
+ */
160
260
  getKnownFollowers(did) {
161
261
  return hostCall("getKnownFollowers", { did });
162
262
  }
263
+ /**
264
+ * Fetch a raw repo record by `(repo, collection, rkey)`.
265
+ * @param {string} repo
266
+ * @param {string} collection
267
+ * @param {string} rkey
268
+ * @returns {Promise<RepoRecord>}
269
+ */
163
270
  getRecord(repo, collection, rkey) {
164
271
  return hostCall("getRecord", { repo, collection, rkey });
165
272
  }
166
273
  }
167
274
 
168
- class App {
275
+ /**
276
+ * The plugin's handle to the running impro app. Exposed as `this.app` on a
277
+ * {@link Plugin} instance. Owns event subscriptions, data accessors
278
+ * ({@link App.data}), and user-scoped actions.
279
+ */
280
+ export class App {
281
+ /** @internal */
169
282
  constructor() {
283
+ /**
284
+ * The signed-in user's basic profile, populated before `onload()` runs.
285
+ * Null when no session is active.
286
+ * @type {ProfileView | null}
287
+ */
170
288
  this.currentUser = null;
289
+ /** Read-only appview accessors — see {@link PluginData}. */
171
290
  this.data = new PluginData();
172
291
  }
292
+ /**
293
+ * Register an event listener. Supported events:
294
+ *
295
+ * - `"post-context-menu"` — `(menu: Menu, post) => void`, called when the
296
+ * user opens a post's context menu.
297
+ * - `"profile-context-menu"` — `(menu: Menu, profile) => void`, called
298
+ * when the user opens a profile's context menu.
299
+ * - `"post-composer-open"` — `(composer: Composer, context: { kind, replyTo, replyRoot, quotedPost }) => void`,
300
+ * called when the post composer opens; use `composer` to seed text.
301
+ *
302
+ * The `listener` signature varies per event (see above).
303
+ * @param {string} event
304
+ * @param {Function} listener
305
+ */
173
306
  on(event, listener) {
174
307
  addEventListener(event, listener);
175
308
  }
176
309
 
310
+ /**
311
+ * Re-run registered feed filters. Pass a `feedURI` to limit the refresh
312
+ * to one feed, or omit/pass `null` to refresh every feed.
313
+ * @param {string | null} [feedURI]
314
+ * @returns {Promise<void>}
315
+ */
177
316
  refreshFeedFilters(feedURI = null) {
178
317
  return hostCall("refreshFeedFilters", feedURI);
179
318
  }
180
319
 
181
- // Actions on behalf of the signed-in user. Each method requires the
182
- // corresponding scope ("mute", "block", "feedFeedback") to be declared in
183
- // the plugin manifest's `permissions.actions` array, which the user must
184
- // grant at install time.
320
+ /**
321
+ * Mute an actor on behalf of the signed-in user. Requires the `"mute"`
322
+ * scope in the plugin manifest's `permissions.actions`.
323
+ * @param {string} did
324
+ * @returns {Promise<void>}
325
+ */
185
326
  muteActor(did) {
186
327
  return hostCall("muteActor", { did, mute: true });
187
328
  }
329
+ /**
330
+ * Unmute an actor. Requires the `"mute"` scope.
331
+ * @param {string} did
332
+ * @returns {Promise<void>}
333
+ */
188
334
  unmuteActor(did) {
189
335
  return hostCall("muteActor", { did, mute: false });
190
336
  }
337
+ /**
338
+ * Block an actor on behalf of the signed-in user. Requires the `"block"`
339
+ * scope in the plugin manifest's `permissions.actions`.
340
+ * @param {string} did
341
+ * @returns {Promise<void>}
342
+ */
191
343
  blockActor(did) {
192
344
  return hostCall("blockActor", { did, block: true });
193
345
  }
346
+ /**
347
+ * Unblock an actor. Requires the `"block"` scope.
348
+ * @param {string} did
349
+ * @returns {Promise<void>}
350
+ */
194
351
  unblockActor(did) {
195
352
  return hostCall("blockActor", { did, block: false });
196
353
  }
197
- // Acts like the user clicking "Show less like this": sends the requestLess
198
- // feedback signal to the feed that served the post and collapses the post
199
- // behind a feedback message in feeds.
354
+ /**
355
+ * Acts like the user clicking "Show less like this": sends the
356
+ * `requestLess` feedback signal to `feedUri` and collapses the post
357
+ * behind a feedback message in feeds. Requires the `"feedFeedback"`
358
+ * scope.
359
+ * @param {string} postUri
360
+ * @param {string} feedUri
361
+ * @returns {Promise<void>}
362
+ */
200
363
  showLessLikeThis(postUri, feedUri) {
201
364
  return hostCall("showLessLikeThis", { postUri, feedUri });
202
365
  }
366
+ /**
367
+ * Sends the `requestMore` feedback signal to `feedUri` for `postUri`.
368
+ * Requires the `"feedFeedback"` scope.
369
+ * @param {string} postUri
370
+ * @param {string} feedUri
371
+ * @returns {Promise<void>}
372
+ */
203
373
  showMoreLikeThis(postUri, feedUri) {
204
374
  return hostCall("showMoreLikeThis", { postUri, feedUri });
205
375
  }
206
376
  }
207
377
 
378
+ /**
379
+ * Proxied fetch through the host. Requires the `"networkRequest"` permission
380
+ * scope and the target URL must be covered by the plugin's manifest allowlist.
381
+ * `init` accepts `method`, `headers` (plain object, `Headers`, `Map`, or
382
+ * `[name, value]` iterable), and a string `body`. Resolves to a
383
+ * {@link PluginResponse}.
384
+ * @param {string} url
385
+ * @param {{ method?: string, headers?: Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>, body?: string }} [init]
386
+ * @returns {Promise<PluginResponse>}
387
+ */
208
388
  export async function fetch(url, init = {}) {
209
389
  const result = await hostCall("fetch", {
210
390
  url,
@@ -234,77 +414,155 @@ function serializeFetchInit(init) {
234
414
  return serialized;
235
415
  }
236
416
 
237
- class PluginResponse {
417
+ /**
418
+ * Response returned from {@link fetch}. Body is buffered by the host and
419
+ * exposed as text or parsed JSON. `status`, `ok`, and `headers` (a `Map`)
420
+ * mirror the underlying HTTP response.
421
+ */
422
+ export class PluginResponse {
423
+ #body;
424
+ /** @internal */
238
425
  constructor({ status, ok, headers, body }) {
426
+ /** @type {number} */
239
427
  this.status = status;
428
+ /** @type {boolean} */
240
429
  this.ok = ok;
430
+ /** @type {Map<string, string>} */
241
431
  this.headers = new Map(Object.entries(headers ?? {}));
242
- this._body = body;
432
+ this.#body = body;
243
433
  }
434
+ /**
435
+ * Resolves with the response body as a string.
436
+ * @returns {Promise<string>}
437
+ */
244
438
  async text() {
245
- return this._body;
439
+ return this.#body;
246
440
  }
441
+ /**
442
+ * Resolves with the response body parsed as JSON.
443
+ * @returns {Promise<unknown>}
444
+ */
247
445
  async json() {
248
- return JSON.parse(this._body);
446
+ return JSON.parse(this.#body);
249
447
  }
250
448
  }
251
449
 
450
+ /**
451
+ * Shows a toast notification. `noticeEl` is a {@link VirtualEl} that can be
452
+ * mutated (e.g. `addClass`, appending children) synchronously after
453
+ * construction — the host serializes and renders the toast on a microtask, so
454
+ * any mutations made in the same task apply to the initial render. Mutations
455
+ * or `setMessage` calls made after that point do NOT propagate to the mounted
456
+ * toast; call {@link Notice.hide} and create a new `Notice` to change it.
457
+ */
252
458
  export class Notice {
459
+ #toastId = uuid.create();
460
+ #timeout;
461
+ #hidden = false;
462
+ /**
463
+ * `timeout` is in milliseconds; `0` (the default) keeps the toast up until
464
+ * {@link Notice.hide} is called.
465
+ * @param {string} message
466
+ * @param {number} [timeout=0]
467
+ */
253
468
  constructor(message, timeout = 0) {
254
- this._toastId = uuid.create();
255
- this._timeout = timeout;
256
- this._hidden = false;
469
+ this.#timeout = timeout;
470
+ /** @type {VirtualEl} */
257
471
  this.noticeEl = new VirtualEl("div");
258
472
  this.noticeEl.addClass("toast");
259
473
  this.noticeEl.setText(message);
260
474
  queueMicrotask(() => {
261
- if (this._hidden) return;
475
+ if (this.#hidden) return;
262
476
  hostCall("showToast", {
263
- toastId: this._toastId,
477
+ toastId: this.#toastId,
264
478
  element: this.noticeEl._serialize(),
265
- timeout: this._timeout,
479
+ timeout: this.#timeout,
266
480
  });
267
481
  });
268
482
  }
483
+ /**
484
+ * Updates `noticeEl`'s text. Only takes effect if called synchronously
485
+ * before the microtask that snapshots the toast for the initial render.
486
+ * @param {string} message
487
+ * @returns {this}
488
+ */
269
489
  setMessage(message) {
270
490
  this.noticeEl.setText(message);
271
491
  return this;
272
492
  }
493
+ /**
494
+ * Dismisses the toast. No-op if already hidden.
495
+ * @returns {void}
496
+ */
273
497
  hide() {
274
- if (this._hidden) return;
275
- this._hidden = true;
276
- hostCall("hideToast", { toastId: this._toastId });
498
+ if (this.#hidden) return;
499
+ this.#hidden = true;
500
+ hostCall("hideToast", { toastId: this.#toastId });
277
501
  }
278
502
  }
279
503
 
504
+ /**
505
+ * Injects a CSS block scoped to the plugin. The stylesheet is mounted by the
506
+ * host on the next microtask; snippets are automatically removed when the
507
+ * plugin unloads.
508
+ */
280
509
  export class StyleSnippet {
510
+ #snippetId = uuid.create();
511
+ #removed = false;
512
+ /**
513
+ * @param {string} cssText
514
+ */
281
515
  constructor(cssText) {
282
- this._snippetId = uuid.create();
283
- this._removed = false;
516
+ /**
517
+ * Resolves once the snippet has been applied by the host.
518
+ * @type {Promise<void>}
519
+ */
284
520
  this.ready = new Promise((resolve, reject) => {
285
521
  queueMicrotask(() => {
286
- if (this._removed) return resolve();
522
+ if (this.#removed) return resolve();
287
523
  hostCall("applyStyleSnippet", {
288
- snippetId: this._snippetId,
524
+ snippetId: this.#snippetId,
289
525
  cssText,
290
526
  }).then(resolve, reject);
291
527
  });
292
528
  });
293
529
  }
530
+ /**
531
+ * Removes the snippet from the document. No-op if already removed.
532
+ * @returns {void}
533
+ */
294
534
  remove() {
295
- if (this._removed) return;
296
- this._removed = true;
297
- hostCall("removeStyleSnippet", { snippetId: this._snippetId });
535
+ if (this.#removed) return;
536
+ this.#removed = true;
537
+ hostCall("removeStyleSnippet", { snippetId: this.#snippetId });
298
538
  }
299
539
  }
300
540
 
301
541
  let registered = false;
302
542
 
543
+ /**
544
+ * Base class for impro plugins. Subclass this and override {@link Plugin.onload}
545
+ * (and optionally {@link Plugin.onunload}) to wire up your plugin's extension
546
+ * points. `this.app` is the shared {@link App} instance for host actions and
547
+ * data. Call `MyPlugin.register()` at the top of your plugin's main.js to boot.
548
+ */
303
549
  export class Plugin {
550
+ /** @type {PluginSettingTab | null} */
551
+ #settingTab = null;
552
+ /** @internal */
304
553
  constructor() {
554
+ /** @type {App} */
305
555
  this.app = new App();
306
556
  }
307
557
 
558
+ /**
559
+ * Adds an item to the impro sidebar. `icon` is a {@link VirtualEl} (typically
560
+ * an SVG) or a string; `callback` runs when the item is clicked.
561
+ * @param {string | VirtualEl} icon
562
+ * @param {string} title
563
+ * @param {() => void} [callback]
564
+ * @returns {void}
565
+ */
308
566
  addSidebarItem(icon, title, callback = () => {}) {
309
567
  const handlerId = uuid.create();
310
568
  callHandlers.set(handlerId, callback);
@@ -317,26 +575,50 @@ export class Plugin {
317
575
  });
318
576
  }
319
577
 
578
+ /**
579
+ * Loads this plugin's account-synced JSON blob. Follows the user across
580
+ * devices via account preferences. Returns whatever was last saved, or null.
581
+ * @returns {Promise<unknown>}
582
+ */
320
583
  async loadData() {
321
584
  return hostCall("loadData");
322
585
  }
323
586
 
587
+ /**
588
+ * Persists `data` as this plugin's account-synced JSON blob.
589
+ * @param {unknown} data
590
+ * @returns {Promise<void>}
591
+ */
324
592
  async saveData(data) {
325
593
  await hostCall("saveData", { data });
326
594
  }
327
595
 
328
- // Device-local counterpart to loadData/saveData: never synced through the
329
- // user's account preferences, so it's the right place for anything that
330
- // shouldn't silently follow the plugin to another device (e.g. a locally
331
- // held secret key). Cleared on uninstall, same as loadData/saveData.
596
+ /**
597
+ * Device-local counterpart to {@link Plugin.loadData}: never synced through
598
+ * the user's account preferences, so it's the right place for anything that
599
+ * shouldn't silently follow the plugin to another device (e.g. a locally
600
+ * held secret key). Cleared on uninstall, same as loadData/saveData.
601
+ * @returns {Promise<unknown>}
602
+ */
332
603
  async loadLocalData() {
333
604
  return hostCall("loadLocalData");
334
605
  }
335
606
 
607
+ /**
608
+ * Device-local counterpart to {@link Plugin.saveData}.
609
+ * @param {unknown} data
610
+ * @returns {Promise<void>}
611
+ */
336
612
  async saveLocalData(data) {
337
613
  await hostCall("saveLocalData", { data });
338
614
  }
339
615
 
616
+ /**
617
+ * Registers a {@link PluginSettingTab} shown under this plugin's entry in
618
+ * the app's settings.
619
+ * @param {PluginSettingTab} tab
620
+ * @returns {void}
621
+ */
340
622
  addSettingTab(tab) {
341
623
  tab.plugin = this;
342
624
  const displayHandlerId = uuid.create();
@@ -351,10 +633,17 @@ export class Plugin {
351
633
  name: tab.name ?? null,
352
634
  displayHandlerId,
353
635
  });
354
- this._settingTab = tab;
636
+ this.#settingTab = tab;
355
637
  }
356
638
 
357
- addFeedFilter(callback = () => {}) {
639
+ /**
640
+ * Registers a feed filter. `callback(feedUri, feedItems)` returns an object
641
+ * `{ [postUri]: false }` for posts to hide from the feed. Only `false` hides;
642
+ * any other value is ignored, so one plugin can't un-hide what another hid.
643
+ * @param {(feedUri: string, feedItems: FeedItem[]) => Record<string, boolean> | Promise<Record<string, boolean>>} callback
644
+ * @returns {void}
645
+ */
646
+ addFeedFilter(callback = () => ({})) {
358
647
  const handlerId = uuid.create();
359
648
  callHandlers.set(handlerId, callback);
360
649
  self.postMessage({
@@ -364,12 +653,21 @@ export class Plugin {
364
653
  });
365
654
  }
366
655
 
367
- // callback(tokens, context) receives the rich-text token stream for one
368
- // post and returns a new token array (or the input unchanged). The host
369
- // batches all posts of a render into one call per plugin.
370
- //
371
- // options.handlesFacetTypes: array of facet feature $type strings this
372
- // transform owns, to prevent render flash of fallback text
656
+ /**
657
+ * Registers a rich-text transform. `callback(tokens, context)` receives the
658
+ * token stream for one post and returns a new token array (or the input
659
+ * unchanged). Tokens are one of: `text` (plain string run), `facet` (linked
660
+ * text with an atproto facet feature), `inline` (a plugin-produced inline
661
+ * {@link VirtualEl}), or `block` (a plugin-produced block VirtualEl). See
662
+ * {@link FlattenedTokens} for pattern-matching across token boundaries.
663
+ *
664
+ * `options.handlesFacetTypes` is an array of facet feature `$type` strings
665
+ * this transform owns, so the host can suppress fallback rendering flash
666
+ * while the transform runs.
667
+ * @param {(tokens: RichTextToken[], context: { uri: string, surface: string, source: { text: string } }) => RichTextToken[] | Promise<RichTextToken[]>} callback
668
+ * @param {{ handlesFacetTypes?: string[] }} [options]
669
+ * @returns {void}
670
+ */
373
671
  registerRichTextTransform(callback = (tokens) => tokens, options = {}) {
374
672
  const handlerId = uuid.create();
375
673
  callHandlers.set(handlerId, async (batch) => {
@@ -395,14 +693,25 @@ export class Plugin {
395
693
  });
396
694
  }
397
695
 
398
- // options.cacheKey: array of context fields. If provided, the host
399
- // will treat the slot content as a pure function of these fields
400
- // - omitting other fields in the callback and caching return values
401
- // until they're invalidated by refreshSlot(). An empty array declares
402
- // that the content depends on no context at all, so one cached result
403
- // serves every instance.
404
- //
405
- // The host batches all pending contexts of a render into one call.
696
+ /**
697
+ * Registers a slot renderer. `<plugin-slot name="...">` elements in the host
698
+ * UI (or other plugins' output) invoke `callback(context)`, where `context`
699
+ * is a flat string map of the slot element's attributes. The callback should
700
+ * return a {@link VirtualEl} or `null`.
701
+ *
702
+ * `options.cacheKey` is an array of context field names. If provided, the
703
+ * host treats the slot content as a pure function of these fields — omitting
704
+ * other fields from the callback's context and caching return values until
705
+ * invalidated by {@link Plugin.refreshSlot}. An empty array declares that
706
+ * the content depends on no context at all, so one cached result serves
707
+ * every instance.
708
+ *
709
+ * The host batches all pending contexts of a render into one call.
710
+ * @param {string} name
711
+ * @param {(context: Record<string, string>) => RenderResult | Promise<RenderResult>} callback
712
+ * @param {{ cacheKey?: string[] }} [options]
713
+ * @returns {void}
714
+ */
406
715
  registerSlot(name, callback = () => null, options = {}) {
407
716
  const handlerId = uuid.create();
408
717
  callHandlers.set(handlerId, async (batch) => {
@@ -431,22 +740,89 @@ export class Plugin {
431
740
  });
432
741
  }
433
742
 
434
- // Makes mounted <plugin-slot name=...> instances re-invoke this plugin's
435
- // registered callback for that slot, and drops any cached results. Useful
436
- // when a slot's content depends on plugin state that changed after render.
437
- //
438
- // options.keys: array of matcher objects to be OR'd together,
439
- // e.g. [{ did: "..." }] - any matching slots will be invalidated / refreshed.
440
- // Omit to refresh every instance. A slot registered with a cacheKey can only
441
- // be matched on those declared fields, since its output depends on nothing
442
- // else.
743
+ /**
744
+ * Registers a full-page view reachable via {@link Plugin.openPage}. `display()`
745
+ * is called on navigation and must return a {@link VirtualEl}, or nothing to
746
+ * render an empty page.
747
+ * @param {{ id: string, title?: string | null, display?: () => RenderResult | Promise<RenderResult> }} options
748
+ * @returns {void}
749
+ */
750
+ registerPage({ id, title = null, display = () => null }) {
751
+ const displayHandlerId = uuid.create();
752
+ callHandlers.set(displayHandlerId, async () => {
753
+ const result = /** @type {unknown} */ (await display());
754
+ if (result == null) return null;
755
+ if (!(result instanceof VirtualEl)) {
756
+ throw new Error(
757
+ `Page "${id}" must return a VirtualEl or null, got ${describeValue(result)}`,
758
+ );
759
+ }
760
+ return result._serialize();
761
+ });
762
+ self.postMessage({
763
+ type: "register",
764
+ target: "page",
765
+ id,
766
+ title,
767
+ displayHandlerId,
768
+ });
769
+ }
770
+
771
+ /**
772
+ * Navigates the user to one of this plugin's registered pages.
773
+ * @param {string} pageId
774
+ * @returns {Promise<void>}
775
+ */
776
+ openPage(pageId) {
777
+ return hostCall("openPage", { pageId });
778
+ }
779
+
780
+ /**
781
+ * Re-invokes a registered page's display callback if the page is open.
782
+ * `options.reset` also discards the rendered tree instead of patching it.
783
+ * @param {string} pageId
784
+ * @param {{ reset?: boolean }} [options]
785
+ * @returns {Promise<void>}
786
+ */
787
+ refreshPage(pageId, { reset = false } = {}) {
788
+ return hostCall("refreshPage", { pageId, reset });
789
+ }
790
+
791
+ /**
792
+ * Makes mounted `<plugin-slot name=...>` instances re-invoke this plugin's
793
+ * registered callback for that slot, and drops any cached results. Useful
794
+ * when a slot's content depends on plugin state that changed after render.
795
+ *
796
+ * `options.keys` is an array of matcher objects OR'd together,
797
+ * e.g. `[{ did: "..." }]` — any matching slots are invalidated and refreshed.
798
+ * Omit to refresh every instance. A slot registered with a `cacheKey` can
799
+ * only be matched on those declared fields, since its output depends on
800
+ * nothing else.
801
+ * @param {string} name
802
+ * @param {{ keys?: Record<string, string>[] }} [options]
803
+ * @returns {Promise<void>}
804
+ */
443
805
  refreshSlot(name, options = {}) {
444
806
  return hostCall("refreshSlot", { name, keys: options.keys ?? null });
445
807
  }
446
808
 
809
+ /**
810
+ * Override in your subclass. Runs after the plugin is loaded and the current user is resolved.
811
+ * @returns {void | Promise<void>}
812
+ */
447
813
  onload() {}
814
+ /**
815
+ * Override in your subclass. Runs when the plugin is being torn down (uninstall/reload).
816
+ * @returns {void | Promise<void>}
817
+ */
448
818
  onunload() {}
449
819
 
820
+ /**
821
+ * Boots the plugin. Call as `MyPlugin.register()` at the top of your plugin's
822
+ * main.js — instantiates the subclass, resolves the current user onto
823
+ * `app.currentUser`, then invokes {@link Plugin.onload}. Idempotent.
824
+ * @returns {void}
825
+ */
450
826
  static register() {
451
827
  if (registered) return;
452
828
  registered = true;
@@ -467,13 +843,23 @@ export class Plugin {
467
843
  }
468
844
  }
469
845
 
846
+ /**
847
+ * Names the type of an arbitrary value, for use in an error message.
848
+ * @param {unknown} value
849
+ * @returns {string}
850
+ */
851
+ function describeValue(value) {
852
+ if (value === null) return "null";
853
+ if (typeof value !== "object") return typeof value;
854
+ return value.constructor?.name ?? "object";
855
+ }
856
+
470
857
  async function getSlotContent(name, callback, context) {
471
- const result = await callback(context);
858
+ const result = /** @type {unknown} */ (await callback(context));
472
859
  if (result == null) return null;
473
860
  if (!(result instanceof VirtualEl)) {
474
- const description = result?.constructor?.name ?? typeof result;
475
861
  throw new Error(
476
- `Slot "${name}" must return a VirtualEl or null, got ${description}`,
862
+ `Slot "${name}" must return a VirtualEl or null, got ${describeValue(result)}`,
477
863
  );
478
864
  }
479
865
  return result._serialize();
@@ -492,11 +878,18 @@ function serializeTransformTokens(tokens) {
492
878
  });
493
879
  }
494
880
 
495
- // Concatenates the renderable text of a token stream into a string with a position map,
496
- // so a transform can pattern-match across token boundaries and map matches back to tokens.
881
+ /**
882
+ * Flattens a rich-text token stream into a plain string with a position map,
883
+ * so a {@link Plugin.registerRichTextTransform | rich-text transform} can
884
+ * pattern-match (e.g. with a regex) across token boundaries and map matches
885
+ * back to the original tokens.
886
+ */
497
887
  export class FlattenedTokens {
888
+ #segments = [];
889
+ /**
890
+ * @param {RichTextToken[]} tokens
891
+ */
498
892
  constructor(tokens) {
499
- this._segments = [];
500
893
  let text = "";
501
894
  for (const token of tokens) {
502
895
  let value = null;
@@ -504,20 +897,33 @@ export class FlattenedTokens {
504
897
  else if (token.type === "facet") value = token.text;
505
898
  const start = text.length;
506
899
  if (value != null) text += value;
507
- this._segments.push({ token, start, end: text.length });
900
+ this.#segments.push({ token, start, end: text.length });
508
901
  }
902
+ /** @type {string} */
509
903
  this.text = text;
510
904
  }
511
905
 
512
- // emit an inert range (no facets)
906
+ /**
907
+ * Return the plain-text slice for `[start, end)` — inert, with no facets.
908
+ * @param {number} start
909
+ * @param {number} end
910
+ * @returns {string}
911
+ */
513
912
  textFor(start, end) {
514
913
  return this.text.slice(start, end);
515
914
  }
516
915
 
517
- // emit a live range, demoting partial facet tokens to text tokens
916
+ /**
917
+ * Return the tokens covering `[start, end)`. Facet tokens partially
918
+ * overlapping the range are demoted to plain text tokens so the emitted
919
+ * slice never carries a truncated facet.
920
+ * @param {number} start
921
+ * @param {number} end
922
+ * @returns {RichTextToken[]}
923
+ */
518
924
  tokensFor(start, end) {
519
925
  const out = [];
520
- for (const segment of this._segments) {
926
+ for (const segment of this.#segments) {
521
927
  if (segment.start === segment.end) {
522
928
  if (segment.start >= start && segment.start < end) {
523
929
  out.push(segment.token);
@@ -538,29 +944,45 @@ export class FlattenedTokens {
538
944
  }
539
945
  }
540
946
 
947
+ /**
948
+ * Convenience wrapper that returns a new {@link FlattenedTokens} for `tokens`.
949
+ * @param {RichTextToken[]} tokens
950
+ * @returns {FlattenedTokens}
951
+ */
541
952
  export function flattenForScan(tokens) {
542
953
  return new FlattenedTokens(tokens);
543
954
  }
544
955
 
545
956
  const openModals = new Map();
546
957
 
958
+ /**
959
+ * A dismissable modal dialog. Subclass and populate `contentEl` and
960
+ * `titleEl` (both {@link VirtualEl}), typically inside {@link Modal.onOpen}.
961
+ * Call `open()` to show and `close()` to hide.
962
+ */
547
963
  export class Modal {
964
+ #modalId = uuid.create();
548
965
  constructor() {
549
- this._modalId = uuid.create();
966
+ /** @type {VirtualEl} */
550
967
  this.contentEl = new VirtualEl("div");
968
+ /** @type {VirtualEl} */
551
969
  this.titleEl = new VirtualEl("h2");
552
970
  }
553
971
 
972
+ /**
973
+ * Show the modal. Runs {@link Modal.onOpen} first, then mounts the current el state.
974
+ * @returns {void}
975
+ */
554
976
  open() {
555
- if (openModals.has(this._modalId)) return;
556
- openModals.set(this._modalId, this);
977
+ if (openModals.has(this.#modalId)) return;
978
+ openModals.set(this.#modalId, this);
557
979
  this.onOpen();
558
980
  self.postMessage({
559
981
  type: "hostCall",
560
982
  method: "openModal",
561
983
  args: [
562
984
  {
563
- modalId: this._modalId,
985
+ modalId: this.#modalId,
564
986
  title: this.titleEl._serialize(),
565
987
  content: this.contentEl._serialize(),
566
988
  },
@@ -568,14 +990,18 @@ export class Modal {
568
990
  });
569
991
  }
570
992
 
993
+ /**
994
+ * Re-render the open modal from the current `titleEl` / `contentEl` state. No-op if closed.
995
+ * @returns {void}
996
+ */
571
997
  update() {
572
- if (!openModals.has(this._modalId)) return;
998
+ if (!openModals.has(this.#modalId)) return;
573
999
  self.postMessage({
574
1000
  type: "hostCall",
575
1001
  method: "updateModal",
576
1002
  args: [
577
1003
  {
578
- modalId: this._modalId,
1004
+ modalId: this.#modalId,
579
1005
  title: this.titleEl._serialize(),
580
1006
  content: this.contentEl._serialize(),
581
1007
  },
@@ -583,74 +1009,159 @@ export class Modal {
583
1009
  });
584
1010
  }
585
1011
 
1012
+ /**
1013
+ * Hide the modal and fire {@link Modal.onClose}.
1014
+ * @returns {void}
1015
+ */
586
1016
  close() {
587
- if (!openModals.has(this._modalId)) return;
588
- openModals.delete(this._modalId);
1017
+ if (!openModals.has(this.#modalId)) return;
1018
+ openModals.delete(this.#modalId);
589
1019
  self.postMessage({
590
1020
  type: "hostCall",
591
1021
  method: "closeModal",
592
- args: [{ modalId: this._modalId }],
1022
+ args: [{ modalId: this.#modalId }],
593
1023
  });
594
1024
  this.onClose();
595
1025
  }
596
1026
 
1027
+ /**
1028
+ * Lifecycle hook — override to populate `titleEl` / `contentEl` before the modal mounts.
1029
+ * @returns {void}
1030
+ */
597
1031
  onOpen() {}
1032
+ /**
1033
+ * Lifecycle hook — override to react to the modal being dismissed (by `close()` or the user).
1034
+ * @returns {void}
1035
+ */
598
1036
  onClose() {}
599
1037
  }
600
1038
 
1039
+ /**
1040
+ * A tab in the plugin's settings UI. Subclass and override {@link PluginSettingTab.display}
1041
+ * to render into `this.containerEl`. Register with `plugin.addSettingTab(tab)`.
1042
+ */
601
1043
  export class PluginSettingTab {
1044
+ /**
1045
+ * The owning plugin. Set by the host in {@link Plugin.addSettingTab}.
1046
+ * @type {Plugin}
1047
+ */
1048
+ plugin;
602
1049
  constructor() {
1050
+ /** @type {VirtualEl} */
603
1051
  this.containerEl = new VirtualEl("div");
1052
+ /** @type {string | null} */
604
1053
  this.name = null;
605
1054
  }
1055
+ /**
1056
+ * Set the tab's label.
1057
+ * @param {string} name
1058
+ * @returns {this}
1059
+ */
606
1060
  setName(name) {
607
1061
  this.name = name;
608
1062
  return this;
609
1063
  }
1064
+ /**
1065
+ * Override to render the tab's contents into `this.containerEl`.
1066
+ * @returns {void}
1067
+ */
610
1068
  display() {}
1069
+ /**
1070
+ * Re-invoke {@link PluginSettingTab.display}. `reset: true` also discards the rendered tree.
1071
+ * @param {{ reset?: boolean }} [options]
1072
+ * @returns {Promise<void>}
1073
+ */
611
1074
  refresh({ reset = false } = {}) {
612
1075
  return hostCall("refreshSettingTab", { reset });
613
1076
  }
614
1077
  }
615
1078
 
1079
+ /**
1080
+ * Fluent builder for a single labeled settings row. `new Setting(containerEl)`
1081
+ * appends a row (name + description + control area) to `containerEl` and
1082
+ * returns a builder for populating it.
1083
+ */
616
1084
  export class Setting {
1085
+ /**
1086
+ * @param {VirtualEl} containerEl
1087
+ */
617
1088
  constructor(containerEl) {
1089
+ /** @type {VirtualEl} */
618
1090
  this.settingEl = containerEl.createDiv({ cls: "setting-item" });
1091
+ /** @type {VirtualEl} */
619
1092
  this.infoEl = this.settingEl.createDiv({ cls: "setting-item-info" });
1093
+ /** @type {VirtualEl} */
620
1094
  this.nameEl = this.infoEl.createEl("h2", { cls: "setting-item-name" });
1095
+ /** @type {VirtualEl} */
621
1096
  this.descEl = this.infoEl.createEl("p", { cls: "setting-item-desc" });
1097
+ /** @type {VirtualEl} */
622
1098
  this.controlEl = this.settingEl.createDiv({
623
1099
  cls: "setting-item-control",
624
1100
  });
625
1101
  }
1102
+ /**
1103
+ * Set the row's name/label.
1104
+ * @param {string} text
1105
+ * @returns {this}
1106
+ */
626
1107
  setName(text) {
627
1108
  this.nameEl.setText(text);
628
1109
  return this;
629
1110
  }
1111
+ /**
1112
+ * Set the row's description text below the name.
1113
+ * @param {string} text
1114
+ * @returns {this}
1115
+ */
630
1116
  setDesc(text) {
631
1117
  this.descEl.setText(text);
632
1118
  return this;
633
1119
  }
1120
+ /**
1121
+ * Add a text input; the callback receives a {@link TextComponent}.
1122
+ * @param {(component: TextComponent) => void} callback
1123
+ * @returns {this}
1124
+ */
634
1125
  addText(callback) {
635
1126
  const component = new TextComponent(this.controlEl);
636
1127
  callback(component);
637
1128
  return this;
638
1129
  }
1130
+ /**
1131
+ * Add a multi-line text input; the callback receives a {@link TextAreaComponent}.
1132
+ * @param {(component: TextAreaComponent) => void} callback
1133
+ * @returns {this}
1134
+ */
639
1135
  addTextArea(callback) {
640
1136
  const component = new TextAreaComponent(this.controlEl);
641
1137
  callback(component);
642
1138
  return this;
643
1139
  }
1140
+ /**
1141
+ * Add a toggle switch; the callback receives a {@link ToggleComponent}.
1142
+ * @param {(component: ToggleComponent) => void} callback
1143
+ * @returns {this}
1144
+ */
644
1145
  addToggle(callback) {
645
1146
  const component = new ToggleComponent(this.controlEl);
646
1147
  callback(component);
647
1148
  return this;
648
1149
  }
1150
+ /**
1151
+ * Add a dropdown; the callback receives a {@link DropdownComponent}.
1152
+ * @param {(component: DropdownComponent) => void} callback
1153
+ * @returns {this}
1154
+ */
649
1155
  addDropdown(callback) {
650
1156
  const component = new DropdownComponent(this.controlEl);
651
1157
  callback(component);
652
1158
  return this;
653
1159
  }
1160
+ /**
1161
+ * Add a button; the callback receives a {@link ButtonComponent}.
1162
+ * @param {(component: ButtonComponent) => void} callback
1163
+ * @returns {this}
1164
+ */
654
1165
  addButton(callback) {
655
1166
  const component = new ButtonComponent(this.controlEl);
656
1167
  callback(component);
@@ -658,202 +1169,391 @@ export class Setting {
658
1169
  }
659
1170
  }
660
1171
 
661
- class TextComponent {
1172
+ /** Single-line text input, built via {@link Setting.addText}. */
1173
+ export class TextComponent {
1174
+ /** @internal */
662
1175
  constructor(containerEl) {
1176
+ /** @type {VirtualEl} */
663
1177
  this.el = containerEl.createEl("input", {
664
1178
  attr: { type: "text" },
665
1179
  cls: "setting-item-text-input",
666
1180
  });
667
1181
  }
1182
+ /**
1183
+ * Set the current value.
1184
+ * @param {string | null} value
1185
+ * @returns {this}
1186
+ */
668
1187
  setValue(value) {
669
1188
  this.el.setAttr("value", value == null ? "" : String(value));
670
1189
  return this;
671
1190
  }
1191
+ /**
1192
+ * Set the placeholder text shown when the input is empty.
1193
+ * @param {string} value
1194
+ * @returns {this}
1195
+ */
672
1196
  setPlaceholder(value) {
673
1197
  this.el.setAttr("placeholder", value);
674
1198
  return this;
675
1199
  }
1200
+ /**
1201
+ * Fires with the new string value on every change.
1202
+ * @param {(value: string) => void} callback
1203
+ * @returns {this}
1204
+ */
676
1205
  onChange(callback) {
677
- this.el.onChange((event) => callback(event.target.value));
1206
+ this.el.onChange((event) => callback(event.target.value ?? ""));
678
1207
  return this;
679
1208
  }
680
1209
  }
681
1210
 
682
- class TextAreaComponent {
1211
+ /** Multi-line text input, built via {@link Setting.addTextArea}. */
1212
+ export class TextAreaComponent {
1213
+ /** @internal */
683
1214
  constructor(containerEl) {
1215
+ /** @type {VirtualEl} */
684
1216
  this.el = containerEl.createEl("textarea", {
685
1217
  cls: "setting-item-textarea",
686
1218
  });
687
1219
  }
1220
+ /**
1221
+ * Set the current value.
1222
+ * @param {string | null} value
1223
+ * @returns {this}
1224
+ */
688
1225
  setValue(value) {
689
1226
  this.el.setText(value == null ? "" : String(value));
690
1227
  return this;
691
1228
  }
1229
+ /**
1230
+ * Set the placeholder text shown when the input is empty.
1231
+ * @param {string} value
1232
+ * @returns {this}
1233
+ */
692
1234
  setPlaceholder(value) {
693
1235
  this.el.setAttr("placeholder", value);
694
1236
  return this;
695
1237
  }
1238
+ /**
1239
+ * Fires with the new string value on every change.
1240
+ * @param {(value: string) => void} callback
1241
+ * @returns {this}
1242
+ */
696
1243
  onChange(callback) {
697
- this.el.onChange((event) => callback(event.target.value));
1244
+ this.el.onChange((event) => callback(event.target.value ?? ""));
698
1245
  return this;
699
1246
  }
700
1247
  }
701
1248
 
702
- class ToggleComponent {
1249
+ /** On/off toggle switch, built via {@link Setting.addToggle}. */
1250
+ export class ToggleComponent {
1251
+ /** @internal */
703
1252
  constructor(containerEl) {
1253
+ /** @type {VirtualEl} */
704
1254
  this.el = containerEl.createEl("toggle-switch", {
705
1255
  cls: "setting-item-toggle",
706
1256
  });
707
1257
  }
1258
+ /**
1259
+ * Set the checked state.
1260
+ * @param {boolean} value
1261
+ * @returns {this}
1262
+ */
708
1263
  setValue(value) {
709
1264
  if (value) this.el.setAttr("checked", "");
710
1265
  else delete this.el.attrs.checked;
711
1266
  return this;
712
1267
  }
1268
+ /**
1269
+ * Fires with the new boolean value on every change.
1270
+ * @param {(checked: boolean) => void} callback
1271
+ * @returns {this}
1272
+ */
713
1273
  onChange(callback) {
714
- this.el.onChange((event) => callback(event.target.checked));
1274
+ this.el.onChange((event) => callback(event.target.checked ?? false));
715
1275
  return this;
716
1276
  }
717
1277
  }
718
1278
 
719
- class DropdownComponent {
1279
+ /** Single-select dropdown, built via {@link Setting.addDropdown}. */
1280
+ export class DropdownComponent {
1281
+ /** @internal */
720
1282
  constructor(containerEl) {
1283
+ /** @type {VirtualEl} */
721
1284
  this.el = containerEl.createEl("select", {
722
1285
  cls: "setting-item-dropdown",
723
1286
  });
724
1287
  }
1288
+ /**
1289
+ * Append one option.
1290
+ * @param {string} value
1291
+ * @param {string} label
1292
+ * @returns {this}
1293
+ */
725
1294
  addOption(value, label) {
726
1295
  this.el.createEl("option", { text: label, attr: { value } });
727
1296
  return this;
728
1297
  }
1298
+ /**
1299
+ * Append every `{ value: label }` entry as an option.
1300
+ * @param {Record<string, string>} map
1301
+ * @returns {this}
1302
+ */
729
1303
  addOptions(map) {
730
1304
  for (const [value, label] of Object.entries(map)) {
731
1305
  this.addOption(value, label);
732
1306
  }
733
1307
  return this;
734
1308
  }
1309
+ /**
1310
+ * Select the option whose value matches.
1311
+ * @param {string} value
1312
+ * @returns {this}
1313
+ */
735
1314
  setValue(value) {
736
1315
  for (const child of this.el.children) {
737
- if (child.attrs?.value === value) {
1316
+ if (!(child instanceof VirtualEl)) continue;
1317
+ if (child.attrs.value === value) {
738
1318
  child.attrs.selected = "";
739
- } else if (child.attrs) {
1319
+ } else {
740
1320
  delete child.attrs.selected;
741
1321
  }
742
1322
  }
743
1323
  return this;
744
1324
  }
1325
+ /**
1326
+ * Fires with the newly selected value on every change.
1327
+ * @param {(value: string) => void} callback
1328
+ * @returns {this}
1329
+ */
745
1330
  onChange(callback) {
746
- this.el.onChange((event) => callback(event.target.value));
1331
+ this.el.onChange((event) => callback(event.target.value ?? ""));
747
1332
  return this;
748
1333
  }
749
1334
  }
750
1335
 
751
- class ButtonComponent {
1336
+ /** Clickable button, built via {@link Setting.addButton}. */
1337
+ export class ButtonComponent {
1338
+ /** @internal */
752
1339
  constructor(containerEl) {
1340
+ /** @type {VirtualEl} */
753
1341
  this.el = containerEl.createEl("button", {
754
1342
  cls: "rounded-button",
755
1343
  });
756
1344
  }
1345
+ /**
1346
+ * Set the button's label.
1347
+ * @param {string} text
1348
+ * @returns {this}
1349
+ */
757
1350
  setButtonText(text) {
758
1351
  this.el.setText(text);
759
1352
  return this;
760
1353
  }
1354
+ /**
1355
+ * Style the button as the row's primary call-to-action.
1356
+ * @returns {this}
1357
+ */
761
1358
  setCta() {
762
1359
  this.el.addClass("rounded-button-primary");
763
1360
  return this;
764
1361
  }
1362
+ /**
1363
+ * Register a click handler.
1364
+ * @param {() => void} callback
1365
+ * @returns {this}
1366
+ */
765
1367
  onClick(callback) {
766
1368
  this.el.onClick(callback);
767
1369
  return this;
768
1370
  }
769
1371
  }
770
1372
 
771
- class IconComponent {
1373
+ /** Renders a host-provided icon by name. Built via {@link VirtualEl.createIcon}. */
1374
+ export class IconComponent {
1375
+ /** @internal */
772
1376
  constructor(containerEl) {
1377
+ /** @type {VirtualEl} */
773
1378
  this.el = containerEl.createEl("plugin-icon");
774
1379
  }
1380
+ /**
1381
+ * Set the icon name.
1382
+ * @param {string} name
1383
+ * @returns {this}
1384
+ */
775
1385
  setIcon(name) {
776
1386
  this.el.setAttr("icon", name);
777
1387
  return this;
778
1388
  }
779
1389
  }
780
1390
 
781
- class BlobImageComponent {
1391
+ /**
1392
+ * Renders a repo blob (by owning DID + blob CID) as an image. Built via
1393
+ * {@link VirtualEl.createBlobImage}.
1394
+ */
1395
+ export class BlobImageComponent {
1396
+ /** @internal */
782
1397
  constructor(containerEl) {
1398
+ /** @type {VirtualEl} */
783
1399
  this.el = containerEl.createEl("plugin-blob-image");
784
1400
  }
1401
+ /**
1402
+ * DID of the repo the blob belongs to.
1403
+ * @param {string} did
1404
+ * @returns {this}
1405
+ */
785
1406
  setDid(did) {
786
1407
  this.el.setAttr("did", did);
787
1408
  return this;
788
1409
  }
1410
+ /**
1411
+ * CID of the blob to render.
1412
+ * @param {string} cid
1413
+ * @returns {this}
1414
+ */
789
1415
  setCid(cid) {
790
1416
  this.el.setAttr("cid", cid);
791
1417
  return this;
792
1418
  }
1419
+ /**
1420
+ * Set the image's alt text.
1421
+ * @param {string} alt
1422
+ * @returns {this}
1423
+ */
793
1424
  setAlt(alt) {
794
1425
  this.el.setAttr("alt", alt);
795
1426
  return this;
796
1427
  }
1428
+ /**
1429
+ * Override the CDN URL prefix used to fetch the blob.
1430
+ * @param {string} prefix
1431
+ * @returns {this}
1432
+ */
797
1433
  setCdnPrefix(prefix) {
798
1434
  this.el.setAttr("cdn-prefix", prefix);
799
1435
  return this;
800
1436
  }
801
1437
  }
802
1438
 
803
- class ProfilesListComponent {
1439
+ /**
1440
+ * Renders a list of profiles from an array of DIDs, hydrated by the host.
1441
+ * Built via {@link VirtualEl.createProfilesList}.
1442
+ */
1443
+ export class ProfilesListComponent {
1444
+ /** @internal */
804
1445
  constructor(containerEl) {
1446
+ /** @type {VirtualEl} */
805
1447
  this.el = containerEl.createEl("plugin-profiles-list");
806
1448
  }
1449
+ /**
1450
+ * Set the DIDs to render (array or comma-separated string).
1451
+ * @param {string[] | string} dids
1452
+ * @returns {this}
1453
+ */
807
1454
  setDids(dids) {
808
1455
  const value = Array.isArray(dids) ? dids.join(",") : String(dids ?? "");
809
1456
  this.el.setAttr("dids", value);
810
1457
  return this;
811
1458
  }
1459
+ /**
1460
+ * Message shown when the list is empty.
1461
+ * @param {string} message
1462
+ * @returns {this}
1463
+ */
812
1464
  setEmptyMessage(message) {
813
1465
  this.el.setAttr("empty-message", message);
814
1466
  return this;
815
1467
  }
816
1468
  }
817
1469
 
818
- class PostsFeedComponent {
1470
+ /**
1471
+ * Renders a feed of posts from an array of post URIs, hydrated by the host.
1472
+ * Built via {@link VirtualEl.createPostsFeed}.
1473
+ */
1474
+ export class PostsFeedComponent {
1475
+ /** @internal */
819
1476
  constructor(containerEl) {
1477
+ /** @type {VirtualEl} */
820
1478
  this.el = containerEl.createEl("plugin-posts-feed");
821
1479
  }
1480
+ /**
1481
+ * Set the post URIs to render (array or comma-separated string).
1482
+ * @param {string[] | string} uris
1483
+ * @returns {this}
1484
+ */
822
1485
  setUris(uris) {
823
1486
  const value = Array.isArray(uris) ? uris.join(",") : String(uris ?? "");
824
1487
  this.el.setAttr("uris", value);
825
1488
  return this;
826
1489
  }
1490
+ /**
1491
+ * Message shown when the feed is empty.
1492
+ * @param {string} message
1493
+ * @returns {this}
1494
+ */
827
1495
  setEmptyMessage(message) {
828
1496
  this.el.setAttr("empty-message", message);
829
1497
  return this;
830
1498
  }
831
1499
  }
832
1500
 
1501
+ /**
1502
+ * A text node in a {@link VirtualEl} tree. Null/undefined coerce to `""`.
1503
+ */
833
1504
  export class VirtualText {
1505
+ /**
1506
+ * @param {string | null | undefined} value
1507
+ */
834
1508
  constructor(value) {
1509
+ /** @type {string} */
835
1510
  this.value = value == null ? "" : String(value);
836
1511
  }
837
1512
 
1513
+ /** @internal */
838
1514
  _serialize() {
839
1515
  return { type: "text", value: this.value };
840
1516
  }
841
1517
  }
842
1518
 
1519
+ /**
1520
+ * Minimal DOM-builder node. Plugins run in a sandbox and cannot touch the real
1521
+ * DOM directly; instead they build a serializable {@link VirtualEl} tree that
1522
+ * the host renders and reconciles.
1523
+ */
843
1524
  export class VirtualEl {
1525
+ /**
1526
+ * @param {string} tag
1527
+ */
844
1528
  constructor(tag) {
1529
+ /** @type {string} */
845
1530
  this.tag = tag;
1531
+ /** @type {Record<string, string>} */
846
1532
  this.attrs = {};
1533
+ /** @type {Record<string, string>} */
847
1534
  this.styles = {};
1535
+ /** @type {(VirtualEl | VirtualText)[]} */
848
1536
  this.children = [];
1537
+ /** @type {Record<string, number>} */
849
1538
  this.events = {};
850
1539
  }
851
1540
 
1541
+ /**
1542
+ * Set an inline style.
1543
+ * @param {string} name
1544
+ * @param {string | null} value
1545
+ * @returns {this}
1546
+ */
852
1547
  setStyle(name, value) {
853
1548
  this.styles[String(name)] = value == null ? "" : String(value);
854
1549
  return this;
855
1550
  }
856
1551
 
1552
+ /**
1553
+ * Register a click handler.
1554
+ * @param {(event?: object) => void} fn
1555
+ * @returns {this}
1556
+ */
857
1557
  onClick(fn) {
858
1558
  const handlerId = uuid.create();
859
1559
  callHandlers.set(handlerId, fn);
@@ -861,6 +1561,11 @@ export class VirtualEl {
861
1561
  return this;
862
1562
  }
863
1563
 
1564
+ /**
1565
+ * Register a change handler (form controls).
1566
+ * @param {(event: { target: { value?: string, checked?: boolean } }) => void} fn
1567
+ * @returns {this}
1568
+ */
864
1569
  onChange(fn) {
865
1570
  const handlerId = uuid.create();
866
1571
  callHandlers.set(handlerId, fn);
@@ -868,6 +1573,11 @@ export class VirtualEl {
868
1573
  return this;
869
1574
  }
870
1575
 
1576
+ /**
1577
+ * Register an input handler (text inputs).
1578
+ * @param {(event: { target: { value?: string } }) => void} fn
1579
+ * @returns {this}
1580
+ */
871
1581
  onInput(fn) {
872
1582
  const handlerId = uuid.create();
873
1583
  callHandlers.set(handlerId, fn);
@@ -875,17 +1585,31 @@ export class VirtualEl {
875
1585
  return this;
876
1586
  }
877
1587
 
1588
+ /**
1589
+ * Replace all children with a single {@link VirtualText} node.
1590
+ * @param {string | null} text
1591
+ * @returns {this}
1592
+ */
878
1593
  setText(text) {
879
1594
  this.children = [];
880
1595
  if (text != null && text !== "") this.children.push(new VirtualText(text));
881
1596
  return this;
882
1597
  }
883
1598
 
1599
+ /**
1600
+ * Remove all children.
1601
+ * @returns {this}
1602
+ */
884
1603
  empty() {
885
1604
  this.children = [];
886
1605
  return this;
887
1606
  }
888
1607
 
1608
+ /**
1609
+ * Append a {@link VirtualEl} or {@link VirtualText}; throws on anything else.
1610
+ * @param {VirtualEl | VirtualText} child
1611
+ * @returns {this}
1612
+ */
889
1613
  appendChild(child) {
890
1614
  if (!(child instanceof VirtualEl) && !(child instanceof VirtualText)) {
891
1615
  throw new TypeError(
@@ -896,27 +1620,57 @@ export class VirtualEl {
896
1620
  return this;
897
1621
  }
898
1622
 
1623
+ /**
1624
+ * Append a {@link VirtualText} child.
1625
+ * @param {string} value
1626
+ * @returns {this}
1627
+ */
899
1628
  appendText(value) {
900
1629
  this.children.push(new VirtualText(value));
901
1630
  return this;
902
1631
  }
903
1632
 
1633
+ /**
1634
+ * Append and return a {@link VirtualText} child.
1635
+ * @param {string} value
1636
+ * @returns {VirtualText}
1637
+ */
904
1638
  createText(value) {
905
1639
  const node = new VirtualText(value);
906
1640
  this.children.push(node);
907
1641
  return node;
908
1642
  }
909
1643
 
1644
+ /**
1645
+ * Add a CSS class, whitespace-joined with any existing classes.
1646
+ * @param {string} cls
1647
+ * @returns {this}
1648
+ */
910
1649
  addClass(cls) {
911
1650
  this.attrs.class = this.attrs.class ? `${this.attrs.class} ${cls}` : cls;
912
1651
  return this;
913
1652
  }
914
1653
 
1654
+ /**
1655
+ * Set an attribute; `undefined` coerces to `""`.
1656
+ * @param {string} name
1657
+ * @param {string | undefined} value
1658
+ * @returns {this}
1659
+ */
915
1660
  setAttr(name, value) {
916
1661
  this.attrs[name] = value === undefined ? "" : value;
917
1662
  return this;
918
1663
  }
919
1664
 
1665
+ /**
1666
+ * Append a child element and return it. `options` accepts `text`,
1667
+ * `cls` (string or string[]), and `attr` (object). The optional callback
1668
+ * receives the new child for further building.
1669
+ * @param {string} tag
1670
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1671
+ * @param {(child: VirtualEl) => void} [callback]
1672
+ * @returns {VirtualEl}
1673
+ */
920
1674
  createEl(tag, options = {}, callback) {
921
1675
  const child = new VirtualEl(tag);
922
1676
  if (options.text != null) child.setText(options.text);
@@ -931,38 +1685,71 @@ export class VirtualEl {
931
1685
  return child;
932
1686
  }
933
1687
 
1688
+ /**
1689
+ * Shorthand for `createEl("div", ...)`.
1690
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1691
+ * @param {(child: VirtualEl) => void} [callback]
1692
+ * @returns {VirtualEl}
1693
+ */
934
1694
  createDiv(options = {}, callback) {
935
1695
  return this.createEl("div", options, callback);
936
1696
  }
937
1697
 
1698
+ /**
1699
+ * Shorthand for `createEl("span", ...)`.
1700
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1701
+ * @param {(child: VirtualEl) => void} [callback]
1702
+ * @returns {VirtualEl}
1703
+ */
938
1704
  createSpan(options = {}, callback) {
939
1705
  return this.createEl("span", options, callback);
940
1706
  }
941
1707
 
1708
+ /**
1709
+ * Append a profiles-list custom component and return its builder.
1710
+ * @param {(c: ProfilesListComponent) => void} [callback]
1711
+ * @returns {ProfilesListComponent}
1712
+ */
942
1713
  createProfilesList(callback) {
943
1714
  const component = new ProfilesListComponent(this);
944
1715
  if (typeof callback === "function") callback(component);
945
1716
  return component;
946
1717
  }
947
1718
 
1719
+ /**
1720
+ * Append a posts-feed custom component and return its builder.
1721
+ * @param {(c: PostsFeedComponent) => void} [callback]
1722
+ * @returns {PostsFeedComponent}
1723
+ */
948
1724
  createPostsFeed(callback) {
949
1725
  const component = new PostsFeedComponent(this);
950
1726
  if (typeof callback === "function") callback(component);
951
1727
  return component;
952
1728
  }
953
1729
 
1730
+ /**
1731
+ * Append an icon custom component and return its builder.
1732
+ * @param {(c: IconComponent) => void} [callback]
1733
+ * @returns {IconComponent}
1734
+ */
954
1735
  createIcon(callback) {
955
1736
  const component = new IconComponent(this);
956
1737
  if (typeof callback === "function") callback(component);
957
1738
  return component;
958
1739
  }
959
1740
 
1741
+ /**
1742
+ * Append a blob-image custom component and return its builder.
1743
+ * @param {(c: BlobImageComponent) => void} [callback]
1744
+ * @returns {BlobImageComponent}
1745
+ */
960
1746
  createBlobImage(callback) {
961
1747
  const component = new BlobImageComponent(this);
962
1748
  if (typeof callback === "function") callback(component);
963
1749
  return component;
964
1750
  }
965
1751
 
1752
+ /** @internal */
966
1753
  _serialize() {
967
1754
  const serialized = {
968
1755
  type: "element",