diff --git a/README.md b/README.md index 99fa774..045d668 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ The site of the [missing-elements](https://github.com/missing-elements) web comp | `/` | The project list, the tools (the build page first, with its how-to), and a footer of links | [src/index.njk](src/index.njk); the lists are in [src/_data/site.js](src/_data/site.js) | | `/pdfjs-viewer/` | The docs of ``, with a live preview | [src/pdfjs-viewer/](src/pdfjs-viewer/) | | `/h5p/build/` | The build page, for people: what it makes, a sample that plays, and the build of a chat's source into a `.h5p`, in the visitor's browser | [src/h5p/build/](src/h5p/build/) | -| `/h5p/play/` | The play page: the activity in a link's `#source=`, built in the visitor's browser as the build page builds it, with any file of their own it names chosen there, and played with nothing beside it but its download and a link to the build page, for a chat app to show in its reply (h5p-toolkit#210); no page links to it | [src/h5p/play/](src/h5p/play/) | +| `/h5p/play/` | The play page: the activity in a link's `#source=`, built in the visitor's browser as the build page builds it, with any file of their own it names chosen there or given by the page that frames it (a video or a recording as its address, played from there at once and fetched whole only for the download), and played with nothing beside it but its download and a link to the build page, for a chat app to show in its reply (h5p-toolkit#210); no page links to it | [src/h5p/play/](src/h5p/play/) | | `/h5p/create-with-ai/` | The how-to, for people: installing the skill, asking a chat, the prompts to start from, the types, and what to do when something goes wrong | [src/h5p/create-with-ai/](src/h5p/create-with-ai/) | | `/h5p/skill/` | The skill as zips to install: `h5p-author.zip`, installed once in a chat's place for skills, or attached to the message in each new chat where it has none, and `h5p-author-chatgpt.zip`, the same skill laid out as a plugin; and a page that lists them and the bundles' addresses, each in full, which no page links to | [src/h5p/skill/](src/h5p/skill/); the zips written by [vite.config.ts](vite.config.ts) | | `/h5p/bundles/` | The skill's build tool and a library bundle per content type, for a chat that runs Node but cannot reach npm; and `h5p-author-build.tar.gz`, the tool and every library in one archive, for a person to attach to a chat whose code can download nothing | written by [vite.config.ts](vite.config.ts) | diff --git a/package.json b/package.json index efe3d58..fe110de 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "@codemirror/state": "6.7.6", "@codemirror/view": "6.43.15", "@lezer/highlight": "1.2.5", - "@missing-elements/h5p-author": "0.15.0", + "@missing-elements/h5p-author": "0.16.0", "@missing-elements/h5p-libraries": "1.1.1", "@missing-elements/h5p-offline-player": "1.7.0", "@missing-elements/h5p-runtime": "1.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b29a16d..5132581 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,8 +33,8 @@ importers: specifier: 1.2.5 version: 1.2.5 '@missing-elements/h5p-author': - specifier: 0.15.0 - version: 0.15.0(@missing-elements/h5p-runtime@1.0.2) + specifier: 0.16.0 + version: 0.16.0(@missing-elements/h5p-runtime@1.0.2) '@missing-elements/h5p-libraries': specifier: 1.1.1 version: 1.1.1 @@ -164,8 +164,8 @@ packages: '@marijn/find-cluster-break@1.0.4': resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==} - '@missing-elements/h5p-author@0.15.0': - resolution: {integrity: sha512-aw4T8zqkH/llh3UfSQOXaVHlKTq9uMKl+gDtcs7Ss6VH545UKLQIBTlVuSwMCVw1Q9xFLnivGhXfKBUvjey6jg==} + '@missing-elements/h5p-author@0.16.0': + resolution: {integrity: sha512-aw1L5chNH0AzkvIq31P9Sur95I/7ZXxW23TPqYm/2lv91CpEilL1gKoSaMTB7W/Aqrcu6YFrZqQqWMgTHCUzZA==} engines: {node: '>=22'} hasBin: true @@ -1278,7 +1278,7 @@ snapshots: '@marijn/find-cluster-break@1.0.4': {} - '@missing-elements/h5p-author@0.15.0(@missing-elements/h5p-runtime@1.0.2)': + '@missing-elements/h5p-author@0.16.0(@missing-elements/h5p-runtime@1.0.2)': dependencies: '@missing-elements/h5p-libraries': 1.1.1 '@missing-elements/h5p-normalize': 1.5.0 diff --git a/src/assets/site.css b/src/assets/site.css index 5e18846..dc23dff 100644 --- a/src/assets/site.css +++ b/src/assets/site.css @@ -1098,6 +1098,8 @@ html[data-standalone] .play { padding: 1rem; } .play-stage { display: grid; border: 1px solid var(--border); border-radius: 12px; overflow: clip; background: var(--surface); } .play-stage > * { grid-area: 1 / 1; min-width: 0; } .play:not([data-state="ready"]) .play-stage { aspect-ratio: 16 / 9; } +/* The activity's own frame keeps its square corners: the stage rounds only what the page draws in it. */ +.play[data-state="ready"] .play-stage { border-radius: 0; } .play .player-box { margin: 0; border: 0; border-radius: 0; } .play:not([data-state="ready"]) .player-box { visibility: hidden; } .play-panel { z-index: 1; display: grid; place-items: center; padding: 1.5rem 1rem; background: var(--surface); text-align: center; } @@ -1133,11 +1135,20 @@ html[data-standalone] .play { padding: 1rem; } .play-meta:empty { width: 6rem; height: 0.7rem; margin: 0.2rem 0; } .play-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0; } .play-actions [hidden] { display: none; } +/* Download of a preview: the file's bytes coming, under the bar, while the activity plays on. */ +.play-keep { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 1rem; padding: 0.625rem 0.75rem; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); } +.play-keep[hidden], .play-keep [hidden] { display: none; } +.play-keep-text { display: grid; flex: 1 1 14rem; gap: 0.4rem; min-width: 0; } +.play-keep-label { margin: 0; font-size: 0.875rem; line-height: 1.4; overflow-wrap: anywhere; } +.play-keep .play-progress { width: 100%; } +.play-progress[data-indeterminate] span { width: 30%; opacity: 0.85; } +#download[aria-disabled="true"] { opacity: 0.7; cursor: progress; } .button-icon { width: 1.05em; height: 1.05em; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } @media (prefers-reduced-motion: no-preference) { .play-spinner { animation: turn 0.8s linear infinite; } .play-progress span { transition: width 0.3s ease-out; } + .play-progress[data-indeterminate] span { animation: slide 1.3s ease-in-out infinite; } .play[data-state="building"] .play-panel, .play[data-state="fetching"] .play-panel { background: linear-gradient(100deg, var(--surface) 40%, color-mix(in srgb, var(--raised) 70%, var(--surface)) 50%, var(--surface) 60%) 0 0 / 250% 100%; animation: sheen 1.8s linear infinite; @@ -1145,6 +1156,7 @@ html[data-standalone] .play { padding: 1rem; } .play-title:empty, .play-meta:empty { animation: breathe 1.4s ease-in-out infinite alternate; } } @keyframes sheen { from { background-position: 125% 0; } to { background-position: -125% 0; } } +@keyframes slide { from { translate: -100% 0; } to { translate: 340% 0; } } @keyframes breathe { from { opacity: 1; } to { opacity: 0.45; } } @media (forced-colors: active) { diff --git a/src/h5p/play/index.njk b/src/h5p/play/index.njk index 6c71c43..de3850c 100644 --- a/src/h5p/play/index.njk +++ b/src/h5p/play/index.njk @@ -52,8 +52,16 @@ csp: "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' da

Open in the build page - +

+ {#- Download of an activity whose video plays from the chat: its bytes come first, while it plays on. -#} + diff --git a/src/h5p/play/play-page.ts b/src/h5p/play/play-page.ts index 2290b5d..c74c525 100644 --- a/src/h5p/play/play-page.ts +++ b/src/h5p/play/play-page.ts @@ -17,6 +17,12 @@ import { baseName, matchFiles, namedFiles, packageName, parseSource, sized, sour * attached (ChatGPT, 2026-11-20: the tool got a piece of text in the file's place), so the page * asks itself. A file chosen here goes nowhere: the build reads it in the browser. * + * A video or a recording the parent holds can come as its address instead of its bytes (#92): the + * activity is built with it left there (h5p-author's `linked`) and plays at once, the browser asking + * the address for the parts it shows. Such a package is a preview, since the address expires, so + * Download asks the parent for the bytes, shows them coming under the stage while the activity plays + * on, and builds the package to keep with the file in it. + * * What is seen is one stage, in one of five states (`data-state` on `main`): `building`, a loader * over the place the player takes; `fetching`, the loader with how much of a file the parent has * brought so far; `asking`, for the person's files; `error`, with the one thing to do about it; @@ -45,6 +51,13 @@ const playerBox = $('player-box') const title = $('title') const meta = $('meta') const download = $('download') +const downloadLabel = $('download-label') +const keepBox = $('keep') +const keepLabel = $('keep-label') +const keepProgress = $('keep-progress') +const keepBar = $('keep-bar') +const keepInstead = $('keep-instead') +const announcer = document.querySelector('[data-status="page"]') const edit = $('edit') const player = $('player') as HTMLElementTagNameMap['h5p-player'] player.runtime = runtime @@ -64,6 +77,20 @@ let packageUrl: string | null = null let builds = 0 /** The missing names the parent was last told, so that it is told again only when they change. */ let told = '' +/** The addresses the parent gave for files it holds, by name: played from there, none of their bytes read. */ +const links = new Map() +/** The names the source gives the files the package last built plays from an address: a preview. */ +let previewed: string[] = [] +/** Whether Download was pressed on a preview, and its package is not saved yet. */ +let keeping = false +/** Whether the parent was asked for the bytes of those files, and has not brought them yet. */ +let bringing = false +/** Whether the package to keep is being built: one at a time. */ +let packing = false +/** Whether the package that plays has its files in it. Files that come after that change nothing. */ +let whole = false +/** Shows the question for the person's files a moment late, where the parent may bring them first. */ +let askTimer: ReturnType | undefined const framed = window.parent !== window if (!framed) document.documentElement.dataset.standalone = '' @@ -95,17 +122,19 @@ function busy(text: string): void { function fail(heading: string, text: string, fixable = false): void { errorTitle.textContent = heading errorText.textContent = text + // Whatever was built does not play: files that come now are built from again. + whole = false fix.hidden = !fixable // The headings above end in no full stop, and a message from elsewhere may be empty. show('error', text ? `${heading}. ${text}` : `${heading}.`) } /** What the activity is, under the stage: its title, and its type with the package's size once built. */ -function about(name: unknown, type: unknown, size?: number): void { +function about(name: unknown, type: unknown, size?: number | string): void { if (typeof name === 'string' && name.trim()) title.textContent = name // "H5P.InteractiveVideo 1.27" as "Interactive Video". const typed = typeof type === 'string' ? type.replace(/^H5P\./, '').replace(/\s[\d.]+$/, '').replace(/([a-z])([A-Z])/g, '$1 $2') : '' - const parts = [typed, size === undefined ? '' : sized(size)].filter(Boolean) + const parts = [typed, size === undefined ? '' : typeof size === 'string' ? size : sized(size)].filter(Boolean) if (parts.length) meta.textContent = parts.join(' · ') } @@ -136,6 +165,34 @@ function filesFor(paths: string[]): { files: Record, missing: stri return matched } +/** Whether a file of that name can be played from an address: a video or a recording. */ +const playable = (name: string): boolean => called(name) === 'video' || called(name) === 'recording' + +/** + * The addresses for the paths still missing, matched as files are: by name, or where one path and + * one address are left, by kind. A picture is never played from an address: its size is read. + */ +function linksFor(paths: string[]): { linked: Record, missing: string[] } { + const given = [...links] + const linked: Record = {} + const missing: string[] = [] + for (const path of paths) { + const [only] = given + const address = !playable(path) ? undefined + : links.get(baseName(path)) ?? (paths.length === 1 && given.length === 1 && only && kind(only[0]) === kind(path) ? only[1] : undefined) + if (address) linked[path] = address + else missing.push(path) + } + return { linked, missing } +} + +/** Something said to a screen reader once, beside the state's own words. */ +function announce(text: string): void { + if (!announcer) return + announcer.textContent = '' + setTimeout(() => { announcer.textContent = text }, 50) +} + /** * Asks for the files still missing, by their names, and tells the parent, which may have them. The * parent is told once for a set of names: one that answers each time with the same files, some of @@ -149,13 +206,30 @@ function ask(missing: string[]): void { askText.textContent = chosen.size ? `Still needed: ${listed}.` : `This activity uses ${listed}. ${one ? 'It stays' : 'They stay'} in your browser.` choose.textContent = one ? 'Choose the file' : 'Choose the files' filesInput.accept = [...new Set(missing.map((path) => `.${kind(path)}`))].join(',') + const missingNow = names.join('\n') + const first = missingNow !== told + if (first) { + told = missingNow + toParent({ type: 'needs-files', names }) + } + // A parent that holds the files answers within a moment: until then the loader stays, so the + // question does not flash up and go. + clearTimeout(askTimer) + askTimer = undefined + if (framed && first && !chosen.size) { + askTimer = setTimeout(() => { + askTimer = undefined + showAsk(listed, one) + }, 1200) + return + } + showAsk(listed, one) +} + +function showAsk(listed: string, one: boolean): void { show('asking', chosen.size ? `Still needed: ${listed}.` : `This activity uses ${one ? 'a file' : 'files'} of yours: ${listed}. Choose ${one ? 'it' : 'them'} from your computer; ${one ? 'it stays' : 'they stay'} in your browser.`) - const missingNow = names.join('\n') - if (missingNow === told) return - told = missingNow - toParent({ type: 'needs-files', names }) } /** @@ -164,7 +238,11 @@ function ask(missing: string[]): void { * their computer, which needs no wait. Told a screen reader once, not with every number. */ function fetching(name: string, received: number, total: number): void { - if (main.dataset.state !== 'asking' && main.dataset.state !== 'fetching') return + if (keeping) return keepCount(name, received, total) + // Asked for, the question shown or still held back a moment: the file on its way is shown in its place. + if (main.dataset.state !== 'asking' && main.dataset.state !== 'fetching' && askTimer === undefined) return + clearTimeout(askTimer) + askTimer = undefined const what = wanted.length === 1 ? called(name || wanted[0]!) : 'file' label.textContent = `Getting your ${what}… ${sized(received)}${total > 0 ? ` of ${sized(total)}` : ''}` note.textContent = 'From the chat to your browser, nowhere else.' @@ -179,30 +257,149 @@ function fetching(name: string, received: number, total: number): void { /** Files given, by the person or by the parent: the activity is built once none is missing. */ function take(files: File[]): void { if (!files.length || !wanted.length) return + // A file that comes late, from a parent still bringing what the person chose themselves + // meanwhile, must not start the activity again under them, nor take the place of the file + // the package to keep is being built from. + if (whole || packing) return // Where one file is named, a second choice replaces the first. if (wanted.length === 1) chosen.clear() for (const file of files) chosen.set(file.name, file) - void play() + // While a preview plays, the files make the package to keep, and the player is left playing: + // saved where Download asked for them, and only made ready for it where the parent sent them unasked. + if (previewed.length) void keep() + else void play() } -async function play(): Promise { - const build = ++builds +/** The words for the files a preview plays from an address: "video", or "files". */ +const previewedAs = (): string => previewed.length === 1 ? called(previewed[0]!) : 'files' + +/** The row under the stage while a download is made ready, with the choice of the file's own where it helps. */ +function preparing(text: string, choice: boolean): void { + keepBox.hidden = false + keepInstead.hidden = !choice + keepLabel.textContent = text + keepProgress.hidden = false + keepProgress.dataset.indeterminate = '' + keepProgress.removeAttribute('aria-valuenow') + download.setAttribute('aria-disabled', 'true') + downloadLabel.textContent = 'Preparing…' +} + +/** + * Download of a preview: the parent is asked for the bytes of what it plays from an address, and + * how much has come is shown under the stage while the activity plays on. The person can choose + * the file from their computer instead, as when it was first asked for. Files that are here + * already, sent unasked or left by a build that failed, are built from at once. + */ +function fetchToKeep(): void { + keeping = true + if (packing) return preparing(`Building the .h5p with your ${previewedAs()} in it…`, false) + if (bringing) return + if (!filesFor(wanted).missing.length) return void keep() + bringing = true + preparing(`Getting your ${previewedAs()} from the chat for the download…`, true) + announce(`Getting your ${previewedAs()} from the chat for the download.`) + toParent({ type: 'needs-bytes', names: previewed.map(baseName) }) +} + +/** How much of a file for the download has come. */ +function keepCount(name: string, received: number, total: number): void { + if (!bringing) return + const what = previewed.length === 1 ? called(name || previewed[0]!) : 'file' + keepLabel.textContent = `Getting your ${what} for the download… ${sized(received)}${total > 0 ? ` of ${sized(total)}` : ''}` + if (total > 0) { + const done = Math.min(100, Math.round(received / total * 100)) + delete keepProgress.dataset.indeterminate + keepProgress.setAttribute('aria-valuenow', String(done)) + keepBar.style.setProperty('--done', `${done}%`) + } +} + +/** + * The package to keep, built with the files in it and given to the parent, while the player plays + * on. It is saved only where Download asked for it: files the parent sends unasked make Download + * a link to it, with nothing shown and nothing saved. + */ +async function keep(): Promise { + if (packing) return const { files, missing } = filesFor(wanted) - if (missing.length) return ask(missing) - busy('Building the activity in your browser…') + if (missing.length) { + if (keeping) keepLabel.textContent = `Still needed for the download: ${new Intl.ListFormat('en-GB', { type: 'conjunction' }).format(missing.map(baseName))}.` + return + } + packing = true + bringing = false + if (keeping) preparing(`Building the .h5p with your ${previewedAs()} in it…`, false) try { opened ??= openPack(installPack) const result = await buildPackage(source, { libraries: await opened, files }) - if (build !== builds) return const name = packageName(String(result.manifest.title ?? '')) if (packageUrl) URL.revokeObjectURL(packageUrl) packageUrl = URL.createObjectURL(result.blob) + // Download may have been pressed while this was built. + const asked = keeping + previewed = [] + keeping = false + whole = true + keepBox.hidden = true download.href = packageUrl download.download = name - download.hidden = false + download.removeAttribute('aria-disabled') + downloadLabel.textContent = 'Download .h5p' about(result.manifest.title, result.builtWith, result.blob.size) + toParent({ type: 'built', file: new File([result.blob], name, { type: 'application/zip' }), title: result.manifest.title, size: sized(result.blob.size) }) + if (!asked) return + announce(`The .h5p is ready, ${sized(result.blob.size)}: downloading.`) + // The download the person asked for. A frame its parent lets download nothing has given the + // parent the file above, to save its own way. + download.click() + } catch (error) { + // Unasked, nothing is said: the preview plays on, and Download builds from the same files. + if (!keeping) return + const text = `The .h5p could not be built: ${error instanceof Error ? error.message : String(error)}` + keepInstead.hidden = false + keepProgress.hidden = true + keepLabel.textContent = text + download.removeAttribute('aria-disabled') + downloadLabel.textContent = 'Try again' + announce(text) + } finally { + packing = false + } +} + +async function play(): Promise { + const build = ++builds + clearTimeout(askTimer) + askTimer = undefined + const found = filesFor(wanted) + const { linked, missing } = linksFor(found.missing) + if (missing.length) return ask(missing) + busy('Building the activity in your browser…') + try { + opened ??= openPack(installPack) + const result = await buildPackage(source, { libraries: await opened, files: found.files, linked }) + if (build !== builds) return + const name = packageName(String(result.manifest.title ?? '')) + if (packageUrl) URL.revokeObjectURL(packageUrl) const file = new File([result.blob], name, { type: 'application/zip' }) - toParent({ type: 'built', file, title: result.manifest.title, size: sized(result.blob.size) }) + previewed = result.linked + download.hidden = false + if (previewed.length) { + // A preview is not a file to hand out: its address expires. Download fetches the bytes first. + // Its link is this page's own, for a press that opens it elsewhere; a press here is taken below. + packageUrl = null + download.href = location.href + download.removeAttribute('download') + about(result.manifest.title, result.builtWith, `${previewedAs() === 'files' ? 'its files play' : `its ${previewedAs()} plays`} from the chat`) + } else { + whole = true + packageUrl = URL.createObjectURL(result.blob) + download.href = packageUrl + download.download = name + about(result.manifest.title, result.builtWith, result.blob.size) + toParent({ type: 'built', file, title: result.manifest.title, size: sized(result.blob.size) }) + } busy('Starting the activity…') playerBox.hidden = false player.file = file @@ -244,6 +441,13 @@ player.addEventListener('error', (event) => { // The file field is hidden, and the buttons open it. choose.addEventListener('click', () => filesInput.click()) instead.addEventListener('click', () => filesInput.click()) +keepInstead.addEventListener('click', () => filesInput.click()) +// Download of a preview fetches the files first; of a package with its files in it, it is a link. +download.addEventListener('click', (event) => { + if (!previewed.length) return + event.preventDefault() + fetchToKeep() +}) filesInput.addEventListener('change', () => { const files = [...(filesInput.files ?? [])] filesInput.value = '' @@ -264,6 +468,21 @@ main.addEventListener('drop', (event) => { take([...event.dataTransfer.files]) }) +/** + * Addresses the parent gives for files it holds, by name: kept where they are http(s) and name a + * video or a recording, and the activity built with them where a file of its own is still missing. + * While a preview plays they are only kept: a new address for the same file is not a new activity. + */ +function takeLinks(given: Record): void { + let added = false + for (const [name, address] of Object.entries(given)) { + if (typeof address !== 'string' || !/^https?:\/\//i.test(address) || !URL.canParse(address) || !playable(name)) continue + links.set(baseName(name), address) + added = true + } + if (added && !previewed.length && filesFor(wanted).missing.length) void play() +} + /** A count of bytes as a message gives it: a number that is one, and not below nothing. */ const amount = (value: unknown): number | null => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null @@ -271,9 +490,10 @@ const amount = (value: unknown): number | null => typeof value === 'number' && N // much of one has come so far, and the chat's theme where it is not the system's. window.addEventListener('message', (event) => { if (!framed || event.source !== window.parent) return - const message = event.data as { source?: unknown, type?: unknown, files?: unknown, name?: unknown, received?: unknown, total?: unknown, theme?: unknown } | null + const message = event.data as { source?: unknown, type?: unknown, files?: unknown, links?: unknown, name?: unknown, received?: unknown, total?: unknown, theme?: unknown } | null if (message?.source !== 'h5p-play-host') return if (message.type === 'files' && Array.isArray(message.files)) take(message.files.filter((file): file is File => file instanceof File)) + else if (message.type === 'links' && message.links && typeof message.links === 'object') takeLinks(message.links as Record) else if (message.type === 'progress' && amount(message.received) !== null) fetching(typeof message.name === 'string' ? message.name : '', amount(message.received)!, amount(message.total) ?? 0) else if (message.type === 'theme' && (message.theme === 'light' || message.theme === 'dark')) document.querySelector('meta[name="color-scheme"]')!.content = message.theme })