Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions nx2/blocks/marketplace-details/marketplace-details.css
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@
color: var(--s2-gray-700);
}

.installed {
display: flex;
align-items: center;
gap: var(--s2-spacing-75);
margin: 0;
font-size: var(--s2-body-size-xs);
line-height: 16px;
color: var(--s2-gray-700);
}

.installed-icon {
width: 14px;
height: 14px;
color: var(--s2-green-900);
}

.description {
margin: 0;
font-size: var(--s2-body-size-l);
Expand Down
134 changes: 103 additions & 31 deletions nx2/blocks/marketplace-details/marketplace-details.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { LitElement, html, nothing } from 'da-lit';

import { loadStyle } from '../../utils/utils.js';
import { fetchMarketplace } from '../marketplace/marketplace-utils.js';
import { hashChange, loadStyle } from '../../utils/utils.js';
import { fetchMarketplace, getInstallTarget } from '../marketplace/marketplace-utils.js';
import {
isInstalled, addInstallRow, getInstallRow, loadInstallState, saveInstall,
} from '../marketplace/marketplace-install.js';
import {
getReadmeSource,
fetchReadme,
Expand All @@ -21,20 +24,28 @@ const README_ERROR = 'Could not load the README.';

const normalizeHref = (value) => toUrl(value)?.href.replace(/\/$/, '');

const decodeHash = (hash = '') => {
const decode = (value) => {
try {
return decodeURIComponent(hash.replace(/^#/, ''));
return decodeURIComponent(value);
} catch {
return undefined;
}
};

// Only Doc Urls listed in the marketplace sheet are rendered, never an arbitrary hash url.
export function findItemByHash({ items = [], hash }) {
const href = normalizeHref(decodeHash(hash));
// `?ext=<Doc Url>` (the hash holds the site); old links carried the Doc Url as hash.
export function getDocHref({ search, hash }) {
const ext = new URLSearchParams(search).get('ext');
if (ext) return ext;
const legacy = hash?.replace(/^#/, '');
return legacy && !legacy.startsWith('/') ? decode(legacy) : undefined;
}

// Only Doc Urls listed in the marketplace sheet are rendered, never an arbitrary url.
export function findItem({ items = [], docHref }) {
const href = normalizeHref(docHref);
if (!href) return undefined;
return items.find(({ docHref }) => (
normalizeHref(docHref) === href && getReadmeSource(docHref)));
return items.find((item) => (
normalizeHref(item.docHref) === href && getReadmeSource(item.docHref)));
}

// `/marketplace/details` -> `/marketplace`
Expand All @@ -45,69 +56,116 @@ const CHEVRON = html`<svg class="back-icon" viewBox="0 0 20 20" aria-hidden="tru
stroke-linecap="round" stroke-linejoin="round" />
</svg>`;

const CHECK = html`<svg class="installed-icon" viewBox="0 0 20 20" aria-hidden="true">
<path d="M4.5 10.5 8 14l7.5-8" fill="none" stroke="currentColor" stroke-width="1.75"
stroke-linecap="round" stroke-linejoin="round" />
</svg>`;

class NxMarketplaceDetails extends LitElement {
static properties = {
_item: { state: true },
_readme: { state: true },
_updated: { state: true },
_heroFailed: { state: true },
_error: { state: true },
_site: { state: true },
_install: { state: true },
_installing: { state: true },
};

connectedCallback() {
super.connectedCallback();
this.shadowRoot.adoptedStyleSheets = [buttonStyle, style];
preloadReadmeRenderer().catch(() => {});
this._onHashChange ??= () => this._load();
window.addEventListener('hashchange', this._onHashChange);
this._load();
this._ready = this._load();
// The hash is the site (`#/org/site`); switching sites only changes the install state.
this._unsubscribeHash = hashChange.subscribe((state) => {
this._site = state?.org && state?.site ? state : undefined;
this._loadInstall();
});
}

disconnectedCallback() {
window.removeEventListener('hashchange', this._onHashChange);
this._unsubscribeHash?.();
super.disconnectedCallback();
}

async _load() {
const { hash } = window.location;
const isStale = () => hash !== window.location.hash;
this._item = undefined;
this._readme = undefined;
this._updated = undefined;
this._heroFailed = false;
this._error = undefined;

const result = await fetchMarketplace({ origin: window.location.origin });
if (isStale()) return;
if (result.error) {
this._error = result.error;
return;
}

const item = findItemByHash({ items: result.items, hash });
const item = findItem({ items: result.items, docHref: getDocHref(window.location) });
this._item = item ?? null;
if (!item) return;

const source = getReadmeSource(item.docHref);
this._loadUpdated({ item, source, isStale });
await this._loadReadme({ source, isStale });
this._loadUpdated({ item, source });
await this._loadReadme({ source });
}

// `_install` stays undefined (nothing shown) without a site or an install url.
async _loadInstall() {
this._install = undefined;
await this._ready;
const site = this._site;
const target = this._item && getInstallTarget(this._item);
if (!site || !target) return;
const state = await loadInstallState(site);
if (site !== this._site || state.error) return;
this._install = this._withInstalled({ ...state, ...target });
}

_withInstalled(state) {
return { ...state, installed: isInstalled({ ...state, title: this._item.title }) };
}

// The whole config is written back, so it is re-read right before saving: edits made since the
// page loaded are kept, and nothing is saved if the extension got installed in the meantime.
async _onInstall() {
if (this._installing) return;
const site = this._site;
const { sheet, path } = this._install;
this._installing = true;
const result = await this._saveInstall({ site, sheet, path });
this._installing = false;
const { showToast, VARIANT_ERROR } = await import('../shared/toast/toast.js');
if (result.error) {
showToast({ text: `${result.error} (${site.site})`, variant: VARIANT_ERROR });
return;
}
if (site !== this._site) return;
this._install = result.install;
if (result.saved) showToast({ text: `${this._item.title} was installed on ${site.site}.` });
}

async _saveInstall({ site, sheet, path }) {
const state = await loadInstallState(site);
if (state.error) return state;
const current = this._withInstalled({ ...state, sheet, path });
if (current.installed) return { install: current };
const row = getInstallRow({ item: this._item, sheet });
const json = addInstallRow({ json: current.json, sheet, row });
const saved = await saveInstall({ ...site, json });
if (saved.error) return saved;
// Trust what was just saved rather than re-reading a config that may not be updated yet.
return { install: { ...current, json, installed: true }, saved: true };
}

async _loadUpdated({ item, source, isStale }) {
async _loadUpdated({ item, source }) {
const { date } = await fetchLastCommitDate(source);
if (isStale()) return;
this._updated = formatDate(date) ?? formatDate(item.date) ?? null;
}

async _loadReadme({ source, isStale }) {
async _loadReadme({ source }) {
const readme = await fetchReadme(source);
if (isStale()) return;
if (readme.error) {
this._error = README_ERROR;
return;
}
const fragment = await renderReadme({ text: readme.text, ...source }).catch(() => undefined);
if (isStale()) return;
if (!fragment) {
this._error = README_ERROR;
return;
Expand All @@ -116,7 +174,8 @@ class NxMarketplaceDetails extends LitElement {
}

_renderBack() {
return html`<a class="back" href=${getParentPath(window.location.pathname)}>${CHEVRON}Back</a>`;
const href = `${getParentPath(window.location.pathname)}${this._site ? `#${this._site.fullpath}` : ''}`;
return html`<a class="back" href=${href}>${CHEVRON}Back</a>`;
}

_hasHero({ imageHref }) {
Expand Down Expand Up @@ -145,15 +204,28 @@ class NxMarketplaceDetails extends LitElement {
`;
}

_renderInstall() {
const { installed, canWrite } = this._install ?? {};
if (!canWrite || installed) return nothing;
return html`<button
type="button"
class="nx-btn-accent"
?disabled=${this._installing}
@click=${this._onInstall}
>Install</button>`;
}

_renderHeader(item) {
return html`
<div class="header ${this._hasHero(item) ? '' : 'no-hero'}">
${this._hasHero(item) ? this._renderHero(item) : nothing}
<div class="info">
<h1>${item.title}</h1>
${this._install?.installed ? html`<p class="installed">${CHECK}Installed</p>` : nothing}
${item.status ? html`<p class="status">${item.status}</p>` : nothing}
${item.description ? html`<p class="description">${item.description}</p>` : nothing}
<div class="actions">
${this._renderInstall()}
<a
class="action nx-btn-outline"
href=${item.docHref}
Expand Down
96 changes: 96 additions & 0 deletions nx2/blocks/marketplace/marketplace-install.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Reads and writes the site config sheets an extension is installed into
// (`library` for plugins, `apps` for apps). Pure helpers first, network last.
import { config } from '../../utils/api.js';
import { toUrl } from './marketplace-readme.js';

const LOAD_ERROR = 'Could not load site config.';
const SAVE_ERROR = 'Could not install extension.';

const getRows = ({ json, sheet }) => {
if (!json) return [];
const rows = json[':type'] === 'multi-sheet'
? json[sheet]?.data
: json[':sheetname'] === sheet && json.data;
return Array.isArray(rows) ? rows : [];
};

const normalizePath = (value) => {
const trimmed = String(value ?? '').trim();
return (toUrl(trimmed)?.href ?? trimmed).replace(/\/$/, '');
};

// The site config editor identifies rows by name ("My Tool" = "my tool"), so a row with the
// same name counts as installed too; adding it again would create an invalid duplicate.
const nameOf = (title) => String(title ?? '').trim().toLowerCase().replaceAll(' ', '-');

export function isInstalled({
json, sheet, path, title,
}) {
const target = normalizePath(path);
const name = title && nameOf(title);
return getRows({ json, sheet })
.some((row) => normalizePath(row.path) === target || (name && nameOf(row.title) === name));
}

// Column names follow the site config editor: apps use `image`, library plugins `icon`.
export function getInstallRow({ item, sheet }) {
const iconKey = sheet === 'library' ? 'icon' : 'image';
return {
title: item.title,
path: item.tryHref,
...(item.iconHref && { [iconKey]: item.iconHref }),
};
}

const sheetOf = (data) => ({
total: data.length, limit: data.length, offset: 0, data,
});

const emptyConfig = () => ({ ':names': [], ':version': 3, ':type': 'multi-sheet' });

// A single-sheet config becomes a multi-sheet so the new sheet can sit next to it.
const toMultiSheet = (json) => {
if (!json) return emptyConfig();
if (json[':type'] === 'multi-sheet') return structuredClone(json);
const {
':sheetname': name = 'data', ':type': _, ':private': priv, ...rest
} = structuredClone(json);
return {
[name]: rest,
':names': [name],
':version': 3,
':type': 'multi-sheet',
...(priv && { ':private': priv }),
};
};

// Returns a copy with the row appended; a missing sheet is added after the existing ones.
export function addInstallRow({ json, sheet, row }) {
const result = toMultiSheet(json);
const rows = [...getRows({ json: result, sheet }), row];
if (!result[sheet]) result[':names'] = [...result[':names'], sheet];
result[sheet] = { ...result[sheet], ...sheetOf(rows) };
return result;
}

export async function loadInstallState({ org, site }) {
try {
const resp = await config.get({ org, site, cachebust: true });
const canWrite = Boolean(resp.permissions?.includes('write'));
if (resp.status === 404) return { json: null, canWrite };
if (!resp.ok) return { error: LOAD_ERROR, status: resp.status };
return { json: await resp.json(), canWrite };
} catch {
return { error: LOAD_ERROR };
}
}

export async function saveInstall({ org, site, json }) {
try {
const resp = await config.save({ org, site, body: JSON.stringify(json) });
if (!resp.ok) return { error: SAVE_ERROR, status: resp.status };
return { ok: true };
} catch {
return { error: SAVE_ERROR };
}
}
Loading
Loading