Skip to content

Commit cb6410a

Browse files
authored
Merge pull request #105 from missing-elements/feat/play-saving-view
feat(play): the saving tab draws no player and closes itself when the package is saved (#104)
2 parents b740a1c + a9a100f commit cb6410a

4 files changed

Lines changed: 143 additions & 26 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. 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/) |
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`): in a tab of its own the page then draws no player: it fetches the files itself, builds the package and tries to save it with no press. Saved, it counts five seconds while it is looked at and then tries to close the tab; a tab the browser keeps open says to press Download where nothing was saved. 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/assets/site.css‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1111,7 +1111,7 @@ html[data-standalone] .play { padding: 1rem; }
11111111
.play[data-drop] .play-stage { border-color: var(--accent); }
11121112
.play[data-drop] .play-panel { background: var(--tint); }
11131113

1114-
.play-loader, .play-ask, .play-error { display: grid; justify-items: center; gap: 0.75rem; width: 100%; min-width: 0; max-width: 26rem; }
1114+
.play-loader, .play-ask, .play-error, .play-saved { display: grid; justify-items: center; gap: 0.75rem; width: 100%; min-width: 0; max-width: 26rem; }
11151115
.play-panel .button { white-space: normal; }
11161116
.play-label, .play-text, .play-note, .play-heading { margin: 0; }
11171117
.play-label { font-size: 0.9375rem; font-weight: 600; line-height: 1.4; }
@@ -1123,6 +1123,8 @@ html[data-standalone] .play { padding: 1rem; }
11231123
.play-progress span { display: block; width: var(--done, 0%); height: 100%; border-radius: inherit; background: var(--accent); }
11241124
.play-icon { box-sizing: border-box; width: 3rem; height: 3rem; padding: 0.75rem; border-radius: 50%; background: var(--tint); color: var(--accent); fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
11251125
.play-error .play-icon { background: color-mix(in srgb, var(--t-tag) 14%, transparent); color: var(--t-tag); }
1126+
.play-saved-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.5rem; margin: 0; }
1127+
.play-saved-actions:not(:has(> :not([hidden]))) { display: none; }
11261128

11271129
/* Under the stage: what the activity is, and what to do with it. Until its name is known a bar
11281130
of its size stands there. */

‎src/h5p/play/index.njk‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ csp: "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' da
4343
<p class="play-text" id="error-text"></p>
4444
<a class="button button-solid button-large" id="fix" target="_blank" rel="noopener" hidden>Open in the build page</a>
4545
</div>
46+
{#- In a tab a link asked to save the package (&save=1): it is saved, and the tab closes itself. -#}
47+
<div class="play-saved" id="saved" hidden>
48+
<svg class="play-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12.5 10 17.5 19 7"/></svg>
49+
<h1 class="play-heading">Your .h5p is saved</h1>
50+
<p class="play-text" id="saved-text"></p>
51+
<p class="play-saved-actions">
52+
<button type="button" class="button" id="saved-stay">Keep this tab open</button>
53+
<button type="button" class="button" id="saved-play" hidden>Play it here</button>
54+
</p>
55+
</div>
4656
</div>
4757
</div>
4858
<div class="play-bar">

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

Lines changed: 129 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,20 @@ import { baseName, compactSource, fragmentFromSource, fragmentWithLinks, kindOf,
4242
* links, Download of a video said to weigh more than the parent saves hands it such a link, at
4343
* once, while the press still lets a tab open.
4444
*
45-
* What is seen is one stage, in one of five states (`data-state` on `main`): `building`, a loader
46-
* over the place the player takes; `fetching`, the loader with how much of a file the parent has
47-
* brought so far; `asking`, for the person's files; `error`, with the one thing to do about it;
48-
* `ready`, the player. The parent is told each as a `status`, in words a screen reader is told too.
45+
* Such a tab is there to save a file, not to play one (#104): it draws no player, only the file
46+
* coming, the package being built, and that it is saved, and then it closes itself, which a tab
47+
* with nothing behind it may do. It waits a few seconds first, counted only while the page is seen
48+
* and has the keyboard: a question of the browser's own, where to save or whether to, may be over
49+
* it otherwise, or waiting in a tab nobody has looked at yet. "Keep this tab open" stops it, and
50+
* the activity can then be played there. Such a tab builds from files only, never from an
51+
* address: what it fetched, or what the person chose in its place.
52+
*
53+
* What is seen is one stage, in one of six states (`data-state` on `main`): `building`, a loader
54+
* over the place the player takes; `fetching`, the loader with how much of a file has come so far,
55+
* from the parent or from its address; `asking`, for the person's files; `error`, with the one
56+
* thing to do about it; `ready`, the player; `saved`, in a tab that only saves, the package saved
57+
* and the tab about to close. The parent is told each as a `status`, in words a screen reader is
58+
* told too.
4959
*/
5060

5161
const $ = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T
@@ -63,6 +73,10 @@ const askText = $('ask-text')
6373
const choose = $<HTMLButtonElement>('choose')
6474
const filesInput = $<HTMLInputElement>('files')
6575
const errorBox = $('error')
76+
const savedBox = $('saved')
77+
const savedText = $('saved-text')
78+
const savedStay = $<HTMLButtonElement>('saved-stay')
79+
const savedPlay = $<HTMLButtonElement>('saved-play')
6680
const errorTitle = $('error-title')
6781
const errorText = $('error-text')
6882
const fix = $<HTMLAnchorElement>('fix')
@@ -81,7 +95,7 @@ const edit = $<HTMLAnchorElement>('edit')
8195
const player = $('player') as HTMLElementTagNameMap['h5p-player']
8296
player.runtime = runtime
8397

84-
type State = 'building' | 'fetching' | 'asking' | 'ready' | 'error'
98+
type State = 'building' | 'fetching' | 'asking' | 'ready' | 'error' | 'saved'
8599
type Opened = Awaited<ReturnType<typeof openPack>>
86100
/** The pack, opened at the first build and kept for the next, which a file chosen later starts. */
87101
let opened: Promise<Opened> | null = null
@@ -134,6 +148,10 @@ let unasked = false
134148
let ownFragment = ''
135149
/** Stops the page's own fetch of a file, where the person chooses it themselves meanwhile. */
136150
let fetchStop: AbortController | null = null
151+
/** Whether this is a tab of its own that a link asked to save the package: it draws no player. */
152+
let savingOnly = carried.save && window.parent === window
153+
/** Counts down to the tab closing itself, once the package is saved. */
154+
let closing: ReturnType<typeof setInterval> | undefined
137155
/** Shows the question for the person's files a moment late, where the parent may bring them first. */
138156
let askTimer: ReturnType<typeof setTimeout> | undefined
139157

@@ -147,6 +165,7 @@ function show(state: State, text: string): void {
147165
loader.hidden = state !== 'building' && state !== 'fetching'
148166
filesBox.hidden = state !== 'asking'
149167
errorBox.hidden = state !== 'error'
168+
savedBox.hidden = state !== 'saved'
150169
// The way to the build page is the problem's own button where it has one.
151170
edit.hidden = state === 'error' && !fix.hidden
152171
if (status.textContent !== text) status.textContent = text
@@ -289,6 +308,12 @@ function take(files: File[]): void {
289308
// meanwhile, must not start the activity again under them, nor take the place of the file
290309
// the package to keep is being built from.
291310
if (whole || packing) return
311+
// In a tab that only saves, a file chosen while files are fetched ends the fetch, and with it
312+
// the addresses: the package is built from files alone, and one still missing is asked for.
313+
if (savingOnly) {
314+
fetchStop?.abort()
315+
links.clear()
316+
}
292317
// Where one file is named, a second choice replaces the first.
293318
if (wanted.length === 1) chosen.clear()
294319
for (const file of files) chosen.set(file.name, file)
@@ -395,29 +420,34 @@ function fetchToKeep(): void {
395420
}
396421

397422
/**
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.
423+
* Files fetched by this page from their addresses, by their paths in the source, counted as they
424+
* come, ten times a second at most. The browser keeps each as a Blob, which it may hold on disk.
400425
*/
426+
async function fetched(from: Record<string, string>, signal: AbortSignal, count: (name: string, received: number, total: number) => void): Promise<File[]> {
427+
const files: File[] = []
428+
for (const [path, address] of Object.entries(from)) {
429+
const response = await fetch(address, { signal })
430+
if (!response.ok || !response.body) throw new Error(`the chat answered ${response.status}`)
431+
const total = Number(response.headers.get('content-length')) || 0
432+
let received = 0
433+
let shown = 0
434+
const counted = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
435+
transform(chunk, controller) {
436+
received += chunk.byteLength
437+
if (performance.now() - shown > 100) { shown = performance.now(); count(baseName(path), received, total) }
438+
controller.enqueue(chunk)
439+
},
440+
}))
441+
files.push(new File([await new Response(counted).blob()], baseName(path), { type: response.headers.get('content-type') ?? '' }))
442+
}
443+
return files
444+
}
445+
446+
/** The files of a preview fetched by this page, where no parent holds them: from the addresses it plays from. */
401447
async function fetchFiles(): Promise<void> {
402448
const stop = fetchStop = new AbortController()
403449
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-
}
450+
const files = await fetched(Object.fromEntries(previewed.map((path) => [path, shownFrom[path] ?? ''])), stop.signal, keepCount)
421451
if (stop.signal.aborted) return
422452
take(files)
423453
} catch (error) {
@@ -434,6 +464,67 @@ async function fetchFiles(): Promise<void> {
434464
}
435465
}
436466

467+
/**
468+
* In a tab that only saves: the files fetched from the addresses the link carried, shown coming in
469+
* the stage, and then built from. One that cannot be fetched is asked for, as where none was given.
470+
*/
471+
async function fetchThenBuild(from: Record<string, string>): Promise<void> {
472+
const stop = fetchStop = new AbortController()
473+
const paths = Object.keys(from)
474+
const what = paths.length === 1 ? called(paths[0]!) : 'files'
475+
label.textContent = `Getting your ${what}…`
476+
note.textContent = 'From the chat to your browser, nowhere else.'
477+
progress.hidden = true
478+
instead.hidden = false
479+
show('fetching', `Getting your ${what} from the chat.`)
480+
try {
481+
const files = await fetched(from, stop.signal, fetching)
482+
if (stop.signal.aborted) return
483+
// The addresses are used up: a file still missing is asked for, not played from another's.
484+
links.clear()
485+
take(files)
486+
} catch {
487+
if (stop.signal.aborted) return
488+
links.clear()
489+
ask(paths)
490+
askText.textContent = `Your ${what} could not be fetched from the chat: its address may have run out. Choose ${paths.length === 1 ? 'it' : 'them'} from your computer; ${paths.length === 1 ? 'it stays' : 'they stay'} in your browser.`
491+
}
492+
}
493+
494+
/**
495+
* The package saved in a tab that only saves, with no press, and the tab closed a few seconds
496+
* later. The seconds are counted only while the page is seen and has the keyboard: otherwise a
497+
* question of the browser's own, where to save or whether to, may be open over it, or waiting
498+
* in a tab that was opened behind another.
499+
*/
500+
function savedHere(file: File): void {
501+
saveUnasked = false
502+
download.click()
503+
const named = `${file.name}, ${sized(file.size)},`
504+
let left = 5
505+
const said = (): void => { savedText.textContent = `${named} is in your downloads. This tab closes in ${left} s.` }
506+
savedStay.hidden = false
507+
savedPlay.hidden = true
508+
said()
509+
show('saved', `Your .h5p is saved: ${named} is in your downloads. This tab closes itself in a few seconds.`)
510+
clearInterval(closing)
511+
closing = setInterval(() => {
512+
if (document.hidden || !document.hasFocus()) return
513+
if (--left > 0) return said()
514+
// A tab the browser lets no page close stays, and says what it would have.
515+
stay()
516+
window.close()
517+
}, 1000)
518+
}
519+
520+
/** The tab kept open: the way on where the browser saved nothing, and the activity to play. */
521+
function stay(): void {
522+
clearInterval(closing)
523+
savedText.textContent = `${kept?.name ?? 'The .h5p'}, ${sized(kept?.size ?? 0)}, is in your downloads. If nothing was saved, press Download.`
524+
savedStay.hidden = true
525+
savedPlay.hidden = false
526+
}
527+
437528
/** How much of a file for the download has come. */
438529
function keepCount(name: string, received: number, total: number): void {
439530
if (!bringing) return
@@ -540,6 +631,8 @@ async function play(): Promise<void> {
540631
about(result.manifest.title, result.builtWith, result.blob.size)
541632
toParent({ type: 'built', file, title: result.manifest.title, size: sized(result.blob.size) })
542633
}
634+
// A tab that only saves has what it came for: no player is drawn.
635+
if (savingOnly && whole) return savedHere(file)
543636
busy('Starting the activity…')
544637
playerBox.hidden = false
545638
player.file = file
@@ -572,6 +665,9 @@ async function start(): Promise<void> {
572665
wanted = namedFiles(source)
573666
const written = source as { title?: unknown, type?: unknown }
574667
about(written.title, written.type)
668+
// A tab that only saves fetches what the link gave addresses for first, and builds once.
669+
const { linked } = savingOnly ? linksFor(wanted) : { linked: {} }
670+
if (Object.keys(linked).length) return fetchThenBuild(linked)
575671
await play()
576672
}
577673

@@ -589,6 +685,15 @@ player.addEventListener('error', (event) => {
589685
fail('It was built, but does not play', (event as unknown as CustomEvent<{ message: string }>).detail.message, true)
590686
})
591687

688+
savedStay.addEventListener('click', stay)
689+
// The package that was saved, played in the tab that was kept open.
690+
savedPlay.addEventListener('click', () => {
691+
if (!kept) return
692+
savingOnly = false
693+
busy('Starting the activity…')
694+
playerBox.hidden = false
695+
player.file = kept
696+
})
592697
// The file field is hidden, and the buttons open it.
593698
choose.addEventListener('click', () => filesInput.click())
594699
instead.addEventListener('click', () => filesInput.click())

0 commit comments

Comments
 (0)