@bridgebrew/plugin-manager 0.0.1 → 0.0.2

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.
@@ -0,0 +1,1173 @@
1
+ // The Plugin manager's Marketplace (research-043 M1), VS Code's Extensions view for what a workspace can install: a
2
+ // search with its filters (`@installed`, `@updates`, `@official`, `@source:`, `@domain:`), the entries in sections
3
+ // (Updates, then each source: the registries, folders, Built-in), one card each with its action on the right, and
4
+ // the chosen one's page beside: its README, versions and facts. Install and Update always ask first (M5): a dialog
5
+ // says what comes from where, and whether Bridge publishes it, before `POST …/plugins/install`. Data from
6
+ // `GET /_bridge/workspaces/<slug>/marketplace` (`?refresh=1` reads the sources again), the readme from `…/detail`.
7
+ import * as React from 'react';
8
+ import {
9
+ Badge,
10
+ Button,
11
+ Dialog,
12
+ DialogBody,
13
+ DialogClose,
14
+ DialogContent,
15
+ DialogDescription,
16
+ DialogFooter,
17
+ DialogHeader,
18
+ DialogTitle,
19
+ DropdownMenu,
20
+ DropdownMenuContent,
21
+ DropdownMenuItem,
22
+ DropdownMenuTrigger,
23
+ EmptyState,
24
+ HttpError,
25
+ ICON_NAMES,
26
+ Icon,
27
+ Input,
28
+ List,
29
+ ListGroup,
30
+ ScrollArea,
31
+ Section,
32
+ SegmentGroup,
33
+ Skeleton,
34
+ Tabs,
35
+ TabsContent,
36
+ TabsList,
37
+ TabsTrigger,
38
+ Tooltip,
39
+ TooltipContent,
40
+ TooltipTrigger,
41
+ cn,
42
+ readJson,
43
+ useToast,
44
+ formatDate,
45
+ } from '@bridge/ui';
46
+ import type { Context } from 'cordis';
47
+ import { Fact, OfficialBadge, PluginGlyph, PluginHeader, PluginListRow } from './plugin-parts.tsx';
48
+ import { PluginDependencies } from './plugin-dependencies.tsx';
49
+ import { Readme, Versions, useEntryDetail } from './plugin-readme.tsx';
50
+ import {
51
+ actionOf,
52
+ installPlan,
53
+ thirdParty,
54
+ entryId,
55
+ filterHints,
56
+ marketModes,
57
+ pageTabs,
58
+ type PageTab,
59
+ parseQuery,
60
+ searching,
61
+ sections,
62
+ sourceText,
63
+ type Catalog,
64
+ type CatalogEntry,
65
+ type CatalogSource,
66
+ type MarketMode,
67
+ updatesMark,
68
+ } from './marketplace-model.ts';
69
+
70
+ type Failure = { message: string; hint?: string };
71
+ /** A manifest may name an icon the kit does not have: its kind's then. */
72
+ const known = new Set<string>(ICON_NAMES);
73
+ const sourceIcon: Record<CatalogSource['type'], string> = {
74
+ 'built-in': 'home',
75
+ folder: 'folder',
76
+ npm: 'globe',
77
+ };
78
+
79
+ const failureOf = async (res: Response): Promise<Failure> => {
80
+ try {
81
+ await readJson(res);
82
+ } catch (cause) {
83
+ if (!(cause instanceof HttpError)) throw cause;
84
+ return { message: cause.message, ...(cause.hint !== undefined && { hint: cause.hint }) };
85
+ }
86
+ return { message: `HTTP ${res.status}` };
87
+ };
88
+
89
+ function EntryIcon({ entry, size = 'md' }: { entry: CatalogEntry; size?: 'md' | 'lg' }) {
90
+ return (
91
+ <PluginGlyph
92
+ icon={entry.icon !== undefined && known.has(entry.icon) ? entry.icon : undefined}
93
+ kind={entry.kind}
94
+ size={size}
95
+ iconSize={size === 'lg' ? 30 : 19}
96
+ className={cn(
97
+ size === 'lg' ? 'size-16 rounded-[12px]' : 'size-10 rounded-default',
98
+ entry.official && 'border-accent/25 bg-accent-subtle text-accent',
99
+ )}
100
+ />
101
+ );
102
+ }
103
+
104
+ /** Published by Bridge: an `@bridgebrew/*` package from the registry that scope comes from (the host says so). */
105
+
106
+ /** The card's action, on the right: Install, Update, or where it already is. */
107
+ function EntryAction({
108
+ entry,
109
+ busy,
110
+ locked,
111
+ ask,
112
+ uninstall,
113
+ compact = true,
114
+ }: {
115
+ entry: CatalogEntry;
116
+ busy: boolean;
117
+ locked: boolean;
118
+ ask: (entry: CatalogEntry) => void;
119
+ /** Removes the installed copy (asks first); absent when it cannot be removed here. */
120
+ uninstall: ((entry: CatalogEntry) => void) | undefined;
121
+ compact?: boolean;
122
+ }) {
123
+ const action = actionOf(entry);
124
+ const small = compact ? 'h-6 gap-1 px-2 text-xs' : undefined;
125
+ if (busy)
126
+ return (
127
+ <Button size="sm" variant="outline" disabled data-entry-action="busy" className={small}>
128
+ <Icon name="loader-circle" size={12} className="animate-spin motion-reduce:animate-none" />
129
+ Installing…
130
+ </Button>
131
+ );
132
+ // No version this Bridge meets: says which build it asks for (research-102 rule 3).
133
+ if (action === 'asks')
134
+ return (
135
+ <Button size="sm" variant="outline" disabled data-entry-action="asks" className={small}>
136
+ Asks for Bridge {entry.asks}
137
+ </Button>
138
+ );
139
+ if (action === 'install' || action === 'update')
140
+ return (
141
+ <Button
142
+ size="sm"
143
+ variant={action === 'update' ? 'outline' : 'primary'}
144
+ disabled={locked}
145
+ data-entry-action={action}
146
+ className={cn(small, action === 'update' && 'border-accent/40 text-accent')}
147
+ onClick={(event) => {
148
+ event.stopPropagation();
149
+ ask(entry);
150
+ }}
151
+ >
152
+ <Icon name={action === 'update' ? 'arrow-up' : 'download'} size={12} />
153
+ {action === 'update' ? `Update to ${entry.update}` : 'Install'}
154
+ </Button>
155
+ );
156
+ const remove = uninstall && entry.installed?.id === entry.name && (
157
+ <Tooltip>
158
+ <TooltipTrigger
159
+ render={
160
+ <Button
161
+ size="sm"
162
+ variant="outline"
163
+ aria-label={`Uninstall ${entry.title}`}
164
+ data-entry-uninstall
165
+ disabled={locked}
166
+ className={cn(
167
+ 'text-destructive hover:bg-destructive-subtle',
168
+ compact ? 'size-6 px-0' : 'gap-1',
169
+ )}
170
+ onClick={(event) => {
171
+ event.stopPropagation();
172
+ uninstall(entry);
173
+ }}
174
+ />
175
+ }
176
+ >
177
+ <Icon name="trash" size={compact ? 12 : 13} />
178
+ {!compact && 'Uninstall'}
179
+ </TooltipTrigger>
180
+ <TooltipContent>Uninstall: remove it from this workspace</TooltipContent>
181
+ </Tooltip>
182
+ );
183
+ return (
184
+ <span className="inline-flex shrink-0 items-center gap-2">
185
+ <span
186
+ data-entry-action={action}
187
+ className="inline-flex shrink-0 items-center gap-1 text-xs text-muted"
188
+ title={
189
+ action === 'other'
190
+ ? `${entry.installed!.id} is installed with the same key`
191
+ : action === 'linked'
192
+ ? 'Installed, linked to its folder'
193
+ : 'Installed'
194
+ }
195
+ >
196
+ <Icon
197
+ name={action === 'other' ? 'circle-dot' : action === 'linked' ? 'link' : 'check'}
198
+ size={12}
199
+ />
200
+ {action === 'other' ? 'Other copy' : action === 'linked' ? 'Linked' : 'Installed'}
201
+ </span>
202
+ {remove}
203
+ </span>
204
+ );
205
+ }
206
+
207
+ function Card({
208
+ entry,
209
+ busy,
210
+ locked,
211
+ ask,
212
+ }: {
213
+ entry: CatalogEntry;
214
+ busy: boolean;
215
+ locked: boolean;
216
+ ask: (entry: CatalogEntry) => void;
217
+ }) {
218
+ return (
219
+ <PluginListRow
220
+ value={entryId(entry)}
221
+ textValue={`${entry.title}, ${entry.description}`}
222
+ data-market-entry={entry.name}
223
+ data-source={entry.source}
224
+ icon={entry.icon !== undefined && known.has(entry.icon) ? entry.icon : undefined}
225
+ kind={entry.kind}
226
+ title={entry.title}
227
+ official={entry.official}
228
+ description={
229
+ <span
230
+ className="line-clamp-2 min-h-4 text-xs leading-4 text-secondary"
231
+ title={entry.description}
232
+ >
233
+ {entry.description || <span className="font-mono text-muted">{entry.name}</span>}
234
+ </span>
235
+ }
236
+ version={entry.version}
237
+ author={entry.author}
238
+ action={
239
+ <EntryAction entry={entry} busy={busy} locked={locked} ask={ask} uninstall={undefined} />
240
+ }
241
+ />
242
+ );
243
+ }
244
+
245
+ const External = ({ href }: { href: string }) => (
246
+ <a
247
+ href={href}
248
+ target="_blank"
249
+ rel="noreferrer"
250
+ className="inline-flex max-w-full items-center gap-1 text-accent hover:underline"
251
+ >
252
+ <span className="truncate">{href.replace(/^https?:\/\//, '')}</span>
253
+ <Icon name="arrow-up-right" size={12} className="shrink-0" />
254
+ </a>
255
+ );
256
+
257
+ const pageTabLabels = {
258
+ details: 'Details',
259
+ dependencies: 'Dependencies',
260
+ versions: 'Versions',
261
+ } as Record<PageTab, string>;
262
+
263
+ function EntryPage({
264
+ ctx,
265
+ slug,
266
+ entry,
267
+ sources,
268
+ installed,
269
+ catalog,
270
+ openEntry,
271
+ busy,
272
+ locked,
273
+ ask,
274
+ openInstalled,
275
+ back,
276
+ read,
277
+ uninstall,
278
+ }: {
279
+ uninstall: ((entry: CatalogEntry) => void) | undefined;
280
+ ctx: Context;
281
+ slug: string;
282
+ /** When the catalog was read. */
283
+ read: string;
284
+ entry: CatalogEntry;
285
+ sources: CatalogSource[];
286
+ /** The plugins installed here and the whole catalog: what provides the contracts it requires. */
287
+ installed: { id: string; key?: string; title: string; state?: string; implements: string[] }[];
288
+ catalog: CatalogEntry[];
289
+ openEntry: (id: string) => void;
290
+ busy: boolean;
291
+ locked: boolean;
292
+ ask: (entry: CatalogEntry) => void;
293
+ openInstalled: (id: string) => void;
294
+ back: () => void;
295
+ }) {
296
+ const { detail, error } = useEntryDetail(ctx, slug, entry, read);
297
+ const source = sources.find(({ id }) => id === entry.source);
298
+ const { tabs, initial } = pageTabs({ installed: false, inCatalog: true });
299
+ return (
300
+ <article
301
+ aria-label={`${entry.title} in the marketplace`}
302
+ data-market-page={entry.name}
303
+ className="flex flex-col gap-5 px-6 pb-12 pt-4"
304
+ >
305
+ <Button type="button" size="sm" onClick={back} className="-ml-1 w-fit @2xl/pm:hidden">
306
+ <Icon name="arrow-left" size={13} />
307
+ Marketplace
308
+ </Button>
309
+ <PluginHeader
310
+ icon={<EntryIcon entry={entry} size="lg" />}
311
+ title={entry.title}
312
+ titleMark={entry.official && <OfficialBadge />}
313
+ name={entry.name}
314
+ version={entry.version}
315
+ badges={
316
+ <>
317
+ <Badge
318
+ data-entry-source={source?.type}
319
+ className={cn(
320
+ 'h-4 gap-1 px-1.5 text-[11px]',
321
+ source?.type === 'built-in' && 'bg-accent-subtle text-accent',
322
+ )}
323
+ >
324
+ {source && <Icon name={sourceIcon[source.type]} size={10} />}
325
+ {sourceText(entry, sources)}
326
+ </Badge>
327
+ {entry.domain && <Badge className="h-4 px-1.5 text-[11px]">{entry.domain}</Badge>}
328
+ </>
329
+ }
330
+ actions={
331
+ <EntryAction
332
+ entry={entry}
333
+ busy={busy}
334
+ locked={locked}
335
+ ask={ask}
336
+ uninstall={uninstall}
337
+ compact={false}
338
+ />
339
+ }
340
+ >
341
+ {entry.description && (
342
+ <p className="mt-1 text-[13px] leading-5 text-secondary">{entry.description}</p>
343
+ )}
344
+ {entry.installed && (
345
+ <p className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted">
346
+ <Icon name="check" size={12} />
347
+ {entry.installed.id === entry.name
348
+ ? `Installed ${entry.installed.linked ? '(linked to its folder)' : `at ${entry.installed.version}`}`
349
+ : `${entry.installed.id} is installed with the same key`}
350
+ <button
351
+ type="button"
352
+ onClick={() => openInstalled(entry.installed!.id)}
353
+ className="cursor-pointer border-0 bg-transparent p-0 font-[inherit] text-xs text-accent hover:underline"
354
+ >
355
+ Manage
356
+ </button>
357
+ </p>
358
+ )}
359
+ </PluginHeader>
360
+ <div className="grid gap-6 @3xl/pm:grid-cols-[minmax(0,1fr)_200px]">
361
+ <Tabs defaultValue={initial}>
362
+ <TabsList aria-label={`${entry.title} details`}>
363
+ {tabs.map((each) => (
364
+ <TabsTrigger key={each} value={each} data-tab={each}>
365
+ {pageTabLabels[each]}
366
+ </TabsTrigger>
367
+ ))}
368
+ </TabsList>
369
+ <TabsContent value="details" className="pt-4">
370
+ <Readme detail={detail} error={error} />
371
+ </TabsContent>
372
+ <TabsContent value="dependencies" className="pt-4">
373
+ <PluginDependencies
374
+ requires={entry.requires ?? []}
375
+ implemented={entry.implements ?? []}
376
+ installed={installed}
377
+ catalog={catalog}
378
+ openInstalled={openInstalled}
379
+ openEntry={openEntry}
380
+ />
381
+ </TabsContent>
382
+ <TabsContent value="versions" className="pt-4">
383
+ <Versions
384
+ versions={detail?.versions ?? [entry.version]}
385
+ latest={entry.version}
386
+ installed={entry.installed?.id === entry.name ? entry.installed.version : undefined}
387
+ />
388
+ </TabsContent>
389
+ </Tabs>
390
+ <dl
391
+ data-facts
392
+ className="m-0 flex flex-col @3xl/pm:border-l @3xl/pm:border-border-subtle @3xl/pm:pl-4"
393
+ >
394
+ <Fact stacked label="Source">
395
+ {source?.type === 'npm' ? (
396
+ <span title={source.location}>{source.label}</span>
397
+ ) : (
398
+ <span className="break-all font-mono text-[12px]" title={entry.install}>
399
+ {entry.install}
400
+ </span>
401
+ )}
402
+ </Fact>
403
+ <Fact stacked label="Publisher">
404
+ {entry.official
405
+ ? 'Bridge'
406
+ : (entry.author ?? (source?.type === 'npm' ? 'Unknown' : 'Local folder'))}
407
+ </Fact>
408
+ {entry.license && (
409
+ <Fact stacked label="License">
410
+ {entry.license}
411
+ </Fact>
412
+ )}
413
+ {entry.updated && (
414
+ <Fact stacked label="Updated">
415
+ {formatDate(entry.updated, { dateStyle: 'medium' })}
416
+ </Fact>
417
+ )}
418
+ {entry.homepage && (
419
+ <Fact stacked label="Homepage">
420
+ <External href={entry.homepage} />
421
+ </Fact>
422
+ )}
423
+ {entry.repository && /^https?:/.test(entry.repository) && (
424
+ <Fact stacked label="Repository">
425
+ <External href={entry.repository} />
426
+ </Fact>
427
+ )}
428
+ {entry.keywords.filter((each) => each !== 'bridge-plugin').length > 0 && (
429
+ <Fact stacked label="Keywords">
430
+ <span className="flex flex-wrap gap-1">
431
+ {entry.keywords
432
+ .filter((each) => each !== 'bridge-plugin')
433
+ .map((each) => (
434
+ <Badge key={each} className="h-4 px-1.5 text-[11px]">
435
+ {each}
436
+ </Badge>
437
+ ))}
438
+ </span>
439
+ </Fact>
440
+ )}
441
+ </dl>
442
+ </div>
443
+ </article>
444
+ );
445
+ }
446
+
447
+ /** Install and Update ask first (M5): what, which version, from where, published by whom. */
448
+ function ApproveDialog({
449
+ entry,
450
+ sources,
451
+ installed,
452
+ catalog,
453
+ failure,
454
+ busy,
455
+ onClose,
456
+ confirm,
457
+ }: {
458
+ entry: CatalogEntry;
459
+ sources: CatalogSource[];
460
+ /** The workspace's plugins with the contracts each implements: what the entry's requirements find. */
461
+ installed: { id: string; key?: string; title: string; state?: string; implements: string[] }[];
462
+ catalog: CatalogEntry[];
463
+ failure: Failure | undefined;
464
+ busy: boolean;
465
+ onClose: () => void;
466
+ confirm: () => void;
467
+ }) {
468
+ const update = actionOf(entry) === 'update';
469
+ const source = sources.find(({ id }) => id === entry.source);
470
+ const plan = installPlan(entry, installed, catalog);
471
+ const blocked = plan.missing.length > 0 || plan.cycle.length > 0 || plan.asks.length > 0;
472
+ /** The installed plugins already providing what it requires: shown checked. */
473
+ const provided = [
474
+ ...new Set(
475
+ (entry.requires ?? []).flatMap((contract) =>
476
+ installed
477
+ .filter((each) => each.state !== 'disabled' && each.implements.includes(contract))
478
+ .map(({ title }) => title),
479
+ ),
480
+ ),
481
+ ];
482
+ /** The plugins of the plan Bridge does not publish: one more dialog to accept them. */
483
+ const strangers = [
484
+ entry,
485
+ ...plan.before.flatMap((step) => (step.kind === 'install' ? [step.entry] : [])),
486
+ ].filter(thirdParty);
487
+ const [trusting, setTrusting] = React.useState(false);
488
+ const title = `${update ? 'Update' : 'Install'} ${entry.title}?`;
489
+ return (
490
+ <Dialog
491
+ open
492
+ onOpenChange={(open) => {
493
+ if (!open && !busy) onClose();
494
+ }}
495
+ >
496
+ <DialogContent aria-label={title} data-approve={entry.name} className="w-[460px]">
497
+ <DialogHeader className="px-5 pt-4">
498
+ <DialogTitle>{title}</DialogTitle>
499
+ </DialogHeader>
500
+ <DialogBody className="flex flex-col gap-3 pb-5">
501
+ <DialogDescription className="m-0 leading-5">
502
+ {update
503
+ ? `${entry.name} goes from ${entry.installed?.version} to ${entry.update} in this workspace.${entry.updateAsks === 'migrates' ? '' : ' Its data and settings stay.'}`
504
+ : `${entry.name} ${entry.version} is added to this workspace and starts at once.`}
505
+ </DialogDescription>
506
+ {update && entry.updateAsks === 'migrates' && (
507
+ <p
508
+ data-approve-migrates
509
+ className="m-0 flex gap-2 rounded-default bg-destructive-subtle px-3 py-2 text-xs leading-5 text-destructive"
510
+ >
511
+ <Icon name="triangle-alert" size={14} className="mt-0.5 shrink-0" />
512
+ This update changes its data and cannot be undone: Back will not be possible.
513
+ </p>
514
+ )}
515
+ <dl className="m-0 flex flex-col rounded-default border border-border-subtle px-3 py-1">
516
+ <Fact stacked label="From">
517
+ {/* The source's name; where exactly (registry, folder) in the tooltip of its mark. */}
518
+ <span className="inline-flex items-center gap-1.5">
519
+ {source?.label ?? entry.source}
520
+ <Tooltip>
521
+ <TooltipTrigger
522
+ render={
523
+ <span
524
+ data-from-detail
525
+ className="inline-flex text-success"
526
+ aria-label={source?.type === 'npm' ? source.location : entry.install}
527
+ />
528
+ }
529
+ >
530
+ <Icon name="check" size={13} />
531
+ </TooltipTrigger>
532
+ <TooltipContent>
533
+ {source?.type === 'npm' ? source.location : entry.install}
534
+ </TooltipContent>
535
+ </Tooltip>
536
+ </span>
537
+ </Fact>
538
+ <Fact stacked label="Publisher">
539
+ {entry.official ? (
540
+ <span className="inline-flex items-center gap-1 text-accent">
541
+ <Icon name="shield-check" size={13} /> Bridge
542
+ </span>
543
+ ) : (
544
+ (entry.author ?? 'Not Bridge')
545
+ )}
546
+ </Fact>
547
+ </dl>
548
+ {(plan.before.length > 0 || provided.length > 0) && (
549
+ <Section title="Dependencies" size="sm" data-approve-dependencies>
550
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
551
+ {provided.map((title) => (
552
+ <li
553
+ key={`here:${title}`}
554
+ data-status="provided"
555
+ className="flex items-center gap-2 text-xs leading-5"
556
+ >
557
+ <Icon name="check" size={13} className="shrink-0 text-success" />
558
+ <span className="min-w-0 truncate text-foreground">{title}</span>
559
+ </li>
560
+ ))}
561
+ {plan.before.map((step) => (
562
+ <li
563
+ key={step.kind === 'install' ? step.entry.name : step.id}
564
+ data-status={step.kind}
565
+ className="flex items-center gap-2 text-xs leading-5"
566
+ >
567
+ <Icon
568
+ name={step.kind === 'install' ? 'download' : 'power'}
569
+ size={13}
570
+ className="shrink-0 text-accent"
571
+ />
572
+ <span className="min-w-0 truncate text-foreground">
573
+ {step.kind === 'install' ? step.entry.title : step.title}
574
+ </span>
575
+ <span className="text-muted">
576
+ {step.kind === 'install' ? 'installed with it' : 'enabled'}
577
+ </span>
578
+ </li>
579
+ ))}
580
+ </ul>
581
+ </Section>
582
+ )}
583
+ {blocked && (
584
+ <p
585
+ data-approve-missing
586
+ className="m-0 flex gap-2 rounded-default bg-destructive-subtle px-3 py-2 text-xs leading-5 text-destructive"
587
+ >
588
+ <Icon name="triangle-alert" size={14} className="mt-0.5 shrink-0" />
589
+ {plan.missing.length > 0
590
+ ? `Nothing installed or in the marketplace provides ${plan.missing.join(', ')}: it could not start.`
591
+ : plan.asks.length > 0
592
+ ? `It needs ${plan.asks.join(', ')}: update Bridge first.`
593
+ : `${plan.cycle.join(', ')} and what it needs require each other: they cannot be installed one after the other.`}
594
+ </p>
595
+ )}
596
+ {failure && (
597
+ <div role="alert" className="flex flex-col gap-1 text-xs leading-5">
598
+ <p className="m-0 text-destructive">{failure.message}</p>
599
+ {failure.hint && <p className="m-0 text-secondary">{failure.hint}</p>}
600
+ </div>
601
+ )}
602
+ </DialogBody>
603
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
604
+ <DialogClose render={<Button variant="outline" disabled={busy} />}>Cancel</DialogClose>
605
+ <Button
606
+ variant="primary"
607
+ disabled={busy || blocked}
608
+ onClick={() => (strangers.length > 0 ? setTrusting(true) : confirm())}
609
+ data-approve-confirm
610
+ >
611
+ {busy && (
612
+ <Icon
613
+ name="loader-circle"
614
+ size={13}
615
+ className="animate-spin motion-reduce:animate-none"
616
+ />
617
+ )}
618
+ {update ? `Update to ${entry.update}` : 'Install'}
619
+ </Button>
620
+ </DialogFooter>
621
+ </DialogContent>
622
+ {trusting && (
623
+ <Dialog
624
+ open
625
+ onOpenChange={(open) => {
626
+ if (!open) setTrusting(false);
627
+ }}
628
+ >
629
+ <DialogContent aria-label="Third-party plugins" data-third-party className="w-[420px]">
630
+ <DialogHeader className="px-5 pt-4">
631
+ <DialogTitle>
632
+ {strangers.length === 1 ? 'A third-party plugin' : 'Third-party plugins'}
633
+ </DialogTitle>
634
+ </DialogHeader>
635
+ <DialogBody className="flex flex-col gap-3 pb-5">
636
+ <DialogDescription className="m-0 leading-5">
637
+ Bridge does not publish {strangers.length === 1 ? 'this plugin' : 'these plugins'}.
638
+ They run in your workspace with the access their manifest asks for: accept only if
639
+ you trust where they come from.
640
+ </DialogDescription>
641
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
642
+ {strangers.map((each) => (
643
+ <li key={each.name} className="flex items-center gap-2 text-xs leading-5">
644
+ <Icon name="triangle-alert" size={13} className="shrink-0 text-warning-text" />
645
+ <span className="text-foreground">{each.title}</span>
646
+ <span className="min-w-0 truncate text-muted">
647
+ {each.author ?? sources.find(({ id }) => id === each.source)?.label}
648
+ </span>
649
+ </li>
650
+ ))}
651
+ </ul>
652
+ </DialogBody>
653
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
654
+ <Button variant="outline" onClick={() => setTrusting(false)} data-third-party-refuse>
655
+ Refuse
656
+ </Button>
657
+ <Button
658
+ variant="primary"
659
+ onClick={() => {
660
+ setTrusting(false);
661
+ confirm();
662
+ }}
663
+ data-third-party-accept
664
+ >
665
+ Accept
666
+ </Button>
667
+ </DialogFooter>
668
+ </DialogContent>
669
+ </Dialog>
670
+ )}
671
+ </Dialog>
672
+ );
673
+ }
674
+
675
+ /** The catalog of workspace `slug` (the entries' installed marks and updates), read again when `revision` changes and on
676
+ * `load(true)` (the sources read again). Off (`enabled` false) for a root with no marketplace. */
677
+ /** What the marketplace shows (list mode, search, chosen entry), kept for the tab's session: leaving the screen and
678
+ * coming back finds it as it was. */
679
+ interface Kept {
680
+ mode?: string;
681
+ query?: string;
682
+ selected?: string | undefined;
683
+ }
684
+ function useKept(key: string): [Kept, (change: Kept) => void] {
685
+ const [kept, setState] = React.useState<Kept>(() => {
686
+ try {
687
+ const value = JSON.parse(sessionStorage.getItem(key) ?? '{}') as unknown;
688
+ return typeof value === 'object' && value !== null ? (value as Kept) : {};
689
+ } catch {
690
+ return {};
691
+ }
692
+ });
693
+ const set = (change: Kept) =>
694
+ setState((was) => {
695
+ const next = { ...was, ...change };
696
+ try {
697
+ sessionStorage.setItem(key, JSON.stringify(next));
698
+ } catch {
699
+ /* this view only */
700
+ }
701
+ return next;
702
+ });
703
+ return [kept, set];
704
+ }
705
+
706
+ /** The last catalog read per workspace, shown at once when the screen opens again while it is read anew. */
707
+ const lastCatalog = new Map<string, Catalog>();
708
+
709
+ export function useCatalog(ctx: Context, slug: string, revision: unknown, enabled = true) {
710
+ const { workspace } = ctx;
711
+ const [catalog, setCatalogState] = React.useState<Catalog | undefined>(() =>
712
+ lastCatalog.get(slug),
713
+ );
714
+ const setCatalog = (next: Catalog) => {
715
+ lastCatalog.set(slug, next);
716
+ setCatalogState(next);
717
+ // The Plugins row's count in the sidebar follows each read of its own workspace's catalog (an update done here).
718
+ if (slug === workspace.slug) ctx.sidebar?.set('plugins', updatesMark(next));
719
+ };
720
+ const [loadError, setLoadError] = React.useState('');
721
+ const [loading, setLoading] = React.useState(false);
722
+ const base = `/_bridge/workspaces/${encodeURIComponent(slug)}/marketplace`;
723
+ const load = React.useCallback(
724
+ async (refresh = false) => {
725
+ setLoading(true);
726
+ try {
727
+ const body = (await readJson(
728
+ await workspace.fetch(`${base}${refresh ? '?refresh=1' : ''}`, { cache: 'no-store' }),
729
+ )) as Catalog;
730
+ setCatalog(body);
731
+ setLoadError('');
732
+ } catch (cause) {
733
+ if ((cause as Error).name !== 'AbortError') setLoadError((cause as Error).message);
734
+ } finally {
735
+ setLoading(false);
736
+ }
737
+ },
738
+ [base],
739
+ );
740
+ React.useEffect(() => {
741
+ if (enabled) void load();
742
+ }, [load, revision, enabled]);
743
+ return { catalog, loadError, loading, load };
744
+ }
745
+ export type CatalogState = ReturnType<typeof useCatalog>;
746
+
747
+ /** Install and Update from anywhere (a card, a page): `ask(entry)` opens the approval `dialog` (render it once), which
748
+ * runs `POST …/plugins/install`; `running` is the entry's id meanwhile. `installed` is called with the plugin's id. */
749
+ export function useApproval(
750
+ ctx: Context,
751
+ slug: string,
752
+ market: CatalogState,
753
+ installed: (id: string) => void,
754
+ present: () => { id: string; key: string; title: string; state: string; implements: string[] }[],
755
+ ) {
756
+ const { workspace } = ctx;
757
+ const { toast } = useToast();
758
+ const [asking, setAsking] = React.useState<CatalogEntry>();
759
+ const [failure, setFailure] = React.useState<Failure>();
760
+ const [running, setRunning] = React.useState<string>();
761
+ /** Installs (or updates) one entry; its failure, if any. */
762
+ const installOne = async (
763
+ entry: CatalogEntry,
764
+ ): Promise<{ failure?: Failure; waiting?: boolean }> => {
765
+ const update = actionOf(entry) === 'update';
766
+ const res = await workspace.fetch(
767
+ `/_bridge/workspaces/${encodeURIComponent(slug)}/plugins/install`,
768
+ {
769
+ method: 'POST',
770
+ headers: { 'content-type': 'application/json' },
771
+ body: JSON.stringify({
772
+ source: entry.install,
773
+ ...(entry.registry !== undefined && { registry: entry.registry }),
774
+ ...(update && { update: true }),
775
+ }),
776
+ },
777
+ );
778
+ if (!res.ok) return { failure: await failureOf(res) };
779
+ const done = (await readJson(res)) as {
780
+ plugin: string;
781
+ warning?: string;
782
+ pendingRestart?: string;
783
+ waiting?: true;
784
+ };
785
+ // An update waits for the running sessions (bridge#434): it applies by itself, a notice says how it went.
786
+ const waits = done.pendingRestart !== undefined || done.waiting === true;
787
+ toast({
788
+ variant: waits ? 'info' : 'success',
789
+ title: done.waiting
790
+ ? `${entry.title} updates once the running sessions finish`
791
+ : done.pendingRestart
792
+ ? `${entry.title} prepared, awaiting approval`
793
+ : `${entry.title} ${update ? `updated to ${entry.update}` : 'installed'}`,
794
+ ...(done.warning !== undefined && { description: done.warning }),
795
+ });
796
+ installed(done.plugin);
797
+ return { waiting: waits };
798
+ };
799
+ /** Enables an installed plugin of the plan; its failure, if any. */
800
+ const enableOne = async (step: {
801
+ key: string;
802
+ title: string;
803
+ }): Promise<{ failure?: Failure; waiting?: boolean }> => {
804
+ const res = await workspace.fetch(
805
+ `/_bridge/workspaces/${encodeURIComponent(slug)}/plugins/${encodeURIComponent(step.key)}/enable`,
806
+ { method: 'POST' },
807
+ );
808
+ if (!res.ok) return { failure: await failureOf(res) };
809
+ toast({ variant: 'success', title: `${step.title} enabled` });
810
+ return {};
811
+ };
812
+ /** The entry, its missing dependencies first (`installPlan`), one after the other; stops at the first failure. */
813
+ const approve = async () => {
814
+ if (!asking) return;
815
+ const entry = asking;
816
+ const { before } = installPlan(entry, present(), market.catalog?.entries ?? []);
817
+ setRunning(entryId(entry));
818
+ setFailure(undefined);
819
+ try {
820
+ for (const step of [...before, { kind: 'install' as const, entry }]) {
821
+ const { failure, waiting } =
822
+ step.kind === 'install' ? await installOne(step.entry) : await enableOne(step);
823
+ const name = step.kind === 'install' ? step.entry.title : step.title;
824
+ if (failure) {
825
+ setFailure(
826
+ step.kind === 'install' && step.entry === entry
827
+ ? failure
828
+ : { ...failure, message: `${name}: ${failure.message}` },
829
+ );
830
+ return;
831
+ }
832
+ // A step awaiting approval (a restart) is not done yet: what needs it waits too.
833
+ if (waiting && !(step.kind === 'install' && step.entry === entry)) {
834
+ setFailure({
835
+ message: `${name} awaits approval: install ${entry.title} once it is approved.`,
836
+ });
837
+ return;
838
+ }
839
+ }
840
+ setAsking(undefined);
841
+ } catch (cause) {
842
+ setFailure({ message: (cause as Error).message });
843
+ } finally {
844
+ setRunning(undefined);
845
+ await market.load();
846
+ }
847
+ };
848
+ const ask = (entry: CatalogEntry) => {
849
+ setFailure(undefined);
850
+ setAsking(entry);
851
+ };
852
+ const dialog = asking && (
853
+ <ApproveDialog
854
+ entry={asking}
855
+ sources={market.catalog?.sources ?? []}
856
+ installed={present()}
857
+ catalog={market.catalog?.entries ?? []}
858
+ failure={failure}
859
+ busy={running !== undefined}
860
+ onClose={() => setAsking(undefined)}
861
+ confirm={() => void approve()}
862
+ />
863
+ );
864
+ return { ask, running, dialog };
865
+ }
866
+ export type Approval = ReturnType<typeof useApproval>;
867
+
868
+ export function Marketplace({
869
+ ctx,
870
+ slug,
871
+ market,
872
+ approval,
873
+ locked,
874
+ switcher,
875
+ installed,
876
+ openInstalled,
877
+ renderInstalled,
878
+ uninstall,
879
+ removable,
880
+ }: {
881
+ ctx: Context;
882
+ slug: string;
883
+ market: CatalogState;
884
+ approval: Approval;
885
+ /** Asks to remove an installed plugin, by id (the Installed tab's dialog); absent for one this screen cannot remove. */
886
+ uninstall: (id: string) => void;
887
+ /** Whether the installed plugin `id` may be removed from here. */
888
+ removable: (id: string) => boolean;
889
+ locked: boolean;
890
+ switcher: React.ReactNode;
891
+ /** The plugins installed here, with the contracts each implements. */
892
+ installed: { id: string; title: string; implements: string[] }[];
893
+ openInstalled: (id: string) => void;
894
+ /** The page of the installed plugin `id` (the Installed tab's, `back` returns to the list); none when it is not listed. */
895
+ renderInstalled: (id: string, back: () => void) => React.ReactNode;
896
+ }) {
897
+ const { catalog, loadError, loading, load } = market;
898
+ const { ask, running } = approval;
899
+ const [kept, setKept] = useKept(`bridge.marketplace.${slug}`);
900
+ const mode = marketModes.find(({ value }) => value === kept.mode)?.value ?? 'name';
901
+ const setMode = (next: MarketMode) => setKept({ mode: next });
902
+ const query = kept.query ?? '';
903
+ const setQuery = (next: string) => setKept({ query: next });
904
+ const uninstallOf = (entry: CatalogEntry) => uninstall(entry.installed!.id);
905
+ const canUninstall = (entry: CatalogEntry) =>
906
+ entry.installed !== undefined && removable(entry.installed.id) ? uninstallOf : undefined;
907
+ const selected = kept.selected;
908
+ const setSelected = (next: string | undefined) => setKept({ selected: next });
909
+ const search = React.useRef<HTMLInputElement>(null);
910
+
911
+ const shown = catalog ? sections(catalog, query, mode) : [];
912
+ const parsed = parseQuery(query);
913
+ const found = new Set(shown.flatMap(({ entries }) => entries.map(entryId))).size;
914
+ const current = catalog?.entries.find((entry) => entryId(entry) === selected);
915
+ // Bridge UI, the toolkit every page draws with: Bridge-wide, so Admin's (research-078).
916
+ const failed = catalog?.sources.filter(({ error }) => error !== undefined) ?? [];
917
+ const page =
918
+ current?.installed?.id === current?.name && current?.installed
919
+ ? renderInstalled(current.installed.id, () => setSelected(undefined))
920
+ : undefined;
921
+
922
+ const addFilter = (token: string) => {
923
+ const words = query.trim();
924
+ setQuery(`${words ? `${words} ` : ''}${token}${token.endsWith(':') ? '' : ' '}`);
925
+ search.current?.focus();
926
+ };
927
+
928
+ return (
929
+ <>
930
+ <aside
931
+ aria-label="Marketplace"
932
+ className={cn(
933
+ 'min-h-0 w-full shrink-0 flex-col border-border @2xl/pm:flex @2xl/pm:w-(--pm-list) @2xl/pm:border-r',
934
+ // A page chosen takes a narrow box alone.
935
+ current ? 'hidden' : 'flex',
936
+ )}
937
+ >
938
+ <div className="flex shrink-0 flex-col gap-2 border-b border-border-subtle px-3 pb-2.5 pt-3">
939
+ {switcher}
940
+ <div className="flex items-center gap-1.5">
941
+ <Input
942
+ ref={search}
943
+ variant="outline"
944
+ type="search"
945
+ aria-label="Search the marketplace"
946
+ placeholder="Search the marketplace"
947
+ icon={<Icon name="search" size={14} />}
948
+ className="min-w-0 flex-1 [&::-webkit-search-cancel-button]:hidden"
949
+ value={query}
950
+ onChange={(event) => setQuery(event.currentTarget.value)}
951
+ onKeyDown={(event) => {
952
+ if (event.key === 'Escape') setQuery('');
953
+ }}
954
+ />
955
+ <DropdownMenu>
956
+ <Tooltip>
957
+ <TooltipTrigger
958
+ render={
959
+ <DropdownMenuTrigger
960
+ render={
961
+ <Button
962
+ type="button"
963
+ variant="outline"
964
+ size="icon"
965
+ aria-label="Filter the marketplace"
966
+ className={cn(
967
+ searching({ ...parsed, words: [] }) &&
968
+ 'border-accent/40 bg-accent-subtle text-accent',
969
+ )}
970
+ />
971
+ }
972
+ />
973
+ }
974
+ >
975
+ <Icon name="filter" size={14} />
976
+ </TooltipTrigger>
977
+ <TooltipContent>Filter</TooltipContent>
978
+ </Tooltip>
979
+ <DropdownMenuContent align="end" aria-label="Filters">
980
+ {filterHints
981
+ .filter(({ token }) => !token.endsWith(':'))
982
+ .map(({ token, label }) => (
983
+ <DropdownMenuItem key={token} onSelect={() => addFilter(token)}>
984
+ <span className="flex-1">{label}</span>
985
+ <span className="font-mono text-[11px] text-muted">{token}</span>
986
+ </DropdownMenuItem>
987
+ ))}
988
+ {catalog?.sources.map((source) => (
989
+ <DropdownMenuItem
990
+ key={source.id}
991
+ onSelect={() => addFilter(`@source:${source.id}`)}
992
+ >
993
+ <Icon name={sourceIcon[source.type]} size={14} />
994
+ <span className="flex-1">{source.label}</span>
995
+ <span className="tabular-nums text-muted">{source.count}</span>
996
+ </DropdownMenuItem>
997
+ ))}
998
+ </DropdownMenuContent>
999
+ </DropdownMenu>
1000
+ <Tooltip>
1001
+ <TooltipTrigger
1002
+ render={
1003
+ <Button
1004
+ size="icon-sm"
1005
+ aria-label="Refresh the sources"
1006
+ disabled={loading}
1007
+ className="size-(--height-md) shrink-0 border border-border"
1008
+ onClick={() => void load(true)}
1009
+ />
1010
+ }
1011
+ >
1012
+ <Icon
1013
+ name="rotate-cw"
1014
+ size={14}
1015
+ className={cn(loading && 'animate-spin motion-reduce:animate-none')}
1016
+ />
1017
+ </TooltipTrigger>
1018
+ <TooltipContent>Refresh the sources</TooltipContent>
1019
+ </Tooltip>
1020
+ </div>
1021
+ <SegmentGroup
1022
+ fullWidth
1023
+ aria-label="List by"
1024
+ items={[...marketModes]}
1025
+ value={mode}
1026
+ onValueChange={(value) => setMode(value as MarketMode)}
1027
+ />
1028
+ {searching(parsed) && catalog && (
1029
+ <p className="flex items-center gap-2 text-xs text-muted">
1030
+ <span role="status" className="flex-1">
1031
+ {found === 0
1032
+ ? 'No plugins found'
1033
+ : `${found} ${found === 1 ? 'plugin' : 'plugins'} found`}
1034
+ </span>
1035
+ <button
1036
+ type="button"
1037
+ onClick={() => setQuery('')}
1038
+ className="cursor-pointer border-0 bg-transparent p-0 font-[inherit] text-xs text-accent hover:underline"
1039
+ >
1040
+ Clear
1041
+ </button>
1042
+ </p>
1043
+ )}
1044
+ </div>
1045
+ {loadError && (
1046
+ <p role="alert" className="mx-3 mt-2 text-sm text-destructive">
1047
+ The marketplace could not be read: {loadError}
1048
+ </p>
1049
+ )}
1050
+ {failed.map((source) => (
1051
+ <p
1052
+ key={source.id}
1053
+ role="status"
1054
+ data-source-error={source.id}
1055
+ className="mx-3 mt-2 flex items-start gap-2 rounded-default bg-warning-subtle px-3 py-2 text-xs leading-5 text-warning-text"
1056
+ >
1057
+ <Icon name="triangle-alert" size={13} className="mt-0.5 shrink-0" />
1058
+ <span className="min-w-0 break-words">{source.error}</span>
1059
+ </p>
1060
+ ))}
1061
+ <ScrollArea
1062
+ className="min-h-0 flex-1"
1063
+ viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!"
1064
+ >
1065
+ {!catalog && !loadError && (
1066
+ <div className="flex flex-col gap-3 px-3 py-3" aria-label="Loading the marketplace">
1067
+ {[0, 1, 2, 3, 4].map((each) => (
1068
+ <div key={each} className="flex gap-3">
1069
+ <Skeleton className="size-10 rounded-default" />
1070
+ <div className="flex flex-1 flex-col gap-1.5">
1071
+ <Skeleton className="h-4 w-1/2" />
1072
+ <Skeleton className="h-3 w-full" />
1073
+ </div>
1074
+ </div>
1075
+ ))}
1076
+ </div>
1077
+ )}
1078
+ {shown.length > 0 && (
1079
+ <List
1080
+ aria-label="Marketplace plugins"
1081
+ selectionMode="single"
1082
+ selectedKey={selected}
1083
+ onSelectionChange={([key]) => {
1084
+ if (key !== undefined) setSelected(key);
1085
+ }}
1086
+ className="pb-6 outline-hidden"
1087
+ >
1088
+ {shown.map((section) => (
1089
+ <ListGroup
1090
+ key={section.id}
1091
+ label={`${section.label} · ${section.entries.length}`}
1092
+ variant="section"
1093
+ data-market-section={section.id}
1094
+ className="flex flex-col gap-px px-2 [&>[data-slot=list-group-header]]:-mx-2"
1095
+ >
1096
+ {section.entries.map((entry) => (
1097
+ <Card
1098
+ key={`${section.id}:${entryId(entry)}`}
1099
+ entry={entry}
1100
+ busy={running === entryId(entry)}
1101
+ locked={locked || running !== undefined}
1102
+ ask={ask}
1103
+ />
1104
+ ))}
1105
+ </ListGroup>
1106
+ ))}
1107
+ </List>
1108
+ )}
1109
+ {catalog && shown.length === 0 && (
1110
+ <EmptyState
1111
+ data-no-results
1112
+ icon={<Icon name="search" size={20} />}
1113
+ title={
1114
+ catalog.entries.length ? 'No plugins match.' : 'No source offers a plugin yet.'
1115
+ }
1116
+ >
1117
+ {query && (
1118
+ <Button variant="outline" size="sm" onClick={() => setQuery('')}>
1119
+ Clear search
1120
+ </Button>
1121
+ )}
1122
+ </EmptyState>
1123
+ )}
1124
+ </ScrollArea>
1125
+ </aside>
1126
+ <ScrollArea
1127
+ className={cn('min-h-0 min-w-0 flex-1 @2xl/pm:block', current ? 'block' : 'hidden')}
1128
+ viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!"
1129
+ >
1130
+ {current && catalog && page ? (
1131
+ <div className="mx-auto w-full max-w-[860px]">{page}</div>
1132
+ ) : current && catalog ? (
1133
+ <div className="mx-auto w-full max-w-[960px]">
1134
+ <EntryPage
1135
+ key={entryId(current)}
1136
+ ctx={ctx}
1137
+ slug={slug}
1138
+ entry={current}
1139
+ sources={catalog.sources}
1140
+ installed={installed}
1141
+ catalog={catalog.entries}
1142
+ openEntry={setSelected}
1143
+ busy={running === entryId(current)}
1144
+ locked={locked || running !== undefined}
1145
+ ask={ask}
1146
+ openInstalled={openInstalled}
1147
+ read={catalog.read}
1148
+ uninstall={canUninstall(current)}
1149
+ back={() => setSelected(undefined)}
1150
+ />
1151
+ </div>
1152
+ ) : (
1153
+ <EmptyState
1154
+ fill
1155
+ className="py-24"
1156
+ icon={<Icon name="package" size={22} />}
1157
+ title={
1158
+ catalog
1159
+ ? `${new Set(catalog.entries.map(({ key }) => key)).size} plugins in ${catalog.sources.length} sources`
1160
+ : 'Reading the sources…'
1161
+ }
1162
+ >
1163
+ <p className="max-w-[320px]">
1164
+ Select one to read about it. Type <code className="font-mono">@installed</code>,{' '}
1165
+ <code className="font-mono">@updates</code> or{' '}
1166
+ <code className="font-mono">@official</code> in the search to filter.
1167
+ </p>
1168
+ </EmptyState>
1169
+ )}
1170
+ </ScrollArea>
1171
+ </>
1172
+ );
1173
+ }