Skip to content

Commit f71698b

Browse files
committed
feat(play): a link may carry the files' addresses and a wish to save, and Download of a video the chat cannot save opens such a tab with one press (#102)
1 parent fa8948b commit f71698b

3 files changed

Lines changed: 156 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ The site of the [missing-elements](https://github.com/missing-elements) web comp
99
| `/` | 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) |
1010
| `/pdfjs-viewer/` | The docs of `<pdfjs-viewer-element>`, with a live preview | [src/pdfjs-viewer/](src/pdfjs-viewer/) |
1111
| `/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/) |
12-
| `/h5p/play/` | The play page, for a chat app to show in its reply (h5p-toolkit#210); no page links to it. It builds the activity in a link's `#source=` in the visitor's browser, as the build page does, and plays it with nothing beside it but its download and a link to the build page. A file of the visitor's own that the source names is chosen there or given by the page that frames it. A video or a recording can be given as its address: it plays from there at once and is fetched whole only for the download. A framing page that saves files itself is handed the download. A package bigger than that page saves stays behind the Download link, and the page says how to save it from such a frame. A framing page that opens links itself is handed the link to the build page. | [src/h5p/play/](src/h5p/play/) |
12+
| `/h5p/play/` | The play page, for a chat app to show in its reply (h5p-toolkit#210); no page links to it. It builds the activity in a link's `#source=` in the visitor's browser, as the build page does, and plays it with nothing beside it but its download and a link to the build page. A file of the visitor's own that the source names is chosen there or given by the page that frames it. A video or a recording can be given as its address: it plays from there at once and is fetched whole only for the download. A framing page that saves files itself is handed the download. A package bigger than that page saves stays behind the Download link, and the page says how to save it from such a frame. A framing page that opens links itself is handed the link to the build page. A link to the page may also carry the files' addresses and a wish to save (`&links=`, `&save=1`): the page then fetches them itself and saves the package with no press, which is how a framing page that opens links gets a package saved that it cannot save itself. | [src/h5p/play/](src/h5p/play/) |
1313
| `/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/) |
1414
| `/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) |
1515
| `/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) |

‎src/h5p/build/build-source.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,48 @@ function isJson(text: string): boolean {
128128
}
129129
}
130130

131+
/** A text as base64url, and back; `null` for what is not one. */
132+
const toBase64Url = (text: string): string => {
133+
let binary = ''
134+
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte)
135+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
136+
}
137+
const fromBase64Url = (value: string): string | null => {
138+
try {
139+
const base64 = value.replace(/-/g, '+').replace(/_/g, '/')
140+
return new TextDecoder().decode(Uint8Array.from(atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4)), (char) => char.charCodeAt(0)))
141+
} catch {
142+
return null
143+
}
144+
}
145+
146+
/**
147+
* What a play link may carry beside its source, for a tab that saves the package with no press:
148+
* `&links=`, the addresses of the person's files by name, as JSON in base64url, and `&save=1`.
149+
* `rest` is the fragment without them, which is what stays in the address bar: an address of a
150+
* person's file is not left in the history. A source written as readable JSON takes the whole
151+
* fragment, so such a link carries neither.
152+
*/
153+
export function linksFromFragment(hash: string): { links: Record<string, unknown>, save: boolean, rest: string } {
154+
const fragment = hash.replace(/^#/, '')
155+
const none = { links: {}, save: false, rest: hash }
156+
if (/(?:^|&)source=(?=\{|%7B)/i.test(fragment)) return none
157+
const params = new URLSearchParams(fragment)
158+
if (!params.has('links') && !params.has('save')) return none
159+
let links: Record<string, unknown> = {}
160+
try {
161+
const given: unknown = JSON.parse(fromBase64Url(params.get('links') ?? '') ?? '')
162+
if (given && typeof given === 'object' && !Array.isArray(given)) links = given as Record<string, unknown>
163+
} catch {
164+
// Not addresses: none.
165+
}
166+
const rest = fragment.split('&').filter((part) => !/^(links|save)(=|$)/.test(part)).join('&')
167+
return { links, save: params.get('save') === '1', rest: rest ? `#${rest}` : '' }
168+
}
169+
170+
/** A fragment from `fragmentFromSource` with addresses and the wish to save beside it, as `linksFromFragment` reads them. */
171+
export const fragmentWithLinks = (fragment: string, links: Record<string, string>): string => `${fragment}&links=${toBase64Url(JSON.stringify(links))}&save=1`
172+
131173
/** Whether a fragment has a `source=` at all, whatever it carries: a link of this page's kind. */
132174
export const linksSource = (hash: string): boolean => new URLSearchParams(hash.replace(/^#/, '')).has('source')
133175

‎src/h5p/play/play-page.ts‎

Lines changed: 113 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import '@missing-elements/h5p-offline-player'
22
import { buildPackage, openPack, SourceError } from '@missing-elements/h5p-author/browser'
33
import { pack as installPack } from '@missing-elements/h5p-libraries/install'
44
import { runtime } from '@missing-elements/h5p-runtime'
5-
import { baseName, kindOf, matchFiles, matchNamed, namedFiles, packageName, parseSource, sized, sourceFromFragment, type Problem } from '../build/build-source'
5+
import { baseName, compactSource, fragmentFromSource, fragmentWithLinks, kindOf, linksFromFragment, matchFiles, matchNamed, namedFiles, packageName, parseSource, sized, sourceFromFragment, type Problem } from '../build/build-source'
66

77
/**
88
* The play page, `/h5p/play/`: the activity in a link's `#source=` built in the browser, as the
@@ -33,6 +33,15 @@ import { baseName, kindOf, matchFiles, matchNamed, namedFiles, packageName, pars
3333
* again (#100). A link of this page opens nothing there on a press, so a parent that opens links
3434
* says so too, and is handed the address.
3535
*
36+
* One press is asked for all the same (#102), and a package built in a frame cannot be passed to
37+
* a tab: the browser keeps a framed page's storage apart. But a tab can build it again from what
38+
* the frame had, the source and the files' addresses, where the store behind the addresses answers
39+
* any site, as the chat's was found to (2026-11-24). So a link to this page may carry `&links=`
40+
* and `&save=1` beside its source: the page then fetches the files itself, shows them coming,
41+
* builds the package and saves it, with no press. Framed by a parent that saves files and opens
42+
* links, Download of a video said to weigh more than the parent saves hands it such a link, at
43+
* once, while the press still lets a tab open.
44+
*
3645
* What is seen is one stage, in one of five states (`data-state` on `main`): `building`, a loader
3746
* over the place the player takes; `fetching`, the loader with how much of a file the parent has
3847
* brought so far; `asking`, for the person's files; `error`, with the one thing to do about it;
@@ -110,6 +119,19 @@ let handedId = 0
110119
let handedTimer: ReturnType<typeof setTimeout> | undefined
111120
/** Whether the parent opens links itself, where a press on one of this page's opens nothing. */
112121
let hostOpens = false
122+
/** The address each file of the preview plays from, by its path in the source, and the sizes the parent gave, by address. */
123+
let shownFrom: Record<string, string> = {}
124+
const sizeAt = new Map<string, number>()
125+
/** What the link carried beside its source: addresses, and the wish to save with no press. Read once, and taken out of the address bar. */
126+
const carried = linksFromFragment(location.hash)
127+
if (carried.rest !== location.hash) history.replaceState(null, '', `${location.pathname}${location.search}${carried.rest}`)
128+
let saveUnasked = carried.save
129+
/** Whether the save now made was asked for by the link: said under the stage, where nobody pressed anything. */
130+
let unasked = false
131+
/** The source as a link's fragment, for a tab of this page that saves the package. */
132+
let ownFragment = ''
133+
/** Stops the page's own fetch of a file, where the person chooses it themselves meanwhile. */
134+
let fetchStop: AbortController | null = null
113135
/** Shows the question for the person's files a moment late, where the parent may bring them first. */
114136
let askTimer: ReturnType<typeof setTimeout> | undefined
115137

@@ -304,6 +326,20 @@ function saying(text: string, { busy = false } = {}): void {
304326
announce(text)
305327
}
306328

329+
/** What the files of a preview weigh, where the parent said for each: the package is that and a little. */
330+
function previewSize(): number | null {
331+
let total = 0
332+
for (const path of previewed) {
333+
const size = sizeAt.get(shownFrom[path] ?? '')
334+
if (size === undefined) return null
335+
total += size
336+
}
337+
return total
338+
}
339+
340+
/** A link to this page, in a tab of its own, that fetches what the preview plays from its addresses and saves the package. */
341+
const savingLink = (): string => `${location.origin}${location.pathname}${fragmentWithLinks(ownFragment, Object.fromEntries(links))}`
342+
307343
/**
308344
* The way to the package where the parent does not save it and its frame may let this page save
309345
* nothing: Download is a link to it, and the browser's own menu opens a link from any frame.
@@ -347,7 +383,48 @@ function fetchToKeep(): void {
347383
bringing = true
348384
preparing(`Getting your ${previewedAs()} from the chat for the download…`, true)
349385
announce(`Getting your ${previewedAs()} from the chat for the download.`)
350-
toParent({ type: 'needs-bytes', names: previewed.map(baseName) })
386+
if (framed) toParent({ type: 'needs-bytes', names: previewed.map(baseName) })
387+
else void fetchFiles()
388+
}
389+
390+
/**
391+
* The files of a preview fetched by this page, where no parent holds them: from the addresses it
392+
* plays from, counted as they come. The browser keeps each as a Blob, which it may hold on disk.
393+
*/
394+
async function fetchFiles(): Promise<void> {
395+
const stop = fetchStop = new AbortController()
396+
try {
397+
const files: File[] = []
398+
for (const path of previewed) {
399+
const response = await fetch(shownFrom[path] ?? '', { signal: stop.signal })
400+
if (!response.ok || !response.body) throw new Error(`the chat answered ${response.status}`)
401+
const total = Number(response.headers.get('content-length')) || 0
402+
let received = 0
403+
let shown = 0
404+
const counted = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
405+
transform(chunk, controller) {
406+
received += chunk.byteLength
407+
// Shown ten times a second at most.
408+
if (performance.now() - shown > 100) { shown = performance.now(); keepCount(baseName(path), received, total) }
409+
controller.enqueue(chunk)
410+
},
411+
}))
412+
files.push(new File([await new Response(counted).blob()], baseName(path), { type: response.headers.get('content-type') ?? '' }))
413+
}
414+
if (stop.signal.aborted) return
415+
take(files)
416+
} catch (error) {
417+
// Stopped for a file the person chose: that one is built from.
418+
if (stop.signal.aborted) return
419+
bringing = false
420+
const text = `Your ${previewedAs()} could not be fetched from the chat (${error instanceof Error ? error.message : String(error)}): its address may have run out. Choose it from your computer instead.`
421+
keepInstead.hidden = false
422+
keepProgress.hidden = true
423+
keepLabel.textContent = text
424+
download.removeAttribute('aria-disabled')
425+
downloadLabel.textContent = 'Try again'
426+
announce(text)
427+
}
351428
}
352429

