Skip to content

Commit b740a1c

Browse files
authored
Merge pull request #103 from missing-elements/feat/play-save-in-tab
feat(play): one press saves a package too big for the chat, in a tab that fetches the video itself (#102)
2 parents fa8948b + ac32868 commit b740a1c

3 files changed

Lines changed: 165 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 tries to save the package with no press, saying to press Download where the browser saved nothing. That 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: 122 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,21 @@ 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 preview's package weighs without those files: its libraries and its content. */
126+
let previewWeighs = 0
127+
/** 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. */
128+
const carried = linksFromFragment(location.hash)
129+
if (carried.rest !== location.hash) history.replaceState(null, '', `${location.pathname}${location.search}${carried.rest}`)
130+
let saveUnasked = carried.save
131+
/** Whether the save now made was asked for by the link: said under the stage, where nobody pressed anything. */
132+
let unasked = false
133+
/** The source as a link's fragment, for a tab of this page that saves the package. */
134+
let ownFragment = ''
135+
/** Stops the page's own fetch of a file, where the person chooses it themselves meanwhile. */
136+
let fetchStop: AbortController | null = null
113137
/** Shows the question for the person's files a moment late, where the parent may bring them first. */
114138
let askTimer: ReturnType<typeof setTimeout> | undefined
115139

@@ -304,6 +328,25 @@ function saying(text: string, { busy = false } = {}): void {
304328
announce(text)
305329
}
306330

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

353437
/** How much of a file for the download has come. */
@@ -377,6 +461,7 @@ async function keep(): Promise<void> {
377461
}
378462
packing = true
379463
bringing = false
464+
fetchStop?.abort()
380465
if (keeping) preparing(`Building the .h5p with your ${previewedAs()} in it…`, false)
381466
try {
382467
opened ??= openPack(installPack)
@@ -400,8 +485,10 @@ async function keep(): Promise<void> {
400485
if (!asked) return
401486
// The download the person asked for: made by a parent that saves files, where it takes this one, or by this page.
402487
if (hostSaves !== null && kept.size <= hostSaves) return handOver(kept)
403-
announce(`The .h5p is ready, ${sized(result.blob.size)}: downloading.`)
404488
download.click()
489+
// A save the link asked for, with no press: said where it shows, with the way on where the browser saved nothing.
490+
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.`)
491+
else announce(`The .h5p is ready, ${sized(result.blob.size)}: downloading.`)
405492
} catch (error) {
406493
// Unasked, nothing is said: the preview plays on, and Download builds from the same files.
407494
if (!keeping) return
@@ -433,12 +520,15 @@ async function play(): Promise<void> {
433520
if (packageUrl) URL.revokeObjectURL(packageUrl)
434521
const file = new File([result.blob], name, { type: 'application/zip' })
435522
previewed = result.linked
523+
shownFrom = linked
524+
previewWeighs = result.blob.size
436525
download.hidden = false
437526
if (previewed.length) {
438527
// 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.
528+
// Its link is this page's own, with the addresses and the wish to save, for a press that opens
529+
// it in a tab, which then saves the package; a press here is taken below.
440530
packageUrl = null
441-
download.href = location.href
531+
download.href = savingLink()
442532
download.removeAttribute('download')
443533
about(result.manifest.title, result.builtWith, `${previewedAs() === 'files' ? 'its files play' : `its ${previewedAs()} plays`} from the chat`)
444534
} else {
@@ -476,13 +566,24 @@ async function start(): Promise<void> {
476566
const parsed = parseSource(text)
477567
if ('problem' in parsed) return fail('The activity cannot be read', 'Open it in the build page to see why.', true)
478568
source = parsed.source
569+
ownFragment = await fragmentFromSource(compactSource(text) ?? '')
570+
// The addresses the link carried, kept before the files are known to be wanted: the build below is the one that uses them.
571+
takeLinks(carried.links, {})
479572
wanted = namedFiles(source)
480573
const written = source as { title?: unknown, type?: unknown }
481574
about(written.title, written.type)
482575
await play()
483576
}
484577

485-
player.addEventListener('ready', () => show('ready', `“${title.textContent}” is ready.`))
578+
player.addEventListener('ready', () => {
579+
show('ready', `“${title.textContent}” is ready.`)
580+
// The save a link asked for: made once, as Download would, with no press.
581+
if (!saveUnasked) return
582+
saveUnasked = false
583+
unasked = true
584+
if (previewed.length) fetchToKeep()
585+
else download.click()
586+
})
486587
player.addEventListener('error', (event) => {
487588
if (player.state === 'ready') return
488589
fail('It was built, but does not play', (event as unknown as CustomEvent<{ message: string }>).detail.message, true)
@@ -498,6 +599,14 @@ keepInstead.addEventListener('click', () => filesInput.click())
498599
download.addEventListener('click', (event) => {
499600
if (previewed.length) {
500601
event.preventDefault()
602+
// A package that will weigh more than the parent saves is not made here, where it could not be
603+
// saved with a press: a tab of this page is opened by the parent, at once, and saves it there.
604+
// Only where every file of the activity is at an address, which is all a tab can reach.
605+
const size = hostSaves !== null && hostOpens && !keeping ? previewSize() : null
606+
if (size !== null && size > hostSaves!) {
607+
toParent({ type: 'open', href: savingLink() })
608+
return saying(`This .h5p is about ${sized(size)}, more than the chat saves. A new tab gets your ${previewedAs()} and saves it there.`)
609+
}
501610
return fetchToKeep()
502611
}
503612
if (hostSaves === null || !kept) return
@@ -542,11 +651,14 @@ const amount = (value: unknown): number | null => typeof value === 'number' && N
542651
* video or a recording, and the activity built with them where a file of its own is still missing.
543652
* While a preview plays they are only kept: a new address for the same file is not a new activity.
544653
*/
545-
function takeLinks(given: Record<string, unknown>): void {
654+
function takeLinks(given: Record<string, unknown>, sizes: Record<string, unknown>): void {
546655
let added = false
547656
for (const [name, address] of Object.entries(given)) {
548657
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.
658+
// What the file there weighs, where the parent knows: a tab is opened for one it could not save.
659+
const size = amount(sizes[name])
660+
if (size !== null) sizeAt.set(address, size)
661+
// The same address again, as with its size once that is known, is nothing new to build with.
550662
if (links.get(baseName(name)) === address) continue
551663
links.set(baseName(name), address)
552664
added = true
@@ -560,10 +672,10 @@ function takeLinks(given: Record<string, unknown>): void {
560672
// one that opens links itself, that it does.
561673
window.addEventListener('message', (event) => {
562674
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
675+
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
564676
if (message?.source !== 'h5p-play-host') return
565677
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>)
678+
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> : {})
567679
else if (message.type === 'saves') hostSaves = amount(message.max) ?? Infinity
568680
else if (message.type === 'opens') hostOpens = true
569681
else if (message.type === 'saved' && handedId && message.id === handedId && typeof message.ok === 'boolean' && (handed || message.ok)) saveDone(message.ok)

0 commit comments

Comments
 (0)