@celljs/ta-extensions 4.6.1 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ /** The styles of the tabs and the market; as STYLE, only the --ta-* variables of the page. */
2
+ export const MARKET_STYLE = `
3
+ .tax-tabs { display: inline-flex; align-self: flex-start; gap: 2px; margin-bottom: -10px; padding: 3px; border-radius: 10px; background: var(--ta-chip); }
4
+ .tax-tab { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 14px 0 11px; border: 0; border-radius: 7px; background: none; color: var(--ta-secondary); font: inherit; font-size: 13px; font-weight: 500; cursor: pointer; transition: background 140ms, color 140ms, box-shadow 140ms; }
5
+ .tax-tab:hover { color: var(--ta-text); }
6
+ .tax-tab.tax-active { background: var(--ta-hover-strong); color: var(--ta-text); box-shadow: 0 1px 2px rgba(0, 0, 0, .12); }
7
+ :root[data-theme='light'] .tax-tab.tax-active { background: var(--ta-card); box-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .06); }
8
+ .tax-tab:focus-visible { outline: 2px solid var(--ta-border-focus); outline-offset: 1px; }
9
+ .tax-empty-action { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 22px 16px; }
10
+ .tax-market { display: flex; flex-direction: column; gap: 14px; }
11
+ .tax-search { display: flex; align-items: center; gap: 10px; height: 44px; padding: 0 8px 0 15px; border: 1px solid var(--ta-border-field); border-radius: 12px; background: var(--ta-input); color: var(--ta-muted); transition: border-color 140ms, box-shadow 140ms; }
12
+ .tax-search:focus-within { border-color: var(--ta-border-focus); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ta-border-focus) 16%, transparent); }
13
+ .tax-search input { flex: 1; min-width: 0; height: 100%; padding: 0; border: 0; background: none; color: var(--ta-text); font: inherit; font-size: 14px; outline: none; }
14
+ .tax-search input::placeholder { color: var(--ta-muted); }
15
+ .tax-search input::-webkit-search-cancel-button { display: none; }
16
+ .tax-search-clear { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; flex: none; padding: 0; border: 0; border-radius: 7px; background: none; color: var(--ta-muted); cursor: pointer; }
17
+ .tax-search-clear:hover { background: var(--ta-hover); color: var(--ta-text); }
18
+ .tax-topics { display: flex; flex-wrap: wrap; gap: 6px; }
19
+ .tax-topic { height: 28px; padding: 0 12px; border: 1px solid var(--ta-border-muted); border-radius: 14px; background: none; color: var(--ta-secondary); font: inherit; font-size: 12.5px; cursor: pointer; transition: background 120ms, border-color 120ms, color 120ms; }
20
+ .tax-topic:hover { background: var(--ta-hover); color: var(--ta-text); }
21
+ .tax-topic.tax-active { border-color: color-mix(in srgb, var(--tax-accent) 55%, transparent); background: color-mix(in srgb, var(--tax-accent) 12%, transparent); color: var(--ta-text); }
22
+ .tax-market .tax-section-head { margin-top: 4px; min-height: 22px; }
23
+ .tax-head-spin { color: var(--ta-muted); }
24
+ .tax-count-note { color: var(--ta-muted); font-size: 12px; }
25
+ .tax-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
26
+ @media (max-width: 640px) { .tax-grid { grid-template-columns: minmax(0, 1fr); } }
27
+ .tax-card { display: flex; flex-direction: column; gap: 10px; min-height: 150px; padding: 14px 14px 12px; border: 1px solid var(--ta-border-muted); border-radius: 14px; box-sizing: border-box; cursor: pointer; outline: none; transition: border-color 140ms, background 140ms, box-shadow 180ms, transform 180ms var(--ta-ease); }
28
+ .tax-card:hover { border-color: var(--ta-border); background: color-mix(in srgb, var(--ta-hover) 45%, transparent); box-shadow: 0 8px 24px -14px rgba(0, 0, 0, .35); transform: translateY(-1px); }
29
+ .tax-card:focus-visible { border-color: var(--ta-border-focus); }
30
+ .tax-card:active { transform: scale(.995); }
31
+ .tax-card-head { display: flex; align-items: center; gap: 12px; min-width: 0; }
32
+ .tax-card-title { display: flex; flex-direction: column; gap: 3px; flex: 1; min-width: 0; }
33
+ .tax-card-name { overflow: hidden; font-size: 14px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
34
+ .tax-scope { color: var(--ta-muted); font-weight: 500; }
35
+ .tax-card-meta { display: flex; align-items: center; gap: 10px; min-width: 0; color: var(--ta-muted); font-size: 12px; }
36
+ .tax-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
37
+ .tax-downloads { display: inline-flex; align-items: center; gap: 2px; flex: none; }
38
+ .tax-card-description { display: -webkit-box; margin: 0; overflow: hidden; color: var(--ta-secondary); font-size: 12.5px; line-height: 1.55; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow-wrap: anywhere; }
39
+ .tax-card-foot { display: flex; align-items: center; gap: 6px; margin-top: auto; min-height: 17px; }
40
+ .tax-card-time { margin-left: auto; color: var(--ta-muted); font-size: 11.5px; white-space: nowrap; }
41
+ .tax-face { display: inline-flex; align-items: center; justify-content: center; flex: none; border-radius: 26%; background: hsl(var(--tax-hue) 70% 50% / .13); color: hsl(var(--tax-hue) 55% 38%); font-weight: 700; letter-spacing: -.02em; user-select: none; }
42
+ :root:not([data-theme='light']) .tax-face { background: hsl(var(--tax-hue) 60% 55% / .17); color: hsl(var(--tax-hue) 75% 74%); }
43
+ .tax-install { display: inline-flex; align-items: center; justify-content: center; gap: 5px; flex: none; height: 28px; padding: 0 14px; border: 0; border-radius: 14px; background: color-mix(in srgb, var(--ta-green) 14%, transparent); color: color-mix(in srgb, var(--ta-green) 82%, var(--ta-text)); font: inherit; font-size: 12.5px; font-weight: 600; white-space: nowrap; cursor: pointer; transition: background 140ms, color 140ms, transform 120ms var(--ta-ease), filter 140ms; }
44
+ .tax-install:hover { background: color-mix(in srgb, var(--ta-green) 24%, transparent); }
45
+ .tax-install:active { transform: scale(.95); }
46
+ .tax-install:focus-visible { outline: 2px solid var(--ta-border-focus); outline-offset: 2px; }
47
+ .tax-install-done, .tax-install-busy { background: var(--ta-chip); color: var(--ta-muted); font-weight: 500; cursor: default; }
48
+ .tax-install-busy { color: var(--ta-secondary); }
49
+ .tax-install-large { height: 34px; padding: 0 22px; border-radius: 9px; font-size: 13.5px; }
50
+ button.tax-install-large { background: var(--ta-green); color: var(--ta-brand-text); }
51
+ button.tax-install-large:hover { background: var(--ta-green); filter: brightness(1.07); }
52
+ .tax-spin { display: inline-flex; animation: tax-spin 900ms linear infinite; }
53
+ @keyframes tax-spin { to { transform: rotate(360deg); } }
54
+ .tax-skeleton { cursor: default; border-color: transparent; background: linear-gradient(100deg, var(--ta-hover) 40%, var(--ta-hover-strong) 50%, var(--ta-hover) 60%) 0 0 / 200% 100%; animation: tax-shimmer 1.4s linear infinite; opacity: .6; }
55
+ .tax-skeleton:hover { border-color: transparent; box-shadow: none; transform: none; }
56
+ @keyframes tax-shimmer { to { background-position: -200% 0; } }
57
+ .tax-more { padding: 6px 0 2px; color: var(--ta-muted); font-size: 12px; text-align: center; }
58
+ .tax-market-error { display: flex; flex-direction: column; align-items: center; gap: 8px; }
59
+ .tax-market-error strong { color: var(--ta-text); font-weight: 600; }
60
+ .tax-market-error span { max-width: 100%; overflow-wrap: anywhere; font-size: 12.5px; }
61
+ .tax-market-note { text-align: center; }
62
+ .tax-detail { display: flex; flex-direction: column; gap: 20px; animation: tax-in 220ms var(--ta-ease); }
63
+ @keyframes tax-in { from { opacity: 0; transform: translateY(6px); } }
64
+ .tax-back { display: inline-flex; align-items: center; gap: 4px; align-self: flex-start; height: 28px; margin: 0 0 -6px -8px; padding: 0 10px 0 6px; border: 0; border-radius: 7px; background: none; color: var(--ta-secondary); font: inherit; font-size: 13px; cursor: pointer; }
65
+ .tax-back:hover { background: var(--ta-hover); color: var(--ta-text); }
66
+ .tax-detail-head { display: flex; align-items: flex-start; gap: 20px; }
67
+ .tax-detail-title { display: flex; flex-direction: column; flex: 1; min-width: 0; }
68
+ .tax-detail-title h1 { margin: 2px 0 0; font-size: 22px; font-weight: 650; letter-spacing: -.01em; line-height: 1.25; overflow-wrap: anywhere; }
69
+ .tax-detail-description { margin: 6px 0 0; color: var(--ta-secondary); font-size: 14px; line-height: 1.55; }
70
+ .tax-detail-facts { display: flex; flex-wrap: wrap; align-items: center; row-gap: 4px; margin-top: 10px; color: var(--ta-muted); font-size: 12.5px; }
71
+ .tax-detail-facts .tax-tag { margin-right: 6px; }
72
+ .tax-detail-facts .tax-tag + .tax-fact { margin-left: 4px; }
73
+ .tax-fact + .tax-fact::before { content: '·'; margin: 0 7px; }
74
+ .tax-detail-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 16px; }
75
+ .tax-button-quiet { height: 34px; color: var(--ta-secondary); text-decoration: none; }
76
+ .tax-button-quiet:hover { color: var(--ta-text); }
77
+ .tax-button-quiet svg { color: var(--ta-muted); }
78
+ .tax-preview { display: block; width: 100%; max-height: 380px; border: 1px solid var(--ta-border-muted); border-radius: 12px; background: var(--ta-raised); object-fit: contain; }
79
+ .tax-readme { padding-top: 20px; border-top: 1px solid var(--ta-border-muted); font-size: 14px; min-width: 0; overflow-wrap: anywhere; }
80
+ .tax-readme img { max-width: 100%; height: auto; }
81
+ .tax-readme-loading { display: flex; flex-direction: column; gap: 12px; }
82
+ .tax-readme-loading span { height: 12px; border-radius: 6px; background: linear-gradient(100deg, var(--ta-hover) 40%, var(--ta-hover-strong) 50%, var(--ta-hover) 60%) 0 0 / 200% 100%; animation: tax-shimmer 1.4s linear infinite; }
83
+ .tax-readme-loading span:nth-child(1) { width: 92%; }
84
+ .tax-readme-loading span:nth-child(2) { width: 78%; }
85
+ .tax-readme-loading span:nth-child(3) { width: 85%; }
86
+ @media (max-width: 640px) {
87
+ .tax-detail-head { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; column-gap: 14px; }
88
+ .tax-detail-title { display: contents; }
89
+ .tax-detail-title > :not(h1) { grid-column: 1 / -1; }
90
+ .tax-detail-head .tax-face { width: 52px !important; height: 52px !important; font-size: 19px !important; }
91
+ .tax-detail-title h1 { margin: 0; font-size: 19px; }
92
+ .tax-detail-description { margin-top: 12px; }
93
+ }
94
+ `;
@@ -0,0 +1,79 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { MarketUtil } from './market-util';
3
+
4
+ describe('MarketUtil', () => {
5
+ it('tells the kinds of a package by its keywords, in one order', () => {
6
+ expect(MarketUtil.kindsOf(['pi-package', 'Theme', 'skill', 'pi-extension', 'other'])).toEqual(['extensions', 'skills', 'themes']);
7
+ expect(MarketUtil.kindsOf(undefined)).toEqual([]);
8
+ });
9
+
10
+ it('counts downloads as galleries do', () => {
11
+ expect(MarketUtil.compact(999)).toBe('999');
12
+ expect(MarketUtil.compact(1234)).toBe('1.2K');
13
+ expect(MarketUtil.compact(887_900)).toBe('888K');
14
+ expect(MarketUtil.compact(3_284_659)).toBe('3.3M');
15
+ });
16
+
17
+ it('says how long ago, in the largest unit that fits', () => {
18
+ const now = Date.parse('2026-11-11T00:00:00Z');
19
+ expect(MarketUtil.ago('2026-11-08T00:00:00Z', 'en', now)).toBe('3 days ago');
20
+ expect(MarketUtil.ago('2026-11-10T23:59:30Z', 'en', now)).toBe('this minute');
21
+ expect(MarketUtil.ago('nope', 'en', now)).toBeUndefined();
22
+ });
23
+
24
+ it('gives a package the same initials and hue every time', () => {
25
+ expect(MarketUtil.monogram('@you/pi-web-access')).toEqual(MarketUtil.monogram('@you/pi-web-access'));
26
+ expect(MarketUtil.monogram('@you/pi-web-access').letters).toBe('WA');
27
+ expect(MarketUtil.monogram('pomodoro').letters).toBe('PO');
28
+ expect(MarketUtil.shortName('@scope/pi-tools')).toBe('tools');
29
+ });
30
+
31
+ it('names an owner, not the robot that published', () => {
32
+ expect(MarketUtil.person('GitHub Actions', 'you')).toBe('you');
33
+ expect(MarketUtil.person(undefined, 'you')).toBe('you');
34
+ expect(MarketUtil.person('github-actions', 'renovate[bot]')).toBeUndefined();
35
+ });
36
+
37
+ it('finds the page of a repository', () => {
38
+ expect(MarketUtil.repositoryUrl('git+https://github.com/a/b.git')).toBe('https://github.com/a/b');
39
+ expect(MarketUtil.repositoryUrl({ url: 'git://github.com/a/b.git' })).toBe('https://github.com/a/b');
40
+ expect(MarketUtil.repositoryUrl('github:a/b')).toBe('https://github.com/a/b');
41
+ expect(MarketUtil.repositoryUrl('file:../b')).toBeUndefined();
42
+ });
43
+
44
+ it('matches each word of a search, a plural too', () => {
45
+ const pkg = { name: 'pi-web-search', description: 'Search the web', keywords: ['theme'] };
46
+ expect(MarketUtil.matches(pkg, 'Web search')).toBe(true);
47
+ expect(MarketUtil.matches(pkg, 'themes')).toBe(true);
48
+ expect(MarketUtil.matches(pkg, 'web pomodoro')).toBe(false);
49
+ });
50
+
51
+ it('makes a README readable without HTML, and its relative links point to the repository', () => {
52
+ const readme = [
53
+ '<p align="center"><img src="./banner.png" alt="Banner" width="600"></p>',
54
+ '<!-- hidden -->',
55
+ '[![npm](https://img.shields.io/npm/v/x.svg)](https://npmjs.com/x) <img src="https://badgen.net/x">',
56
+ '<h2 align="center">Install <b>it</b></h2>',
57
+ 'See [the docs](docs/usage.md), <a href="https://pi.dev">pi</a> and ![demo](https://x.dev/demo.gif).',
58
+ '```html',
59
+ '<div class="kept"><img src="./in-code.png"></div>',
60
+ '```',
61
+ ].join('\n');
62
+ const text = MarketUtil.readableReadme(readme, 'https://github.com/a/b');
63
+ expect(text).toContain('![Banner](https://raw.githubusercontent.com/a/b/HEAD/banner.png)');
64
+ expect(text).toContain('## Install it');
65
+ expect(text).toContain('[the docs](https://github.com/a/b/blob/HEAD/docs/usage.md)');
66
+ expect(text).toContain('[pi](https://pi.dev)');
67
+ expect(text).toContain('![demo](https://x.dev/demo.gif)');
68
+ expect(text).toContain('<div class="kept"><img src="./in-code.png"></div>');
69
+ expect(text).not.toContain('shields.io');
70
+ expect(text).not.toContain('badgen');
71
+ expect(text).not.toContain('hidden');
72
+ expect(text).not.toContain('<p');
73
+ });
74
+
75
+ it('leaves links alone without a repository on GitHub', () => {
76
+ expect(MarketUtil.readableReadme('[a](docs/a.md)', undefined)).toBe('[a](docs/a.md)');
77
+ expect(MarketUtil.readableReadme('[a](docs/a.md)', 'https://gitlab.com/a/b')).toBe('[a](docs/a.md)');
78
+ });
79
+ });
@@ -0,0 +1,239 @@
1
+ /** What the market tells by the keywords of a package: pi's gallery has no other mark of the kind. */
2
+ export type MarketKind = 'extensions' | 'skills' | 'prompts' | 'themes';
3
+
4
+ /** A pi package of npm, as the market lists it. */
5
+ export interface MarketPackage {
6
+ name: string;
7
+ version: string;
8
+ description?: string;
9
+ /** Who published it last, by npm user name. */
10
+ publisher?: string;
11
+ /** Downloads of the last month. */
12
+ downloads?: number;
13
+ /** When its version was published (ISO). */
14
+ date?: string;
15
+ kinds: MarketKind[];
16
+ links: MarketLinks;
17
+ }
18
+
19
+ export interface MarketLinks {
20
+ npm: string;
21
+ repository?: string;
22
+ homepage?: string;
23
+ }
24
+
25
+ /** One page of a search. */
26
+ export interface MarketPage {
27
+ /** How many there are, when the search has no words: npm counts every package of the keyword. */
28
+ total?: number;
29
+ packages: MarketPackage[];
30
+ /** Where the next page starts; undefined at the end. */
31
+ next?: number;
32
+ }
33
+
34
+ /** A package of the market with what its page shows: its README and the previews of pi's gallery. */
35
+ export interface MarketDetail extends MarketPackage {
36
+ license?: string;
37
+ /** Links and images of the README made absolute, to its repository. */
38
+ readme?: string;
39
+ /** `pi.image` and `pi.video` of its package.json, as pi's gallery shows them. */
40
+ image?: string;
41
+ video?: string;
42
+ /** What it holds, by `pi` of its package.json; empty when it has none and the kinds tell. */
43
+ resources: ('extensions' | 'web' | 'skills' | 'prompts' | 'themes')[];
44
+ }
45
+
46
+ const KIND_WORDS: Record<string, MarketKind> = {
47
+ extension: 'extensions',
48
+ extensions: 'extensions',
49
+ 'pi-extension': 'extensions',
50
+ skill: 'skills',
51
+ skills: 'skills',
52
+ 'pi-skill': 'skills',
53
+ prompt: 'prompts',
54
+ prompts: 'prompts',
55
+ 'pi-prompt': 'prompts',
56
+ 'prompt-template': 'prompts',
57
+ theme: 'themes',
58
+ themes: 'themes',
59
+ 'pi-theme': 'themes',
60
+ };
61
+
62
+ const KIND_ORDER: MarketKind[] = ['extensions', 'skills', 'prompts', 'themes'];
63
+
64
+ export namespace MarketUtil {
65
+ export function kindsOf(keywords: unknown): MarketKind[] {
66
+ const found = new Set<MarketKind>();
67
+ for (const keyword of Array.isArray(keywords) ? keywords : []) {
68
+ const kind = typeof keyword === 'string' ? KIND_WORDS[keyword.toLowerCase()] : undefined;
69
+ if (kind) {
70
+ found.add(kind);
71
+ }
72
+ }
73
+ return KIND_ORDER.filter(kind => found.has(kind));
74
+ }
75
+
76
+ /** 1234 → 1.2K, 3284659 → 3.3M: as galleries count downloads. */
77
+ export function compact(count: number): string {
78
+ const units: [number, string][] = [
79
+ [1e9, 'B'],
80
+ [1e6, 'M'],
81
+ [1e3, 'K'],
82
+ ];
83
+ for (const [size, unit] of units) {
84
+ if (count >= size) {
85
+ const value = count / size;
86
+ return `${value >= 100 ? Math.round(value) : Number(value.toFixed(1))}${unit}`;
87
+ }
88
+ }
89
+ return String(count);
90
+ }
91
+
92
+ /** How long ago, in the largest unit that fits; `now` for the tests. */
93
+ export function ago(iso: string | undefined, language: string, now = Date.now()): string | undefined {
94
+ const time = iso ? Date.parse(iso) : Number.NaN;
95
+ if (Number.isNaN(time)) {
96
+ return undefined;
97
+ }
98
+ const seconds = Math.round((time - now) / 1000);
99
+ const steps: [Intl.RelativeTimeFormatUnit, number][] = [
100
+ ['year', 31536000],
101
+ ['month', 2592000],
102
+ ['week', 604800],
103
+ ['day', 86400],
104
+ ['hour', 3600],
105
+ ['minute', 60],
106
+ ];
107
+ const format = new Intl.RelativeTimeFormat(language, { numeric: 'auto' });
108
+ for (const [unit, size] of steps) {
109
+ if (Math.abs(seconds) >= size) {
110
+ return format.format(Math.round(seconds / size), unit);
111
+ }
112
+ }
113
+ return format.format(0, 'minute');
114
+ }
115
+
116
+ /** Who to name for a package: an owner of it, not the robot of CI that published it last. */
117
+ export function person(...names: (string | undefined)[]): string | undefined {
118
+ return names.find(name => !!name && !/^github[ -]actions$|\[bot\]$|^npm-?bot$/i.test(name)) ?? undefined;
119
+ }
120
+
121
+ /** The name a person reads: without its scope, and without a `pi-` that every one has. */
122
+ export function shortName(name: string): string {
123
+ const plain = name.slice(name.lastIndexOf('/') + 1);
124
+ return plain.replace(/^pi-(?=.)/, '');
125
+ }
126
+
127
+ /** One or two letters and a hue, the same for a name every time: the face of a package that has no picture. */
128
+ export function monogram(name: string): { letters: string; hue: number } {
129
+ const words = shortName(name)
130
+ .split(/[-_.\s]+/)
131
+ .filter(Boolean);
132
+ const letters = (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? name).slice(0, 2)).toUpperCase();
133
+ let hash = 0;
134
+ for (let i = 0; i < name.length; i++) {
135
+ hash = (hash * 31 + name.charCodeAt(i)) | 0;
136
+ }
137
+ return { letters, hue: Math.abs(hash) % 360 };
138
+ }
139
+
140
+ /** `git+https://github.com/a/b.git` → `https://github.com/a/b`; undefined when it is not a page of the web. */
141
+ export function repositoryUrl(repository: unknown): string | undefined {
142
+ const raw = typeof repository === 'string' ? repository : (repository as { url?: unknown } | undefined)?.url;
143
+ if (typeof raw !== 'string') {
144
+ return undefined;
145
+ }
146
+ const github = /^github:(.+)$/.exec(raw) ?? /^([\w.-]+\/[\w.-]+)$/.exec(raw);
147
+ const url = github
148
+ ? `https://github.com/${github[1]}`
149
+ : raw
150
+ .replace(/^git\+/, '')
151
+ .replace(/^git:\/\//, 'https://')
152
+ .replace(/^ssh:\/\/git@/, 'https://');
153
+ return /^https?:\/\//.test(url) ? url.replace(/\.git$/, '').replace(/\/$/, '') : undefined;
154
+ }
155
+
156
+ /** Whether a package has each word of a search, in its name, description or keywords (`themes` finds `theme`). */
157
+ export function matches(pkg: Pick<MarketPackage, 'name' | 'description'> & { keywords?: string[] }, query: string): boolean {
158
+ const text = [pkg.name, pkg.description ?? '', ...(pkg.keywords ?? [])].join(' ').toLowerCase();
159
+ return query
160
+ .toLowerCase()
161
+ .split(/\s+/)
162
+ .filter(Boolean)
163
+ .every(word => text.includes(word) || (word.length > 3 && word.endsWith('s') && text.includes(word.slice(0, -1))));
164
+ }
165
+
166
+ /**
167
+ * A README as the page shows it, in the Markdown of Ta, which shows no HTML: images, links and
168
+ * headings of HTML become Markdown, badges go, other tags leave their text; code stays as it is.
169
+ * Links and images relative to the package point into its repository on GitHub.
170
+ */
171
+ export function readableReadme(readme: string, repository: string | undefined): string {
172
+ const parts = readme.split(/(^[ \t]*(?:```|~~~)[^\n]*\n[\s\S]*?^[ \t]*(?:```|~~~)[ \t]*$)/m);
173
+ return parts
174
+ .map((part, index) => (index % 2 === 1 ? part : absoluteReadme(fromHtml(part), repository).replace(/\n{3,}/g, '\n\n')))
175
+ .join('')
176
+ .trim();
177
+ }
178
+
179
+ function attribute(tag: string, name: string): string | undefined {
180
+ return new RegExp(`\\b${name}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag)?.[2];
181
+ }
182
+
183
+ function isBadge(src: string): boolean {
184
+ return /shields\.io|badgen\.net|badge/i.test(src);
185
+ }
186
+
187
+ function fromHtml(text: string): string {
188
+ return text
189
+ .replace(/<!--[\s\S]*?-->/g, '')
190
+ .replace(/<(source|meta|link)\b[^>]*>/gi, '')
191
+ .replace(/<img\b[^>]*>/gi, tag => {
192
+ const src = attribute(tag, 'src');
193
+ return src && !isBadge(src) ? `\n\n![${attribute(tag, 'alt') ?? ''}](${src})\n\n` : '';
194
+ })
195
+ .replace(/!\[[^\]]*\]\(([^)\s]+)[^)]*\)/g, (whole, src: string) => (isBadge(src) ? '' : whole))
196
+ .replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, (tag, inner: string) => {
197
+ const href = attribute(tag, 'href');
198
+ const label = inner.trim();
199
+ return !label ? '' : href && !label.includes('![') ? `[${label}](${href})` : label;
200
+ })
201
+ .replace(/\[\s*\]\([^)]*\)/g, '')
202
+ .replace(
203
+ /<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi,
204
+ (_whole, level: string, inner: string) => `\n\n${'#'.repeat(Number(level))} ${inner.replace(/<[^>]+>/g, '').trim()}\n\n`,
205
+ )
206
+ .replace(/<br\s*\/?>/gi, '\n')
207
+ .replace(
208
+ /<\/?(p|div|span|center|picture|details|summary|b|strong|em|i|u|sub|sup|kbd|small|big|font|table|thead|tbody|tr|td|th|hr|section|article|figure|figcaption)\b[^>]*>/gi,
209
+ '',
210
+ )
211
+ .replace(/^[ \t]+$/gm, '');
212
+ }
213
+
214
+ /**
215
+ * The links and images of a README made absolute: those relative to the package point into its
216
+ * repository on GitHub, where npm shows them too. Others are left as they are.
217
+ */
218
+ export function absoluteReadme(readme: string, repository: string | undefined): string {
219
+ const github = repository ? /^https:\/\/github\.com\/([^/]+\/[^/#?]+)/.exec(repository)?.[1] : undefined;
220
+ if (!github) {
221
+ return readme;
222
+ }
223
+ const resolve = (target: string, image: boolean) => {
224
+ if (/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(target)) {
225
+ return target;
226
+ }
227
+ const path = target.replace(/^\.?\//, '');
228
+ return image ? `https://raw.githubusercontent.com/${github}/HEAD/${path}` : `https://github.com/${github}/blob/HEAD/${path}`;
229
+ };
230
+ return readme
231
+ .replace(/(!?)\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(\s+"[^"]*")?\s*\)/g, (_whole, bang: string, text: string, target: string, title = '') => {
232
+ return `${bang}[${text}](${resolve(target, bang === '!')}${title})`;
233
+ })
234
+ .replace(
235
+ /(<img\b[^>]*\bsrc=)(["'])([^"']+)\2/gi,
236
+ (_whole, head: string, quote: string, target: string) => `${head}${quote}${resolve(target, true)}${quote}`,
237
+ );
238
+ }
239
+ }
@@ -0,0 +1,245 @@
1
+ import { type ExtensionsContext, icon } from './context';
2
+ import { ExtensionWords } from './i18n';
3
+ import { MarketDetailView } from './market-detail';
4
+ import { InstallButton, PackageFace, PackageName } from './market-parts';
5
+ import { type MarketPackage, MarketUtil } from './market-util';
6
+ import { React } from './react';
7
+
8
+ /** How long the market waits for the user to stop typing before it asks npm. */
9
+ const DEBOUNCE = 300;
10
+
11
+ /**
12
+ * The market: a search of the pi packages of npm, the most used first, with topics to start from; a
13
+ * package installs in one click, or opens on a page of its own with its README.
14
+ */
15
+ export function MarketView({ context }: { context: ExtensionsContext }): React.ReactElement {
16
+ const { market, selected } = context;
17
+ const name = selected.use();
18
+ const list = React.useRef<HTMLDivElement>(null);
19
+ // The list stays below the page of a package, scrolled where it was.
20
+ const scroll = React.useRef(0);
21
+ const scroller = () => list.current?.closest('.tax-page') ?? undefined;
22
+ const open = (next: string) => {
23
+ scroll.current = scroller()?.scrollTop ?? 0;
24
+ selected.set(next);
25
+ };
26
+ React.useLayoutEffect(() => {
27
+ const element = scroller();
28
+ if (element) {
29
+ element.scrollTop = name ? 0 : scroll.current;
30
+ }
31
+ }, [name]);
32
+ React.useEffect(() => {
33
+ void market.search(market.state.query);
34
+ }, [market]);
35
+ return (
36
+ <>
37
+ <div ref={list} hidden={!!name}>
38
+ <MarketList context={context} onOpen={open} />
39
+ </div>
40
+ {name && <MarketDetailView key={name} context={context} name={name} onBack={() => selected.set(undefined)} />}
41
+ </>
42
+ );
43
+ }
44
+
45
+ function MarketList({ context, onOpen }: { context: ExtensionsContext; onOpen(name: string): void }): React.ReactElement {
46
+ const { pi, market, actions } = context;
47
+ const words = actions.words;
48
+ const state = React.useSyncExternalStore(
49
+ listener => market.subscribe(listener),
50
+ () => market.state,
51
+ );
52
+ const [text, setText] = React.useState(state.query);
53
+ const input = React.useRef<HTMLInputElement>(null);
54
+ React.useEffect(() => {
55
+ const timer = setTimeout(() => void market.search(text), DEBOUNCE);
56
+ return () => clearTimeout(timer);
57
+ }, [market, text]);
58
+ const pick = (query: string) => {
59
+ setText(query);
60
+ void market.search(query);
61
+ };
62
+ const Search = icon(pi, 'Search');
63
+ const X = icon(pi, 'X');
64
+ const { packages, loading, error, query, total, next } = state;
65
+ const count = query ? (next === undefined ? packages?.length : undefined) : total;
66
+ const first = loading && !packages;
67
+ return (
68
+ <div className="tax-market">
69
+ <form
70
+ className="tax-search"
71
+ onSubmit={event => {
72
+ event.preventDefault();
73
+ void market.search(text);
74
+ }}
75
+ >
76
+ <Search size={16} />
77
+ <input
78
+ ref={input}
79
+ type="search"
80
+ value={text}
81
+ placeholder={words.marketSearch}
82
+ aria-label={words.marketSearch}
83
+ spellCheck={false}
84
+ onChange={event => setText(event.target.value)}
85
+ onKeyDown={event => {
86
+ if (event.key === 'Escape' && text) {
87
+ event.preventDefault();
88
+ pick('');
89
+ }
90
+ }}
91
+ />
92
+ {text && (
93
+ <button
94
+ type="button"
95
+ className="tax-search-clear"
96
+ aria-label={words.marketClear}
97
+ title={words.marketClear}
98
+ onClick={() => {
99
+ pick('');
100
+ input.current?.focus();
101
+ }}
102
+ >
103
+ <X size={14} />
104
+ </button>
105
+ )}
106
+ </form>
107
+ <div className="tax-topics">
108
+ {words.topics.map(topic => (
109
+ <button
110
+ key={topic.query}
111
+ type="button"
112
+ className={`tax-topic${query === topic.query ? ' tax-active' : ''}`}
113
+ aria-pressed={query === topic.query}
114
+ onClick={() => pick(query === topic.query ? '' : topic.query)}
115
+ >
116
+ {topic.label}
117
+ </button>
118
+ ))}
119
+ </div>
120
+ <div className="tax-section-head">
121
+ <h2>
122
+ {query ? words.marketResults : words.marketPopular}
123
+ {loading && packages && <span className="tax-spin tax-head-spin">{React.createElement(icon(pi, 'LoaderCircle'), { size: 13 })}</span>}
124
+ </h2>
125
+ {count !== undefined && !error && (
126
+ <span className="tax-count-note">{ExtensionWords.fill(words.marketCount, { count: count.toLocaleString(pi.ui.language) })}</span>
127
+ )}
128
+ </div>
129
+ {error ? (
130
+ <div className="tax-empty tax-market-error">
131
+ <strong>{words.marketError}</strong>
132
+ <span>{error}</span>
133
+ <button type="button" className="tax-button" onClick={() => void market.search(text)}>
134
+ {words.retry}
135
+ </button>
136
+ </div>
137
+ ) : first ? (
138
+ <div className="tax-grid" aria-busy="true">
139
+ {Array.from({ length: 6 }, (_, index) => (
140
+ <div key={index} className="tax-card tax-skeleton" />
141
+ ))}
142
+ </div>
143
+ ) : packages?.length === 0 ? (
144
+ <div className="tax-empty">{ExtensionWords.fill(words.marketEmpty, { query })}</div>
145
+ ) : (
146
+ <>
147
+ <div className="tax-grid">
148
+ {packages?.map(pkg => (
149
+ <MarketCard key={pkg.name} context={context} pkg={pkg} onOpen={onOpen} />
150
+ ))}
151
+ </div>
152
+ <MoreSentinel context={context} />
153
+ </>
154
+ )}
155
+ <div className="tax-note tax-market-note">{words.marketNote}</div>
156
+ </div>
157
+ );
158
+ }
159
+
160
+ /** Asks for the next page as the end of the list comes near, as feeds do. */
161
+ function MoreSentinel({ context }: { context: ExtensionsContext }): React.ReactElement | null {
162
+ const { market, actions } = context;
163
+ const words = actions.words;
164
+ const state = React.useSyncExternalStore(
165
+ listener => market.subscribe(listener),
166
+ () => market.state,
167
+ );
168
+ const ref = React.useRef<HTMLDivElement>(null);
169
+ const more = !!state.packages && state.next !== undefined;
170
+ React.useEffect(() => {
171
+ const element = ref.current;
172
+ if (!element || !more) {
173
+ return undefined;
174
+ }
175
+ const observer = new IntersectionObserver(entries => entries.some(entry => entry.isIntersecting) && void market.more(), { rootMargin: '480px 0px' });
176
+ observer.observe(element);
177
+ return () => observer.disconnect();
178
+ }, [market, more, state.packages?.length]);
179
+ if (!state.packages?.length) {
180
+ return null;
181
+ }
182
+ return (
183
+ <div ref={ref} className="tax-more">
184
+ {more ? words.loadingMore : words.allShown}
185
+ </div>
186
+ );
187
+ }
188
+
189
+ interface MarketCardProps {
190
+ context: ExtensionsContext;
191
+ pkg: MarketPackage;
192
+ onOpen(name: string): void;
193
+ }
194
+
195
+ /** A package: its face, name, who made it and how much it is used; what it does; a button to install it. */
196
+ function MarketCard({ context, pkg, onOpen }: MarketCardProps): React.ReactElement {
197
+ const { pi, actions } = context;
198
+ const words = actions.words;
199
+ const Down = icon(pi, 'ArrowDown');
200
+ const ago = MarketUtil.ago(pkg.date, pi.ui.language);
201
+ return (
202
+ // biome-ignore lint/a11y/useSemanticElements: a card holds a button of its own, which a button cannot
203
+ <div
204
+ className="tax-card"
205
+ role="button"
206
+ tabIndex={0}
207
+ aria-label={pkg.name}
208
+ onClick={() => onOpen(pkg.name)}
209
+ onKeyDown={event => {
210
+ if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {
211
+ event.preventDefault();
212
+ onOpen(pkg.name);
213
+ }
214
+ }}
215
+ >
216
+ <div className="tax-card-head">
217
+ <PackageFace name={pkg.name} size={40} />
218
+ <div className="tax-card-title">
219
+ <div className="tax-card-name" title={pkg.name}>
220
+ <PackageName name={pkg.name} />
221
+ </div>
222
+ <div className="tax-card-meta">
223
+ {pkg.publisher && <span className="tax-ellipsis">{ExtensionWords.fill(words.by, { name: pkg.publisher })}</span>}
224
+ {pkg.downloads !== undefined && pkg.downloads > 0 && (
225
+ <span className="tax-downloads">
226
+ <Down size={11} />
227
+ {ExtensionWords.fill(words.perMonth, { count: MarketUtil.compact(pkg.downloads) })}
228
+ </span>
229
+ )}
230
+ </div>
231
+ </div>
232
+ <InstallButton context={context} name={pkg.name} />
233
+ </div>
234
+ <p className="tax-card-description">{pkg.description}</p>
235
+ <div className="tax-card-foot">
236
+ {pkg.kinds.map(kind => (
237
+ <span key={kind} className="tax-tag">
238
+ {words.marketKinds[kind]}
239
+ </span>
240
+ ))}
241
+ {ago && <span className="tax-card-time">{ago}</span>}
242
+ </div>
243
+ </div>
244
+ );
245
+ }