353430
/** How much of a file for the download has come. */
@@ -377,6 +454,7 @@ async function keep(): Promise<void> {
377454
}
378455
packing = true
379456
bringing = false
457+
fetchStop?.abort()
380458
if (keeping) preparing(`Building the .h5p with your ${previewedAs()} in it…`, false)
381459
try {
382460
opened ??= openPack(installPack)
@@ -400,8 +478,10 @@ async function keep(): Promise<void> {
400478
if (!asked) return
401479
// The download the person asked for: made by a parent that saves files, where it takes this one, or by this page.
402480
if (hostSaves !== null && kept.size <= hostSaves) return handOver(kept)
403-
announce(`The .h5p is ready, ${sized(result.blob.size)}: downloading.`)
404481
download.click()
482+
// A save the link asked for, with no press: said where it shows, with the way on where the browser saved nothing.
483+
if (unasked) saying(`Your .h5p is saved to your downloads, ${sized(result.blob.size)}. You can close this tab. If nothing was saved, press Download.`)
484+
else announce(`The .h5p is ready, ${sized(result.blob.size)}: downloading.`)
405485
} catch (error) {
406486
// Unasked, nothing is said: the preview plays on, and Download builds from the same files.
407487
if (!keeping) return
@@ -433,12 +513,14 @@ async function play(): Promise<void> {
433513
if (packageUrl) URL.revokeObjectURL(packageUrl)
434514
const file = new File([result.blob], name, { type: 'application/zip' })
435515
previewed = result.linked
516+
shownFrom = linked
436517
download.hidden = false
437518
if (previewed.length) {
438519
// A preview is not a file to hand out: its address expires. Download fetches the bytes first.
439-
// Its link is this page's own, for a press that opens it elsewhere; a press here is taken below.
520+
// Its link is this page's own, with the addresses and the wish to save, for a press that opens
521+
// it in a tab, which then saves the package; a press here is taken below.
440522
packageUrl = null
441-
download.href = location.href
523+
download.href = savingLink()
442524
download.removeAttribute('download')
443525
about(result.manifest.title, result.builtWith, `${previewedAs() === 'files' ? 'its files play' : `its ${previewedAs()} plays`} from the chat`)
444526
} else {
@@ -476,13 +558,24 @@ async function start(): Promise<void> {
476558
const parsed = parseSource(text)
477559
if ('problem' in parsed) return fail('The activity cannot be read', 'Open it in the build page to see why.', true)
478560
source = parsed.source
561+
ownFragment = await fragmentFromSource(compactSource(text) ?? '')
562+
// The addresses the link carried, kept before the files are known to be wanted: the build below is the one that uses them.
563+
takeLinks(carried.links, {})
479564
wanted = namedFiles(source)
480565
const written = source as { title?: unknown, type?: unknown }
481566
about(written.title, written.type)
482567
await play()
483568
}
484569

485-
player.addEventListener('ready', () => show('ready', `“${title.textContent}” is ready.`))
570+
player.addEventListener('ready', () => {
571+
show('ready', `“${title.textContent}” is ready.`)
572+
// The save a link asked for: made once, as Download would, with no press.
573+
if (!saveUnasked) return
574+
saveUnasked = false
575+
unasked = true
576+
if (previewed.length) fetchToKeep()
577+
else download.click()
578+
})
486579
player.addEventListener('error', (event) => {
487580
if (player.state === 'ready') return
488581
fail('It was built, but does not play', (event as unknown as CustomEvent<{ message: string }>).detail.message, true)
@@ -498,6 +591,13 @@ keepInstead.addEventListener('click', () => filesInput.click())
498591
download.addEventListener('click', (event) => {
499592
if (previewed.length) {
500593
event.preventDefault()
594+
// A video the parent says weighs more than it saves is not fetched here, where it could not be
595+
// saved with a press: a tab of this page is opened by the parent, at once, and saves it there.
596+
const size = hostSaves !== null && hostOpens && !keeping ? previewSize() : null
597+
if (size !== null && size > hostSaves!) {
598+
toParent({ type: 'open', href: savingLink() })
599+
return saying(`This .h5p is over ${sized(size)}, more than the chat saves. A new tab gets your ${previewedAs()} and saves it there.`)
600+
}
501601
return fetchToKeep()
502602
}
503603
if (hostSaves === null || !kept) return
@@ -542,11 +642,14 @@ const amount = (value: unknown): number | null => typeof value === 'number' && N
542642
* video or a recording, and the activity built with them where a file of its own is still missing.
543643
* While a preview plays they are only kept: a new address for the same file is not a new activity.
544644
*/
545-
function takeLinks(given: Record<string, unknown>): void {
645+
function takeLinks(given: Record<string, unknown>, sizes: Record<string, unknown>): void {
546646
let added = false
547647
for (const [name, address] of Object.entries(given)) {
548648
if (typeof address !== 'string' || !/^https?:\/\//i.test(address) || !URL.canParse(address) || !playable(name)) continue
549-
// The same address again is nothing new to build with.
649+
// What the file there weighs, where the parent knows: a tab is opened for one it could not save.
650+
const size = amount(sizes[name])
651+
if (size !== null) sizeAt.set(address, size)
652+
// The same address again, as with its size once that is known, is nothing new to build with.
550653
if (links.get(baseName(name)) === address) continue
551654
links.set(baseName(name), address)
552655
added = true
@@ -560,10 +663,10 @@ function takeLinks(given: Record<string, unknown>): void {
560663
// one that opens links itself, that it does.
561664
window.addEventListener('message', (event) => {
562665
if (!framed || event.source !== window.parent) return
563-
const message = event.data as { source?: unknown, type?: unknown, files?: unknown, links?: unknown, name?: unknown, received?: unknown, total?: unknown, theme?: unknown, max?: unknown, id?: unknown, ok?: unknown } | null
666+
const message = event.data as { source?: unknown, type?: unknown, files?: unknown, links?: unknown, sizes?: unknown, name?: unknown, received?: unknown, total?: unknown, theme?: unknown, max?: unknown, id?: unknown, ok?: unknown } | null
564667
if (message?.source !== 'h5p-play-host') return
565668
if (message.type === 'files' && Array.isArray(message.files)) take(message.files.filter((file): file is File => file instanceof File))
566-
else if (message.type === 'links' && message.links && typeof message.links === 'object') takeLinks(message.links as Record<string, unknown>)
669+
else if (message.type === 'links' && message.links && typeof message.links === 'object') takeLinks(message.links as Record<string, unknown>, message.sizes && typeof message.sizes === 'object' ? message.sizes as Record<string, unknown> : {})
567670
else if (message.type === 'saves') hostSaves = amount(message.max) ?? Infinity
568671
else if (message.type === 'opens') hostOpens = true
569672
else if (message.type === 'saved' && handedId && message.id === handedId && typeof message.ok === 'boolean' && (handed || message.ok)) saveDone(message.ok)

0 commit comments

Comments
 (0)