-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathvsx-extension.tsx
663 lines (573 loc) · 24.1 KB
/
vsx-extension.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// *****************************************************************************
// Copyright (C) 2020 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
// *****************************************************************************
import * as markdownit from '@theia/core/shared/markdown-it';
import * as React from '@theia/core/shared/react';
import * as DOMPurify from '@theia/core/shared/dompurify';
import { injectable, inject } from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { TreeElement, TreeElementNode } from '@theia/core/lib/browser/source-tree';
import { OpenerService, open, OpenerOptions } from '@theia/core/lib/browser/opener-service';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import { PluginServer, DeployedPlugin, PluginType, PluginIdentifiers, PluginDeployOptions } from '@theia/plugin-ext/lib/common/plugin-protocol';
import { VSCodeExtensionUri } from '@theia/plugin-ext-vscode/lib/common/plugin-vscode-uri';
import { ProgressService } from '@theia/core/lib/common/progress-service';
import { Endpoint } from '@theia/core/lib/browser/endpoint';
import { VSXEnvironment } from '../common/vsx-environment';
import { VSXExtensionsSearchModel } from './vsx-extensions-search-model';
import { CommandRegistry, MenuPath, nls } from '@theia/core/lib/common';
import { codicon, ContextMenuRenderer, TooltipService, TreeWidget } from '@theia/core/lib/browser';
import { VSXExtensionNamespaceAccess, VSXUser } from '@theia/ovsx-client/lib/ovsx-types';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
export const EXTENSIONS_CONTEXT_MENU: MenuPath = ['extensions_context_menu'];
export namespace VSXExtensionsContextMenu {
export const INSTALL = [...EXTENSIONS_CONTEXT_MENU, '1_install'];
export const COPY = [...EXTENSIONS_CONTEXT_MENU, '2_copy'];
}
@injectable()
export class VSXExtensionData {
readonly version?: string;
readonly iconUrl?: string;
readonly publisher?: string;
readonly name?: string;
readonly displayName?: string;
readonly description?: string;
readonly averageRating?: number;
readonly downloadCount?: number;
readonly downloadUrl?: string;
readonly readmeUrl?: string;
readonly licenseUrl?: string;
readonly repository?: string;
readonly license?: string;
readonly readme?: string;
readonly preview?: boolean;
readonly namespaceAccess?: VSXExtensionNamespaceAccess;
readonly publishedBy?: VSXUser;
static KEYS: Set<(keyof VSXExtensionData)> = new Set([
'version',
'iconUrl',
'publisher',
'name',
'displayName',
'description',
'averageRating',
'downloadCount',
'downloadUrl',
'readmeUrl',
'licenseUrl',
'repository',
'license',
'readme',
'preview',
'namespaceAccess',
'publishedBy'
]);
}
@injectable()
export class VSXExtensionOptions {
readonly id: string;
}
export const VSXExtensionFactory = Symbol('VSXExtensionFactory');
export type VSXExtensionFactory = (options: VSXExtensionOptions) => VSXExtension;
@injectable()
export class VSXExtension implements VSXExtensionData, TreeElement {
/**
* Ensure the version string begins with `'v'`.
*/
static formatVersion(version: string | undefined): string | undefined {
if (version && !version.startsWith('v')) {
return `v${version}`;
}
return version;
}
@inject(VSXExtensionOptions)
protected readonly options: VSXExtensionOptions;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(HostedPluginSupport)
protected readonly pluginSupport: HostedPluginSupport;
@inject(PluginServer)
protected readonly pluginServer: PluginServer;
@inject(ProgressService)
protected readonly progressService: ProgressService;
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
@inject(VSXEnvironment)
readonly environment: VSXEnvironment;
@inject(VSXExtensionsSearchModel)
readonly search: VSXExtensionsSearchModel;
@inject(TooltipService)
readonly tooltipService: TooltipService;
@inject(WindowService)
readonly windowService: WindowService;
@inject(CommandRegistry)
readonly commandRegistry: CommandRegistry;
protected readonly data: Partial<VSXExtensionData> = {};
get uri(): URI {
return VSCodeExtensionUri.toUri(this.id);
}
get id(): string {
return this.options.id;
}
get visible(): boolean {
return !!this.name;
}
get plugin(): DeployedPlugin | undefined {
return this.pluginSupport.getPlugin(this.id as PluginIdentifiers.UnversionedId);
}
get installed(): boolean {
return !!this.plugin;
}
get builtin(): boolean {
return this.plugin?.type === PluginType.System;
}
update(data: Partial<VSXExtensionData>): void {
for (const key of VSXExtensionData.KEYS) {
if (key in data) {
Object.assign(this.data, { [key]: data[key] });
}
}
}
reloadWindow(): void {
this.windowService.reload();
}
protected getData<K extends keyof VSXExtensionData>(key: K): VSXExtensionData[K] {
const model = this.plugin?.metadata.model;
if (model && key in model) {
return model[key as keyof typeof model] as VSXExtensionData[K];
}
return this.data[key];
}
get iconUrl(): string | undefined {
const plugin = this.plugin;
const iconUrl = plugin && plugin.metadata.model.iconUrl;
if (iconUrl) {
return new Endpoint({ path: iconUrl }).getRestUrl().toString();
}
return this.data['iconUrl'];
}
get publisher(): string | undefined {
return this.getData('publisher');
}
get name(): string | undefined {
return this.getData('name');
}
get displayName(): string | undefined {
return this.getData('displayName') || this.name;
}
get description(): string | undefined {
return this.getData('description');
}
get version(): string | undefined {
return this.getData('version');
}
get averageRating(): number | undefined {
return this.getData('averageRating');
}
get downloadCount(): number | undefined {
return this.getData('downloadCount');
}
get downloadUrl(): string | undefined {
return this.getData('downloadUrl');
}
get readmeUrl(): string | undefined {
const plugin = this.plugin;
const readmeUrl = plugin && plugin.metadata.model.readmeUrl;
if (readmeUrl) {
return new Endpoint({ path: readmeUrl }).getRestUrl().toString();
}
return this.data['readmeUrl'];
}
get licenseUrl(): string | undefined {
let licenseUrl = this.data['licenseUrl'];
if (licenseUrl) {
return licenseUrl;
} else {
const plugin = this.plugin;
licenseUrl = plugin && plugin.metadata.model.licenseUrl;
if (licenseUrl) {
return new Endpoint({ path: licenseUrl }).getRestUrl().toString();
}
}
}
get repository(): string | undefined {
return this.getData('repository');
}
get license(): string | undefined {
return this.getData('license');
}
get readme(): string | undefined {
return this.getData('readme');
}
get preview(): boolean | undefined {
return this.getData('preview');
}
get namespaceAccess(): VSXExtensionNamespaceAccess | undefined {
return this.getData('namespaceAccess');
}
get publishedBy(): VSXUser | undefined {
return this.getData('publishedBy');
}
get tooltipId(): string {
return this.tooltipService.tooltipId;
}
get tooltip(): string {
let md = `__${this.displayName}__ ${VSXExtension.formatVersion(this.version)}\n\n${this.description}\n_____\n\nPublisher: ${this.publisher}`;
if (this.license) {
md += ` \rLicense: ${this.license}`;
}
if (this.downloadCount) {
md += ` \rDownload count: ${downloadCompactFormatter.format(this.downloadCount)}`;
}
if (this.averageRating) {
md += ` \rAverage Rating: ${this.averageRating.toFixed(1)}`;
}
return markdownit().render(md);
}
protected _busy = 0;
get busy(): boolean {
return !!this._busy;
}
async install(options?: PluginDeployOptions): Promise<void> {
this._busy++;
try {
await this.progressService.withProgress(nls.localizeByDefault("Installing extension '{0}' v{1}...", this.id, this.version ?? 0), 'extensions', () =>
this.pluginServer.deploy(this.uri.toString(), undefined, options)
);
} finally {
this._busy--;
}
}
async uninstall(): Promise<void> {
this._busy++;
try {
const { plugin } = this;
if (plugin) {
await this.progressService.withProgress(
nls.localizeByDefault('Uninstalling {0}...', this.id), 'extensions',
() => this.pluginServer.uninstall(PluginIdentifiers.componentsToVersionedId(plugin.metadata.model))
);
}
} finally {
this._busy--;
}
}
handleContextMenu(e: React.MouseEvent<HTMLElement, MouseEvent>): void {
e.preventDefault();
this.contextMenuRenderer.render({
menuPath: EXTENSIONS_CONTEXT_MENU,
anchor: {
x: e.clientX,
y: e.clientY,
},
args: [this]
});
}
/**
* Get the registry link for the given extension.
* @param path the url path.
* @returns the registry link for the given extension at the path.
*/
async getRegistryLink(path = ''): Promise<URI> {
const uri = new URI(await this.environment.getRegistryUri());
return uri.resolve('extension/' + this.id.replace('.', '/')).resolve(path);
}
async serialize(): Promise<string> {
const serializedExtension: string[] = [];
serializedExtension.push(`Name: ${this.displayName}`);
serializedExtension.push(`Id: ${this.id}`);
serializedExtension.push(`Description: ${this.description}`);
serializedExtension.push(`Version: ${this.version}`);
serializedExtension.push(`Publisher: ${this.publisher}`);
if (this.downloadUrl !== undefined) {
const registryLink = await this.getRegistryLink();
serializedExtension.push(`Open VSX Link: ${registryLink.toString()}`);
};
return serializedExtension.join('\n');
}
async open(options: OpenerOptions = { mode: 'reveal' }): Promise<void> {
await this.doOpen(this.uri, options);
}
async doOpen(uri: URI, options?: OpenerOptions): Promise<void> {
await open(this.openerService, uri, options);
}
render(host: TreeWidget): React.ReactNode {
const node = <VSXExtensionComponent extension={this} host={host} />;
this.tooltipService.update();
return node;
}
}
export abstract class AbstractVSXExtensionComponent<Props extends AbstractVSXExtensionComponent.Props = AbstractVSXExtensionComponent.Props> extends React.Component<Props> {
readonly install = async (event?: React.MouseEvent) => {
event?.stopPropagation();
this.forceUpdate();
try {
const pending = this.props.extension.install();
this.forceUpdate();
await pending;
} finally {
this.forceUpdate();
}
};
readonly uninstall = async (event?: React.MouseEvent) => {
event?.stopPropagation();
try {
const pending = this.props.extension.uninstall();
this.forceUpdate();
await pending;
} finally {
this.forceUpdate();
}
};
readonly reloadWindow = (event?: React.MouseEvent) => {
event?.stopPropagation();
this.props.extension.reloadWindow();
};
protected readonly manage = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
e.stopPropagation();
this.props.extension.handleContextMenu(e);
};
protected renderAction(host?: TreeWidget): React.ReactNode {
const { builtin, busy, plugin } = this.props.extension;
const isFocused = (host?.model.getFocusedNode() as TreeElementNode)?.element === this.props.extension;
const tabIndex = (!host || isFocused) ? 0 : undefined;
const installed = !!plugin;
const outOfSynch = plugin?.metadata.outOfSync;
if (builtin) {
return <div className="codicon codicon-settings-gear action" tabIndex={tabIndex} onClick={this.manage}></div>;
}
if (busy) {
if (installed) {
return <button className="theia-button action theia-mod-disabled">{nls.localizeByDefault('Uninstalling')}</button>;
}
return <button className="theia-button action prominent theia-mod-disabled">{nls.localizeByDefault('Installing')}</button>;
}
if (installed) {
return <div>
{
outOfSynch
? <button className="theia-button action" onClick={this.reloadWindow}>{nls.localizeByDefault('Reload Required')}</button>
: <button className="theia-button action" onClick={this.uninstall}>{nls.localizeByDefault('Uninstall')}</button>
}
<div className="codicon codicon-settings-gear action" onClick={this.manage}></div>
</div>;
}
return <button className="theia-button prominent action" onClick={this.install}>{nls.localizeByDefault('Install')}</button>;
}
}
export namespace AbstractVSXExtensionComponent {
export interface Props {
extension: VSXExtension;
}
}
const downloadFormatter = new Intl.NumberFormat();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const downloadCompactFormatter = new Intl.NumberFormat(undefined, { notation: 'compact', compactDisplay: 'short' } as any);
export namespace VSXExtensionComponent {
export interface Props extends AbstractVSXExtensionComponent.Props {
host: TreeWidget;
}
}
export class VSXExtensionComponent<Props extends VSXExtensionComponent.Props = VSXExtensionComponent.Props> extends AbstractVSXExtensionComponent<Props> {
override render(): React.ReactNode {
const { iconUrl, publisher, displayName, description, version, downloadCount, averageRating, tooltipId, tooltip } = this.props.extension;
return <div className='theia-vsx-extension noselect' data-for={tooltipId} data-tip={tooltip}>
{iconUrl ?
<img className='theia-vsx-extension-icon' src={iconUrl} /> :
<div className='theia-vsx-extension-icon placeholder' />}
<div className='theia-vsx-extension-content'>
<div className='title'>
<div className='noWrapInfo'>
<span className='name'>{displayName}</span> <span className='version'>{VSXExtension.formatVersion(version)}</span>
</div>
<div className='stat'>
{!!downloadCount && <span className='download-count'><i className={codicon('cloud-download')} />{downloadCompactFormatter.format(downloadCount)}</span>}
{!!averageRating && <span className='average-rating'><i className={codicon('star-full')} />{averageRating.toFixed(1)}</span>}
</div>
</div>
<div className='noWrapInfo theia-vsx-extension-description'>{description}</div>
<div className='theia-vsx-extension-action-bar'>
<span className='noWrapInfo theia-vsx-extension-publisher'>{publisher}</span>
{this.renderAction(this.props.host)}
</div>
</div>
</div >;
}
}
export class VSXExtensionEditorComponent extends AbstractVSXExtensionComponent {
protected header: HTMLElement | undefined;
protected body: HTMLElement | undefined;
protected _scrollContainer: HTMLElement | undefined;
get scrollContainer(): HTMLElement | undefined {
return this._scrollContainer;
}
override render(): React.ReactNode {
const {
builtin, preview, id, iconUrl, publisher, displayName, description, version,
averageRating, downloadCount, repository, license, readme
} = this.props.extension;
const { baseStyle, scrollStyle } = this.getSubcomponentStyles();
const sanitizedReadme = !!readme ? DOMPurify.sanitize(readme) : undefined;
return <React.Fragment>
<div className='header' style={baseStyle} ref={ref => this.header = (ref || undefined)}>
{iconUrl ?
<img className='icon-container' src={iconUrl} /> :
<div className='icon-container placeholder' />}
<div className='details'>
<div className='title'>
<span title='Extension name' className='name' onClick={this.openExtension}>{displayName}</span>
<span title='Extension identifier' className='identifier'>{id}</span>
{preview && <span className='preview'>Preview</span>}
{builtin && <span className='builtin'>Built-in</span>}
</div>
<div className='subtitle'>
<span title='Publisher name' className='publisher' onClick={this.searchPublisher}>
{this.renderNamespaceAccess()}
{publisher}
</span>
{!!downloadCount && <span className='download-count' onClick={this.openExtension}>
<i className={codicon('cloud-download')} />{downloadFormatter.format(downloadCount)}</span>}
{averageRating !== undefined && <span className='average-rating' onClick={this.openAverageRating}>{this.renderStars()}</span>}
{repository && <span className='repository' onClick={this.openRepository}>Repository</span>}
{license && <span className='license' onClick={this.openLicense}>{license}</span>}
{version && <span className='version'>{VSXExtension.formatVersion(version)}</span>}
</div>
<div className='description noWrapInfo'>{description}</div>
{this.renderAction()}
</div>
</div>
{
sanitizedReadme &&
< div className='scroll-container'
style={scrollStyle}
ref={ref => this._scrollContainer = (ref || undefined)}>
<div className='body'
ref={ref => this.body = (ref || undefined)}
onClick={this.openLink}
style={baseStyle}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: sanitizedReadme }}
/>
</div>
}
</React.Fragment >;
}
protected renderNamespaceAccess(): React.ReactNode {
const { publisher, namespaceAccess, publishedBy } = this.props.extension;
if (namespaceAccess === undefined) {
return undefined;
}
let tooltip = publishedBy ? ` Published by "${publishedBy.loginName}".` : '';
let icon;
if (namespaceAccess === 'public') {
icon = 'globe';
tooltip = `Everyone can publish to "${publisher}" namespace.` + tooltip;
} else {
icon = 'shield';
tooltip = `Only verified owners can publish to "${publisher}" namespace.` + tooltip;
}
return <i className={`${codicon(icon)} namespace-access`} title={tooltip} onClick={this.openPublishedBy} />;
}
protected renderStars(): React.ReactNode {
const rating = this.props.extension.averageRating || 0;
const renderStarAt = (position: number) => position <= rating ?
<i className={codicon('star-full')} /> :
position > rating && position - rating < 1 ?
<i className={codicon('star-half')} /> :
<i className={codicon('star-empty')} />;
return <React.Fragment>
{renderStarAt(1)}{renderStarAt(2)}{renderStarAt(3)}{renderStarAt(4)}{renderStarAt(5)}
</React.Fragment>;
}
protected getSubcomponentStyles(): { baseStyle: React.CSSProperties, scrollStyle: React.CSSProperties; } {
const visibility: 'unset' | 'hidden' = this.header ? 'unset' : 'hidden';
const baseStyle = { visibility };
const scrollStyle = this.header?.clientHeight ? { visibility, height: `calc(100% - (${this.header.clientHeight}px + 1px))` } : baseStyle;
return { baseStyle, scrollStyle };
}
// TODO replace with webview
readonly openLink = (event: React.MouseEvent) => {
if (!this.body) {
return;
}
const target = event.nativeEvent.target;
if (!(target instanceof HTMLElement)) {
return;
}
let node = target;
while (node.tagName.toLowerCase() !== 'a') {
if (node === this.body) {
return;
}
if (!(node.parentElement instanceof HTMLElement)) {
return;
}
node = node.parentElement;
}
const href = node.getAttribute('href');
if (href && !href.startsWith('#')) {
event.preventDefault();
this.props.extension.doOpen(new URI(href));
}
};
readonly openExtension = async (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
const uri = await extension.getRegistryLink();
extension.doOpen(uri);
};
readonly searchPublisher = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
if (extension.publisher) {
extension.search.query = extension.publisher;
}
};
readonly openPublishedBy = async (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
const homepage = extension.publishedBy && extension.publishedBy.homepage;
if (homepage) {
extension.doOpen(new URI(homepage));
}
};
readonly openAverageRating = async (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
const uri = await extension.getRegistryLink('reviews');
extension.doOpen(uri);
};
readonly openRepository = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
if (extension.repository) {
extension.doOpen(new URI(extension.repository));
}
};
readonly openLicense = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const extension = this.props.extension;
const licenseUrl = extension.licenseUrl;
if (licenseUrl) {
extension.doOpen(new URI(licenseUrl));
}
};
}