@impro.social/impro-plugin 0.0.6

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 +687 -0
  2. package/package.json +13 -0
package/main.js ADDED
@@ -0,0 +1,687 @@
1
+ export class SimpleUUID {
2
+ constructor() {
3
+ this._id = 0;
4
+ }
5
+ create() {
6
+ return this._id++;
7
+ }
8
+ }
9
+
10
+ const uuid = new SimpleUUID();
11
+
12
+ const callHandlers = new Map();
13
+
14
+ const pendingHostCalls = new Map();
15
+
16
+ function hostCall(method, ...args) {
17
+ const hostCallId = uuid.create();
18
+ return new Promise((resolve, reject) => {
19
+ pendingHostCalls.set(hostCallId, { resolve, reject });
20
+ self.postMessage({ type: "hostCall", method, hostCallId, args });
21
+ });
22
+ }
23
+
24
+ const eventListeners = new Map();
25
+
26
+ function addEventListener(event, listener) {
27
+ let listeners = eventListeners.get(event);
28
+ if (!listeners) {
29
+ listeners = new Set();
30
+ eventListeners.set(event, listeners);
31
+ const handlerId = uuid.create();
32
+ callHandlers.set(handlerId, async (...args) => {
33
+ const menu = new Menu();
34
+ for (const eventListener of listeners) {
35
+ try {
36
+ await eventListener(menu, ...args);
37
+ } catch (error) {
38
+ console.error(`"${event}" listener threw:`, error);
39
+ }
40
+ }
41
+ return menu._serialize();
42
+ });
43
+ self.postMessage({
44
+ type: "register",
45
+ target: "eventListener",
46
+ event,
47
+ handlerId,
48
+ });
49
+ }
50
+ listeners.add(listener);
51
+ }
52
+
53
+ export class MenuItem {
54
+ constructor() {
55
+ this.title = "";
56
+ this.icon = null;
57
+ this._callback = () => {};
58
+ }
59
+ setTitle(title) {
60
+ this.title = title;
61
+ return this;
62
+ }
63
+ setIcon(icon) {
64
+ this.icon = icon;
65
+ return this;
66
+ }
67
+ onClick(callback) {
68
+ this._callback = callback;
69
+ return this;
70
+ }
71
+ }
72
+
73
+ export class Menu {
74
+ constructor() {
75
+ this.items = [];
76
+ }
77
+ addItem(builder) {
78
+ const item = new MenuItem();
79
+ builder(item);
80
+ this.items.push(item);
81
+ return this;
82
+ }
83
+ _serialize() {
84
+ return this.items.map((item) => {
85
+ const handlerId = uuid.create();
86
+ callHandlers.set(handlerId, item._callback);
87
+ return { title: item.title, icon: item.icon, handlerId };
88
+ });
89
+ }
90
+ }
91
+
92
+ class PluginData {
93
+ getPost(uri) {
94
+ return hostCall("getPost", { uri });
95
+ }
96
+ getProfile(did) {
97
+ return hostCall("getProfile", { did });
98
+ }
99
+ }
100
+
101
+ class App {
102
+ constructor() {
103
+ this.currentUser = null;
104
+ this.data = new PluginData();
105
+ }
106
+ on(event, listener) {
107
+ addEventListener(event, listener);
108
+ }
109
+
110
+ refreshFeedFilters(feedURI = null) {
111
+ return hostCall("refreshFeedFilters", feedURI);
112
+ }
113
+ }
114
+
115
+ export async function fetch(url, init = {}) {
116
+ const result = await hostCall("fetch", {
117
+ url,
118
+ init: serializeFetchInit(init),
119
+ });
120
+ return new PluginResponse(result);
121
+ }
122
+
123
+ function serializeFetchInit(init) {
124
+ const serialized = {};
125
+ if (init.method != null) serialized.method = String(init.method);
126
+ if (init.headers != null) {
127
+ const headers = {};
128
+ if (typeof init.headers.forEach === "function") {
129
+ // Headers, Map, and similar iterables expose forEach(value, name)
130
+ init.headers.forEach((value, name) => {
131
+ headers[name] = value;
132
+ });
133
+ } else if (typeof init.headers[Symbol.iterator] === "function") {
134
+ for (const [name, value] of init.headers) headers[name] = value;
135
+ } else {
136
+ Object.assign(headers, init.headers);
137
+ }
138
+ serialized.headers = headers;
139
+ }
140
+ if (init.body != null) serialized.body = init.body;
141
+ return serialized;
142
+ }
143
+
144
+ class PluginResponse {
145
+ constructor({ status, ok, headers, body }) {
146
+ this.status = status;
147
+ this.ok = ok;
148
+ this.headers = new Map(Object.entries(headers ?? {}));
149
+ this._body = body;
150
+ }
151
+ async text() {
152
+ return this._body;
153
+ }
154
+ async json() {
155
+ return JSON.parse(this._body);
156
+ }
157
+ }
158
+
159
+ export class Notice {
160
+ constructor(message, timeout = 0) {
161
+ this._toastId = uuid.create();
162
+ this._timeout = timeout;
163
+ this._hidden = false;
164
+ this.noticeEl = new VirtualEl("div");
165
+ this.noticeEl.addClass("toast");
166
+ this.noticeEl.setText(message);
167
+ queueMicrotask(() => {
168
+ if (this._hidden) return;
169
+ hostCall("showToast", {
170
+ toastId: this._toastId,
171
+ element: this.noticeEl._serialize(),
172
+ timeout: this._timeout,
173
+ });
174
+ });
175
+ }
176
+ setMessage(message) {
177
+ this.noticeEl.setText(message);
178
+ return this;
179
+ }
180
+ hide() {
181
+ if (this._hidden) return;
182
+ this._hidden = true;
183
+ hostCall("hideToast", { toastId: this._toastId });
184
+ }
185
+ }
186
+
187
+ export class StyleSnippet {
188
+ constructor(cssText) {
189
+ this._snippetId = uuid.create();
190
+ this._removed = false;
191
+ this.ready = new Promise((resolve, reject) => {
192
+ queueMicrotask(() => {
193
+ if (this._removed) return resolve();
194
+ hostCall("applyStyleSnippet", {
195
+ snippetId: this._snippetId,
196
+ cssText,
197
+ }).then(resolve, reject);
198
+ });
199
+ });
200
+ }
201
+ remove() {
202
+ if (this._removed) return;
203
+ this._removed = true;
204
+ hostCall("removeStyleSnippet", { snippetId: this._snippetId });
205
+ }
206
+ }
207
+
208
+ let registered = false;
209
+
210
+ export class Plugin {
211
+ constructor() {
212
+ this.app = new App();
213
+ }
214
+
215
+ addSidebarItem(icon, title, callback = () => {}) {
216
+ const handlerId = uuid.create();
217
+ callHandlers.set(handlerId, callback);
218
+ self.postMessage({
219
+ type: "register",
220
+ target: "sidebarItem",
221
+ icon,
222
+ title,
223
+ handlerId,
224
+ });
225
+ }
226
+
227
+ async loadData() {
228
+ return hostCall("loadData");
229
+ }
230
+
231
+ async saveData(data) {
232
+ await hostCall("saveData", { data });
233
+ }
234
+
235
+ addSettingTab(tab) {
236
+ tab.plugin = this;
237
+ const displayHandlerId = uuid.create();
238
+ callHandlers.set(displayHandlerId, () => {
239
+ tab.containerEl = new VirtualEl("div");
240
+ tab.display();
241
+ return tab.containerEl._serialize();
242
+ });
243
+ self.postMessage({
244
+ type: "register",
245
+ target: "settingTab",
246
+ name: tab.name ?? null,
247
+ displayHandlerId,
248
+ });
249
+ this._settingTab = tab;
250
+ }
251
+
252
+ addFeedFilter(callback = () => {}) {
253
+ const handlerId = uuid.create();
254
+ callHandlers.set(handlerId, callback);
255
+ self.postMessage({
256
+ type: "register",
257
+ target: "feedFilter",
258
+ handlerId,
259
+ });
260
+ }
261
+
262
+ registerSlot(name, callback = () => null) {
263
+ const handlerId = uuid.create();
264
+ callHandlers.set(handlerId, async (context) => {
265
+ const result = await callback(context);
266
+ if (result == null) return null;
267
+ if (!(result instanceof VirtualEl)) {
268
+ const description = result?.constructor?.name ?? typeof result;
269
+ throw new Error(
270
+ `Slot "${name}" must return a VirtualEl (or null), got ${description}`,
271
+ );
272
+ }
273
+ return result._serialize();
274
+ });
275
+ self.postMessage({
276
+ type: "register",
277
+ target: "slot",
278
+ name,
279
+ handlerId,
280
+ });
281
+ }
282
+
283
+ onload() {}
284
+ onunload() {}
285
+
286
+ static register() {
287
+ if (registered) return;
288
+ registered = true;
289
+ const instance = new this();
290
+ hostCall("getCurrentUser")
291
+ .then((user) => {
292
+ instance.app.currentUser = user;
293
+ return instance.onload();
294
+ })
295
+ .then(
296
+ () => self.postMessage({ type: "ready" }),
297
+ (error) =>
298
+ self.postMessage({
299
+ type: "ready",
300
+ error: error?.message ?? String(error),
301
+ }),
302
+ );
303
+ }
304
+ }
305
+
306
+ const openModals = new Map();
307
+
308
+ export class Modal {
309
+ constructor() {
310
+ this._modalId = uuid.create();
311
+ this.contentEl = new VirtualEl("div");
312
+ this.titleEl = new VirtualEl("h2");
313
+ }
314
+
315
+ open() {
316
+ if (openModals.has(this._modalId)) return;
317
+ openModals.set(this._modalId, this);
318
+ this.onOpen();
319
+ self.postMessage({
320
+ type: "hostCall",
321
+ method: "openModal",
322
+ args: [
323
+ {
324
+ modalId: this._modalId,
325
+ title: this.titleEl._serialize(),
326
+ content: this.contentEl._serialize(),
327
+ },
328
+ ],
329
+ });
330
+ }
331
+
332
+ close() {
333
+ if (!openModals.has(this._modalId)) return;
334
+ openModals.delete(this._modalId);
335
+ self.postMessage({
336
+ type: "hostCall",
337
+ method: "closeModal",
338
+ args: [{ modalId: this._modalId }],
339
+ });
340
+ this.onClose();
341
+ }
342
+
343
+ onOpen() {}
344
+ onClose() {}
345
+ }
346
+
347
+ export class PluginSettingTab {
348
+ constructor() {
349
+ this.containerEl = new VirtualEl("div");
350
+ this.name = null;
351
+ }
352
+ setName(name) {
353
+ this.name = name;
354
+ return this;
355
+ }
356
+ display() {}
357
+ refresh() {
358
+ return hostCall("refreshSettingTab");
359
+ }
360
+ }
361
+
362
+ export class Setting {
363
+ constructor(containerEl) {
364
+ this.settingEl = containerEl.createDiv({ cls: "setting-item" });
365
+ this.infoEl = this.settingEl.createDiv({ cls: "setting-item-info" });
366
+ this.nameEl = this.infoEl.createEl("h2", { cls: "setting-item-name" });
367
+ this.descEl = this.infoEl.createEl("p", { cls: "setting-item-desc" });
368
+ this.controlEl = this.settingEl.createDiv({
369
+ cls: "setting-item-control",
370
+ });
371
+ }
372
+ setName(text) {
373
+ this.nameEl.setText(text);
374
+ return this;
375
+ }
376
+ setDesc(text) {
377
+ this.descEl.setText(text);
378
+ return this;
379
+ }
380
+ addText(callback) {
381
+ const component = new TextComponent(this.controlEl);
382
+ callback(component);
383
+ return this;
384
+ }
385
+ addToggle(callback) {
386
+ const component = new ToggleComponent(this.controlEl);
387
+ callback(component);
388
+ return this;
389
+ }
390
+ addDropdown(callback) {
391
+ const component = new DropdownComponent(this.controlEl);
392
+ callback(component);
393
+ return this;
394
+ }
395
+ addButton(callback) {
396
+ const component = new ButtonComponent(this.controlEl);
397
+ callback(component);
398
+ return this;
399
+ }
400
+ }
401
+
402
+ class TextComponent {
403
+ constructor(containerEl) {
404
+ this.el = containerEl.createEl("input", {
405
+ attr: { type: "text" },
406
+ cls: "setting-item-text-input",
407
+ });
408
+ }
409
+ setValue(value) {
410
+ this.el.setAttr("value", value == null ? "" : String(value));
411
+ return this;
412
+ }
413
+ setPlaceholder(value) {
414
+ this.el.setAttr("placeholder", value);
415
+ return this;
416
+ }
417
+ onChange(callback) {
418
+ this.el.onChange((event) => callback(event.target.value));
419
+ return this;
420
+ }
421
+ }
422
+
423
+ class ToggleComponent {
424
+ constructor(containerEl) {
425
+ this.el = containerEl.createEl("toggle-switch", {
426
+ cls: "setting-item-toggle",
427
+ });
428
+ }
429
+ setValue(value) {
430
+ if (value) this.el.setAttr("checked", "");
431
+ else delete this.el.attrs.checked;
432
+ return this;
433
+ }
434
+ onChange(callback) {
435
+ this.el.onChange((event) => callback(event.target.checked));
436
+ return this;
437
+ }
438
+ }
439
+
440
+ class DropdownComponent {
441
+ constructor(containerEl) {
442
+ this.el = containerEl.createEl("select", {
443
+ cls: "setting-item-dropdown",
444
+ });
445
+ }
446
+ addOption(value, label) {
447
+ this.el.createEl("option", { text: label, attr: { value } });
448
+ return this;
449
+ }
450
+ addOptions(map) {
451
+ for (const [value, label] of Object.entries(map)) {
452
+ this.addOption(value, label);
453
+ }
454
+ return this;
455
+ }
456
+ setValue(value) {
457
+ for (const child of this.el.children) {
458
+ if (child.attrs?.value === value) {
459
+ child.attrs.selected = "";
460
+ } else if (child.attrs) {
461
+ delete child.attrs.selected;
462
+ }
463
+ }
464
+ return this;
465
+ }
466
+ onChange(callback) {
467
+ this.el.onChange((event) => callback(event.target.value));
468
+ return this;
469
+ }
470
+ }
471
+
472
+ class ButtonComponent {
473
+ constructor(containerEl) {
474
+ this.el = containerEl.createEl("button", {
475
+ cls: "rounded-button",
476
+ });
477
+ }
478
+ setButtonText(text) {
479
+ this.el.setText(text);
480
+ return this;
481
+ }
482
+ setCta() {
483
+ this.el.addClass("rounded-button-primary");
484
+ return this;
485
+ }
486
+ onClick(callback) {
487
+ this.el.onClick(callback);
488
+ return this;
489
+ }
490
+ }
491
+
492
+ class IconComponent {
493
+ constructor(containerEl) {
494
+ this.el = containerEl.createEl("plugin-icon");
495
+ }
496
+ setIcon(name) {
497
+ this.el.setAttr("icon", name);
498
+ return this;
499
+ }
500
+ }
501
+
502
+ class ProfilesListComponent {
503
+ constructor(containerEl) {
504
+ this.el = containerEl.createEl("plugin-profiles-list");
505
+ }
506
+ setDids(dids) {
507
+ const value = Array.isArray(dids) ? dids.join(",") : String(dids ?? "");
508
+ this.el.setAttr("dids", value);
509
+ return this;
510
+ }
511
+ setEmptyMessage(message) {
512
+ this.el.setAttr("empty-message", message);
513
+ return this;
514
+ }
515
+ }
516
+
517
+ class PostsFeedComponent {
518
+ constructor(containerEl) {
519
+ this.el = containerEl.createEl("plugin-posts-feed");
520
+ }
521
+ setUris(uris) {
522
+ const value = Array.isArray(uris) ? uris.join(",") : String(uris ?? "");
523
+ this.el.setAttr("uris", value);
524
+ return this;
525
+ }
526
+ setEmptyMessage(message) {
527
+ this.el.setAttr("empty-message", message);
528
+ return this;
529
+ }
530
+ }
531
+
532
+ export class VirtualEl {
533
+ constructor(tag) {
534
+ this.tag = tag;
535
+ this.attrs = {};
536
+ this.text = null;
537
+ this.children = [];
538
+ this.events = {};
539
+ }
540
+
541
+ onClick(fn) {
542
+ const handlerId = uuid.create();
543
+ callHandlers.set(handlerId, fn);
544
+ this.events.click = handlerId;
545
+ return this;
546
+ }
547
+
548
+ onChange(fn) {
549
+ const handlerId = uuid.create();
550
+ callHandlers.set(handlerId, fn);
551
+ this.events.change = handlerId;
552
+ return this;
553
+ }
554
+
555
+ onInput(fn) {
556
+ const handlerId = uuid.create();
557
+ callHandlers.set(handlerId, fn);
558
+ this.events.input = handlerId;
559
+ return this;
560
+ }
561
+
562
+ setText(text) {
563
+ this.text = text;
564
+ this.children = [];
565
+ return this;
566
+ }
567
+
568
+ empty() {
569
+ this.text = null;
570
+ this.children = [];
571
+ return this;
572
+ }
573
+
574
+ addClass(cls) {
575
+ this.attrs.class = this.attrs.class ? `${this.attrs.class} ${cls}` : cls;
576
+ return this;
577
+ }
578
+
579
+ setAttr(name, value) {
580
+ this.attrs[name] = value === undefined ? "" : value;
581
+ return this;
582
+ }
583
+
584
+ createEl(tag, options = {}, callback) {
585
+ const child = new VirtualEl(tag);
586
+ if (options.text != null) child.text = options.text;
587
+ if (options.cls) {
588
+ child.attrs.class = Array.isArray(options.cls)
589
+ ? options.cls.join(" ")
590
+ : options.cls;
591
+ }
592
+ if (options.attr) Object.assign(child.attrs, options.attr);
593
+ this.children.push(child);
594
+ if (typeof callback === "function") callback(child);
595
+ return child;
596
+ }
597
+
598
+ createDiv(options = {}, callback) {
599
+ return this.createEl("div", options, callback);
600
+ }
601
+
602
+ createSpan(options = {}, callback) {
603
+ return this.createEl("span", options, callback);
604
+ }
605
+
606
+ createProfilesList(callback) {
607
+ const component = new ProfilesListComponent(this);
608
+ if (typeof callback === "function") callback(component);
609
+ return component;
610
+ }
611
+
612
+ createPostsFeed(callback) {
613
+ const component = new PostsFeedComponent(this);
614
+ if (typeof callback === "function") callback(component);
615
+ return component;
616
+ }
617
+
618
+ createIcon(callback) {
619
+ const component = new IconComponent(this);
620
+ if (typeof callback === "function") callback(component);
621
+ return component;
622
+ }
623
+
624
+ _serialize() {
625
+ return {
626
+ tag: this.tag,
627
+ attrs: this.attrs,
628
+ text: this.text,
629
+ children: this.children.map((child) => child._serialize()),
630
+ events: this.events,
631
+ };
632
+ }
633
+ }
634
+
635
+ self.onmessage = async (event) => {
636
+ const message = event.data;
637
+ if (!message || typeof message !== "object") return;
638
+
639
+ // RPC calls
640
+ if (message.type === "call") {
641
+ const fn = callHandlers.get(message.handlerId);
642
+ if (!fn) {
643
+ self.postMessage({
644
+ type: "result",
645
+ callId: message.callId,
646
+ error: `unknown handler ${message.handlerId}`,
647
+ });
648
+ return;
649
+ }
650
+ try {
651
+ const value = await fn(...message.args);
652
+ self.postMessage({ type: "result", callId: message.callId, value });
653
+ } catch (error) {
654
+ self.postMessage({
655
+ type: "result",
656
+ callId: message.callId,
657
+ error: error.message ?? String(error),
658
+ });
659
+ }
660
+ return;
661
+ }
662
+
663
+ // Host call results
664
+ if (message.type === "hostResult") {
665
+ const pending = pendingHostCalls.get(message.hostCallId);
666
+ if (!pending) return;
667
+ pendingHostCalls.delete(message.hostCallId);
668
+ if (message.error) pending.reject(new Error(message.error));
669
+ else pending.resolve(message.value);
670
+ return;
671
+ }
672
+
673
+ // Events
674
+ if (message.type === "event") {
675
+ switch (message.event) {
676
+ case "modalDismissed": {
677
+ const modal = openModals.get(message.data.modalId);
678
+ if (modal) {
679
+ openModals.delete(message.data.modalId);
680
+ modal.onClose();
681
+ }
682
+ return;
683
+ }
684
+ }
685
+ return;
686
+ }
687
+ };
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@impro.social/impro-plugin",
3
+ "version": "0.0.6",
4
+ "type": "module",
5
+ "main": "main.js",
6
+ "license": "0BSD",
7
+ "exports": {
8
+ ".": "./main.js"
9
+ },
10
+ "files": [
11
+ "main.js"
12
+ ]
13
+ }