diff --git a/README.md b/README.md index 2eb2d1686..a48eb36c0 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,26 @@ src ``` Export your component in `src/index.ts` +### Naming +Custom elements all share one global registry, and that registry is shared with every other script on the host page. Give each element a name specific enough that nothing else would plausibly want it. + +If a component is built from several elements, prefix its parts with the component's own name rather than naming them generically, and keep the file name matching the tag: +``` +src +- elements + - ia-foobar + - ia-foobar.ts // ia-foobar + - ia-foobar-list-item.ts // ia-foobar-list-item, not ia-list-item +``` +Declare each element in `HTMLElementTagNameMap` so `querySelector` is typed and a mistyped tag in a template is caught at build time: +```ts +declare global { + interface HTMLElementTagNameMap { + 'ia-foobar-list-item': IAFoobarListItem; + } +} +``` + ### Story To demo your component, we have a component catalog that you can add your demo to. Create a component in your component directory. Name it `COMPONENT-NAME-story.ts`, ie `ia-button-story.ts`. diff --git a/demo/story-components/story-styles-settings.test.ts b/demo/story-components/story-styles-settings.test.ts index cb7b94393..27aa65518 100644 --- a/demo/story-components/story-styles-settings.test.ts +++ b/demo/story-components/story-styles-settings.test.ts @@ -5,6 +5,7 @@ import { html } from 'lit'; import type { StoryStylesSettings, StyleInputData, + StylePalette, } from './story-styles-settings'; import './story-styles-settings'; @@ -24,6 +25,18 @@ function getInput(el: StoryStylesSettings, id: string): HTMLInputElement { return input as HTMLInputElement; } +/** Finds one of the panel's action buttons by its visible label. */ +function button(el: StoryStylesSettings, label: string): HTMLButtonElement { + const match = [...(el.shadowRoot?.querySelectorAll('button') ?? [])].find( + (b) => b.textContent?.includes(label), + ); + expect(match, `button "${label}" should exist`).to.exist; + return match as HTMLButtonElement; +} + +const randomizeButton = (el: StoryStylesSettings) => button(el, 'Randomize'); +const revertButton = (el: StoryStylesSettings) => button(el, 'Revert'); + describe('StoryStylesSettings', () => { describe('range inputs', () => { const rangeData: StyleInputData = { @@ -78,6 +91,28 @@ describe('StoryStylesSettings', () => { expect(readout?.textContent).to.equal('200px'); }); + test('the panel still re-renders after the readout has updated', async () => { + const el = await makeSettings(rangeData); + const input = getInput(el, 'foos'); + + input.value = '200'; + input.dispatchEvent(new Event('input')); + await el.updateComplete; + + // Writing to the readout imperatively would eject Lit's markers, so + // every later re-render of the panel would throw. + el.requestUpdate(); + await el.updateComplete; + + expect(el.shadowRoot?.querySelectorAll('.style-input')).to.have.lengthOf( + 1, + ); + expect( + el.shadowRoot?.querySelector('output.style-readout') + ?.textContent, + ).to.equal('200px'); + }); + test('readout omits unit when unit is not provided', async () => { const el = await makeSettings({ settings: [ @@ -156,6 +191,41 @@ describe('StoryStylesSettings', () => { expect(input.hasAttribute('step')).to.be.false; }); + test('leaves the panel untouched when a story opts into nothing', async () => { + const el = await makeSettings({ + settings: [ + { + label: 'Ink', + cssVariable: '--ink', + defaultValue: '#ffffff', + inputType: 'color', + }, + ], + }); + + // Stories that ask for no extras must render exactly as before, so + // adding these controls for one component does not alter every demo. + const buttons = [ + ...(el.shadowRoot?.querySelectorAll('button') ?? []), + ].map((b) => b.textContent?.trim()); + expect(buttons).to.deep.equal(['Apply']); + expect(el.shadowRoot?.querySelector('.style-var')).to.not.exist; + expect(el.shadowRoot?.querySelector('.applied-palette')).to.not.exist; + }); + + test('shows the CSS variable only when the story asks for it', async () => { + const withVars = await makeSettings({ + showCssVariables: true, + settings: [ + { label: 'Ink', cssVariable: '--ink', defaultValue: '#ffffff' }, + ], + }); + + expect( + withVars.shadowRoot?.querySelector('.style-var')?.textContent, + ).to.contain('--ink'); + }); + test('input without inputType defaults to type=text', async () => { const el = await makeSettings({ settings: [ @@ -171,4 +241,157 @@ describe('StoryStylesSettings', () => { expect(input.type).to.equal('text'); }); }); + + describe('palettes', () => { + const PALETTES: StylePalette[] = [ + { + name: 'Midnight', + values: { '--ink': '#e0e6ed', '--paper': '#1b263b' }, + }, + { + name: 'Forest', + values: { '--ink': '#e8f5e9', '--paper': '#14301a' }, + }, + ]; + + const paletteData: StyleInputData = { + revertable: true, + settings: [ + { + label: 'Ink', + cssVariable: '--ink', + defaultValue: '#ffffff', + inputType: 'color', + }, + { + label: 'Paper', + cssVariable: '--paper', + defaultValue: '#000000', + inputType: 'color', + }, + { label: 'Width', cssVariable: '--width', defaultValue: '10px' }, + ], + palettes: PALETTES, + }; + + /** The palette whose values currently fill the inputs, if any. */ + function activePalette(el: StoryStylesSettings): StylePalette | undefined { + return PALETTES.find( + (p) => + getInput(el, 'ink').value === p.values['--ink'] && + getInput(el, 'paper').value === p.values['--paper'], + ); + } + + test('applies one whole palette rather than unrelated colors', async () => { + const el = await makeSettings(paletteData); + const applied = new Promise((resolve) => { + el.addEventListener('stylesApplied', (e) => resolve(e as CustomEvent), { + once: true, + }); + }); + + randomizeButton(el).click(); + + // Every color came from the same palette — that coordination is what + // keeps the foreground/background pairings legible. + const palette = activePalette(el); + expect(palette, 'inputs should match exactly one palette').to.exist; + + // The non-color input is left alone so the layout holds still. + expect(getInput(el, 'width').value).to.equal('10px'); + + // The palette is applied, not just staged in the inputs. + const styles = (await applied).detail.styles as string; + expect(styles).to.contain(`--ink: ${palette?.values['--ink']}`); + expect(styles).to.contain(`--paper: ${palette?.values['--paper']}`); + }); + + test('names the theme it applied', async () => { + const el = await makeSettings(paletteData); + + randomizeButton(el).click(); + await el.updateComplete; + + const readout = + el.shadowRoot?.querySelector('.applied-palette')?.textContent; + expect(readout).to.contain(activePalette(el)?.name); + }); + + test('never applies the same theme twice in a row', async () => { + const el = await makeSettings(paletteData); + let previous: string | undefined; + + // Each click must visibly change something, otherwise the control looks + // broken. + for (let i = 0; i < 6; i++) { + randomizeButton(el).click(); + await el.updateComplete; + const current = activePalette(el)?.name; + expect(current, `click ${i + 1} should apply a palette`).to.exist; + expect( + current, + `click ${i + 1} repeated the previous theme`, + ).to.not.equal(previous); + previous = current; + } + }); + + test('reverting clears both the colors and the theme name', async () => { + const el = await makeSettings(paletteData); + + randomizeButton(el).click(); + await el.updateComplete; + expect(el.shadowRoot?.querySelector('.applied-palette')).to.exist; + + revertButton(el).click(); + await el.updateComplete; + + expect(getInput(el, 'ink').value).to.equal('#ffffff'); + expect(getInput(el, 'paper').value).to.equal('#000000'); + expect(el.shadowRoot?.querySelector('.applied-palette')).to.not.exist; + }); + + test('survives repeated randomize/revert cycles', async () => { + const el = await makeSettings(paletteData); + + // Re-rendering must not disturb the settings rows. Interpolating + // straight into lets the parser hoist them into an implicit + // tbody, ejecting Lit's markers and throwing on the next update. + for (let i = 0; i < 3; i++) { + randomizeButton(el).click(); + await el.updateComplete; + revertButton(el).click(); + await el.updateComplete; + } + + expect(el.shadowRoot?.querySelectorAll('.style-input')).to.have.lengthOf( + 3, + ); + expect(el.shadowRoot?.querySelector('.applied-palette')).to.not.exist; + expect(getInput(el, 'ink').value).to.equal('#ffffff'); + }); + + test('offers randomize only alongside palettes, and revert only on request', async () => { + const revertOnly = await makeSettings({ + revertable: true, + settings: [ + { + label: 'Ink', + cssVariable: '--ink', + defaultValue: '#ffffff', + inputType: 'color', + }, + ], + }); + + const buttons = [ + ...(revertOnly.shadowRoot?.querySelectorAll('button') ?? []), + ].map((b) => b.textContent?.trim()); + // Color inputs alone are not enough — without themes there is nothing + // coherent to swap in. + expect(buttons.some((b) => b?.includes('Randomize'))).to.be.false; + expect(buttons.some((b) => b?.includes('Revert'))).to.be.true; + }); + }); }); diff --git a/demo/story-components/story-styles-settings.ts b/demo/story-components/story-styles-settings.ts index 15bd285b6..c35f3f1ae 100644 --- a/demo/story-components/story-styles-settings.ts +++ b/demo/story-components/story-styles-settings.ts @@ -6,9 +6,10 @@ import { type CSSResultGroup, type TemplateResult, } from 'lit'; -import { property, queryAll } from 'lit/decorators.js'; +import { property, queryAll, state } from 'lit/decorators.js'; import { customElement } from 'lit/decorators/custom-element.js'; import { ifDefined } from 'lit/directives/if-defined.js'; +import { when } from 'lit/directives/when.js'; import themeStyles from '@src/themes/theme-styles'; import { labelToId } from '../story-utils'; @@ -26,8 +27,32 @@ export type StyleInputSettings = { unit?: string; }; +/** + * A named set of coordinated color values, keyed by CSS custom property. + * Supplying these lets the randomize control swap in a whole coherent theme + * instead of assigning each color independently — which keeps every + * foreground/background pairing legible. + */ +export type StylePalette = { + name: string; + values: Record; +}; + export type StyleInputData = { settings: StyleInputSettings[]; + + /** + * Alternate themes. Supplying them adds a control that swaps between them, + * which is a quick way to check that every part of a component follows its + * color knobs. + */ + palettes?: StylePalette[]; + + /** Adds a control that restores this story's default styling. */ + revertable?: boolean; + + /** Shows the CSS custom property each control sets, beside it. */ + showCssVariables?: boolean; }; /** @@ -37,6 +62,12 @@ export type StyleInputData = { export class StoryStylesSettings extends LitElement { @property({ type: Object }) styleInputData?: StyleInputData; + /** Name of the palette currently showing, if any. */ + @state() private appliedPaletteName?: string; + + /** Live range-slider readouts, keyed by CSS variable. */ + @state() private rangeReadouts: Record = {}; + @queryAll('.style-input') private styleInputs?: NodeListOf; @@ -46,15 +77,95 @@ export class StoryStylesSettings extends LitElement { return html`
- ${this.styleInputData.settings.map((input) => - this.renderStyleRow(input), - )} + + + ${this.styleInputData.settings.map((input) => + this.renderStyleRow(input), + )} +
+ ${when( + this.styleInputData.palettes?.length, + () => html` + + `, + )} + ${when( + this.styleInputData.revertable, + () => html``, + )} + ${when( + this.appliedPaletteName, + () => + html`Theme: ${this.appliedPaletteName}`, + )} `; } + /** + * Swaps in one of the story's themes, so a single click reveals any part of + * the component that fails to pick up its color knobs — anything still + * wearing its old color stands out against the rest. + * + * A whole theme is applied at once rather than a color at a time, so the + * foreground/background pairings stay legible. Values the theme does not + * name (sizes, timings) are left alone so the layout holds still. + */ + private randomizeColors(): void { + const palette = this.nextPalette(); + if (!palette) return; + + this.appliedPaletteName = palette.name; + this.styleInputs?.forEach((input) => { + const value = palette.values[input.dataset.variable ?? '']; + if (value) input.value = value; + }); + + this.applyStyles(); + } + + /** + * Picks a palette other than the one already showing, so every click + * visibly changes something. + */ + private nextPalette(): StylePalette | undefined { + const palettes = this.styleInputData?.palettes ?? []; + if (!palettes.length) return undefined; + + const candidates = + palettes.length > 1 + ? palettes.filter((p) => p.name !== this.appliedPaletteName) + : palettes; + return candidates[Math.floor(Math.random() * candidates.length)]; + } + + /** + * Restores every input to its default and clears the applied styles, so the + * demo component falls back to its own default styling. + */ + private resetStyles(): void { + this.appliedPaletteName = undefined; + const defaults = new Map( + (this.styleInputData?.settings ?? []).map((s) => [s.cssVariable, s]), + ); + this.rangeReadouts = {}; + this.styleInputs?.forEach((input) => { + const setting = defaults.get(input.dataset.variable ?? ''); + if (!setting) return; + input.value = String(setting.defaultValue); + }); + + this.dispatchEvent( + new CustomEvent('stylesApplied', { detail: { styles: '' } }), + ); + } + /** * Renders one row of the settings table for the given style input. */ @@ -84,9 +195,16 @@ export class StoryStylesSettings extends LitElement { /> ${input.inputType === 'range' ? html`${input.defaultValue}${input.unit ?? ''}${this.readoutFor(input)}` : nothing} + ${when( + this.styleInputData?.showCssVariables, + () => + html`${input.cssVariable}`, + )} `; @@ -94,15 +212,29 @@ export class StoryStylesSettings extends LitElement { /** * Updates the live readout next to a range slider as it moves. + * + * This records the value in reactive state rather than writing to the + * `` directly: that element holds Lit-rendered content, and + * overwriting its text would eject Lit's markers and break every later + * re-render of the panel. */ private updateRangeReadout(e: Event): void { const input = e.currentTarget as HTMLInputElement; - const output = this.renderRoot.querySelector( - `output[for="${CSS.escape(input.id)}"]`, - ); - if (!output) return; + const variable = input.dataset.variable; + if (!variable) return; const unit = input.dataset.unit ?? ''; - output.textContent = `${input.value}${unit}`; + this.rangeReadouts = { + ...this.rangeReadouts, + [variable]: `${input.value}${unit}`, + }; + } + + /** The text to show beside a range slider — live value, else its default. */ + private readoutFor(input: StyleInputSettings): string { + return ( + this.rangeReadouts[input.cssVariable] ?? + `${input.defaultValue}${input.unit ?? ''}` + ); } /** @@ -143,9 +275,25 @@ export class StoryStylesSettings extends LitElement { text-align: right; } + /* The CSS custom property each control sets, shown to its right. */ + .style-var { + margin-left: 0.75em; + font-family: monospace; + font-size: 0.72rem; + color: #767676; + white-space: nowrap; + } + input[type='range'] { margin: 5px; } + + /* Names the theme the randomize control just applied. */ + .applied-palette { + margin-left: 0.75em; + font-size: 0.78rem; + color: #595959; + } `, ]; } diff --git a/demo/story-template.ts b/demo/story-template.ts index 4680d4429..4abc828df 100644 --- a/demo/story-template.ts +++ b/demo/story-template.ts @@ -295,12 +295,10 @@ export class StoryTemplate extends LitElement { if (slottedComponent) this.slottedDemoComponent = slottedComponent; } - /* Applies styles from the settings to the component and code demo */ + /* Applies styles from the settings to the component and code demo; an empty + string clears them (Reset), reverting to the component's own defaults. */ private handleStylesApplied(e: CustomEvent): void { - const stringifiedStyles = e.detail.styles; - if (!stringifiedStyles) return; - - this.stringifiedStyles = stringifiedStyles; + this.stringifiedStyles = e.detail.styles || undefined; } /* Applies props from the settings to the component and code demo */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dea83ceb1..d25e160c5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,7 +29,7 @@ importers: devDependencies: '@eslint/eslintrc': specifier: ^3.3.5 - version: 3.3.6 + version: 3.3.6(supports-color@7.2.0) '@eslint/js': specifier: ^9.39.1 version: 9.39.5 @@ -38,10 +38,10 @@ importers: version: 3.0.1 '@typescript-eslint/eslint-plugin': specifier: ^8.46.4 - version: 8.64.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5)(typescript@5.9.3) + version: 8.64.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/parser': specifier: ^8.46.4 - version: 8.64.0(eslint@9.39.5)(typescript@5.9.3) + version: 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@vitest/browser': specifier: ^4.0.8 version: 4.1.10(vite@7.3.6(@types/node@26.1.1))(vitest@4.1.10) @@ -53,34 +53,34 @@ importers: version: 4.1.10(@vitest/browser@4.1.10)(vitest@4.1.10) eslint: specifier: ^9.39.1 - version: 9.39.5 + version: 9.39.5(supports-color@7.2.0) eslint-config-prettier: specifier: ^10.1.8 - version: 10.1.8(eslint@9.39.5) + version: 10.1.8(eslint@9.39.5(supports-color@7.2.0)) eslint-plugin-html: specifier: ^8.1.3 version: 8.1.4 eslint-plugin-import: specifier: ^2.32.0 - version: 2.32.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5) + version: 2.32.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0) eslint-plugin-lit: specifier: ^1.15.0 - version: 1.15.0(eslint@9.39.5) + version: 1.15.0(eslint@9.39.5(supports-color@7.2.0)) eslint-plugin-lit-a11y: specifier: ^4.1.4 - version: 4.1.4(eslint@9.39.5) + version: 4.1.4(eslint@9.39.5(supports-color@7.2.0)) eslint-plugin-no-only-tests: specifier: ^3.3.0 version: 3.4.0 eslint-plugin-wc: specifier: ^2.2.1 - version: 2.2.1(eslint@9.39.5) + version: 2.2.1(eslint@9.39.5(supports-color@7.2.0)) highlight.js: specifier: ^11.11.1 version: 11.11.1 madge: specifier: ^8.0.0 - version: 8.0.0(typescript@5.9.3) + version: 8.0.0(supports-color@7.2.0)(typescript@5.9.3) playwright: specifier: ^1.60.0 version: 1.61.1 @@ -1237,6 +1237,7 @@ packages: eslint@9.39.5: resolution: {integrity: sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. hasBin: true peerDependencies: jiti: '*' @@ -2613,17 +2614,17 @@ snapshots: '@esbuild/win32-x64@0.28.1': optional: true - '@eslint-community/eslint-utils@4.9.1(eslint@9.39.5)': + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.5(supports-color@7.2.0))': dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -2636,10 +2637,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.6': + '@eslint/eslintrc@3.3.6(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -2859,15 +2860,15 @@ snapshots: '@types/trusted-types@2.0.7': {} - '@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.64.0(eslint@9.39.5)(typescript@5.9.3) + '@typescript-eslint/parser': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.64.0 - '@typescript-eslint/type-utils': 8.64.0(eslint@9.39.5)(typescript@5.9.3) - '@typescript-eslint/utils': 8.64.0(eslint@9.39.5)(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.64.0 - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) ignore: 7.0.6 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -2875,23 +2876,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.64.0 '@typescript-eslint/types': 8.64.0 - '@typescript-eslint/typescript-estree': 8.64.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.64.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.64.0 - debug: 4.4.3 - eslint: 9.39.5 + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.64.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.64.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.64.0(typescript@5.9.3) '@typescript-eslint/types': 8.64.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -2905,13 +2906,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.64.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.64.0 - '@typescript-eslint/typescript-estree': 8.64.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.64.0(eslint@9.39.5)(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5 + '@typescript-eslint/typescript-estree': 8.64.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -2919,13 +2920,13 @@ snapshots: '@typescript-eslint/types@8.64.0': {} - '@typescript-eslint/typescript-estree@8.64.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.64.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.64.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.64.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.64.0(typescript@5.9.3) '@typescript-eslint/types': 8.64.0 '@typescript-eslint/visitor-keys': 8.64.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.5 semver: 7.8.5 tinyglobby: 0.2.17 @@ -2934,13 +2935,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.64.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/utils@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.64.0 '@typescript-eslint/types': 8.64.0 - '@typescript-eslint/typescript-estree': 8.64.0(typescript@5.9.3) - eslint: 9.39.5 + '@typescript-eslint/typescript-estree': 8.64.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -3317,13 +3318,17 @@ snapshots: es-errors: 1.3.0 is-data-view: 1.0.2 - debug@3.2.7: + debug@3.2.7(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 deep-extend@0.6.0: {} @@ -3345,12 +3350,12 @@ snapshots: has-property-descriptors: 1.0.2 object-keys: 1.1.1 - dependency-tree@11.5.0: + dependency-tree@11.5.0(supports-color@7.2.0): dependencies: '@discoveryjs/json-ext': 1.1.0 commander: 12.1.0 filing-cabinet: 5.5.1 - precinct: 12.3.2 + precinct: 12.3.2(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -3391,16 +3396,16 @@ snapshots: detective-stylus@5.0.1: {} - detective-typescript@14.1.2(typescript@5.9.3): + detective-typescript@14.1.2(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/typescript-estree': 8.64.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.64.0(supports-color@7.2.0)(typescript@5.9.3) ast-module-types: 6.0.2 node-source-walk: 7.0.2 typescript: 5.9.3 transitivePeerDependencies: - supports-color - detective-vue2@2.3.0(typescript@5.9.3): + detective-vue2@2.3.0(supports-color@7.2.0)(typescript@5.9.3): dependencies: '@dependents/detective-less': 5.0.3 '@vue/compiler-sfc': 3.5.39 @@ -3408,7 +3413,7 @@ snapshots: detective-sass: 6.0.2 detective-scss: 5.0.2 detective-stylus: 5.0.1 - detective-typescript: 14.1.2(typescript@5.9.3) + detective-typescript: 14.1.2(supports-color@7.2.0)(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -3609,25 +3614,25 @@ snapshots: optionalDependencies: source-map: 0.6.1 - eslint-config-prettier@10.1.8(eslint@9.39.5): + eslint-config-prettier@10.1.8(eslint@9.39.5(supports-color@7.2.0)): dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) - eslint-import-resolver-node@0.3.10: + eslint-import-resolver-node@0.3.10(supports-color@7.2.0): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@7.2.0) is-core-module: 2.16.2 resolve: 2.0.0-next.7 transitivePeerDependencies: - supports-color - eslint-module-utils@2.14.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.5): + eslint-module-utils@2.14.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10(supports-color@7.2.0))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@7.2.0) optionalDependencies: - '@typescript-eslint/parser': 8.64.0(eslint@9.39.5)(typescript@5.9.3) - eslint: 9.39.5 - eslint-import-resolver-node: 0.3.10 + '@typescript-eslint/parser': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(supports-color@7.2.0) + eslint-import-resolver-node: 0.3.10(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3635,18 +3640,18 @@ snapshots: dependencies: htmlparser2: 10.1.0 - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5): + eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 array.prototype.findlastindex: 1.2.6 array.prototype.flat: 1.3.3 array.prototype.flatmap: 1.3.3 - debug: 3.2.7 + debug: 3.2.7(supports-color@7.2.0) doctrine: 2.1.0 - eslint: 9.39.5 - eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.14.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.5) + eslint: 9.39.5(supports-color@7.2.0) + eslint-import-resolver-node: 0.3.10(supports-color@7.2.0) + eslint-module-utils: 2.14.0(@typescript-eslint/parser@8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10(supports-color@7.2.0))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0) hasown: 2.0.4 is-core-module: 2.16.2 is-glob: 4.0.3 @@ -3658,39 +3663,39 @@ snapshots: string.prototype.trimend: 1.0.10 tsconfig-paths: 3.15.0 optionalDependencies: - '@typescript-eslint/parser': 8.64.0(eslint@9.39.5)(typescript@5.9.3) + '@typescript-eslint/parser': 8.64.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) transitivePeerDependencies: - eslint-import-resolver-typescript - eslint-import-resolver-webpack - supports-color - eslint-plugin-lit-a11y@4.1.4(eslint@9.39.5): + eslint-plugin-lit-a11y@4.1.4(eslint@9.39.5(supports-color@7.2.0)): dependencies: '@thepassle/axobject-query': 4.0.0 aria-query: 5.3.2 axe-core: 4.12.1 dom5: 3.0.1 emoji-regex: 10.6.0 - eslint: 9.39.5 - eslint-plugin-lit: 1.15.0(eslint@9.39.5) + eslint: 9.39.5(supports-color@7.2.0) + eslint-plugin-lit: 1.15.0(eslint@9.39.5(supports-color@7.2.0)) eslint-rule-extender: 0.0.1 language-tags: 1.0.9 parse5: 7.3.0 parse5-htmlparser2-tree-adapter: 6.0.1 requireindex: 1.2.0 - eslint-plugin-lit@1.15.0(eslint@9.39.5): + eslint-plugin-lit@1.15.0(eslint@9.39.5(supports-color@7.2.0)): dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) parse5: 6.0.1 parse5-htmlparser2-tree-adapter: 6.0.1 requireindex: 1.2.0 eslint-plugin-no-only-tests@3.4.0: {} - eslint-plugin-wc@2.2.1(eslint@9.39.5): + eslint-plugin-wc@2.2.1(eslint@9.39.5(supports-color@7.2.0)): dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) is-valid-element-name: 1.0.0 js-levenshtein-esm: 1.2.0 @@ -3707,14 +3712,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5: + eslint@9.39.5(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.6 + '@eslint/eslintrc': 3.3.6(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -3724,7 +3729,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -4232,13 +4237,13 @@ snapshots: chalk: 4.1.2 is-unicode-supported: 0.1.0 - madge@8.0.0(typescript@5.9.3): + madge@8.0.0(supports-color@7.2.0)(typescript@5.9.3): dependencies: chalk: 4.1.2 commander: 7.2.0 commondir: 1.0.1 - debug: 4.4.3 - dependency-tree: 11.5.0 + debug: 4.4.3(supports-color@7.2.0) + dependency-tree: 11.5.0(supports-color@7.2.0) ora: 5.4.1 pluralize: 8.0.0 pretty-ms: 7.0.1 @@ -4470,7 +4475,7 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - precinct@12.3.2: + precinct@12.3.2(supports-color@7.2.0): dependencies: '@dependents/detective-less': 5.0.3 commander: 12.1.0 @@ -4481,8 +4486,8 @@ snapshots: detective-sass: 6.0.2 detective-scss: 5.0.2 detective-stylus: 5.0.1 - detective-typescript: 14.1.2(typescript@5.9.3) - detective-vue2: 2.3.0(typescript@5.9.3) + detective-typescript: 14.1.2(supports-color@7.2.0)(typescript@5.9.3) + detective-vue2: 2.3.0(supports-color@7.2.0)(typescript@5.9.3) module-definition: 6.0.2 node-source-walk: 7.0.2 postcss: 8.5.19 diff --git a/src/elements/ia-item-navigator/element-names.test.ts b/src/elements/ia-item-navigator/element-names.test.ts new file mode 100644 index 000000000..6929a5364 --- /dev/null +++ b/src/elements/ia-item-navigator/element-names.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, test } from 'vitest'; + +import './ia-item-navigator'; +import './ia-itemnav-menu-slider'; +import './ia-itemnav-menu-button'; +import './ia-itemnav-no-theater-available'; +import './menus/ia-itemnav-viewable-files-panel'; +import './menus/ia-itemnav-share-panel'; +import './menus/ia-itemnav-sort-files-button'; + +/** + * Custom elements share one global registry, so the navigator's parts are + * namespaced under its own prefix. Without that, names like `ia-menu-slider` + * collide with whatever else the host page has loaded — including older + * releases of this same component, where a second registration throws rather + * than degrading. + */ +const NAMESPACED_ELEMENTS = [ + 'ia-itemnav-menu-slider', + 'ia-itemnav-menu-button', + 'ia-itemnav-no-theater-available', + 'ia-itemnav-viewable-files-panel', + 'ia-itemnav-share-panel', + 'ia-itemnav-sort-files-button', +]; + +/** + * Names this component must not claim. The first four are generic enough that + * any page could want them; the last three are registered verbatim by the + * `@internetarchive/ia-item-navigator` package that consumers still load + * during the migration. + */ +const NAMES_TO_AVOID = [ + 'ia-menu-button', + 'ia-share-panel', + 'ia-viewable-files-panel', + 'ia-sort-files-button', + 'ia-menu-slider', + 'ia-itemnav-loader', + 'ia-no-theater-available', +]; + +describe('item navigator element names', () => { + test('registers the navigator under its own name', () => { + expect(customElements.get('ia-item-navigator')).to.exist; + }); + + test.each(NAMESPACED_ELEMENTS)('registers %s', (tag) => { + expect(customElements.get(tag), `${tag} should be registered`).to.exist; + }); + + test.each(NAMES_TO_AVOID)('leaves %s free for other components', (tag) => { + expect(customElements.get(tag), `${tag} should not be claimed`).to.not + .exist; + }); +}); diff --git a/src/elements/ia-item-navigator/ia-item-navigator-story.ts b/src/elements/ia-item-navigator/ia-item-navigator-story.ts new file mode 100644 index 000000000..2b4a74a1e --- /dev/null +++ b/src/elements/ia-item-navigator/ia-item-navigator-story.ts @@ -0,0 +1,627 @@ +import { css, html, LitElement, nothing, type CSSResultGroup } from 'lit'; +import { customElement, state } from 'lit/decorators.js'; + +import './ia-item-navigator'; +import './menus/ia-itemnav-viewable-files-panel'; +import './menus/ia-itemnav-sort-files-button'; +import './menus/ia-itemnav-share-panel'; +import { viewableFilesIcon } from './menus/ia-itemnav-viewable-files-panel'; +import { shareIcon } from './menus/ia-itemnav-share-panel'; +import { maskedIcon } from './masked-icon'; +import listIconUrl from './menus/icons/list.svg'; +import type { + MenuProviderInterface, + MenuShortcutInterface, +} from './interfaces/menu-interfaces'; +import type { FileSortOption, ViewableFileInfo } from './menus/models'; +import type { + StyleInputData, + StylePalette, +} from '@demo/story-components/story-styles-settings'; +import '@demo/story-template'; + +/** A generic list-ish glyph for the "About" demo menu entry. */ +const demoIcon = maskedIcon(listIconUrl); + +/** + * Alternate themes for the demo's randomize control. + * + * Each one recolors the whole navigator at once, which makes any element that + * fails to follow its color knob obvious — it keeps the old color while + * everything around it changes. They are supplied as coordinated sets rather + * than random colors so every pairing the component actually renders stays + * legible: text on the drawer, the open panel and the embed field; icons over + * the drawer and over the theater; active vs inactive icons; borders and the + * active-file accent. All clear WCAG AA — 4.5:1 for text, 3:1 for icons, + * borders and other non-text — with text landing at AAA throughout. + * + * The component's own defaults are deliberately absent: Revert already + * restores those. + */ +const DEMO_PALETTES: StylePalette[] = [ + { + name: 'Midnight', + values: { + '--item-navigator-theater-bg-color': '#0d1b2a', + '--item-navigator-share-embed-bg': '#12233a', + '--item-navigator-menu-slider-bg': '#1b263b', + '--item-navigator-active-button-bg': '#2c3e50', + '--item-navigator-text-color': '#e0e6ed', + '--item-navigator-icon-color': '#e0e6ed', + '--item-navigator-icon-active-color': '#7fd8ff', + '--item-navigator-icon-inactive-color': '#9fb3c8', + '--item-navigator-border-color': '#5c7799', + '--item-navigator-active-file-border-color': '#4cc9f0', + }, + }, + { + name: 'Forest', + values: { + '--item-navigator-theater-bg-color': '#08160c', + '--item-navigator-share-embed-bg': '#0e2413', + '--item-navigator-menu-slider-bg': '#14301a', + '--item-navigator-active-button-bg': '#1f4a29', + '--item-navigator-text-color': '#e8f5e9', + '--item-navigator-icon-color': '#e8f5e9', + '--item-navigator-icon-active-color': '#7bd88f', + '--item-navigator-icon-inactive-color': '#9dbca4', + '--item-navigator-border-color': '#4d8259', + '--item-navigator-active-file-border-color': '#7bd88f', + }, + }, + { + name: 'Plum', + values: { + '--item-navigator-theater-bg-color': '#150c1a', + '--item-navigator-share-embed-bg': '#1f1226', + '--item-navigator-menu-slider-bg': '#2b1733', + '--item-navigator-active-button-bg': '#3d2147', + '--item-navigator-text-color': '#f3e8f7', + '--item-navigator-icon-color': '#f3e8f7', + '--item-navigator-icon-active-color': '#d9a6ff', + '--item-navigator-icon-inactive-color': '#b39ec0', + '--item-navigator-border-color': '#8a6398', + '--item-navigator-active-file-border-color': '#d09bff', + }, + }, + { + name: 'Solarized', + values: { + '--item-navigator-theater-bg-color': '#00212b', + '--item-navigator-share-embed-bg': '#002b36', + '--item-navigator-menu-slider-bg': '#073642', + '--item-navigator-active-button-bg': '#0b4553', + '--item-navigator-text-color': '#eee8d5', + '--item-navigator-icon-color': '#eee8d5', + '--item-navigator-icon-active-color': '#5fd3c8', + '--item-navigator-icon-inactive-color': '#93a1a1', + '--item-navigator-border-color': '#4d8fa1', + '--item-navigator-active-file-border-color': '#5fd3c8', + }, + }, + { + name: 'High Contrast', + values: { + '--item-navigator-theater-bg-color': '#000000', + '--item-navigator-share-embed-bg': '#000000', + '--item-navigator-menu-slider-bg': '#000000', + '--item-navigator-active-button-bg': '#1a1a1a', + '--item-navigator-text-color': '#ffffff', + '--item-navigator-icon-color': '#ffffff', + '--item-navigator-icon-active-color': '#ffff00', + '--item-navigator-icon-inactive-color': '#c0c0c0', + '--item-navigator-border-color': '#ffffff', + '--item-navigator-active-file-border-color': '#ffff00', + }, + }, +]; + +/** archive.org bases for embeddable item viewers and direct file downloads. */ +const EMBED_BASE = 'https://archive.org/embed'; +const DOWNLOAD_BASE = 'https://archive.org/download'; + +type DemoMediaType = 'image' | 'pdf' | 'video' | 'audio' | 'book'; + +/** A viewable file backed by a real, iframe-embeddable archive.org item. */ +interface DemoFile extends ViewableFileInfo { + identifier: string; + mediatype: DemoMediaType; + /** For PDFs, the direct file to load in the browser's native PDF viewer. */ + pdfFile?: string; +} + +function demoFile( + identifier: string, + title: string, + mediatype: DemoMediaType, + orig_sort: number, + pdfFile?: string, +): DemoFile { + return { + identifier, + mediatype, + pdfFile, + title, + file_prefix: identifier, + file_subprefix: identifier, + // file_source only drives the PDF flag in the panel. + file_source: mediatype === 'pdf' ? `${identifier}.pdf` : identifier, + url_path: `/details/${identifier}`, + image: '', + author: '', + orig_sort, + }; +} + +/** + * A handful of real, public Dolly Parton items — one per media type, so the + * demo shows the navigator hosting whatever a consumer slots into it. + * Selecting one swaps the slotted theater. PDFs load the file directly in the + * browser's own viewer; everything else embeds the archive.org player. + * + * The album and the book are lending items, so they embed as samples and + * preview pages rather than the whole work — which is what a consumer would + * hit in production too. + */ +const DEMO_FILES: DemoFile[] = [ + demoFile( + 'Dolly-Parton-Coat-Of-Many-Colors', + 'Coat of Many Colors (album cover)', + 'image', + 0, + ), + demoFile('9to-5and-odd-jobs', '9 to 5 and Odd Jobs', 'image', 1), + demoFile('musikladen-77', 'Musikladen Concert, 1977', 'video', 2), + demoFile( + 'lp_rhinestone-original-soundtrack-record_various-dolly-parton-floyd-parton-kin-v', + 'Rhinestone: Original Soundtrack Recording', + 'audio', + 3, + ), + demoFile('isbn_9780590899352', 'Coat of Many Colors', 'book', 4), + demoFile('sounds-78-03', 'Sounds, 3/78', 'pdf', 5, 'sounds-78-03.pdf'), +]; + +@customElement('ia-item-navigator-story') +export class IAItemNavigatorStory extends LitElement { + @state() private loaded = true; + + @state() private viewAvailable = true; + + @state() private headerOn = true; + + @state() private fullscreen = false; + + @state() private animationsOn = true; + + @state() private sortOrderBy: FileSortOption = 'default'; + + @state() private sortedFiles: ViewableFileInfo[] = [...DEMO_FILES]; + + @state() private selectedSubPrefix = DEMO_FILES[0].file_subprefix; + + private handleFileListSorted(e: Event): void { + const { sortType, sortedFiles } = (e as CustomEvent).detail; + this.sortOrderBy = sortType; + this.sortedFiles = sortedFiles; + } + + private get selectedFile(): DemoFile { + return ( + DEMO_FILES.find((f) => f.file_subprefix === this.selectedSubPrefix) ?? + DEMO_FILES[0] + ); + } + + /** PDFs load the file directly; everything else uses the item embed viewer. */ + private get theaterSrc(): string { + const file = this.selectedFile; + return file.mediatype === 'pdf' && file.pdfFile + ? `${DOWNLOAD_BASE}/${file.identifier}/${encodeURIComponent(file.pdfFile)}` + : `${EMBED_BASE}/${file.identifier}`; + } + + /** + * Intercepts clicks on the viewable-files links so, instead of navigating + * away, the demo swaps the slotted theater to the chosen file — showing how + * a host drives the navigator's `main` slot dynamically. + */ + private handleFileClick(e: Event): void { + const link = e + .composedPath() + .find((n): n is HTMLAnchorElement => n instanceof HTMLAnchorElement); + if (!link) return; + e.preventDefault(); + const href = link.getAttribute('href'); + const file = DEMO_FILES.find((f) => `//archive.org${f.url_path}` === href); + if (file) this.selectedSubPrefix = file.file_subprefix; + } + + /** The archive.org identifier of whichever demo file is selected. */ + private get demoIdentifier(): string { + return this.selectedFile.identifier; + } + + private get menuContents(): MenuProviderInterface[] { + const shared = { + identifier: this.demoIdentifier, + baseHost: 'archive.org', + subPrefix: '', + }; + return [ + { + ...shared, + id: 'viewable-files', + label: `Viewable Files (${DEMO_FILES.length})`, + icon: viewableFilesIcon, + actionButton: html` + + `, + component: html` + this.handleFileClick(e)} + > + `, + }, + { + ...shared, + id: 'share', + label: 'Share this item', + icon: shareIcon, + component: html` + + `, + }, + { + ...shared, + id: 'about', + label: 'About This Item', + icon: demoIcon, + component: html` +

+ The item navigator is a shell: each menu entry here is a "provider" + supplying its own panel body. The theater on the right is slotted in + by the host. +

+ `, + }, + ]; + } + + /** Minimized-rail shortcuts, mirroring the upstream demo. */ + private get menuShortcuts(): MenuShortcutInterface[] { + return [ + { + id: 'viewable-files', + label: 'Viewable Files', + icon: viewableFilesIcon, + }, + { id: 'share', label: 'Share this item', icon: shareIcon }, + ]; + } + + private get styleInputData(): StyleInputData { + return { + settings: [ + // Sizing / motion + { + label: 'Base font size', + cssVariable: '--item-navigator-base-font-size', + defaultValue: 10, + inputType: 'range', + min: 8, + max: 16, + step: 1, + unit: 'px', + }, + { + label: 'Menu width', + cssVariable: '--item-navigator-menu-width', + defaultValue: 320, + inputType: 'range', + min: 200, + max: 480, + step: 10, + unit: 'px', + }, + { + label: 'Shortcut rail width', + cssVariable: '--item-navigator-menu-margin', + defaultValue: 42, + inputType: 'range', + min: 30, + max: 64, + step: 2, + unit: 'px', + }, + { + label: 'Animation timing', + cssVariable: '--item-navigator-animation-timing', + defaultValue: 200, + inputType: 'range', + min: 0, + max: 800, + step: 50, + unit: 'ms', + }, + // Text + icons + { + label: 'Text color', + cssVariable: '--item-navigator-text-color', + defaultValue: '#ffffff', + inputType: 'color', + }, + { + label: 'Icon color', + cssVariable: '--item-navigator-icon-color', + defaultValue: '#ffffff', + inputType: 'color', + }, + { + label: 'Icon color · active', + cssVariable: '--item-navigator-icon-active-color', + defaultValue: '#ffffff', + inputType: 'color', + }, + { + label: 'Icon color · inactive', + cssVariable: '--item-navigator-icon-inactive-color', + defaultValue: '#999999', + inputType: 'color', + }, + // Borders / accents + { + label: 'Border color', + cssVariable: '--item-navigator-border-color', + defaultValue: '#4b4b4b', + inputType: 'color', + }, + { + label: 'Active file border', + cssVariable: '--item-navigator-active-file-border-color', + defaultValue: '#538bc5', + inputType: 'color', + }, + // Backgrounds + { + label: 'Theater background', + cssVariable: '--item-navigator-theater-bg-color', + defaultValue: '#000000', + inputType: 'color', + }, + { + label: 'Menu drawer background', + cssVariable: '--item-navigator-menu-slider-bg', + defaultValue: '#212121', + inputType: 'color', + }, + { + label: 'Active panel background', + cssVariable: '--item-navigator-active-button-bg', + defaultValue: '#333333', + inputType: 'color', + }, + { + label: 'Embed field background', + cssVariable: '--item-navigator-share-embed-bg', + defaultValue: '#151515', + inputType: 'color', + }, + ], + palettes: DEMO_PALETTES, + revertable: true, + showCssVariables: true, + }; + } + + render() { + return html` + +
+
+ + ${this.headerTemplate} ${this.theaterTemplate} + +
+
+ +
+ + ${this.toggleRow('Loaded', 'loaded')} + ${this.toggleRow('View available (theater)', 'viewAvailable')} + ${this.toggleRow('Header', 'headerOn')} + ${this.toggleRow('Fullscreen', 'fullscreen')} + ${this.toggleRow('Animate', 'animationsOn')} +
+

+ Turn "View available" off to show the no-theater placeholder. Open + "Viewable Files" and use the sort button in its header. Narrow the + demo below 600px to see the drawer switch from shift to overlay. +

+
+ +
+

+ The navigator is a shell: project a theater into + slot="main" and an optional bar into + slot="header", then drive the drawer with the + menuContents provider array (and the minimized rail + with menuShortcuts). It never renders a viewer itself. +

+
+
+ `; + } + + /** A row with a labelled checkbox bound to the given boolean state field. */ + private toggleRow( + label: string, + field: + | 'loaded' + | 'viewAvailable' + | 'headerOn' + | 'fullscreen' + | 'animationsOn', + ) { + return html` + + ${label} + + { + this[field] = (e.target as HTMLInputElement).checked; + }} + /> + + + `; + } + + private get headerTemplate() { + if (!this.headerOn && !this.fullscreen) return nothing; + return html` +
+ Internet Archive + ${this.selectedFile.title} + ${this.fullscreen + ? html`` + : nothing} +
+ `; + } + + private get theaterTemplate() { + const file = this.selectedFile; + return html` +
+ +
+ `; + } + + private get exampleUsage(): string { + return ` +
…your header…
+
…your theater…
+
`; + } + + static get styles(): CSSResultGroup { + return css` + .frame-wrapper { + height: 460px; + border: 1px solid #ccc; + } + + /* Opt into menu-button labels (the component ships icon-only by + default), matching the upstream demo. */ + ia-item-navigator { + --item-navigator-menu-button-label-display: block; + } + + .demo-header { + display: flex; + align-items: center; + gap: 12px; + background: #1a1a1a; + color: #fff; + padding: 8px 12px; + font-size: 0.9rem; + } + + .demo-header .brand { + font-weight: 600; + white-space: nowrap; + } + + .demo-header .title { + color: #6cb2ff; + text-decoration: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .demo-header .exit-fs { + margin-left: auto; + cursor: pointer; + } + + .demo-theater { + height: 100%; + width: 100%; + } + + .theater-embed { + width: 100%; + height: 100%; + border: 0; + display: block; + } + + .hint { + font-size: 0.78rem; + color: #555; + } + + table { + margin-bottom: 0.5rem; + } + `; + } +} diff --git a/src/elements/ia-item-navigator/ia-item-navigator.test.ts b/src/elements/ia-item-navigator/ia-item-navigator.test.ts new file mode 100644 index 000000000..ed13cf223 --- /dev/null +++ b/src/elements/ia-item-navigator/ia-item-navigator.test.ts @@ -0,0 +1,546 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test, vi } from 'vitest'; + +import { IAItemNavigator } from './ia-item-navigator'; +import './ia-item-navigator'; +import type { IAItemNavMenuSlider } from './ia-itemnav-menu-slider'; +import type { IAItemNavNoTheaterAvailable } from './ia-itemnav-no-theater-available'; +import type { + MenuProviderInterface, + MenuShortcutInterface, +} from './interfaces/menu-interfaces'; +/** Builds a minimal, well-typed menu provider for tests. */ +function provider( + id: string, + overrides: Partial = {}, +): MenuProviderInterface { + return { + id, + label: `${id} label`, + icon: html`${id}`, + identifier: 'test-item', + baseHost: 'archive.org', + subPrefix: '', + component: html`
${id} body
`, + ...overrides, + }; +} + +describe('IAItemNavigator', () => { + test('renders the frame with sensible defaults', async () => { + const el = await fixture( + html``, + ); + + expect(el).to.be.instanceOf(IAItemNavigator); + expect(el.shadowRoot?.querySelector('#frame')).to.exist; + expect(el.viewAvailable).to.equal(true); + expect(el.loaded).to.equal(false); + expect(el.menuOpened).to.equal(false); + expect(el.baseHost).to.equal('archive.org'); + }); + + test('renders no side menu when there are no providers', async () => { + const el = await fixture( + html``, + ); + + expect(el.shouldRenderMenu).to.equal(false); + expect(el.shadowRoot?.querySelector('nav')).to.not.exist; + }); + + test('renders the drawer and toggle button once providers are set', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents'), provider('about')]; + await el.updateComplete; + + expect(el.shouldRenderMenu).to.equal(true); + expect(el.shadowRoot?.querySelector('nav')).to.exist; + expect(el.shadowRoot?.querySelector('button.toggle-menu')).to.exist; + expect(el.shadowRoot?.querySelector('ia-itemnav-menu-slider')).to.exist; + }); + + test('toggleMenu / closeMenu drive the menuOpened state', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents')]; + await el.updateComplete; + + el.toggleMenu(); + expect(el.menuOpened).to.equal(true); + + el.toggleMenu(); + expect(el.menuOpened).to.equal(false); + + el.toggleMenu(true); + expect(el.menuOpened).to.equal(true); + + el.closeMenu(); + expect(el.menuOpened).to.equal(false); + }); + + test('clicking the toggle button opens the drawer and marks the frame open', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents')]; + await el.updateComplete; + + const toggle = el.shadowRoot?.querySelector( + 'button.toggle-menu', + ) as HTMLButtonElement; + toggle.click(); + await el.updateComplete; + + expect(el.menuOpened).to.equal(true); + expect(el.shadowRoot?.querySelector('#frame')?.className).to.contain( + 'open', + ); + }); + + test('passes providers and selected menu through to the slider', async () => { + const el = await fixture( + html``, + ); + const providers = [provider('contents'), provider('about')]; + el.menuContents = providers; + el.openMenu = 'about'; + await el.updateComplete; + + const slider = el.shadowRoot?.querySelector( + 'ia-itemnav-menu-slider', + ); + expect(slider).to.exist; + expect(slider?.menus).to.have.lengthOf(2); + expect(slider?.selectedMenu).to.equal('about'); + }); + + test('shows the no-theater placeholder when the view is unavailable', async () => { + const el = await fixture( + html``, + ); + el.viewAvailable = false; + await el.updateComplete; + + const placeholder = + el.shadowRoot?.querySelector( + 'ia-itemnav-no-theater-available', + ); + expect(placeholder).to.exist; + expect(placeholder?.identifier).to.equal('abc123'); + }); + + test('loadingStateUpdated marks the navigator loaded', async () => { + const el = await fixture( + html``, + ); + + el.loadingStateUpdated( + new CustomEvent('loadingStateUpdated', { + detail: { loaded: true }, + }) as never, + ); + expect(el.loaded).to.equal(true); + }); + + test('slotChange re-dispatches a slotChange event with the slot type', async () => { + const el = await fixture( + html``, + ); + const listener = vi.fn(); + el.addEventListener('slotChange', listener); + + const slot = el.shadowRoot?.querySelector( + 'slot[name="header"]', + ) as HTMLSlotElement; + slot.dispatchEvent(new Event('slotchange')); + + expect(listener).toHaveBeenCalledOnce(); + expect(listener.mock.calls[0][0].detail.type).to.equal('header'); + }); + + test('manageViewportFullscreen reflects state and re-emits fullscreenToggled', async () => { + const el = await fixture( + html``, + ); + const listener = vi.fn(); + el.addEventListener('fullscreenToggled', listener); + + el.manageViewportFullscreen( + new CustomEvent('x', { detail: { isFullScreen: true } }) as never, + ); + expect(el.viewportInFullscreen).to.equal(true); + expect(listener).toHaveBeenCalledOnce(); + + el.manageViewportFullscreen( + new CustomEvent('x', { detail: { isFullScreen: false } }) as never, + ); + expect(el.viewportInFullscreen).to.equal(null); + }); + + test('gives the drawer its own column above 600px and overlays below it', async () => { + // A container query drives this, so it has to be measured in real layout + // rather than by poking a method. Animation off so the computed values are + // the settled ones, not a frame mid-transition. + const el = await fixture( + html``, + ); + el.menuOpened = true; + await el.updateComplete; + + const reader = el.shadowRoot?.querySelector('#reader') as HTMLElement; + + // Wide: the reader is inset by the drawer's width, so they sit side by side. + reader.getBoundingClientRect(); + expect(getComputedStyle(reader).marginLeft).to.equal('320px'); + + // Narrow: no room for a column, so the drawer covers a full-width reader. + el.style.width = '400px'; + reader.getBoundingClientRect(); + expect(getComputedStyle(reader).marginLeft).to.equal('0px'); + + // And back, to show the query tracks the frame rather than latching. + el.style.width = '900px'; + reader.getBoundingClientRect(); + expect(getComputedStyle(reader).marginLeft).to.equal('320px'); + }); + + test('the breakpoint follows the component width, not the viewport', async () => { + // Two navigators in one document share a viewport, so any difference + // between them can only come from their own widths — which is what a + // container query buys over a media query. + const wide = await fixture( + html``, + ); + const narrow = await fixture( + html``, + ); + wide.menuOpened = true; + narrow.menuOpened = true; + await Promise.all([wide.updateComplete, narrow.updateComplete]); + + const readerOf = (el: IAItemNavigator) => + el.shadowRoot?.querySelector('#reader') as HTMLElement; + + readerOf(wide).getBoundingClientRect(); + expect(getComputedStyle(readerOf(wide)).marginLeft).to.equal('320px'); + expect(getComputedStyle(readerOf(narrow)).marginLeft).to.equal('0px'); + }); + + test('setOpenMenu toggles the selected panel on repeat selection', async () => { + const el = await fixture( + html``, + ); + + el.setOpenMenu(new CustomEvent('x', { detail: { id: 'share' } }) as never); + expect(el.openMenu).to.equal('share'); + + el.setOpenMenu(new CustomEvent('x', { detail: { id: 'share' } }) as never); + expect(el.openMenu).to.equal(undefined); + }); + + test('openShortcut opens the drawer at the requested menu', async () => { + const el = await fixture( + html``, + ); + + el.openShortcut('contents'); + expect(el.openMenu).to.equal('contents'); + expect(el.menuOpened).to.equal(true); + }); + + describe('opening straight to a panel', () => { + const navigatorWith = async (menus: string[]) => { + const el = await fixture( + html``, + ); + el.menuContents = menus.map((id) => provider(id)); + await el.updateComplete; + return el; + }; + + test('marks the drawer as entering so the panel rides in', async () => { + const el = await navigatorWith(['contents']); + + el.openShortcut('contents'); + await el.updateComplete; + + // The panel is nested in the drawer, so sliding both would compound + // their transforms; the marker tells the panel to hold still. + expect(el.menuClass).to.contain('drawer-entering'); + }); + + test('leaves the panel free to animate when the drawer is already open', async () => { + const el = await navigatorWith(['contents', 'share']); + el.openShortcut('contents'); + await el.updateComplete; + + // A second shortcut with the drawer already open is a panel change, not + // a drawer opening, so the panel should slide across as usual. + el.openShortcut('share'); + await el.updateComplete; + expect(el.menuClass).to.not.contain('drawer-entering'); + }); + + test.each([ + [ + 'selecting another channel', + (el: IAItemNavigator) => + el.setOpenMenu( + new CustomEvent('menuTypeSelected', { + detail: { id: 'share' }, + }) as never, + ), + ], + ['closing the panel', (el: IAItemNavigator) => el.closeSidePanel()], + ['closing the drawer', (el: IAItemNavigator) => el.closeMenu()], + ])('%s clears the marker', async (_label, act) => { + const el = await navigatorWith(['contents', 'share']); + el.openShortcut('contents'); + await el.updateComplete; + expect(el.menuClass).to.contain('drawer-entering'); + + // Nothing waits on the drawer's transitionend to clear this — a + // zero-duration transition never fires one, which would strand the + // marker on and suppress the panel's animation for good. + act(el); + await el.updateComplete; + expect(el.menuClass).to.not.contain('drawer-entering'); + }); + }); + + test('closeSidePanel clears the open channel but leaves the drawer open', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents')]; + el.openShortcut('contents'); + await el.updateComplete; + expect(el.openMenu).to.equal('contents'); + expect(el.menuOpened).to.equal(true); + + el.closeSidePanel(); + expect(el.openMenu).to.equal(undefined); + // The sub-panel closing must not close the drawer itself. + expect(el.menuOpened).to.equal(true); + }); + + test("the slider's menuPanelClosed event clears openMenu without closing the drawer", async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents')]; + el.openShortcut('contents'); + await el.updateComplete; + + const slider = el.shadowRoot?.querySelector('ia-itemnav-menu-slider'); + slider?.dispatchEvent( + new CustomEvent('menuPanelClosed', { + detail: { id: 'contents' }, + bubbles: true, + composed: true, + }), + ); + await el.updateComplete; + + expect(el.openMenu).to.equal(undefined); + expect(el.menuOpened).to.equal(true); + }); + + test('a channel can be reopened after its sub-panel is closed', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('contents'), provider('share')]; + el.openShortcut('share'); + await el.updateComplete; + + el.closeSidePanel(); + await el.updateComplete; + expect(el.openMenu).to.equal(undefined); + + // Reopening the same channel works because openMenu was cleared in sync. + el.openShortcut('share'); + expect(el.openMenu).to.equal('share'); + expect(el.menuOpened).to.equal(true); + }); + + test('takes the identifier straight from the attribute', async () => { + // A plain string needs no converter, which is why the attribute and the + // property agree without one. + const el = await fixture( + html``, + ); + expect(el.identifier).to.equal('an-item'); + }); + + test('loadingStateUpdated defaults a missing loaded flag to false', async () => { + const el = await fixture( + html``, + ); + expect(el.loaded).to.equal(true); + el.loadingStateUpdated(new CustomEvent('x', { detail: {} }) as never); + expect(el.loaded).to.equal(false); + }); + + test('re-dispatches slotChange for the main slot too', async () => { + const el = await fixture( + html``, + ); + const listener = vi.fn(); + el.addEventListener('slotChange', listener); + + const mainSlot = el.shadowRoot?.querySelector( + 'slot[name="main"]', + ) as HTMLSlotElement; + mainSlot.dispatchEvent(new Event('slotchange')); + + expect(listener).toHaveBeenCalledOnce(); + expect(listener.mock.calls[0][0].detail.type).to.equal('main'); + }); + + test('the header slot tracks its content, margins included', async () => { + // The navigator used to measure the slotted header and write the height + // back as an inline style. `offsetHeight` excludes margins, so a header + // with vertical margins was under-sized and its bottom margin overlapped + // the reader. The slot sizes itself now, so the margin is part of the box. + const el = await fixture( + html` +
+
header
+
+
theater
+
`, + ); + await el.updateComplete; + + const slot = el.shadowRoot?.querySelector( + 'slot[name="header"]', + ) as HTMLElement; + const reader = el.shadowRoot?.querySelector('#reader') as HTMLElement; + + // 15px of content plus 12px top and bottom margin. + expect(Math.round(slot.getBoundingClientRect().height)).to.equal(39); + + // Nothing carries an imposed height any more. + expect(slot.getAttribute('style')).to.equal(null); + + // And the header no longer bleeds into the theater below it. + const headerBottom = slot.getBoundingClientRect().bottom; + expect(headerBottom).to.be.at.most(reader.getBoundingClientRect().top); + }); + + test('the header slot follows a header that changes height', async () => { + const el = await fixture( + html` +
header
+
`, + ); + await el.updateComplete; + + const slot = el.shadowRoot?.querySelector( + 'slot[name="header"]', + ) as HTMLElement; + expect(Math.round(slot.getBoundingClientRect().height)).to.equal(20); + + // No observer, no re-render — the slot is sized by its content. + const inner = el.querySelector('#hdr') as HTMLElement; + inner.style.height = '60px'; + expect(Math.round(slot.getBoundingClientRect().height)).to.equal(60); + }); + + test('setMenuContents and setMenuShortcuts copy the incoming arrays', async () => { + const el = await fixture( + html``, + ); + const contents = [provider('a'), provider('b')]; + el.setMenuContents(new CustomEvent('x', { detail: contents }) as never); + expect(el.menuContents).to.have.lengthOf(2); + expect(el.menuContents).to.not.equal(contents); // copied, not aliased + + const shortcuts: MenuShortcutInterface[] = [ + { id: 'a', label: 'A', icon: html`a` }, + ]; + el.setMenuShortcuts(new CustomEvent('x', { detail: shortcuts }) as never); + expect(el.menuShortcuts).to.have.lengthOf(1); + expect(el.menuShortcuts).to.not.equal(shortcuts); + }); + + test('manageSideMenuEvents ignores empty ids and handles open/toggle', async () => { + const el = await fixture( + html``, + ); + + // No menuId → no-op. + el.manageSideMenuEvents( + new CustomEvent('x', { detail: { menuId: '', action: 'open' } }) as never, + ); + expect(el.menuOpened).to.equal(false); + + // action: 'open' → opens at that menu. + el.manageSideMenuEvents( + new CustomEvent('x', { + detail: { menuId: 'share', action: 'open' }, + }) as never, + ); + expect(el.openMenu).to.equal('share'); + expect(el.menuOpened).to.equal(true); + + // action: 'toggle' → sets menu and toggles the drawer (closed here). + el.manageSideMenuEvents( + new CustomEvent('x', { + detail: { menuId: 'about', action: 'toggle' }, + }) as never, + ); + expect(el.openMenu).to.equal('about'); + expect(el.menuOpened).to.equal(false); + + // An unrecognized action is a no-op (neither open nor toggle). + el.manageSideMenuEvents( + new CustomEvent('x', { + detail: { menuId: 'about', action: '' }, + }) as never, + ); + expect(el.openMenu).to.equal('about'); + expect(el.menuOpened).to.equal(false); + }); + + test('renders shortcut buttons and passes through a fullscreen shortcut', async () => { + const el = await fixture( + html``, + ); + el.menuContents = [provider('share')]; + el.menuShortcuts = [ + { id: 'share', label: 'Share', icon: html`S` }, + { id: 'fullscreen', label: 'FS', icon: html`F` }, + ]; + await el.updateComplete; + + // The non-fullscreen shortcut becomes a button; fullscreen renders raw. + const shareShortcut = el.shadowRoot?.querySelector( + 'button.shortcut.share', + ) as HTMLButtonElement; + expect(shareShortcut).to.exist; + expect(el.shadowRoot?.querySelector('button.shortcut.fullscreen')).to.not + .exist; + expect(el.shadowRoot?.querySelector('.fs')).to.exist; + + // Clicking a shortcut opens the drawer at that channel. + shareShortcut.click(); + expect(el.openMenu).to.equal('share'); + expect(el.menuOpened).to.equal(true); + }); +}); diff --git a/src/elements/ia-item-navigator/ia-item-navigator.ts b/src/elements/ia-item-navigator/ia-item-navigator.ts new file mode 100644 index 000000000..994ca55b3 --- /dev/null +++ b/src/elements/ia-item-navigator/ia-item-navigator.ts @@ -0,0 +1,622 @@ +import { + css, + html, + LitElement, + TemplateResult, + nothing, + type CSSResultGroup, +} from 'lit'; +import { customElement, property, state, query } from 'lit/decorators.js'; +import { classMap } from 'lit/directives/class-map.js'; +import themeStyles from '@src/themes/theme-styles'; + +import { ellipsesIcon } from './icons'; +import './ia-itemnav-menu-slider'; +import './ia-itemnav-no-theater-available'; +import type { IAItemNavMenuSlider } from './ia-itemnav-menu-slider'; + +import { + ToggleSideMenuOpenEvent, + ToggleSidePanelOpenEvent, + SetSideMenuContentsEvent, + SetSideMenuShortcutsEvent, + LoadingStateUpdatedEvent, + ManageFullscreenEvent, +} from './interfaces/event-interfaces'; +import { + MenuProviderInterface, + MenuShortcutInterface, + MenuId, +} from './interfaces/menu-interfaces'; + +/** + * A fullscreen-capable frame that hosts an Archive.org item's theater. The + * consumer projects a header bar and the theater itself into the `header` and + * `main` slots; a collapsible left drawer (`ia-itemnav-menu-slider`) is driven by a + * data array of menu providers, and a minimized rail shows shortcut icons. + * + * The navigator is a shell — it does not know how to render any particular + * viewer. Menu panel bodies are opaque `TemplateResult`s supplied by the + * consumer via `menuContents`. + */ +@customElement('ia-item-navigator') +export class IAItemNavigator extends LitElement { + /** archive.org item identifier. */ + @property({ type: String }) identifier?: string; + + @property({ type: Boolean, reflect: true }) viewAvailable: boolean = true; + + @property({ type: String }) baseHost = 'archive.org'; + + @property({ type: Boolean }) signedIn = false; + + @property({ type: Array }) menuContents: MenuProviderInterface[] = []; + + @property({ type: Array }) menuShortcuts: MenuShortcutInterface[] = []; + + @property({ type: Boolean, reflect: true, attribute: true }) + viewportInFullscreen: boolean | null = null; + + @property({ type: Boolean, reflect: true }) menuOpened = false; + + @property({ type: String, reflect: true }) openMenu?: MenuId; + + /** + * Whether the slotted theater is ready. While false the reader stays + * hidden and the frame is empty. + * + * The navigator used to fill that gap with its own spinner, but a shell + * shouldn't decide what loading looks like — and its glyph and fullscreen + * caption were branding a consumer couldn't override. An indicator returns + * once WEBDEV-8951 moves the shared status indicators into elements, so the + * navigator can use that one instead of carrying its own. + */ + @property({ type: Boolean, reflect: true, attribute: true }) loaded: boolean = + false; + + /** + * Set for the render where the drawer opens straight to a panel, so the + * panel holds still and rides in. Every other path clears it, rather + * than waiting for the drawer's `transitionend` — that never fires when + * animations are disabled, which would strand the flag on. + */ + @state() private drawerEntering = false; + + @query('ia-itemnav-menu-slider') private menuSlider!: IAItemNavMenuSlider; + + @query('button.toggle-menu') private toggleMenuButton!: HTMLButtonElement; + + slotChange(e: Event, type: 'header' | 'main'): void { + const slottedContent = ( + e.target as HTMLSlotElement + ).assignedNodes()?.[0] as HTMLElement; + + this.dispatchEvent( + new CustomEvent('slotChange', { + detail: { slot: slottedContent, type }, + }), + ); + this.requestUpdate(); + } + + render(): TemplateResult { + const displayReaderClass = this.loaded ? '' : 'hidden'; + return html` +
+ this.slotChange(e, 'header')} + > + +
+ `; + } + + get noTheaterView(): TemplateResult { + return html``; + } + + get renderViewport(): TemplateResult | typeof nothing { + if (!this.viewAvailable) { + return this.noTheaterView; + } + + const slotVisibility = !this.loaded ? 'opacity: 0;' : 'opacity: 1;'; + return html` +
+ this.slotChange(e, 'main')} + > +
+ `; + } + + loadingStateUpdated(e: LoadingStateUpdatedEvent): void { + const { loaded } = e.detail; + this.loaded = loaded ?? false; + } + + /** Fullscreen Management */ + manageViewportFullscreen(e: ManageFullscreenEvent): void { + const fullscreenStatus = !!e.detail.isFullScreen; + this.viewportInFullscreen = !fullscreenStatus ? null : fullscreenStatus; + + const event = new CustomEvent('fullscreenToggled', { + detail: e.detail, + }) as ManageFullscreenEvent; + + this.dispatchEvent(event); + } + /** End Fullscreen Management */ + + /** Side menu */ + get shouldRenderMenu(): boolean { + return !!this.menuContents?.length; + } + + toggleMenu(forceValue: boolean | undefined = undefined): void { + this.drawerEntering = false; + this.menuOpened = forceValue !== undefined ? forceValue : !this.menuOpened; + this.moveFocusForDrawer(); + } + + /** + * Opening the drawer moves focus into it; closing hands focus back to the + * toggle. Without this, opening from the shortcut rail would leave focus on + * a button that is about to be hidden, dropping it to the document. + */ + private moveFocusForDrawer(): void { + this.updateComplete.then(() => { + if (this.menuOpened) { + this.menuSlider?.focusDrawer(); + } else { + this.toggleMenuButton?.focus(); + } + }); + } + + /** + * Closing the drawer also closes whatever panel was open inside it, so the + * two can't disagree and a stale panel can't reappear on the next open. + */ + closeMenu(): void { + this.openMenu = undefined; + this.toggleMenu(false); + } + + setOpenMenu(e: ToggleSidePanelOpenEvent): void { + this.drawerEntering = false; + const { id } = e.detail; + this.openMenu = id !== this.openMenu ? id : undefined; + } + + /** + * Clears the open channel when the slider closes its sub-panel, without + * closing the drawer. Keeps `openMenu` in sync with the slider so the same + * channel can be reopened afterwards. + */ + closeSidePanel(): void { + this.drawerEntering = false; + this.openMenu = undefined; + } + + setMenuContents(e: SetSideMenuContentsEvent): void { + const updatedContents = [...e.detail]; + this.menuContents = updatedContents; + } + + setMenuShortcuts(e: SetSideMenuShortcutsEvent): void { + this.menuShortcuts = [...e.detail]; + } + + /** Toggles Side Menu & Sets viewable subpanel */ + manageSideMenuEvents(e: ToggleSideMenuOpenEvent): void { + const { menuId, action } = e.detail; + if (!menuId) { + return; + } + + if (action === 'open') { + this.openShortcut(menuId); + } else if (action === 'toggle') { + this.openMenu = menuId; + this.toggleMenu(); + } + } + + get menuToggleButton(): TemplateResult { + const label = this.menuOpened ? 'Close side panel' : 'Open side panel'; + return html` + + `; + } + + get selectedMenuId(): MenuId | '' { + return this.openMenu || ''; + } + + get renderSideMenu(): TemplateResult { + return html` + + `; + } + /** End Side menu */ + + /** Menu Shortcuts */ + openShortcut(selectedMenuId: MenuId = ''): void { + // Opening straight to a panel is one movement: the drawer carries the + // panel in, so the panel must not also slide (see `.drawer-entering`). + // Only when the drawer is actually closed — switching shortcuts while it + // is already open should still animate the panel across. + this.drawerEntering = !this.menuOpened; + this.openMenu = selectedMenuId; + this.menuOpened = true; + // The rail hides itself once the drawer opens, taking the focused + // shortcut with it, so focus has to be placed deliberately. + this.moveFocusForDrawer(); + } + + get shortcuts(): TemplateResult { + const shortcuts = this.menuShortcuts.map(({ icon, id, label }) => { + if (id === 'fullscreen') { + return html`${icon}`; + } + + return html` +
  • + +
  • + `; + }); + return html`
      + ${shortcuts} +
    `; + } + /** End Menu Shortcuts */ + + /** Misc Render */ + get menuClass(): string { + const hasMenuOrShortcuts = + this.menuContents?.length || this.menuShortcuts?.length; + const drawerState = this.menuOpened && hasMenuOrShortcuts ? 'open' : ''; + const fullscreenState = this.viewportInFullscreen ? 'fullscreen' : ''; + // When the side menu renders, the minimized rail floats over the left edge; + // `has-menu` lets the reader reserve its width so the theater isn't covered. + const railState = this.shouldRenderMenu ? 'has-menu' : ''; + const enteringState = this.drawerEntering ? 'drawer-entering' : ''; + return `${drawerState} ${fullscreenState} ${railState} ${enteringState}`; + } + + static get styles(): CSSResultGroup { + const subnavWidth = css`var(--item-navigator-menu-width--)`; + const transitionTiming = css`var(--item-navigator-animation-timing--)`; + const transitionEffect = css`transform ${transitionTiming} ease-out`; + const menuMargin = css`var(--item-navigator-menu-margin--)`; + const theaterBg = css`var(--item-navigator-theater-bg-color--)`; + const iconSize = css`var(--item-navigator-icon-size--)`; + + return [ + themeStyles, + css` + :host { + --item-navigator-menu-width--: var( + --item-navigator-menu-width, + 320px + ); + --item-navigator-animation-timing--: var( + --item-navigator-animation-timing, + 200ms + ); + --item-navigator-menu-margin--: var( + --item-navigator-menu-margin, + 42px + ); + --item-navigator-theater-bg-color--: var( + --item-navigator-theater-bg-color, + #000 + ); + /* Every glyph is square, so one knob sizes both axes. */ + --item-navigator-icon-size--: var(--item-navigator-icon-size, 2.4em); + /* Icons follow the adjustable text color by default. */ + --item-navigator-icon-color--: var( + --item-navigator-icon-color, + var(--item-navigator-text-color, var(--true-white)) + ); + + /* + * The component's internal sizing is expressed in em against this + * base (10px matches petabox's base font size, which the upstream + * demo set on the document root). Anchoring it here makes the + * navigator self-contained — its scale no longer depends on the + * consumer's root font-size. Override to rescale everything. + */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + :host, + #frame, + .menu-and-reader { + position: relative; + overflow: hidden; + display: block; + } + + :host, + #frame { + min-height: inherit; + height: inherit; + } + + slot { + display: block; + width: 100%; + } + + slot * { + display: block; + height: inherit; + } + + #frame { + background-color: ${theaterBg}; + color-scheme: dark; + display: flex; + flex-direction: column; + /* + * The overlay/shift breakpoint keys off the navigator's own width, + * not the viewport's, so the frame is the query container. This + * replaces a host-injected resize observer that set the class from + * JS: layout drives it now, so there is nothing to inject, register + * or tear down. The inline-size type contains width only, leaving the + * flex column's height behaviour alone. + */ + container-type: inline-size; + container-name: navframe; + } + + #frame.fullscreen { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + z-index: 9; + /* + * Override the inherited height/min-height from the base #frame rule: + * on a fixed element an explicit height wins over top/bottom, so the + * inset (0 on all sides) can't fill the viewport unless height is + * released back to auto. + */ + height: auto; + min-height: 0; + } + + .hidden { + display: none !important; + } + + button { + /* Buttons don't inherit font-size from the UA stylesheet; inherit it + so em-sized icons resolve against the component's base, not the + browser's default button font-size. */ + font: inherit; + cursor: pointer; + padding: 0; + border: 0; + } + + .menu-and-reader { + position: relative; + display: flex; + flex: 1; + } + + nav button { + background: none; + } + + nav .minimized { + background: rgba(0, 0, 0, 0.7); + padding-top: 6px; + position: absolute; + width: ${menuMargin}; + z-index: 2; + left: 0; + border-bottom-right-radius: 5%; + } + + nav .minimized button { + margin-bottom: 0.2em; + margin: auto; + display: inline-flex; + vertical-align: middle; + align-items: center; + justify-content: center; + width: ${menuMargin}; + height: ${menuMargin}; + } + + nav .minimized button > * { + /** Prevent the icon's SVG description from stealing tooltip message */ + pointer-events: none; + } + + nav .minimized button.toggle-menu > * { + border: 2px solid var(--item-navigator-icon-color--); + border-radius: ${iconSize}; + width: ${iconSize}; + height: ${iconSize}; + margin: auto; + } + + /* The rail is a list for assistive tech; strip the list chrome so it + still reads as a row of icons. */ + .shortcuts, + .shortcuts li { + list-style: none; + padding: 0; + margin: 0; + } + + .toggle-menu .ia-icon, + .shortcuts .ia-icon { + width: ${iconSize}; + height: ${iconSize}; + } + + /* Our glyphs are masked spans: the mask supplies the shape, this + supplies the paint. */ + span.ia-icon { + background-color: var(--item-navigator-icon-color--); + } + + /* Host-supplied icons may still be inline svg, so keep theming those + the original way. */ + .ia-icon .fill-color { + fill: var(--item-navigator-icon-color--); + } + + #menu { + position: absolute; + top: 0; + bottom: 0; + left: 0; + z-index: 3; + overflow: hidden; + width: ${subnavWidth}; + transform: translateX(calc(${subnavWidth} * -1)); + transition: ${transitionEffect}; + } + + #reader { + position: relative; + z-index: 1; + transform: translateX(0); + width: 100%; + display: flex; + /* + * Ease the reader's size/position changes so the slotted theater + * glides in sync with the sliding drawer (shift mode) and settles + * smoothly on resize, rather than snapping. Overlay mode opts out + * below so the full-width theater tracks resizes instantly. + */ + transition: + width ${transitionTiming} ease-out, + margin-left ${transitionTiming} ease-out, + transform ${transitionTiming} ease-out; + } + + #reader > * { + width: 100%; + display: flex; + flex: 1; + } + + /* + * The minimized rail floats over the frame's left edge while the drawer + * is closed, so pad the theater content by its width to avoid overlap. + * This lives on the reader's content (not the reader box) and isn't + * transitioned, so it snaps away on open — letting the reader box track + * the drawer's edge exactly during the shift, rather than trailing it. + */ + .has-menu:not(.open) #reader > * { + box-sizing: border-box; + padding-left: ${menuMargin}; + } + + /* Opening straight to a panel is one movement. The panel is nested in + #menu, so its own slide would compose with the drawer's transform + and send it twice the distance in the same time — arriving late and + travelling at double speed. Holding it still lets the drawer carry + it in. */ + .drawer-entering #menu { + --item-navigator-panel-transition--: none; + } + + .open #menu { + width: ${subnavWidth}; + transform: translateX(0); + transition: ${transitionEffect}; + } + + /* Shift: the drawer pushes the theater aside. */ + .open #reader { + width: calc(100% - ${subnavWidth}); + margin-left: ${subnavWidth}; + } + + /* + * Overlay: too narrow to give the drawer its own column, so it covers + * a full-width theater. The transition is dropped here so the theater + * tracks resizes instantly instead of easing behind them. + */ + @container navframe (max-width: 600px) { + .open #reader { + width: 100%; + margin-left: 0; + transition: none; + } + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-item-navigator': IAItemNavigator; + } +} diff --git a/src/elements/ia-item-navigator/ia-itemnav-menu-button.test.ts b/src/elements/ia-item-navigator/ia-itemnav-menu-button.test.ts new file mode 100644 index 000000000..bd1cfba27 --- /dev/null +++ b/src/elements/ia-item-navigator/ia-itemnav-menu-button.test.ts @@ -0,0 +1,111 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test, vi } from 'vitest'; + +import { IAItemNavMenuButton } from './ia-itemnav-menu-button'; +import './ia-itemnav-menu-button'; +import { maskedIcon } from './masked-icon'; + +describe('IAItemNavMenuButton', () => { + test('renders a + `; + } + + render(): TemplateResult { + return this.href ? this.linkButton : this.clickButton; + } + + static get styles(): CSSResultGroup { + return [ + themeStyles, + css` + :host { + --item-navigator-text-color--: var( + --item-navigator-text-color, + var(--true-white) + ); + --item-navigator-active-button-bg--: var( + --item-navigator-active-button-bg, + var(--mid-gray) + ); + --item-navigator-menu-button-label-display--: var( + --item-navigator-menu-button-label-display, + none + ); + --item-navigator-icon-inactive-color--: var( + --item-navigator-icon-inactive-color, + var(--lighter-gray) + ); + --item-navigator-icon-active-color--: var( + --item-navigator-icon-active-color, + var(--item-navigator-text-color--) + ); + /* Every glyph is square, so one knob sizes both axes. */ + --item-navigator-icon-size--: var(--item-navigator-icon-size, 2.4em); + + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + a { + display: inline-block; + text-decoration: none; + } + + button.menu-item { + -webkit-appearance: none; + appearance: none; + /* Inherit font-size so the em-sized icon/label resolve against the + component base rather than the UA default button font-size. */ + font: inherit; + } + + .menu-item { + display: inline-flex; + width: 100%; + padding: 0; + text-align: left; + background: transparent; + align-items: center; + border: none; + cursor: pointer; + transition: background-color 0.2s; + border-radius: 6px; + } + + .menu-item:hover { + background-color: rgba(255, 255, 255, 0.1); + } + + .label { + display: var(--item-navigator-menu-button-label-display--); + padding: 0; + font-size: 1.6em; + font-weight: 400; + color: var(--item-navigator-text-color--); + text-align: left; + vertical-align: middle; + margin-left: 1em; + } + + .menu-details { + color: var(--item-navigator-text-color--); + display: inline-block; + margin-left: 0.5em; + font-style: italic; + font-size: 1.5em; + } + + .menu-item > .icon { + position: relative; + display: inline-flex; + min-width: 4.2em; + max-width: 4.2em; + height: 4.2em; + vertical-align: middle; + align-items: center; + justify-content: center; + } + + .menu-item > .icon > * { + /* Prevent tooltip containing icon literal description */ + pointer-events: none; + } + + /* Size the glyph within the icon box to match the shortcut-rail + icons, rather than letting the svg fill the whole box. */ + .menu-item > .icon .ia-icon { + width: var(--item-navigator-icon-size--); + height: var(--item-navigator-icon-size--); + } + + /* The open entry's icon shares the panel's background and rounds into + it, so it has to sit above the panel to read as one shape. The rest + stay below: they have no background of their own, so the panel would + slide visibly behind them. */ + .menu-item[aria-expanded='true'] .icon { + z-index: 2; + background-color: var(--item-navigator-active-button-bg--); + border-radius: 1em 0 0 1em; + } + + /* Our glyphs are masked spans: the mask supplies the shape, these + supply the paint. */ + .icon span.ia-icon { + background-color: var(--item-navigator-icon-inactive-color--); + } + + .icon.active span.ia-icon { + background-color: var(--item-navigator-icon-active-color--); + } + + /* Host-supplied icons may still be inline svg, so keep theming those + the original way. */ + .icon .fill-color { + fill: var(--item-navigator-icon-inactive-color--); + } + + .icon.active .fill-color { + fill: var(--item-navigator-icon-active-color--); + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-menu-button': IAItemNavMenuButton; + } +} diff --git a/src/elements/ia-item-navigator/ia-itemnav-menu-slider.test.ts b/src/elements/ia-item-navigator/ia-itemnav-menu-slider.test.ts new file mode 100644 index 000000000..2adaafce3 --- /dev/null +++ b/src/elements/ia-item-navigator/ia-itemnav-menu-slider.test.ts @@ -0,0 +1,351 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test, vi } from 'vitest'; + +import { IAItemNavMenuSlider } from './ia-itemnav-menu-slider'; +import './ia-itemnav-menu-slider'; +import type { MenuProviderInterface } from './interfaces/menu-interfaces'; + +function provider( + id: string, + overrides: Partial = {}, +): MenuProviderInterface { + return { + id, + label: `${id} label`, + icon: html`${id}`, + identifier: 'test-item', + baseHost: 'archive.org', + subPrefix: '', + component: html`
    ${id} body
    `, + ...overrides, + }; +} + +async function sliderWith( + menus: MenuProviderInterface[], +): Promise { + const el = await fixture( + html``, + ); + el.menus = menus; + await el.updateComplete; + return el; +} + +describe('IAItemNavMenuSlider', () => { + test('renders one menu button per provider', async () => { + const el = await sliderWith([provider('a'), provider('b'), provider('c')]); + expect( + el.shadowRoot?.querySelectorAll('ia-itemnav-menu-button'), + ).to.have.lengthOf(3); + }); + + test('renders a close button', async () => { + const el = await sliderWith([provider('a')]); + expect(el.shadowRoot?.querySelector('button.close')).to.exist; + }); + + test('reports the selection instead of deciding it', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + const selected = vi.fn(); + el.addEventListener('menuTypeSelected', selected); + + const menuButton = el.shadowRoot?.querySelector('ia-itemnav-menu-button'); + ( + menuButton?.shadowRoot?.querySelector('button') as HTMLButtonElement + ).click(); + await el.updateComplete; + + // The navigator owns which panel is open, so there is only ever one copy + // of that state to keep straight. + expect(selected).toHaveBeenCalledOnce(); + expect(selected.mock.calls[0][0].detail.id).to.equal('a'); + expect(el.selectedMenu).to.equal(''); + }); + + test('opens whichever panel the host selects', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + el.selectedMenu = 'b'; + await el.updateComplete; + + expect(el.selectedMenuClass).to.equal('open'); + expect( + el.shadowRoot?.querySelector('.selected-menu .panel-body')?.textContent, + ).to.contain('b body'); + }); + + test('a closed panel is out of the tab order and the a11y tree', async () => { + const el = await sliderWith([provider('a')]); + const panel = el.shadowRoot?.querySelector('.content') as HTMLElement; + + expect(panel.hasAttribute('inert'), 'closed panel should be inert').to.be + .true; + + el.selectedMenu = 'a'; + await el.updateComplete; + expect(panel.hasAttribute('inert'), 'open panel should be reachable').to.be + .false; + }); + + test('names the panel by its heading', async () => { + const el = await sliderWith([provider('a')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + const panel = el.shadowRoot?.querySelector('.content') as HTMLElement; + const headingId = panel.getAttribute('aria-labelledby'); + expect(headingId).to.exist; + expect( + el.shadowRoot?.querySelector(`#${headingId}`)?.textContent, + ).to.contain('a label'); + }); + + test('renders the selected provider body', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + el.selectedMenu = 'b'; + await el.updateComplete; + + const body = el.shadowRoot?.querySelector('.selected-menu .panel-body'); + expect(body?.textContent).to.contain('b body'); + }); + + test('the drawer close button asks the host to close the drawer', async () => { + const el = await sliderWith([provider('a')]); + const listener = vi.fn(); + el.addEventListener('menuSliderClosed', listener); + + ( + el.shadowRoot?.querySelector('.menu > button.close') as HTMLButtonElement + ).click(); + + expect(listener).toHaveBeenCalledOnce(); + }); + + test('the two close buttons are named for what they close', async () => { + const el = await sliderWith([provider('a')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + const drawerClose = el.shadowRoot?.querySelector('.menu > button.close'); + const panelClose = el.shadowRoot?.querySelector( + '.content header button.close', + ); + + expect(drawerClose?.getAttribute('aria-label')).to.equal( + 'Close navigation', + ); + expect(panelClose?.getAttribute('aria-label')).to.equal('Close a label'); + }); + + test('closing the sub-panel leaves the drawer alone', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + const panelClosed = vi.fn(); + const drawerClosed = vi.fn(); + el.addEventListener('menuPanelClosed', panelClosed); + el.addEventListener('menuSliderClosed', drawerClosed); + + const closeButton = el.shadowRoot?.querySelector( + '.content header button.close', + ) as HTMLButtonElement; + expect(closeButton).to.exist; + closeButton.click(); + + expect(panelClosed).toHaveBeenCalledOnce(); + expect(panelClosed.mock.calls[0][0].detail.id).to.equal('a'); + expect(drawerClosed).not.toHaveBeenCalled(); + }); + + test('Escape closes the open panel first, then the drawer', async () => { + const el = await sliderWith([provider('a')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + const panelClosed = vi.fn(); + const drawerClosed = vi.fn(); + el.addEventListener('menuPanelClosed', panelClosed); + el.addEventListener('menuSliderClosed', drawerClosed); + const main = el.shadowRoot?.querySelector('.main') as HTMLElement; + + // First Escape reaches for the panel, not the drawer. + main.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); + expect(panelClosed).toHaveBeenCalledOnce(); + expect(drawerClosed).not.toHaveBeenCalled(); + + // Once the host has cleared the selection, Escape closes the drawer. + el.selectedMenu = ''; + await el.updateComplete; + main.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); + expect(drawerClosed).toHaveBeenCalledOnce(); + }); + + test('closing a panel hands focus back to the button that opened it', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + el.selectedMenu = 'b'; + await el.updateComplete; + + // The host clears the selection in response to menuPanelClosed. + el.selectedMenu = ''; + await el.updateComplete; + + const buttons = el.shadowRoot?.querySelectorAll('ia-itemnav-menu-button'); + expect(el.shadowRoot?.activeElement).to.equal(buttons?.[1]); + }); + + test('opening a panel moves focus into it', async () => { + const el = await sliderWith([provider('a')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + expect(el.shadowRoot?.activeElement).to.equal( + el.shadowRoot?.querySelector('.content'), + ); + }); + + test('closePanel is safe when nothing is selected', async () => { + const el = await sliderWith([provider('a')]); + expect(() => el.closePanel()).to.not.throw(); + }); + + describe('panel movement', () => { + const panelOf = (el: IAItemNavMenuSlider) => + el.shadowRoot?.querySelector('.content') as HTMLElement; + + /** + * Whether the panel is covering the menu list or parked off to its left. + * Read from the rendered box rather than the transform, so the assertion + * survives a change in how the movement is expressed. + */ + const panelCoversMenu = (el: IAItemNavMenuSlider) => { + const panel = panelOf(el).getBoundingClientRect(); + const list = ( + el.shadowRoot?.querySelector('.menu-list') as HTMLElement + ).getBoundingClientRect(); + return panel.left >= list.left; + }; + + /** Settles transforms instantly so positions can be read, not awaited. */ + const withoutAnimation = async (menus: MenuProviderInterface[]) => { + const el = await sliderWith(menus); + el.style.setProperty('--item-navigator-animation-timing', '0ms'); + await el.updateComplete; + return el; + }; + + test('the panel slides on the edges between empty and open', async () => { + const el = await withoutAnimation([provider('a')]); + + expect(panelCoversMenu(el), 'closed panel should be off to the left').to + .be.false; + + el.selectedMenu = 'a'; + await el.updateComplete; + expect(panelCoversMenu(el), 'open panel should cover the menu').to.be + .true; + + el.selectedMenu = ''; + await el.updateComplete; + expect(panelCoversMenu(el), 'panel should slide back out').to.be.false; + }); + + test('switching between panels swaps contents without moving', async () => { + const el = await withoutAnimation([provider('a'), provider('b')]); + const panel = panelOf(el); + + el.selectedMenu = 'a'; + await el.updateComplete; + const settled = panelOf(el).getBoundingClientRect().left; + expect(panelCoversMenu(el)).to.be.true; + + el.selectedMenu = 'b'; + await el.updateComplete; + + // The panel is already in place, so only its contents change — it keeps + // the open class and never re-runs the slide. + expect(panel.classList.contains('open')).to.be.true; + expect(panelOf(el).getBoundingClientRect().left).to.equal(settled); + expect( + el.shadowRoot?.querySelector('.selected-menu .panel-body')?.textContent, + ).to.contain('b body'); + }); + + test('the host can suppress the slide so the panel rides in', async () => { + const el = await sliderWith([provider('a')]); + const panel = panelOf(el); + + // Default: the panel animates itself. + expect(getComputedStyle(panel).transitionDuration).to.not.equal('0s'); + + // The navigator hands this down while the drawer is opening, so the + // panel holds still and the drawer carries it in. + el.style.setProperty('--item-navigator-panel-transition--', 'none'); + await el.updateComplete; + expect(getComputedStyle(panel).transitionDuration).to.equal('0s'); + }); + }); + + test('ignores non-Escape keydowns', async () => { + const el = await sliderWith([provider('a')]); + el.selectedMenu = 'a'; + await el.updateComplete; + + const main = el.shadowRoot?.querySelector('.main') as HTMLElement; + main.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })); + await el.updateComplete; + // Nothing changed — the panel stays open. + expect(el.selectedMenu).to.equal('a'); + }); + + test("surfaces a selected provider's action button in the panel header", async () => { + const el = await sliderWith([ + provider('a', { + actionButton: html``, + }), + provider('b'), + ]); + el.selectedMenu = 'a'; + await el.updateComplete; + // updated() sets selectedMenuAction, which schedules a follow-up render. + await el.updateComplete; + + // renderMenuHeader then renders the action button inside the header. + expect(el.selectedMenuAction).to.not.equal(undefined); + const header = el.shadowRoot?.querySelector('.content header'); + expect(header?.classList.contains('with-secondary-action')).to.equal(true); + expect(header?.querySelector('.custom-action .my-action')).to.exist; + }); + + test('a selected provider without an action button gets a plain header', async () => { + const el = await sliderWith([provider('a'), provider('b')]); + el.selectedMenu = 'b'; // provider('b') has no actionButton + await el.updateComplete; + await el.updateComplete; + + const header = el.shadowRoot?.querySelector('.content header'); + expect(header?.classList.contains('with-secondary-action')).to.equal(false); + expect(header?.querySelector('.custom-action')).to.not.exist; + }); + + test('renders menu buttons with details, followable and href wired through', async () => { + const el = await sliderWith([ + provider('plain'), + provider('linky', { + href: '/go', + followable: true, + menuDetails: html`2 files`, + }), + ]); + + const buttons = el.shadowRoot?.querySelectorAll('ia-itemnav-menu-button'); + expect(buttons).to.have.lengthOf(2); + const linky = buttons?.[1] as HTMLElement & { + href: string; + followable: boolean; + }; + expect(linky.href).to.equal('/go'); + expect(linky.followable).to.equal(true); + }); +}); diff --git a/src/elements/ia-item-navigator/ia-itemnav-menu-slider.ts b/src/elements/ia-item-navigator/ia-itemnav-menu-slider.ts new file mode 100644 index 000000000..0aa19fb4d --- /dev/null +++ b/src/elements/ia-item-navigator/ia-itemnav-menu-slider.ts @@ -0,0 +1,422 @@ +import { + css, + html, + LitElement, + nothing, + type PropertyValues, + TemplateResult, + type CSSResultGroup, +} from 'lit'; +import { customElement, property, query } from 'lit/decorators.js'; +import themeStyles from '@src/themes/theme-styles'; +import { collapseSidebarIcon } from './icons'; +import './ia-itemnav-menu-button'; +import type { IAItemNavMenuButton } from './ia-itemnav-menu-button'; +import { MenuProviderInterface } from './interfaces/menu-interfaces'; + +const sliderEvents = { + closeDrawer: 'menuSliderClosed', + closePanel: 'menuPanelClosed', +}; + +/** + * The sliding drawer that lists the navigator's menu providers and renders the + * body of whichever provider is currently selected. + */ +@customElement('ia-itemnav-menu-slider') +export class IAItemNavMenuSlider extends LitElement { + @property({ type: Array }) menus: MenuProviderInterface[] = []; + + /** + * Which panel is open. The navigator owns this — the slider only reports + * what the user did and renders whatever comes back, so there is one copy + * of the state rather than two that have to agree. + */ + @property({ type: String }) selectedMenu = ''; + + @property({ type: Object }) selectedMenuAction: + | TemplateResult + | typeof nothing = nothing; + + @query('.content') private panel?: HTMLElement; + + @query('.menu-list') private menuList?: HTMLUListElement; + + @query('.menu > button.close') private drawerCloseButton?: HTMLElement; + + /** Focus should follow what the user did, not the first render. */ + private isFirstRender = true; + + protected updated(changed: PropertyValues): void { + const actionButton = this.selectedMenuDetails?.actionButton || nothing; + if (actionButton !== this.selectedMenuAction) { + this.selectedMenuAction = actionButton; + } + + if (!this.isFirstRender && changed.has('selectedMenu')) { + this.moveFocusForSelection(changed.get('selectedMenu') as string); + } + this.isFirstRender = false; + } + + /** + * Opening a panel moves focus into it, so it is announced by name; closing + * hands focus back to the button that opened it. + */ + private moveFocusForSelection(previousMenu: string): void { + if (this.selectedMenu) { + this.panel?.focus(); + } else if (previousMenu) { + this.menuButtonFor(previousMenu)?.focus(); + } + } + + private menuButtonFor(menuId: string): IAItemNavMenuButton | undefined { + const buttons = + this.menuList?.querySelectorAll( + 'ia-itemnav-menu-button', + ) ?? []; + return [...buttons].find((button) => button.buttonId === menuId); + } + + /** + * Moves focus into the drawer — the open panel if there is one, otherwise + * the first thing worth acting on. Exposed so the navigator doesn't have to + * reach through this component's shadow DOM to place focus. + */ + focusDrawer(): void { + if (this.selectedMenu) { + this.panel?.focus(); + return; + } + const firstMenuButton = this.menuList?.querySelector( + 'ia-itemnav-menu-button', + ); + (firstMenuButton ?? this.drawerCloseButton)?.focus(); + } + + /** Asks the navigator to close the whole drawer. */ + closeMenu(): void { + this.dispatchEvent( + new CustomEvent(sliderEvents.closeDrawer, { + detail: this.selectedMenuDetails, + }), + ); + } + + /** Asks the navigator to close just the open panel. */ + closePanel(): void { + this.dispatchEvent( + new CustomEvent(sliderEvents.closePanel, { + detail: { id: this.selectedMenu }, + }), + ); + } + + /** Escape closes the panel first, then the drawer. */ + handleKeyDown(event: KeyboardEvent): void { + if (event.key !== 'Escape') return; + event.preventDefault(); + if (this.selectedMenu) { + this.closePanel(); + } else { + this.closeMenu(); + } + } + + get selectedMenuDetails(): MenuProviderInterface | undefined { + return this.menus.find((menu) => menu.id === this.selectedMenu); + } + + /* render */ + + get selectedMenuClass(): string { + return this.selectedMenu ? 'open' : ''; + } + + get menuItems(): TemplateResult[] { + return this.menus.map( + (menu) => html` +
  • + +
  • + `, + ); + } + + get renderMenuHeader(): TemplateResult { + const { label = '', menuDetails = '' } = this.selectedMenuDetails || {}; + // `selectedMenuAction` defaults to Lit's `nothing` sentinel, which is + // truthy — so compare against it explicitly, otherwise the header would + // always get the secondary-action treatment (and an empty action span). + const hasAction = this.selectedMenuAction !== nothing; + const headerClass = hasAction ? 'with-secondary-action' : ''; + const actionBlock = hasAction + ? html`${this.selectedMenuAction}` + : nothing; + const closeLabel = label ? `Close ${label}` : 'Close this panel'; + return html` +
    +
    +

    ${label}

    + ${menuDetails} +
    + ${actionBlock} + +
    + `; + } + + get closeButton(): TemplateResult { + return html` + + `; + } + + /** @inheritdoc */ + render(): TemplateResult { + const panelOpen = !!this.selectedMenu; + return html` +
    + +
    + `; + } + + static get styles(): CSSResultGroup { + const menuButtonWidth = css`42px`; + const sliderWidth = css`var(--item-navigator-menu-width--)`; + const transitionTiming = css`var(--item-navigator-animation-timing--)`; + + return [ + themeStyles, + css` + :host { + --item-navigator-menu-width--: var( + --item-navigator-menu-width, + 320px + ); + --item-navigator-animation-timing--: var( + --item-navigator-animation-timing, + 200ms + ); + --item-navigator-text-color--: var( + --item-navigator-text-color, + var(--true-white) + ); + --item-navigator-menu-slider-bg--: var( + --item-navigator-menu-slider-bg, + #212121 + ); + --item-navigator-active-button-bg--: var( + --item-navigator-active-button-bg, + var(--mid-gray) + ); + --item-navigator-border-color--: var( + --item-navigator-border-color, + #4b4b4b + ); + /* Every glyph is square, so one knob sizes both axes. */ + --item-navigator-header-icon-size--: var( + --item-navigator-header-icon-size, + 2em + ); + --item-navigator-icon-color--: var( + --item-navigator-icon-color, + var(--item-navigator-text-color--) + ); + + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + .main { + overflow: hidden; + width: 100%; + height: 100%; + } + + /* The drawer's own slide is owned by the navigator's #menu; this just + fills it. */ + .menu { + position: absolute; + top: 0; + left: 0; + bottom: 0; + width: ${sliderWidth}; + padding: 0.5em 0.5em 0 0; + box-sizing: border-box; + font-size: 1.4em; + color: var(--item-navigator-text-color--); + background: var(--item-navigator-menu-slider-bg--); + } + + button { + cursor: pointer; + } + + header { + margin: 0 0 0.5em 0; + } + + header * { + margin: 0; + display: inline-block; + } + + header button { + cursor: pointer; + } + + header.with-secondary-action .details { + width: 80%; + } + + header .details { + font-weight: bold; + width: 88%; + } + + header .custom-action > *, + button.close { + padding: 0; + background-color: transparent; + border: 0; + } + + header .custom-action, + button.close { + position: absolute; + } + + button.close { + /* Reset to the base so the header icon (em) doesn't compound + against .menu's enlarged font-size. */ + font-size: var(--item-navigator-base-font-size--); + min-width: 38px; + min-height: 38px; + display: flex; + justify-content: center; + align-items: center; + right: 0; + top: 0; + } + + button.close .ia-icon { + width: var(--item-navigator-header-icon-size--); + height: var(--item-navigator-header-icon-size--); + } + + /* Our glyphs are masked spans: the mask supplies the shape, this + supplies the paint. */ + span.ia-icon { + background-color: var(--item-navigator-icon-color--); + } + + /* Host-supplied icons may still be inline svg, so keep theming those + the original way. */ + .ia-icon .fill-color { + fill: var(--item-navigator-icon-color--); + } + + .content { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: ${menuButtonWidth}; + z-index: 1; + transform: translateX(calc(${sliderWidth} * -1)); + transition: var( + --item-navigator-panel-transition--, + transform ${transitionTiming} ease-out + ); + background: var(--item-navigator-active-button-bg--); + border-right: 0.2em solid; + border-color: var(--item-navigator-border-color--); + padding: 0.5em 0 0 0.5em; + display: flex; + flex-direction: column; + } + + .content.open { + transform: translateX(0); + } + + .content:focus { + outline: none; + } + + .menu-list { + padding: 0; + margin: 0; + list-style: none; + background: var(--item-navigator-menu-slider-bg--); + } + + .menu-list li { + margin-bottom: 0.2em; + } + + .content > section { + overflow: auto; + overscroll-behavior: contain; + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-menu-slider': IAItemNavMenuSlider; + } +} diff --git a/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.test.ts b/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.test.ts new file mode 100644 index 000000000..14aa1499a --- /dev/null +++ b/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.test.ts @@ -0,0 +1,61 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test, vi } from 'vitest'; + +import { IAItemNavNoTheaterAvailable } from './ia-itemnav-no-theater-available'; +import './ia-itemnav-no-theater-available'; + +describe('IAItemNavNoTheaterAvailable', () => { + test('renders the placeholder message', async () => { + const el = await fixture( + html``, + ); + expect(el.shadowRoot?.querySelector('h2')?.textContent).to.contain( + 'NO PREVIEW AVAILABLE', + ); + }); + + test('links to the item download page', async () => { + const el = await fixture( + html``, + ); + expect(el.downloadUrl).to.equal('/download/my-item'); + expect(el.shadowRoot?.querySelector('a')?.getAttribute('href')).to.equal( + '/download/my-item', + ); + }); + + test('emits loadingStateUpdated once the identifier is set', async () => { + const el = await fixture( + html``, + ); + const listener = vi.fn(); + el.addEventListener('loadingStateUpdated', listener); + + el.identifier = 'abc'; + await el.updateComplete; + + expect(listener).toHaveBeenCalledOnce(); + expect((listener.mock.calls[0][0] as CustomEvent).detail.loaded).to.equal( + true, + ); + }); + + test('does not re-emit loadingStateUpdated on updates that leave the identifier unchanged', async () => { + const el = await fixture( + html``, + ); + const listener = vi.fn(); + el.addEventListener('loadingStateUpdated', listener); + + // An update with no identifier change must skip emitLoaded(). + el.requestUpdate(); + await el.updateComplete; + + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.ts b/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.ts new file mode 100644 index 000000000..ed0c4f830 --- /dev/null +++ b/src/elements/ia-item-navigator/ia-itemnav-no-theater-available.ts @@ -0,0 +1,112 @@ +import { + LitElement, + html, + TemplateResult, + PropertyValues, + css, + type CSSResultGroup, +} from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import themeStyles from '@src/themes/theme-styles'; + +/** + * Placeholder shown in place of the theater when `viewAvailable` is false, + * i.e. the item has no files that can be experienced in the browser. Emits + * `loadingStateUpdated` so the navigator hides its loading spinner. + */ +@customElement('ia-itemnav-no-theater-available') +export class IAItemNavNoTheaterAvailable extends LitElement { + @property({ type: String }) identifier?: string = ''; + + emitLoaded(): void { + this.dispatchEvent( + new CustomEvent<{ loaded: boolean }>('loadingStateUpdated', { + detail: { loaded: true }, + }), + ); + } + + updated(changed: PropertyValues): void { + if (changed.has('identifier')) { + this.emitLoaded(); + } + } + + get downloadUrl(): string { + return `/download/${this.identifier}`; + } + + render(): TemplateResult { + return html` +
    +

    THERE IS NO PREVIEW AVAILABLE FOR THIS ITEM

    +

    + This item does not appear to have any files that can be experienced on + Archive.org.
    + Please download files in this item to interact with them on your + computer. +

    + Show all files +
    + `; + } + + static get styles(): CSSResultGroup { + return [ + themeStyles, + css` + :host { + --item-navigator-text-color--: var( + --item-navigator-text-color, + var(--true-white) + ); + color: var(--item-navigator-text-color--); + text-align: center; + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + section { + width: 100%; + margin: 5%; + padding: 0 5%; + } + + p { + font-size: 1.4em; + } + + a { + color: var(--item-navigator-text-color--); + background-color: var(--navy-blue); + min-height: 35px; + cursor: pointer; + line-height: normal; + border-radius: 0.4em; + text-align: center; + vertical-align: middle; + font-size: 1.4em; + font-family: var(--base-font-family); + display: inline-block; + padding: 0.85em 1.2em; + border: 1px solid var(--lightest-gray); + white-space: nowrap; + appearance: auto; + box-sizing: border-box; + user-select: none; + text-decoration: none; + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-no-theater-available': IAItemNavNoTheaterAvailable; + } +} diff --git a/src/elements/ia-item-navigator/icons.ts b/src/elements/ia-item-navigator/icons.ts new file mode 100644 index 000000000..e7c32c6c7 --- /dev/null +++ b/src/elements/ia-item-navigator/icons.ts @@ -0,0 +1,19 @@ +import { maskedIcon } from './masked-icon'; + +import ellipsesUrl from './icons/ellipses.svg'; +import collapseSidebarUrl from './icons/collapse-sidebar.svg'; + +/** + * Icons taken from the `@internetarchive/icon-ellipses` and + * `@internetarchive/icon-collapse-sidebar` packages (v1.4.1). They ship as + * standalone `.svg` files — rather than icon package dependencies or inline + * templates — so their path data stays out of the JS bundle. Each is rendered + * as a CSS-masked span (see `maskedIcon`) so host components can still recolor + * it via their own custom properties. + */ + +/** Three-dot "more options" glyph used by the menu toggle button. */ +export const ellipsesIcon = maskedIcon(ellipsesUrl); + +/** Circular "collapse sidebar" glyph used by the menu/panel close buttons. */ +export const collapseSidebarIcon = maskedIcon(collapseSidebarUrl); diff --git a/src/elements/ia-item-navigator/icons/collapse-sidebar.svg b/src/elements/ia-item-navigator/icons/collapse-sidebar.svg new file mode 100644 index 000000000..09943cac7 --- /dev/null +++ b/src/elements/ia-item-navigator/icons/collapse-sidebar.svg @@ -0,0 +1,7 @@ + + + diff --git a/src/elements/ia-item-navigator/icons/ellipses.svg b/src/elements/ia-item-navigator/icons/ellipses.svg new file mode 100644 index 000000000..09c40732f --- /dev/null +++ b/src/elements/ia-item-navigator/icons/ellipses.svg @@ -0,0 +1,7 @@ + + + diff --git a/src/elements/ia-item-navigator/interfaces/event-interfaces.ts b/src/elements/ia-item-navigator/interfaces/event-interfaces.ts new file mode 100644 index 000000000..741f71a09 --- /dev/null +++ b/src/elements/ia-item-navigator/interfaces/event-interfaces.ts @@ -0,0 +1,50 @@ +import { + MenuProviderInterface, + MenuShortcutInterface, + MenuId, +} from './menu-interfaces'; + +/** Toggles Menu && Sets open panel */ +export interface ToggleSideMenuOpenEvent extends CustomEvent { + type: 'updateSideMenu'; + detail: { + menuId: MenuId | undefined | ''; + action: 'open' | 'toggle' | ''; + }; +} + +/** Sets open panel */ +export interface ToggleSidePanelOpenEvent extends CustomEvent { + type: 'menuTypeSelected'; + detail: { + id: MenuId | ''; + }; +} + +/** Sets menu order that is displayed */ +export interface SetSideMenuContentsEvent extends CustomEvent { + type: 'menuUpdated'; + detail: MenuProviderInterface[]; +} + +/** Sets menu shortcuts that is displayed */ +export interface SetSideMenuShortcutsEvent extends CustomEvent { + type: 'menuUpdated'; + detail: MenuShortcutInterface[]; +} + +/** Toggles fullscreen mode */ +export interface ManageFullscreenEvent extends CustomEvent { + type: 'ViewportInFullScreen'; + detail: { + isFullScreen: boolean; + }; +} + +/** Toggles loading view */ +export interface LoadingStateUpdatedEvent extends CustomEvent { + type: 'loadingStateUpdated'; + detail: { + loaded: boolean; + }; +} diff --git a/src/elements/ia-item-navigator/interfaces/menu-interfaces.ts b/src/elements/ia-item-navigator/interfaces/menu-interfaces.ts new file mode 100644 index 000000000..b2c97b99a --- /dev/null +++ b/src/elements/ia-item-navigator/interfaces/menu-interfaces.ts @@ -0,0 +1,25 @@ +import { TemplateResult } from 'lit'; + +export type MenuId = string; +export interface MenuShortcutInterface { + icon: TemplateResult; + id: MenuId; + label: string; +} + +export interface MenuDetailsInterface extends MenuShortcutInterface { + menuDetails?: TemplateResult; + selected?: boolean; + followable?: boolean; + href?: string; + component?: TemplateResult; +} + +export interface MenuProviderInterface extends MenuDetailsInterface { + /** archive.org item identifier. */ + identifier: string; + baseHost: string; + subPrefix: string; + updated?: unknown; + actionButton?: TemplateResult; +} diff --git a/src/elements/ia-item-navigator/masked-icon.test.ts b/src/elements/ia-item-navigator/masked-icon.test.ts new file mode 100644 index 000000000..e5e4d43a3 --- /dev/null +++ b/src/elements/ia-item-navigator/masked-icon.test.ts @@ -0,0 +1,92 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test } from 'vitest'; + +import { maskedIcon } from './masked-icon'; + +const ICON_URL = '/some/where/glyph.svg'; + +/** + * What a bundler actually hands us for a small SVG: an inlined `data:` URI + * whose markup is quoted with apostrophes. This is the case that breaks if the + * `url()` isn't quoted, so it's worth testing explicitly. + */ +const INLINED_DATA_URI = + "data:image/svg+xml,%3csvg viewBox='0 0 18 18' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='%23000' d='m9 0h9v9z'/%3e%3c/svg%3e"; + +describe('maskedIcon', () => { + test('renders the glyph as a masked span rather than inline svg', async () => { + const el = await fixture( + html`
    ${maskedIcon(ICON_URL)}
    `, + ); + const icon = el.querySelector('.ia-icon') as HTMLElement; + + // The point of the mask approach: no svg markup ships in the JS bundle. + expect(el.querySelector('svg')).to.not.exist; + expect(icon.tagName).to.equal('SPAN'); + }); + + test('points the mask at the standalone svg asset', async () => { + const el = await fixture( + html`
    ${maskedIcon(ICON_URL)}
    `, + ); + const icon = el.querySelector('.ia-icon') as HTMLElement; + const { maskImage, webkitMaskImage } = getComputedStyle(icon); + + // Both prefixes are emitted so Safari/iOS render the glyph too. + expect(maskImage).to.contain(ICON_URL); + expect(webkitMaskImage).to.contain(ICON_URL); + }); + + test('still applies the mask when the icon is an inlined data URI', async () => { + const el = await fixture( + html`
    ${maskedIcon(INLINED_DATA_URI)}
    `, + ); + const icon = el.querySelector('.ia-icon') as HTMLElement; + const { maskImage } = getComputedStyle(icon); + + // An unquoted url() containing apostrophes is invalid CSS, so the whole + // declaration would be dropped and the glyph would paint as a solid block. + expect(maskImage).to.not.equal('none'); + expect(maskImage).to.contain('data:image/svg+xml'); + }); + + test('scales the glyph to the box without repeating it', async () => { + const el = await fixture( + html`
    ${maskedIcon(ICON_URL)}
    `, + ); + const styles = getComputedStyle( + el.querySelector('.ia-icon') as HTMLElement, + ); + + expect(styles.maskRepeat).to.equal('no-repeat'); + expect(styles.maskSize).to.equal('contain'); + expect(styles.display).to.equal('inline-block'); + }); + + test('takes its paint from background-color so hosts can recolor it', async () => { + const el = await fixture( + html`
    + + ${maskedIcon(ICON_URL)} +
    `, + ); + const icon = el.querySelector('.ia-icon') as HTMLElement; + + expect(getComputedStyle(icon).backgroundColor).to.equal('rgb(10, 20, 30)'); + }); + + test('hides the decorative glyph from assistive tech', async () => { + const el = await fixture( + html`
    ${maskedIcon(ICON_URL)}
    `, + ); + + expect( + (el.querySelector('.ia-icon') as HTMLElement).getAttribute('aria-hidden'), + ).to.equal('true'); + }); +}); diff --git a/src/elements/ia-item-navigator/masked-icon.ts b/src/elements/ia-item-navigator/masked-icon.ts new file mode 100644 index 000000000..80c6a5b3d --- /dev/null +++ b/src/elements/ia-item-navigator/masked-icon.ts @@ -0,0 +1,30 @@ +import { html, type TemplateResult } from 'lit'; + +/** + * Renders an icon from a standalone `.svg` file as a CSS-masked element. + * + * The glyphs live as `.svg` assets rather than inline templates so their path + * data stays out of the JS bundle. They are drawn with `mask-image` (not + * ``) so host components can still recolor them: the mask supplies the + * shape and `background-color` supplies the paint, which keeps the + * `--item-navigator-icon-color` theming working. + * + * The mask geometry is set inline so an icon renders correctly wherever it is + * slotted — including inside a consumer's shadow DOM, for the icons this + * package exports publicly. Hosts only supply `background-color` and a size, + * both of which legitimately vary per host. Icons are decorative (always + * labelled by adjacent text or an `aria-label` on the control), so the span is + * `aria-hidden`. + * + * The `url()` is quoted deliberately: bundlers inline small SVGs as `data:` + * URIs whose markup contains apostrophes, and an *unquoted* CSS `url()` token + * cannot contain them — the whole `mask-image` declaration would be dropped + * and the glyph would paint as a solid block. + */ +export const maskedIcon = (url: string): TemplateResult => html` + +`; diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.test.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.test.ts new file mode 100644 index 000000000..ad32180b4 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.test.ts @@ -0,0 +1,157 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { afterEach, describe, expect, test, vi } from 'vitest'; + +import { IAItemNavSharePanel } from './ia-itemnav-share-panel'; +import './ia-itemnav-share-panel'; + +/** Reaches the private copy handler for the edge-case paths. */ +type WithCopy = { copyToClipboard(e: MouseEvent): Promise }; + +describe('IAItemNavSharePanel', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + test('auto-populates the social sharing options', async () => { + const el = await fixture( + html``, + ); + await el.updateComplete; + + const links = el.shadowRoot?.querySelectorAll('a.share-option'); + expect(links).to.have.lengthOf(5); + const names = [...(links ?? [])].map((a) => a.textContent?.trim()); + expect(names).to.deep.equal([ + 'Twitter', + 'Facebook', + 'Tumblr', + 'Pinterest', + 'Email', + ]); + }); + + test('builds share URLs from the identifier, host and sub-prefix', async () => { + const el = await fixture( + html``, + ); + await el.updateComplete; + + const twitter = el.sharingOptions.find((o) => o.name === 'Twitter'); + expect(twitter?.url).to.contain( + encodeURIComponent('https://example.org/details/my-item/vol1'), + ); + }); + + test('exposes iframe and bbcode embed snippets and a help URL', async () => { + const el = await fixture( + html``, + ); + expect(el.iframeEmbed).to.contain( + 'src="https://example.org/embed/my-item"', + ); + expect(el.bbcodeEmbed).to.contain('[archiveorg my-item'); + expect(el.helpURL).to.contain('identifier=my-item'); + }); + + test('renders a header only when renderHeader is set', async () => { + const el = await fixture( + html``, + ); + expect(el.shadowRoot?.querySelector('header')).to.not.exist; + + el.renderHeader = true; + await el.updateComplete; + expect(el.shadowRoot?.querySelector('header h3')?.textContent).to.contain( + 'Share this book', + ); + }); + + test('flashes the "copied" note when an embed block is clicked', async () => { + const el = await fixture( + html``, + ); + await el.updateComplete; + + const code = el.shadowRoot?.querySelector('.code') as HTMLElement; + const note = code.querySelector('small') as HTMLElement; + expect(note.classList.contains('visible')).to.equal(false); + + code.click(); + // copy handler is async (Clipboard API, then note toggle) + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(note.classList.contains('visible')).to.equal(true); + }); + + test('copy is a no-op when the clicked target has no embed code', async () => { + const el = await fixture( + html``, + ); + const bare = document.createElement('div'); + await expect( + (el as unknown as WithCopy).copyToClipboard({ + currentTarget: bare, + } as unknown as MouseEvent), + ).resolves.toBeUndefined(); + }); + + test('falls back to execCommand when the async clipboard rejects', async () => { + const el = await fixture( + html``, + ); + await el.updateComplete; + const code = el.shadowRoot?.querySelector('.code') as HTMLElement; + const note = code.querySelector('small') as HTMLElement; + + vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValue( + new Error('no async clipboard'), + ); + const exec = vi.spyOn(document, 'execCommand').mockReturnValue(true); + + await (el as unknown as WithCopy).copyToClipboard({ + currentTarget: code, + } as unknown as MouseEvent); + + expect(exec).toHaveBeenCalledWith('copy'); + expect(note.classList.contains('visible')).to.equal(true); + }); + + test('clears the copied note after the timeout window', async () => { + const el = await fixture( + html``, + ); + await el.updateComplete; + const code = el.shadowRoot?.querySelector('.code') as HTMLElement; + const note = code.querySelector('small') as HTMLElement; + + vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined); + vi.useFakeTimers(); + + await (el as unknown as WithCopy).copyToClipboard({ + currentTarget: code, + } as unknown as MouseEvent); + expect(note.classList.contains('visible')).to.equal(true); + + vi.advanceTimersByTime(4000); + expect(note.classList.contains('visible')).to.equal(false); + }); +}); diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.ts new file mode 100644 index 000000000..35e58dc09 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-share-panel.ts @@ -0,0 +1,379 @@ +import { + css, + html, + LitElement, + nothing, + PropertyValues, + TemplateResult, + type CSSResultGroup, +} from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import themeStyles from '@src/themes/theme-styles'; +import { + shareIcon, + twitterIcon, + facebookIcon, + tumblrIcon, + pinterestIcon, + emailIcon, + linkIcon, +} from './share-icons'; + +type ShareOption = { + name: string; + icon: TemplateResult | string; + url: string; +}; + +/** Icon for the share menu shortcut / menu entry. */ +export { shareIcon }; + +/** + * The "share this item" side panel: social sharing links (Twitter, Facebook, + * Tumblr, Pinterest, email) plus copyable iframe / bbcode embed snippets. + * Sharing options are derived from the item identifier/metadata and rebuilt + * whenever `sharingOptions` is reset to empty. + */ +@customElement('ia-itemnav-share-panel') +export class IAItemNavSharePanel extends LitElement { + @property({ type: String }) baseHost = 'archive.org'; + + @property({ type: String }) creator = ''; + + @property({ type: String }) description = ''; + + @property({ type: Boolean }) embedOptionsVisible = false; + + @property({ type: String }) identifier = ''; + + @property({ type: Array }) sharingOptions: ShareOption[] = []; + + @property({ type: String }) type = ''; + + @property({ type: Boolean }) renderHeader = false; + + @property({ type: String }) fileSubPrefix = ''; + + private copyNoteTimeouts = new WeakMap< + Element, + ReturnType + >(); + + updated(changed: PropertyValues): void { + if (changed.has('sharingOptions') && !this.sharingOptions.length) { + this.loadProviders(); + } + } + + loadProviders(): void { + let shareUrl = `https://${this.baseHost}/details/${this.identifier}`; + if (this.fileSubPrefix) { + shareUrl += `/${this.fileSubPrefix}`; + } + const shareBlurb = [ + this.description, + this.creator, + 'Free Download, Borrow, and Streaming', + 'Internet Archive', + ] + .filter(Boolean) + .join(' : '); + + this.sharingOptions = [ + { + name: 'Twitter', + icon: twitterIcon, + url: `https://twitter.com/intent/tweet?${new URLSearchParams({ + url: shareUrl, + text: shareBlurb, + via: 'internetarchive', + })}`, + }, + { + name: 'Facebook', + icon: facebookIcon, + url: `https://www.facebook.com/sharer/sharer.php?${new URLSearchParams({ + u: shareUrl, + })}`, + }, + { + name: 'Tumblr', + icon: tumblrIcon, + url: `https://www.tumblr.com/widgets/share/tool/preview?${new URLSearchParams( + { + posttype: 'link', + canonicalUrl: shareUrl, + title: shareBlurb, + }, + )}`, + }, + { + name: 'Pinterest', + icon: pinterestIcon, + url: `http://www.pinterest.com/pin/create/button/?${new URLSearchParams( + { + url: shareUrl, + description: shareBlurb, + }, + )}`, + }, + { + name: 'Email', + icon: emailIcon, + url: `mailto:?${new URLSearchParams({ + subject: shareBlurb, + body: shareUrl, + })}`, + }, + ]; + } + + /** + * Copies the embed snippet in the clicked `.code` block, preferring the async + * Clipboard API and falling back to the legacy `execCommand` path for + * browsers that lack it, then briefly flashes the "Copied" note. + */ + private async copyToClipboard(event: MouseEvent): Promise { + const currentTarget = event.currentTarget as HTMLElement; + const textarea = currentTarget.querySelector('textarea'); + const note = currentTarget.querySelector('small'); + if (!textarea || !note) return; + + try { + await navigator.clipboard.writeText(textarea.value); + } catch { + // Fallback for browsers without the async Clipboard API. + textarea.select(); + document.execCommand('copy'); + textarea.blur(); + } + + note.classList.add('visible'); + clearTimeout(this.copyNoteTimeouts.get(note)); + this.copyNoteTimeouts.set( + note, + setTimeout(() => note.classList.remove('visible'), 4000), + ); + } + + get iframeEmbed(): string { + return ``; + } + + get bbcodeEmbed(): string { + return `[archiveorg ${this.identifier} width=560 height=384 frameborder=0 webkitallowfullscreen=true mozallowfullscreen=true]`; + } + + get helpURL(): string { + return `https://${this.baseHost}/help/audio.php?identifier=${this.identifier}`; + } + + get header(): TemplateResult | typeof nothing { + const header = html`

    Share this ${this.type}

    `; + return this.renderHeader ? header : nothing; + } + + render(): TemplateResult { + return html` + ${this.header} +
    + ${this.sharingOptions.map( + (option) => + html``, + )} +
    + +
    +

    Embed

    +
    + + Copied to clipboard +
    +

    + Embed for wordpress.com hosted blogs and archive.org item + <description> tags +

    +
    + + Copied to clipboard +
    +

    + Want more? + Advanced embedding details, examples, and help! +

    +
    +
    +
    + `; + } + + static get styles(): CSSResultGroup { + return [ + themeStyles, + css` + :host { + --item-navigator-text-color--: var( + --item-navigator-text-color, + var(--true-white) + ); + --item-navigator-border-color--: var( + --item-navigator-border-color, + #4b4b4b + ); + /* Icons follow the adjustable text color by default. */ + --item-navigator-icon-color--: var( + --item-navigator-icon-color, + var(--item-navigator-text-color--) + ); + --item-navigator-share-embed-bg--: var( + --item-navigator-share-embed-bg, + #151515 + ); + + display: block; + height: 100%; + overflow-y: auto; + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + color: var(--item-navigator-text-color--); + box-sizing: border-box; + } + + header { + display: flex; + align-items: baseline; + } + + h3 { + padding: 0; + margin: 0 1em 0 0; + font-size: 1.6em; + } + + h4 { + font-size: 1.4em; + } + + :host > div { + padding: 1em 0; + } + + .share-option { + display: block; + padding: 0.5em 0; + font-size: 1.6em; + text-decoration: none; + color: var(--item-navigator-text-color--); + cursor: pointer; + transition: background-color 0.2s; + border-radius: 6px; + } + + .share-option:hover { + background-color: rgba(255, 255, 255, 0.05); + } + + .share-option > * { + display: inline-block; + padding: 0.2em; + margin-right: 1em; + vertical-align: middle; + border: 1px solid var(--item-navigator-border-color--); + border-radius: 7px; + } + + .share-option .ia-icon { + /* Reset to the base so the icon (em) doesn't compound against the + share-option's enlarged font-size. */ + font-size: var(--item-navigator-base-font-size--); + width: 2em; + height: 2em; + } + + /* Our glyphs are masked spans: the mask supplies the shape, this + supplies the paint. */ + span.ia-icon { + background-color: var(--item-navigator-icon-color--); + } + + /* Host-supplied icons may still be inline svg, so keep theming those + the original way. */ + .ia-icon .fill-color { + fill: var(--item-navigator-icon-color--); + } + + /* Hide the triangle that appears on details tags */ + summary::marker { + content: ''; + } + + summary::-webkit-details-marker { + display: none; + } + + .embed { + padding-right: 5px; + } + + .embed a { + color: var(--item-navigator-text-color--); + } + + .code { + position: relative; + } + + textarea { + display: block; + width: 100%; + height: 120px; + padding: 0.8em 1em; + box-sizing: border-box; + resize: none; + cursor: pointer; + font: normal 1.4em var(--base-font-family); + color: var(--item-navigator-text-color--); + background: var(--item-navigator-share-embed-bg--); + } + + small { + position: absolute; + bottom: 0; + left: 0; + height: 3em; + padding: 0.5em 1em; + box-sizing: border-box; + font: normal 1.2em/2em var(--base-font-family); + color: var(--item-navigator-share-embed-bg--); + background: var(--item-navigator-text-color--); + opacity: 0; + transition: opacity 300ms linear; + } + + small.visible { + opacity: 1; + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-share-panel': IAItemNavSharePanel; + } +} diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.test.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.test.ts new file mode 100644 index 000000000..ab418ef50 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.test.ts @@ -0,0 +1,163 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test, vi } from 'vitest'; + +import { IAItemNavSortFilesButton } from './ia-itemnav-sort-files-button'; +import './ia-itemnav-sort-files-button'; +import type { ViewableFileInfo } from './models'; + +function file(title: string, origSort: number): ViewableFileInfo { + return { + title, + orig_sort: origSort, + url_path: `/details/${title}`, + image: '', + author: '', + file_subprefix: title, + file_source: `${title}.pdf`, + file_prefix: title, + }; +} + +describe('IAItemNavSortFilesButton', () => { + test('starts in the default (neutral) state', async () => { + const el = await fixture( + html``, + ); + expect(el.sortOrderBy).to.equal('default'); + expect(el.shadowRoot?.querySelector('.sort-by.neutral-icon')).to.exist; + }); + + test('cycles default → ascending → descending → default on click', async () => { + const el = await fixture( + html``, + ); + + const clickButton = async () => { + ( + el.shadowRoot?.querySelector('button.sort-by') as HTMLButtonElement + ).click(); + await el.updateComplete; + }; + + await clickButton(); + expect(el.sortOrderBy).to.equal('title_asc'); + expect(el.shadowRoot?.querySelector('.sort-by.asc-icon')).to.exist; + + await clickButton(); + expect(el.sortOrderBy).to.equal('title_desc'); + expect(el.shadowRoot?.querySelector('.sort-by.desc-icon')).to.exist; + + await clickButton(); + expect(el.sortOrderBy).to.equal('default'); + expect(el.shadowRoot?.querySelector('.sort-by.neutral-icon')).to.exist; + }); + + test('sorts the file list and emits fileListSorted with the ordered files', async () => { + const el = await fixture( + html``, + ); + el.fileListRaw = [file('Beta', 1), file('Alpha', 0), file('Gamma', 2)]; + await el.updateComplete; + + const listener = vi.fn(); + el.addEventListener('fileListSorted', listener); + + el.sortVolumes('title_asc'); + + expect(listener).toHaveBeenCalledOnce(); + const event = listener.mock.calls[0][0] as CustomEvent; + expect(event.composed).to.equal(true); + expect(event.detail.sortType).to.equal('title_asc'); + expect( + event.detail.sortedFiles.map((f: ViewableFileInfo) => f.title), + ).to.deep.equal(['Alpha', 'Beta', 'Gamma']); + }); + + test('sorts titles in descending order', async () => { + const el = await fixture( + html``, + ); + el.fileListRaw = [file('Beta', 1), file('Alpha', 0), file('Gamma', 2)]; + await el.updateComplete; + + el.sortVolumes('title_desc'); + expect(el.fileListSorted.map((f) => f.title)).to.deep.equal([ + 'Gamma', + 'Beta', + 'Alpha', + ]); + }); + + test('restores the original order when sorting back to default', async () => { + const el = await fixture( + html``, + ); + el.fileListRaw = [file('Beta', 1), file('Alpha', 0), file('Gamma', 2)]; + await el.updateComplete; + + el.sortVolumes('default'); + expect(el.fileListSorted.map((f) => f.title)).to.deep.equal([ + 'Alpha', + 'Beta', + 'Gamma', + ]); + }); + + test('does not mutate the source list in place', async () => { + const el = await fixture( + html``, + ); + const raw = [file('Beta', 1), file('Alpha', 0)]; + el.fileListRaw = raw; + await el.updateComplete; + + el.sortVolumes('title_asc'); + expect(raw.map((f) => f.title)).to.deep.equal(['Beta', 'Alpha']); + }); + + test('default sort treats a missing orig_sort as 0', async () => { + const el = await fixture( + html``, + ); + const a: ViewableFileInfo = { ...file('A', 0) }; + const b: ViewableFileInfo = { ...file('B', 0) }; + delete a.orig_sort; + delete b.orig_sort; + el.fileListRaw = [a, b]; + await el.updateComplete; + + expect(() => el.sortVolumes('default')).to.not.throw(); + expect(el.fileListSorted).to.have.lengthOf(2); + }); + + test('paints the sort glyph with the themed icon color', async () => { + const el = await fixture( + html``, + ); + const icon = el.shadowRoot?.querySelector('.ia-icon') as HTMLElement; + + // The glyph is a masked span, so the theming knob drives background-color. + expect(icon.tagName).to.equal('SPAN'); + expect(getComputedStyle(icon).backgroundColor).to.equal('rgb(0, 128, 64)'); + }); + + test('recolors every state of the sort toggle', async () => { + const el = await fixture( + html``, + ); + + for (const state of ['title_asc', 'title_desc', 'default'] as const) { + el.sortVolumes(state); + await el.updateComplete; + const icon = el.shadowRoot?.querySelector('.ia-icon') as HTMLElement; + expect(getComputedStyle(icon).backgroundColor, state).to.equal( + 'rgb(200, 100, 50)', + ); + } + }); +}); diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.ts new file mode 100644 index 000000000..7b44783e5 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-sort-files-button.ts @@ -0,0 +1,147 @@ +import { + css, + html, + LitElement, + type CSSResultGroup, + TemplateResult, +} from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import themeStyles from '@src/themes/theme-styles'; +import { maskedIcon } from '../masked-icon'; +import sortAscUrl from './icons/sort-asc.svg'; +import sortDescUrl from './icons/sort-desc.svg'; +import sortNeutralUrl from './icons/sort-neutral.svg'; +import type { FileSortOption, ViewableFileInfo } from './models'; + +const sortAscIcon = maskedIcon(sortAscUrl); + +const sortDescIcon = maskedIcon(sortDescUrl); + +const sortNeutralIcon = maskedIcon(sortNeutralUrl); + +/** + * A tri-state sort toggle for the viewable-files panel header. Cycles + * default → title ascending → title descending → default, sorting the supplied + * file list and emitting `fileListSorted` on each change. + */ +@customElement('ia-itemnav-sort-files-button') +export class IAItemNavSortFilesButton extends LitElement { + @property({ type: Array }) fileListRaw: ViewableFileInfo[] = []; + + @property({ type: Array }) fileListSorted: ViewableFileInfo[] = []; + + @property({ type: String, reflect: true }) sortOrderBy: FileSortOption = + 'default'; + + render(): TemplateResult { + return html`
    ${this.sortButton}
    `; + } + + get sortButton(): TemplateResult { + const sortIcons: Record = { + default: html` + + `, + title_asc: html` + + `, + title_desc: html` + + `, + }; + + return sortIcons[this.sortOrderBy]; + } + + sortVolumes(sortType: FileSortOption): void { + this.sortOrderBy = sortType; + + const sortedFiles = [...this.fileListRaw].sort((a, b) => { + if (sortType === 'title_asc') return a.title.localeCompare(b.title); + if (sortType === 'title_desc') return b.title.localeCompare(a.title); + return (a.orig_sort ?? 0) - (b.orig_sort ?? 0); + }); + + this.dispatchEvent( + new CustomEvent('fileListSorted', { + detail: { + sortType, + sortedFiles, + }, + bubbles: true, + composed: true, + }), + ); + this.fileListSorted = sortedFiles; + } + + static get styles(): CSSResultGroup { + return [ + themeStyles, + css` + :host { + /* Every glyph is square, so one knob sizes both axes. Matches the + panel header's close button, which sits beside this one. */ + --item-navigator-header-icon-size--: var( + --item-navigator-header-icon-size, + 2em + ); + --item-navigator-icon-color--: var( + --item-navigator-icon-color, + var(--item-navigator-text-color, var(--true-white)) + ); + + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + button.sort-by { + padding: 0; + background-color: transparent; + border: 0; + cursor: pointer; + display: inline-flex; + /* Buttons don't inherit font-size, and the UA default would make the + em-sized glyph larger than the close button beside it. */ + font: inherit; + } + + /* The glyph is a masked span: the mask supplies the shape, this + supplies the paint. */ + button.sort-by .ia-icon { + width: var(--item-navigator-header-icon-size--); + height: var(--item-navigator-header-icon-size--); + background-color: var(--item-navigator-icon-color--); + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-sort-files-button': IAItemNavSortFilesButton; + } +} diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.test.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.test.ts new file mode 100644 index 000000000..739667708 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.test.ts @@ -0,0 +1,199 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { html } from 'lit'; +import { describe, expect, test } from 'vitest'; + +import { IAItemNavViewableFilesPanel } from './ia-itemnav-viewable-files-panel'; +import './ia-itemnav-viewable-files-panel'; +import type { ViewableFileInfo } from './models'; + +function file( + overrides: Partial & { title: string }, +): ViewableFileInfo { + return { + url_path: `/details/${overrides.title}`, + image: '', + author: '', + file_subprefix: overrides.title, + file_source: `${overrides.title}.txt`, + file_prefix: overrides.title, + ...overrides, + }; +} + +describe('IAItemNavViewableFilesPanel', () => { + test('renders nothing when the file list is empty', async () => { + const el = await fixture( + html``, + ); + expect(el.shadowRoot?.querySelector('ul')).to.not.exist; + }); + + test('renders one entry per file with its title', async () => { + const el = await fixture( + html``, + ); + el.fileList = [file({ title: 'Volume 1' }), file({ title: 'Volume 2' })]; + await el.updateComplete; + + const items = el.shadowRoot?.querySelectorAll('li'); + expect(items).to.have.lengthOf(2); + expect(items?.[0].textContent).to.contain('Volume 1'); + }); + + test('marks the entry matching the current subPrefix as active', async () => { + const el = await fixture( + html``, + ); + el.fileList = [ + file({ title: 'V1', file_subprefix: 'v1' }), + file({ title: 'V2', file_subprefix: 'v2' }), + ]; + el.subPrefix = 'v2'; + await el.updateComplete; + + const active = el.shadowRoot?.querySelectorAll('.content.active'); + expect(active).to.have.lengthOf(1); + expect(active?.[0].textContent).to.contain('V2'); + }); + + test('flags PDF sources with a PDF label', async () => { + const el = await fixture( + html``, + ); + el.fileList = [ + file({ title: 'A book', file_source: 'book.pdf' }), + file({ title: 'A text', file_source: 'plain.txt' }), + ]; + await el.updateComplete; + + const labels = el.shadowRoot?.querySelectorAll('.pdf-label'); + expect(labels).to.have.lengthOf(1); + }); + + test('builds file URLs against the base host', async () => { + const el = await fixture( + html``, + ); + const url = el.fileUrl(file({ title: 'x', url_path: '/details/x' })); + expect(url).to.equal('//example.org/details/x'); + }); + + test('appends the sort order to URLs only when addSortToUrl is set', async () => { + const el = await fixture( + html``, + ); + el.addSortToUrl = true; + el.sortOrderBy = 'title_asc'; + await el.updateComplete; + + expect(el.fileUrl(file({ title: 'x', url_path: '/details/x' }))).to.equal( + '//example.org/details/x?sort=title_asc', + ); + + el.sortOrderBy = 'default'; + expect(el.fileUrl(file({ title: 'x', url_path: '/details/x' }))).to.equal( + '//example.org/details/x', + ); + }); + + test('does not flag a file with no file_source as a PDF', async () => { + const el = await fixture( + html``, + ); + const noSource: ViewableFileInfo = { ...file({ title: 'sourceless' }) }; + delete (noSource as Partial).file_source; + el.fileList = [noSource]; + await el.updateComplete; + + expect(el.shadowRoot?.querySelectorAll('li')).to.have.lengthOf(1); + expect(el.shadowRoot?.querySelector('.pdf-label')).to.not.exist; + }); + + /** Renders the panel inside a short, scrolling box like the drawer's. */ + async function scrollingPanel( + subPrefix: string, + count = 25, + ): Promise<{ el: IAItemNavViewableFilesPanel; box: HTMLElement }> { + const files = Array.from({ length: count }, (_, i) => + file({ title: `v${i}`, file_subprefix: `v${i}` }), + ); + const box = await fixture( + html`
    + +
    `, + ); + const el = box.querySelector( + 'ia-itemnav-viewable-files-panel', + ) as IAItemNavViewableFilesPanel; + await el.updateComplete; + return { el, box }; + } + + /** Whether the active row is actually within the scrolling box. */ + function activeRowIsVisible( + el: IAItemNavViewableFilesPanel, + box: HTMLElement, + ): boolean { + const active = el.shadowRoot?.querySelector('.content.active'); + if (!active) return false; + const row = active.getBoundingClientRect(); + const view = box.getBoundingClientRect(); + return row.top >= view.top - 1 && row.bottom <= view.bottom + 1; + } + + test('brings the active file into view without waiting on a timer', async () => { + const { el, box } = await scrollingPanel('v20'); + + // No sleep: the row is in place as soon as the update completes. + expect(activeRowIsVisible(el, box), 'active row should be scrolled to').to + .be.true; + }); + + test('follows the active file when the selection moves', async () => { + const { el, box } = await scrollingPanel('v0'); + expect(activeRowIsVisible(el, box)).to.be.true; + + el.subPrefix = 'v24'; + await el.updateComplete; + await el.updateComplete; + + expect(activeRowIsVisible(el, box), 'should follow the new selection').to.be + .true; + }); + + test('scrolls once the file list arrives, not only on first render', async () => { + // Hosts commonly build the panel first and hand it a list afterwards. + const box = await fixture( + html`
    + +
    `, + ); + const el = box.querySelector( + 'ia-itemnav-viewable-files-panel', + ) as IAItemNavViewableFilesPanel; + await el.updateComplete; + + el.fileList = Array.from({ length: 25 }, (_, i) => + file({ title: `v${i}`, file_subprefix: `v${i}` }), + ); + await el.updateComplete; + await el.updateComplete; + + expect(activeRowIsVisible(el, box)).to.be.true; + }); + + test('leaves an already-visible row where it is', async () => { + const { el, box } = await scrollingPanel('v0'); + expect(box.scrollTop).to.equal(0); + expect(activeRowIsVisible(el, box)).to.be.true; + }); +}); diff --git a/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.ts b/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.ts new file mode 100644 index 000000000..cd230d5d2 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/ia-itemnav-viewable-files-panel.ts @@ -0,0 +1,229 @@ +import { + css, + html, + LitElement, + nothing, + type PropertyValues, + TemplateResult, + type CSSResultGroup, +} from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import { repeat } from 'lit/directives/repeat.js'; +import themeStyles from '@src/themes/theme-styles'; +import { maskedIcon } from '../masked-icon'; +import viewableFilesUrl from './icons/viewable-files.svg'; +import type { FileSortOption, ViewableFileInfo } from './models'; + +/** Icon for the viewable-files menu shortcut / menu entry. */ +export const viewableFilesIcon = maskedIcon(viewableFilesUrl); + +/** + * The "viewable files" side panel: a scrollable list of the item's viewable + * files/volumes, linking each to its page on the host and highlighting the one + * matching the current `subPrefix`. Populated by the host via `fileList` + * (typically re-ordered by an `ia-itemnav-sort-files-button`). + */ +@customElement('ia-itemnav-viewable-files-panel') +export class IAItemNavViewableFilesPanel extends LitElement { + @property({ type: String }) baseHost: string = 'archive.org'; + + @property({ type: String }) sortOrderBy: FileSortOption = 'default'; + + @property({ type: String }) subPrefix: string = ''; + + @property({ type: Array }) fileList: ViewableFileInfo[] = []; + + @property({ type: Boolean, reflect: true }) addSortToUrl = false; + + /** + * Keeps the active file in view whenever the list or the selection changes. + * + * Both are needed: hosts commonly build this panel once and hand it a + * `fileList` afterwards, and the selection can move while the panel stays + * open. Reacting to the change means there is nothing to wait on — the row + * exists by the time the update completes. + */ + protected updated(changed: PropertyValues): void { + if (changed.has('fileList') || changed.has('subPrefix')) { + this.revealActiveFile(); + } + } + + connectedCallback(): void { + super.connectedCallback(); + // Hosts reuse this element across opens, and the scroll container it sits + // in may have been reset while it was away. + this.revealActiveFile(); + } + + private async revealActiveFile(): Promise { + await this.updateComplete; + // `nearest` leaves an already-visible row alone, which is what the + // Chrome-only `scrollIntoViewIfNeeded` used to buy us. + this.shadowRoot + ?.querySelector('.content.active') + ?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + } + + fileUrl(item: ViewableFileInfo): string { + const baseUrl = `//${this.baseHost}${item.url_path}`; + if (this.addSortToUrl && this.sortOrderBy !== 'default') { + return `${baseUrl}?sort=${this.sortOrderBy}`; + } + return baseUrl; + } + + get pdfLabel(): TemplateResult { + return html`view this PDF`; + } + + fileLi(item: ViewableFileInfo): TemplateResult { + const activeClass = this.subPrefix === item.file_subprefix ? ' active' : ''; + const hrefUrl = this.fileUrl(item); + const isPdf = (item.file_source ?? '').match(/^[^+]+\.pdf$/i); + + return html` +
  • +
    + +
  • + `; + } + + get fileListTemplate(): TemplateResult { + const filesDisplay = repeat( + this.fileList, + (file) => file?.file_prefix, + this.fileLi.bind(this), + ); + return html` +
      + ${filesDisplay} +
      +
    + `; + } + + render(): TemplateResult | typeof nothing { + return this.fileList.length ? this.fileListTemplate : nothing; + } + + static get styles(): CSSResultGroup { + return [ + themeStyles, + css` + :host { + --item-navigator-text-color--: var( + --item-navigator-text-color, + var(--true-white) + ); + --item-navigator-border-color--: var( + --item-navigator-border-color, + #4b4b4b + ); + --item-navigator-active-file-border-color--: var( + --item-navigator-active-file-border-color, + #538bc5 + ); + + display: block; + overflow-y: auto; + box-sizing: border-box; + color: var(--item-navigator-text-color--); + margin-top: 14px; + margin-bottom: 2em; + --active-border-width--: 2px; + /* 10px base (petabox scale); internal sizing is em against it. */ + --item-navigator-base-font-size--: var( + --item-navigator-base-font-size, + 10px + ); + font-size: var(--item-navigator-base-font-size--); + } + + a { + color: var(--item-navigator-text-color--); + text-decoration: none; + } + + ul { + padding: 0; + list-style: none; + margin: var(--active-border-width--) 0.5em 1em 0; + } + + ul > li:first-child .separator { + display: none; + } + + li { + cursor: pointer; + position: relative; + } + + li .content { + border: var(--active-border-width--) solid transparent; + padding: 0.2em 0 0.4em 0.2em; + } + + li .content.active { + border: var(--active-border-width--) solid + var(--item-navigator-active-file-border-color--); + } + + li.content a { + display: flex; + } + + .item-title { + margin-block-start: 0em; + margin-block-end: 0em; + font-size: 14px; + font-weight: bold; + word-wrap: break-word; + padding-left: 5px; + } + + .separator { + background-color: var(--item-navigator-border-color--); + width: 98%; + margin: 1px auto; + height: 1px; + } + + .pdf-label { + border: 1px solid; + padding: 2px 5px; + border-radius: 20px; + display: inline-block; + margin-left: 5px; + font-size: 0.9em; + } + + .pdf-label .sr-only { + position: absolute; + clip: rect(1px, 1px, 1px, 1px); + padding: 0; + border: 0; + height: 1px; + width: 1px; + overflow: hidden; + } + `, + ]; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ia-itemnav-viewable-files-panel': IAItemNavViewableFilesPanel; + } +} diff --git a/src/elements/ia-item-navigator/menus/icons/email.svg b/src/elements/ia-item-navigator/menus/icons/email.svg new file mode 100644 index 000000000..8ae0c1c04 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/email.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/facebook.svg b/src/elements/ia-item-navigator/menus/icons/facebook.svg new file mode 100644 index 000000000..bc136cf95 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/facebook.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/link.svg b/src/elements/ia-item-navigator/menus/icons/link.svg new file mode 100644 index 000000000..0a17e6af8 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/link.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/list.svg b/src/elements/ia-item-navigator/menus/icons/list.svg new file mode 100644 index 000000000..03b969dfc --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/list.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/pinterest.svg b/src/elements/ia-item-navigator/menus/icons/pinterest.svg new file mode 100644 index 000000000..1121a06bb --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/pinterest.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/share.svg b/src/elements/ia-item-navigator/menus/icons/share.svg new file mode 100644 index 000000000..a98fe4a5c --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/share.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/sort-asc.svg b/src/elements/ia-item-navigator/menus/icons/sort-asc.svg new file mode 100644 index 000000000..eb3afee9e --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/sort-asc.svg @@ -0,0 +1,22 @@ + + + + + + + diff --git a/src/elements/ia-item-navigator/menus/icons/sort-desc.svg b/src/elements/ia-item-navigator/menus/icons/sort-desc.svg new file mode 100644 index 000000000..dcda8640a --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/sort-desc.svg @@ -0,0 +1,21 @@ + + + + + + + diff --git a/src/elements/ia-item-navigator/menus/icons/sort-neutral.svg b/src/elements/ia-item-navigator/menus/icons/sort-neutral.svg new file mode 100644 index 000000000..d156e8979 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/sort-neutral.svg @@ -0,0 +1,13 @@ + + + + + + + diff --git a/src/elements/ia-item-navigator/menus/icons/tumblr.svg b/src/elements/ia-item-navigator/menus/icons/tumblr.svg new file mode 100644 index 000000000..09598f282 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/tumblr.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/twitter.svg b/src/elements/ia-item-navigator/menus/icons/twitter.svg new file mode 100644 index 000000000..28f38a16e --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/twitter.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/icons/viewable-files.svg b/src/elements/ia-item-navigator/menus/icons/viewable-files.svg new file mode 100644 index 000000000..4fb74cc0e --- /dev/null +++ b/src/elements/ia-item-navigator/menus/icons/viewable-files.svg @@ -0,0 +1,6 @@ + + + diff --git a/src/elements/ia-item-navigator/menus/models.ts b/src/elements/ia-item-navigator/menus/models.ts new file mode 100644 index 000000000..b2e3047a2 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/models.ts @@ -0,0 +1,17 @@ +/** Sort orders offered by the viewable-files panel's sort button. */ +export type FileSortOption = 'default' | 'title_asc' | 'title_desc'; + +/** A single viewable file / volume entry rendered in the viewable-files panel. */ +export interface ViewableFileInfo { + url_path: string; + image: string; + title: string; + author: string; + file_subprefix: string; + file_source: string; + file_origin?: string; + /** Used as the `repeat` key when rendering the list. */ + file_prefix?: string; + /** Original ordering index, used to restore the default sort. */ + orig_sort?: number; +} diff --git a/src/elements/ia-item-navigator/menus/share-icons.ts b/src/elements/ia-item-navigator/menus/share-icons.ts new file mode 100644 index 000000000..79ab1c892 --- /dev/null +++ b/src/elements/ia-item-navigator/menus/share-icons.ts @@ -0,0 +1,32 @@ +import { type TemplateResult } from 'lit'; +import { maskedIcon } from '../masked-icon'; + +import shareUrl from './icons/share.svg'; +import twitterUrl from './icons/twitter.svg'; +import facebookUrl from './icons/facebook.svg'; +import tumblrUrl from './icons/tumblr.svg'; +import pinterestUrl from './icons/pinterest.svg'; +import emailUrl from './icons/email.svg'; +import linkUrl from './icons/link.svg'; + +/** + * Icons taken from the `@internetarchive/icon-*` packages (v1.4.1) used by the + * share panel. They ship as standalone `.svg` files — rather than icon package + * dependencies or inline templates — so their path data stays out of the JS + * bundle, and render as CSS-masked spans (see `maskedIcon`) so the panel can + * still theme them. Icons are decorative, labelled by adjacent text. + */ + +export const shareIcon: TemplateResult = maskedIcon(shareUrl); + +export const twitterIcon: TemplateResult = maskedIcon(twitterUrl); + +export const facebookIcon: TemplateResult = maskedIcon(facebookUrl); + +export const tumblrIcon: TemplateResult = maskedIcon(tumblrUrl); + +export const pinterestIcon: TemplateResult = maskedIcon(pinterestUrl); + +export const emailIcon: TemplateResult = maskedIcon(emailUrl); + +export const linkIcon: TemplateResult = maskedIcon(linkUrl); diff --git a/src/elements/index.ts b/src/elements/index.ts index 4847a5e86..86314f78c 100644 --- a/src/elements/index.ts +++ b/src/elements/index.ts @@ -1,3 +1,7 @@ export * from './ia-button/ia-button'; export * from './ia-combo-box/ia-combo-box'; export * from './ia-dropdown-search-bar/ia-dropdown-search-bar'; +export * from './ia-item-navigator/ia-item-navigator'; +export * from './ia-item-navigator/menus/ia-itemnav-viewable-files-panel'; +export * from './ia-item-navigator/menus/ia-itemnav-sort-files-button'; +export * from './ia-item-navigator/menus/ia-itemnav-share-panel';