diff --git a/nx2/blocks/marketplace-details/marketplace-details.css b/nx2/blocks/marketplace-details/marketplace-details.css index eb3e3f777..fa0fb3523 100644 --- a/nx2/blocks/marketplace-details/marketplace-details.css +++ b/nx2/blocks/marketplace-details/marketplace-details.css @@ -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); diff --git a/nx2/blocks/marketplace-details/marketplace-details.js b/nx2/blocks/marketplace-details/marketplace-details.js index 2b4403923..c9545a1ee 100644 --- a/nx2/blocks/marketplace-details/marketplace-details.js +++ b/nx2/blocks/marketplace-details/marketplace-details.js @@ -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, @@ -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=` (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` @@ -45,6 +56,11 @@ const CHEVRON = html` `; +const CHECK = html``; + class NxMarketplaceDetails extends LitElement { static properties = { _item: { state: true }, @@ -52,62 +68,104 @@ class NxMarketplaceDetails extends LitElement { _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; @@ -116,7 +174,8 @@ class NxMarketplaceDetails extends LitElement { } _renderBack() { - return html`${CHEVRON}Back`; + const href = `${getParentPath(window.location.pathname)}${this._site ? `#${this._site.fullpath}` : ''}`; + return html`${CHEVRON}Back`; } _hasHero({ imageHref }) { @@ -145,15 +204,28 @@ class NxMarketplaceDetails extends LitElement { `; } + _renderInstall() { + const { installed, canWrite } = this._install ?? {}; + if (!canWrite || installed) return nothing; + return html``; + } + _renderHeader(item) { return html`
${this._hasHero(item) ? this._renderHero(item) : nothing}

${item.title}

+ ${this._install?.installed ? html`

${CHECK}Installed

` : nothing} ${item.status ? html`

${item.status}

` : nothing} ${item.description ? html`

${item.description}

` : nothing}
+ ${this._renderInstall()} { + 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 }; + } +} diff --git a/nx2/blocks/marketplace/marketplace-utils.js b/nx2/blocks/marketplace/marketplace-utils.js index 4639aca12..eb828a4b6 100644 --- a/nx2/blocks/marketplace/marketplace-utils.js +++ b/nx2/blocks/marketplace/marketplace-utils.js @@ -23,9 +23,10 @@ export function normalizeItem({ row, origin }) { const imageHref = toSafeHref({ value: row.Image, origin }); const status = (row.Status ?? '').trim(); const date = (row.Date ?? '').trim(); + const type = (row.Type ?? '').trim(); return { - title, description, docHref, tryHref, category, iconHref, imageHref, status, date, + title, description, docHref, tryHref, category, iconHref, imageHref, status, date, type, }; } @@ -56,16 +57,25 @@ export function getVisibleItems({ items, filter, query }) { return searchItems({ items: filterByCategory({ items, filter }), query }); } -// GitHub READMEs render on a details page below the list page: -// `/marketplace` -> `/marketplace/details#`. -export function getDetailsHref({ docHref, listPath = '' }) { +// GitHub READMEs render on a details page below the list page, keeping the site hash: +// `/marketplace#/org/site` -> `/marketplace/details?ext=#/org/site`. +export function getDetailsHref({ docHref, listPath = '', fullpath }) { if (!getReadmeSource(docHref)) return undefined; - return `${listPath.replace(/\/$/, '')}/details#${docHref}`; + // `:` and `/` are valid in a query value; leaving them keeps the url readable. + const ext = encodeURIComponent(docHref).replaceAll('%3A', ':').replaceAll('%2F', '/'); + const hash = fullpath ? `#${fullpath}` : ''; + return `${listPath.replace(/\/$/, '')}/details?ext=${ext}${hash}`; } -function getDetailsAction({ docHref, listPath }) { +// Where an extension gets installed in the site config. `Try Url` doubles as install url for now. +export function getInstallTarget({ type, tryHref }) { + if (!tryHref) return undefined; + return { sheet: type?.trim().toLowerCase() === 'plugin' ? 'library' : 'apps', path: tryHref }; +} + +function getDetailsAction({ docHref, listPath, fullpath }) { if (!docHref) return undefined; - const detailsHref = getDetailsHref({ docHref, listPath }); + const detailsHref = getDetailsHref({ docHref, listPath, fullpath }); return { id: 'details', label: 'View details', href: detailsHref ?? docHref, external: !detailsHref, }; @@ -73,9 +83,9 @@ function getDetailsAction({ docHref, listPath }) { // List rows: View details last (rightmost). Grid cards: View details first. export function getActions({ - docHref, tryHref, view = 'list', listPath, + docHref, tryHref, view = 'list', listPath, fullpath, }) { - const details = getDetailsAction({ docHref, listPath }); + const details = getDetailsAction({ docHref, listPath, fullpath }); const tryOut = tryHref && { id: 'try', label: 'Try out', href: tryHref, external: true, }; diff --git a/nx2/blocks/marketplace/marketplace.js b/nx2/blocks/marketplace/marketplace.js index 924b2638b..3688d5856 100644 --- a/nx2/blocks/marketplace/marketplace.js +++ b/nx2/blocks/marketplace/marketplace.js @@ -1,7 +1,7 @@ import { LitElement, html, nothing } from 'da-lit'; import { getConfig } from '../../scripts/nx.js'; -import { loadStyle } from '../../utils/utils.js'; +import { hashChange, loadStyle } from '../../utils/utils.js'; import { fetchMarketplace, getActions, @@ -34,10 +34,13 @@ class NxMarketplace extends LitElement { _filter: { state: true }, _query: { state: true }, _view: { state: true }, + _fullpath: { state: true }, }; connectedCallback() { super.connectedCallback(); + // The site (`#/org/site`) travels on to the details page. + this._unsubscribeHash = hashChange.subscribe((state) => { this._fullpath = state?.fullpath; }); this.shadowRoot.adoptedStyleSheets = [buttonStyle, style]; this._failedIconHrefs ??= new Set(); this._filter ??= 'all'; @@ -48,6 +51,11 @@ class NxMarketplace extends LitElement { } } + disconnectedCallback() { + this._unsubscribeHash?.(); + super.disconnectedCallback(); + } + async _load() { const result = await fetchMarketplace({ origin: window.location.origin }); if (result.error) { @@ -86,7 +94,9 @@ class NxMarketplace extends LitElement { _renderActions(item) { return html`
- ${getActions({ ...item, view: this._view, listPath: window.location.pathname }) + ${getActions({ + ...item, view: this._view, listPath: window.location.pathname, fullpath: this._fullpath, + }) .map(({ label, href, external }) => html` { +describe('getDocHref', () => { + it('reads the ext query parameter', () => { + expect(getDocHref({ search: `?x=1&ext=${TRELLO}`, hash: '#/org/site' })).to.equal(TRELLO); + expect(getDocHref({ search: `?ext=${encodeURIComponent(TRELLO)}`, hash: '' })).to.equal(TRELLO); + }); + + it('still reads old links that carried the doc url as hash', () => { + expect(getDocHref({ search: '', hash: `#${TRELLO}` })).to.equal(TRELLO); + expect(getDocHref({ search: '', hash: `#${encodeURIComponent(TRELLO)}` })).to.equal(TRELLO); + }); + + it('returns undefined without a doc url', () => { + [{ search: '', hash: '' }, { search: '', hash: '#/org/site' }, { search: '', hash: '#%E0%A4%A' }] + .forEach((location) => expect(getDocHref(location), location.hash).to.equal(undefined)); + }); +}); + +describe('findItem', () => { const items = [ { title: 'Trello', docHref: `${TRELLO}/` }, { title: 'Docs', docHref: 'https://www.aem.live/docs' }, ]; - it('matches plain, encoded and slash variants of a doc url', () => { - [`#${TRELLO}`, `#${TRELLO}/`, `#${encodeURIComponent(TRELLO)}`].forEach((hash) => { - expect(findItemByHash({ items, hash })?.title, hash).to.equal('Trello'); + it('matches a doc url with or without a trailing slash', () => { + [TRELLO, `${TRELLO}/`].forEach((docHref) => { + expect(findItem({ items, docHref })?.title, docHref).to.equal('Trello'); }); }); - it('returns undefined for empty, malformed, unknown and non-GitHub hashes', () => { - ['', '#', '#%E0%A4%A', '#https://github.com/o/other', '#https://www.aem.live/docs'].forEach((hash) => { - expect(findItemByHash({ items, hash }), hash).to.equal(undefined); + it('returns undefined for missing, unknown and non-GitHub doc urls', () => { + [undefined, '', 'https://github.com/o/other', 'https://www.aem.live/docs'].forEach((docHref) => { + expect(findItem({ items, docHref }), docHref).to.equal(undefined); }); }); }); @@ -61,8 +81,12 @@ describe('nx-marketplace-details', () => { await el.updateComplete; } - function mount(hash) { - window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}${hash}`); + // `ext` holds the doc url, the hash the site, e.g. `?ext=#/org/site`. + function mount(docHref, site = '') { + const url = new URL(window.location.href); + url.searchParams.set('ext', docHref); + url.hash = site; + window.history.replaceState(null, '', url.href); div = document.createElement('div'); div.innerHTML = '
ignored
'; document.body.append(div); @@ -70,13 +94,31 @@ describe('nx-marketplace-details', () => { return div.firstElementChild; } + let siteConfig; + let configStatus; + let configActions; + let saved; + beforeEach(() => { resetMarketplaceCache(); readmeStatus = 200; commitStatus = 200; + siteConfig = { ':type': 'sheet', ':sheetname': 'data', data: [] }; + configStatus = 200; + configActions = 'read,write'; + saved = []; origFetch = window.fetch; - window.fetch = async (url, opts) => { + window.fetch = async (url, opts = {}) => { const href = String(url); + if (href.startsWith(`${HLX_ADMIN}/ping/`)) return new Response('', { status: 200 }); + if (href.startsWith(`${DA_ADMIN}/config/o/s/`)) { + const headers = { 'x-da-actions': `/o/s/=${configActions}` }; + if (opts.method === 'PUT') { + saved.push(JSON.parse(opts.body.get('config'))); + return new Response('', { status: configStatus, headers }); + } + return new Response(JSON.stringify(siteConfig), { status: 200, headers }); + } if (new URL(href, window.location.origin).pathname === MARKETPLACE_PATH) { return new Response(JSON.stringify({ data: ROWS }), { status: 200 }); } @@ -93,18 +135,21 @@ describe('nx-marketplace-details', () => { afterEach(() => { window.fetch = origFetch; div?.remove(); - window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}`); + const url = new URL(window.location.href); + url.searchParams.delete('ext'); + url.hash = ''; + window.history.replaceState(null, '', url.href); }); it('replaces the block content with the element', () => { - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); expect(el.tagName).to.equal('NX-MARKETPLACE-DETAILS'); expect(div.children.length).to.equal(1); expect(div.style.display).to.equal('contents'); }); it('renders the sheet row as header and the README below', async () => { - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); const { shadowRoot } = el; expect(shadowRoot.querySelector('.hero').getAttribute('src')).to.equal(HERO); @@ -134,7 +179,7 @@ describe('nx-marketplace-details', () => { } it('lists creator, category and last commit date', async () => { - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); await waitForMeta(el, 'Updated'); expect(getMeta(el)).to.deep.equal([ @@ -146,14 +191,14 @@ describe('nx-marketplace-details', () => { it('falls back to the sheet date when GitHub limits the request', async () => { commitStatus = 403; - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); await waitForMeta(el, 'Updated'); expect(getMeta(el).at(-1)).to.deep.equal(['Updated', 'Oct 1, 2026']); }); it('hides rows and the hero it has no data for', async () => { - const el = mount(`#${MSM}`); + const el = mount(MSM); await waitForRender(el); expect(el.shadowRoot.querySelector('.hero')).to.equal(null); expect(el.shadowRoot.querySelector('.status')).to.equal(null); @@ -161,7 +206,7 @@ describe('nx-marketplace-details', () => { }); it('hides the hero when the image fails to load', async () => { - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); el.shadowRoot.querySelector('.hero').dispatchEvent(new Event('error')); await el.updateComplete; @@ -169,7 +214,7 @@ describe('nx-marketplace-details', () => { }); it('links back to the parent page', async () => { - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); const parent = window.location.pathname.replace(/\/[^/]*\/?$/, '') || '/'; const back = el.shadowRoot.querySelector('.back'); @@ -178,7 +223,7 @@ describe('nx-marketplace-details', () => { }); it('shows not found for a url that is not in the marketplace', async () => { - const el = mount('#https://github.com/evil/phish'); + const el = mount('https://github.com/evil/phish'); await waitForRender(el); expect(el.shadowRoot.querySelector('.error').textContent.trim()).to.equal('Extension not found.'); expect(el.shadowRoot.querySelector('h1')).to.equal(null); @@ -187,24 +232,145 @@ describe('nx-marketplace-details', () => { it('keeps the header and links to GitHub when the README fails', async () => { readmeStatus = 404; - const el = mount(`#${TRELLO}`); + const el = mount(TRELLO); await waitForRender(el); expect(el.shadowRoot.querySelector('h1').textContent.trim()).to.equal('Trello'); expect(el.shadowRoot.querySelector('.error').textContent.trim()).to.equal('Could not load the README.'); expect(el.shadowRoot.querySelector('.readme')).to.equal(null); }); - it('re-renders when the hash changes', async () => { - const el = mount(`#${TRELLO}`); + it('still renders old links with the doc url as hash', async () => { + const url = new URL(window.location.href); + url.hash = TRELLO; + window.history.replaceState(null, '', url.href); + div = document.createElement('div'); + document.body.append(div); + init(div); + const el = div.firstElementChild; await waitForRender(el); - window.history.replaceState(null, '', `${window.location.pathname}#${MSM}`); - window.dispatchEvent(new HashChangeEvent('hashchange')); - await waitForRender(el, '.readme h2'); - for (let i = 0; i < 100 && el.shadowRoot.querySelector('h1')?.textContent.trim() !== 'MSM'; i += 1) { + expect(el.shadowRoot.querySelector('.info h1').textContent.trim()).to.equal('Trello'); + }); + + const installButton = (el) => [...el.shadowRoot.querySelectorAll('.actions button')] + .find((b) => b.textContent.trim() === 'Install'); + // Booleans keep failure reports small; serializing a DOM node can crash the test browser. + const hasInstall = (el) => Boolean(installButton(el)); + const isShownInstalled = (el) => Boolean(el.shadowRoot.querySelector('.installed')); + + async function waitFor(el, check) { + for (let i = 0; i < 100 && !check(); i += 1) { // eslint-disable-next-line no-await-in-loop await new Promise((resolve) => { setTimeout(resolve, 10); }); + // eslint-disable-next-line no-await-in-loop + await el.updateComplete; } - expect(el.shadowRoot.querySelector('h1').textContent.trim()).to.equal('MSM'); - expect(el.shadowRoot.querySelector('.readme h2').textContent).to.equal('Usage'); + } + + it('shows installed when the try url is in the apps sheet of the site', async () => { + siteConfig = { + ':type': 'multi-sheet', ':names': ['apps'], apps: { data: [{ title: 'Trello', path: 'https://example.com/try' }] }, + }; + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => el.shadowRoot.querySelector('.installed')); + expect(el.shadowRoot.querySelector('.installed').textContent.trim()).to.equal('Installed'); + expect(hasInstall(el)).to.equal(false); + }); + + it('installs into the apps sheet with name, url and icon', async () => { + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => installButton(el)); + installButton(el).click(); + await waitFor(el, () => el.shadowRoot.querySelector('.installed')); + expect(saved).to.have.length(1); + expect(saved[0].apps.data).to.deep.equal([{ title: 'Trello', path: 'https://example.com/try', image: HERO }]); + expect(saved[0].data.data).to.deep.equal([]); + expect(hasInstall(el)).to.equal(false); + }); + + it('installs into the latest config, keeping changes made after the page loaded', async () => { + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => installButton(el)); + siteConfig = { + ':type': 'multi-sheet', ':names': ['data'], data: { data: [{ key: 'added-later', value: '1' }] }, + }; + installButton(el).click(); + await waitFor(el, () => isShownInstalled(el)); + expect(saved).to.have.length(1); + expect(saved[0].data.data).to.deep.equal([{ key: 'added-later', value: '1' }]); + expect(saved[0].apps.data).to.have.length(1); + }); + + it('does not save when the extension was installed in the meantime', async () => { + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => installButton(el)); + siteConfig = { + ':type': 'multi-sheet', ':names': ['apps'], apps: { data: [{ title: 'Trello', path: 'https://example.com/try' }] }, + }; + installButton(el).click(); + await waitFor(el, () => isShownInstalled(el)); + expect(saved).to.have.length(0); + expect(isShownInstalled(el)).to.equal(true); + }); + + it('saves to the site it was clicked on, even if the site changes meanwhile', async () => { + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => installButton(el)); + installButton(el).click(); + const url = new URL(window.location.href); + url.hash = '/o/other'; + window.history.replaceState(null, '', url.href); + window.dispatchEvent(new HashChangeEvent('hashchange')); + await waitFor(el, () => saved.length); + expect(saved).to.have.length(1); + expect(isShownInstalled(el)).to.equal(false); + }); + + it('keeps the install button when saving fails', async () => { + configStatus = 500; + const el = mount(TRELLO, '#/o/s'); + await waitForRender(el); + await waitFor(el, () => installButton(el)); + installButton(el).click(); + await waitFor(el, () => saved.length && !installButton(el)?.disabled); + expect(isShownInstalled(el)).to.equal(false); + expect(hasInstall(el)).to.equal(true); + }); + + it('hides install without write access, a site or an install url', async () => { + configActions = 'read'; + const readOnly = mount(TRELLO, '#/o/s'); + await waitForRender(readOnly); + await new Promise((resolve) => { setTimeout(resolve, 50); }); + expect(hasInstall(readOnly)).to.equal(false); + div.remove(); + + configActions = 'read,write'; + const noSite = mount(TRELLO); + await waitForRender(noSite); + await new Promise((resolve) => { setTimeout(resolve, 50); }); + expect(hasInstall(noSite)).to.equal(false); + div.remove(); + + const noTryUrl = mount(MSM, '#/o/s'); + await waitForRender(noTryUrl); + await new Promise((resolve) => { setTimeout(resolve, 50); }); + expect(hasInstall(noTryUrl)).to.equal(false); + }); + + it('updates the install state when the site changes', async () => { + const el = mount(TRELLO); + await waitForRender(el); + expect(hasInstall(el)).to.equal(false); + const url = new URL(window.location.href); + url.hash = '/o/s'; + window.history.replaceState(null, '', url.href); + window.dispatchEvent(new HashChangeEvent('hashchange')); + await waitFor(el, () => installButton(el)); + expect(hasInstall(el)).to.equal(true); }); }); diff --git a/test/nx2/blocks/marketplace/marketplace-install.test.js b/test/nx2/blocks/marketplace/marketplace-install.test.js new file mode 100644 index 000000000..1f4b9925d --- /dev/null +++ b/test/nx2/blocks/marketplace/marketplace-install.test.js @@ -0,0 +1,177 @@ +import { expect } from '@esm-bundle/chai'; +import { DA_ADMIN } from '../../../../nx2/utils/utils.js'; +import { + calls, installFetch, restoreFetch, lastCall, +} from '../../mocks/fetch.js'; +import { + isInstalled, + addInstallRow, + getInstallRow, + loadInstallState, + saveInstall, +} from '../../../../nx2/blocks/marketplace/marketplace-install.js'; + +const APP = 'https://da.live/app/o/r/tools/apps/msm/msm'; + +const multi = (sheets) => ({ + ...Object.fromEntries(Object.entries(sheets).map(([name, data]) => [name, { + total: data.length, limit: data.length, offset: 0, data, + }])), + ':names': Object.keys(sheets), + ':version': 3, + ':type': 'multi-sheet', +}); + +describe('isInstalled', () => { + const json = multi({ data: [], apps: [{ title: 'MSM', path: ` ${APP}/ ` }] }); + + it('matches the path in the target sheet, ignoring whitespace and a trailing slash', () => { + expect(isInstalled({ json, sheet: 'apps', path: APP })).to.equal(true); + }); + + it('does not match other sheets, other paths or missing config', () => { + expect(isInstalled({ json, sheet: 'library', path: APP })).to.equal(false); + expect(isInstalled({ json, sheet: 'apps', path: `${APP}-other` })).to.equal(false); + expect(isInstalled({ json: null, sheet: 'apps', path: APP })).to.equal(false); + }); + + it('treats an entry with the same name as installed, since the title identifies a row', () => { + const named = multi({ apps: [{ title: ' msm ', path: 'https://other.example/msm' }] }); + expect(isInstalled({ + json: named, sheet: 'apps', path: APP, title: 'MSM', + })).to.equal(true); + }); + + it('reads a single-sheet config whose sheet has the target name', () => { + const single = { ':type': 'sheet', ':sheetname': 'apps', data: [{ path: APP }] }; + expect(isInstalled({ json: single, sheet: 'apps', path: APP })).to.equal(true); + }); +}); + +describe('getInstallRow', () => { + const item = { title: 'MSM', tryHref: APP, iconHref: 'https://da.live/media/msm.png' }; + + it('uses image for apps and icon for library plugins', () => { + expect(getInstallRow({ item, sheet: 'apps' })).to.deep.equal({ title: 'MSM', path: APP, image: item.iconHref }); + expect(getInstallRow({ item, sheet: 'library' })).to.deep.equal({ title: 'MSM', path: APP, icon: item.iconHref }); + }); + + it('leaves the icon out when there is none', () => { + expect(getInstallRow({ item: { title: 'MSM', tryHref: APP }, sheet: 'apps' })).to.deep.equal({ title: 'MSM', path: APP }); + }); +}); + +describe('addInstallRow', () => { + const row = { title: 'MSM', path: APP }; + + it('appends to an existing sheet without touching the input', () => { + const json = multi({ data: [{ key: 'a', value: '1' }], apps: [{ title: 'Other', path: 'x' }] }); + const before = structuredClone(json); + const result = addInstallRow({ json, sheet: 'apps', row }); + expect(json).to.deep.equal(before); + expect(result.apps.data).to.deep.equal([{ title: 'Other', path: 'x' }, row]); + expect(result.apps.total).to.equal(2); + expect(result.data).to.deep.equal(json.data); + }); + + it('keeps private settings and other sheet metadata', () => { + const json = { + ...multi({ data: [{ key: 'a', value: '1' }], apps: [] }), + ':private': { 'private-data': { data: [{ key: 'secret', value: 'x' }] } }, + }; + json.data[':colWidths'] = [100, 200]; + const result = addInstallRow({ json, sheet: 'apps', row }); + expect(result[':private']).to.deep.equal(json[':private']); + expect(result.data[':colWidths']).to.deep.equal([100, 200]); + + const single = { + ':type': 'sheet', ':sheetname': 'data', ':private': { p: 1 }, data: [], + }; + expect(addInstallRow({ json: single, sheet: 'apps', row })[':private']).to.deep.equal({ p: 1 }); + }); + + it('adds a missing sheet after the existing ones', () => { + const json = multi({ data: [{ key: 'a', value: '1' }] }); + const result = addInstallRow({ json, sheet: 'library', row }); + expect(result[':names']).to.deep.equal(['data', 'library']); + expect(result.library.data).to.deep.equal([row]); + }); + + it('turns a single-sheet config into a multi-sheet one, keeping its data', () => { + const json = { + ':type': 'sheet', ':sheetname': 'data', total: 1, limit: 1, offset: 0, data: [{ key: 'a', value: '1' }], + }; + const result = addInstallRow({ json, sheet: 'apps', row }); + expect(result[':type']).to.equal('multi-sheet'); + expect(result[':names']).to.deep.equal(['data', 'apps']); + expect(result.data.data).to.deep.equal([{ key: 'a', value: '1' }]); + expect(result.apps.data).to.deep.equal([row]); + }); + + it('creates a config when the site has none', () => { + const result = addInstallRow({ json: null, sheet: 'apps', row }); + expect(result[':names']).to.deep.equal(['apps']); + expect(result.apps.data).to.deep.equal([row]); + }); +}); + +describe('loadInstallState', () => { + // isHlx6 memoizes per org/site, so each test uses its own site. + let counter = 0; + const site = () => { + counter += 1; + return `site-${counter}`; + }; + afterEach(() => restoreFetch()); + + it('returns the site config and write access', async () => { + const json = multi({ apps: [{ path: APP }] }); + installFetch({ body: JSON.stringify(json), headers: { 'x-da-actions': '/o/s/=read,write' } }); + const s = site(); + const result = await loadInstallState({ org: 'o', site: s }); + expect(result).to.deep.equal({ json, canWrite: true }); + expect(calls.some(({ url }) => url.startsWith(`${DA_ADMIN}/config/o/${s}/`))).to.equal(true); + }); + + it('reports read-only access', async () => { + installFetch({ body: '{}', headers: { 'x-da-actions': '/o/s/=read' } }); + expect((await loadInstallState({ org: 'o', site: site() })).canWrite).to.equal(false); + }); + + it('treats a missing config as empty', async () => { + installFetch({ status: 404, body: '', headers: { 'x-da-actions': '/o/s/=read,write' } }); + expect(await loadInstallState({ org: 'o', site: site() })).to.deep.equal({ json: null, canWrite: true }); + }); + + it('returns an error when the config cannot be read', async () => { + installFetch({ status: 403, body: '' }); + expect(await loadInstallState({ org: 'o', site: site() })) + .to.deep.equal({ error: 'Could not load site config.', status: 403 }); + }); +}); + +describe('saveInstall', () => { + let counter = 0; + const site = () => { + counter += 1; + return `save-${counter}`; + }; + afterEach(() => restoreFetch()); + + it('saves the whole config', async () => { + installFetch({ status: 200 }); + const json = multi({ apps: [{ path: APP }] }); + const s = site(); + expect(await saveInstall({ org: 'o', site: s, json })).to.deep.equal({ ok: true }); + const call = lastCall(); + expect(call.method).to.equal('PUT'); + expect(call.url).to.equal(`${DA_ADMIN}/config/o/${s}/`); + expect(JSON.parse(call.body.get('config'))).to.deep.equal(json); + }); + + it('returns an error when saving fails', async () => { + installFetch({ status: 403 }); + expect(await saveInstall({ org: 'o', site: site(), json: {} })) + .to.deep.equal({ error: 'Could not install extension.', status: 403 }); + }); +}); diff --git a/test/nx2/blocks/marketplace/marketplace-utils.test.js b/test/nx2/blocks/marketplace/marketplace-utils.test.js index 2eb3a36e4..deb8f910f 100644 --- a/test/nx2/blocks/marketplace/marketplace-utils.test.js +++ b/test/nx2/blocks/marketplace/marketplace-utils.test.js @@ -8,6 +8,7 @@ import { getCategoryFilters, getActions, getDetailsHref, + getInstallTarget, searchItems, getVisibleItems, } from '../../../../nx2/blocks/marketplace/marketplace-utils.js'; @@ -33,6 +34,7 @@ describe('normalizeItem', () => { Image: '/media/apps-msm.png', Status: ' Early Access ', Date: ' 2026-10-01 ', + Type: ' App ', }; expect(normalizeItem({ row, origin })).to.deep.equal({ title: 'MSM', @@ -44,6 +46,7 @@ describe('normalizeItem', () => { imageHref: `${origin}/media/apps-msm.png`, status: 'Early Access', date: '2026-10-01', + type: 'App', }); }); @@ -112,9 +115,9 @@ describe('normalizeItem', () => { expect(result.category).to.equal(''); }); - it('ignores the Type column', () => { + it('reads the Type column, which decides the install sheet', () => { const row = { Title: 'MSM', 'Doc Url': 'https://da.live/a', Type: 'App & Plugin' }; - expect('type' in normalizeItem({ row, origin })).to.equal(false); + expect(normalizeItem({ row, origin }).type).to.equal('App & Plugin'); }); }); @@ -129,7 +132,7 @@ describe('getActions', () => { it('points GitHub docs at the details page under the list path', () => { const details = { - id: 'details', label: 'View details', href: '/marketplace/details#https://github.com/o/r', external: false, + id: 'details', label: 'View details', href: '/marketplace/details?ext=https://github.com/o/r', external: false, }; expect(getActions({ docHref: 'https://github.com/o/r', listPath: '/marketplace' })).to.deep.equal([details]); expect(getActions({ docHref: 'https://github.com/o/r', listPath: '/marketplace/' })).to.deep.equal([details]); @@ -154,13 +157,40 @@ describe('getActions', () => { }); describe('getDetailsHref', () => { - it('builds the details href for GitHub README sources only', () => { + it('puts the doc url in ext and keeps the site as hash', () => { expect(getDetailsHref({ docHref: 'https://github.com/o/r', listPath: '/apps/marketplace' })) - .to.equal('/apps/marketplace/details#https://github.com/o/r'); + .to.equal('/apps/marketplace/details?ext=https://github.com/o/r'); + expect(getDetailsHref({ docHref: 'https://github.com/o/r/tree/main/x', listPath: '/marketplace', fullpath: '/org/site' })) + .to.equal('/marketplace/details?ext=https://github.com/o/r/tree/main/x#/org/site'); + }); + + it('escapes characters that would break the query', () => { + const href = getDetailsHref({ docHref: 'https://github.com/o/r/tree/a&b', listPath: '/m' }); + expect(new URL(href, 'https://da.live').searchParams.get('ext')).to.equal('https://github.com/o/r/tree/a&b'); + }); + + it('returns undefined for non-GitHub docs', () => { expect(getDetailsHref({ docHref: 'https://www.aem.live/docs', listPath: '/marketplace' })).to.equal(undefined); }); }); +describe('getInstallTarget', () => { + const tryHref = 'https://da.live/app/o/r/tools/x'; + it('installs plugins into the library sheet and everything else into apps', () => { + expect(getInstallTarget({ type: 'Plugin', tryHref })).to.deep.equal({ sheet: 'library', path: tryHref }); + expect(getInstallTarget({ type: 'App', tryHref })).to.deep.equal({ sheet: 'apps', path: tryHref }); + expect(getInstallTarget({ type: 'App & Plugin', tryHref })).to.deep.equal({ sheet: 'apps', path: tryHref }); + }); + + it('reads the type case-insensitively', () => { + expect(getInstallTarget({ type: ' plugin ', tryHref }).sheet).to.equal('library'); + }); + + it('returns undefined without an install url', () => { + expect(getInstallTarget({ type: 'Plugin' })).to.equal(undefined); + }); +}); + describe('filterByCategory', () => { const items = [ { title: 'A', category: 'Core' }, diff --git a/test/nx2/blocks/marketplace/marketplace.test.js b/test/nx2/blocks/marketplace/marketplace.test.js index dbf605295..93e7ffdc2 100644 --- a/test/nx2/blocks/marketplace/marketplace.test.js +++ b/test/nx2/blocks/marketplace/marketplace.test.js @@ -240,12 +240,30 @@ describe('nx-marketplace', () => { const link = el.shadowRoot.querySelector('.item-actions a'); const listPath = window.location.pathname.replace(/\/$/, ''); - expect(link.getAttribute('href')).to.equal(`${listPath}/details#https://github.com/o/r`); + expect(link.getAttribute('href')).to.equal(`${listPath}/details?ext=https://github.com/o/r`); expect(link.hasAttribute('target')).to.equal(false); expect(link.hasAttribute('rel')).to.equal(false); expect(link.getAttribute('aria-label')).to.equal('View details: Trello'); }); + it('keeps the current site hash on the details link', async () => { + const { pathname, search } = window.location; + window.history.replaceState(null, '', `${pathname}${search}#/org/site`); + restoreFetch = installFetch(() => jsonResponse({ + data: [{ Title: 'Trello', Description: 'd', 'Doc Url': 'https://github.com/o/r' }], + })); + div = document.createElement('div'); + document.body.append(div); + init(div); + + const el = div.firstElementChild; + await waitForLoad(el); + window.history.replaceState(null, '', `${pathname}${search}`); + + const link = el.shadowRoot.querySelector('.item-actions a'); + expect(link.getAttribute('href')).to.match(/\/details\?ext=https:\/\/github\.com\/o\/r#\/org\/site$/); + }); + it('shows empty message', async () => { restoreFetch = installFetch(() => jsonResponse({ data: [] })); div = document.createElement('div');