Skip to content

Commit f0bc657

Browse files
authored
Merge pull request #89 from missing-elements/feat/play-page-files
feat(play): the play page asks for the files a source names
2 parents 759cc61 + 85e73e1 commit f0bc657

4 files changed

Lines changed: 132 additions & 17 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: the activity in a link's `#source=`, built in the visitor's browser as the build page builds it, 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/) |
12+
| `/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/) |
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: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,7 +1091,9 @@ pre.prompt { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 0.9375re
10911091
.play { padding: 0.5rem; }
10921092
.play .player-box { margin: 0; }
10931093
.play-status { margin: 0 0 0.5rem; color: var(--muted); font-size: 0.9rem; }
1094+
.play-status[data-state="asking"] { color: inherit; }
10941095
.play-status[data-state="error"] { color: inherit; font-weight: 600; }
1096+
.play-files { margin: 0 0 0.5rem; }
10951097
.play-status[data-state="ready"] { display: none; }
10961098
.play-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0.5rem 0 0; }
10971099
.play-actions [hidden] { display: none; }

‎src/h5p/play/index.njk‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@ csp: "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' da
1212
so that a chat app can show the activity in its reply: play-page.ts builds it and plays it. -#}
1313
<main class="play" id="main">
1414
<p class="play-status" id="status" role="status" data-state="building">Building the activity in your browser…</p>
15-
<div class="player-box">
15+
{#- For a source that names files of the person's own, a video beside it: chosen here, where
16+
they stay in the browser. The field is hidden, and the button opens it. -#}
17+
<p class="play-files" id="files-box" hidden>
18+
<button type="button" class="button button-solid" id="choose">Choose the file</button>
19+
<input type="file" id="files" multiple hidden>
20+
</p>
21+
<div class="player-box" id="player-box" hidden>
1622
<h5p-player id="player"></h5p-player>
1723
</div>
1824
<p class="play-actions">

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

Lines changed: 122 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,52 @@ 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 { namedFiles, packageName, parseSource, sized, sourceFromFragment, type Problem } from '../build/build-source'
5+
import { baseName, matchFiles, 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
99
* build page builds it, and played, with nothing else on the page but its file to download and a
1010
* way to the build page. A chat app frames it to show the activity in a reply (h5p-toolkit#210).
1111
* Framed, it tells the frame's parent its height, and gives it the built file, which a parent that
1212
* may not let the frame download can save its own way. Nothing leaves the browser otherwise.
13+
*
14+
* A source that names files of the person's own, a video beside it, is asked for them here: the
15+
* person chooses them from their computer, or the frame's parent gives them, and the activity is
16+
* built once they are all here. A chat app was found to hand a card no file the person attached
17+
* (ChatGPT, 2026-11-20: the tool got a piece of text in the file's place), so the page asks itself.
18+
* A file chosen here goes nowhere: the build reads it in the browser.
1319
*/
1420

1521
const $ = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T
1622
const status = $('status')
23+
const filesBox = $('files-box')
24+
const choose = $<HTMLButtonElement>('choose')
25+
const filesInput = $<HTMLInputElement>('files')
26+
const playerBox = $('player-box')
1727
const download = $<HTMLAnchorElement>('download')
1828
const edit = $<HTMLAnchorElement>('edit')
1929
const player = $('player') as HTMLElementTagNameMap['h5p-player']
2030
player.runtime = runtime
2131

32+
type Opened = Awaited<ReturnType<typeof openPack>>
33+
/** The pack, opened at the first build and kept for the next, which a file chosen later starts. */
34+
let opened: Promise<Opened> | null = null
35+
/** The source the link carries, once read, and the files it names. */
36+
let source: unknown
37+
let wanted: string[] = []
38+
/** The files given so far, by name. */
39+
const chosen = new Map<string, File>()
40+
/** The address of the package last built, given back when the next one replaces it. */
41+
let packageUrl: string | null = null
42+
/** Counts builds, so that one overtaken by a newer one shows nothing. */
43+
let builds = 0
44+
/** The missing names the parent was last told, so that it is told again only when they change. */
45+
let told = ''
46+
2247
const framed = window.parent !== window
2348
const toParent = (message: Record<string, unknown>): void => { if (framed) window.parent.postMessage({ source: 'h5p-play', ...message }, '*') }
2449

25-
function say(text: string, state: 'building' | 'ready' | 'error'): void {
50+
function say(text: string, state: 'building' | 'asking' | 'ready' | 'error'): void {
2651
status.textContent = text
2752
status.dataset.state = state
2853
toParent({ type: 'status', state, text })
@@ -34,41 +59,123 @@ edit.href = `/h5p/build/${location.hash}`
3459
// The page's height for the parent, which sizes its frame to it.
3560
if (framed) new ResizeObserver(() => toParent({ type: 'height', height: Math.ceil(document.documentElement.getBoundingClientRect().height) })).observe(document.body)
3661

37-
async function play(): Promise<void> {
38-
let text: string | null
39-
try {
40-
text = await sourceFromFragment(location.hash)
41-
} catch {
42-
return say('The link is damaged: its activity cannot be read. Ask the chat for it again.', 'error')
62+
/** A file's kind, by the ending of its name. */
63+
const kind = (name: string): string => name.slice(name.lastIndexOf('.') + 1).toLowerCase()
64+
65+
/**
66+
* The given files for the paths the source names, matched by name as the build page matches them.
67+
* Where it names one file and one of the same kind was given, that is the file whatever it is
68+
* called: a chat may write the name its own way, and the source cannot be changed here.
69+
*/
70+
function filesFor(paths: string[]): { files: Record<string, File>, missing: string[] } {
71+
const given = [...chosen.values()]
72+
const matched = matchFiles(paths, given)
73+
const [path] = paths
74+
const [file] = given
75+
if (matched.missing.length && paths.length === 1 && given.length === 1 && path !== undefined && file !== undefined && kind(path) === kind(file.name)) {
76+
return { files: { [path]: file }, missing: [] }
4377
}
44-
if (text === null) return say('The link carries no activity. This page plays the one an AI chat put in its link.', 'error')
45-
const parsed = parseSource(text)
46-
if ('problem' in parsed) return say('The activity in the link cannot be read. Open it in the build page to see why.', 'error')
47-
if (namedFiles(parsed.source).length) return say('The activity names files of your own: open it in the build page to choose them.', 'error')
78+
return matched
79+
}
80+
81+
/**
82+
* Asks for the files still missing, by their names, and tells the parent, which may have them. The
83+
* parent is told once for a set of names: one that answers each time with the same files, some of
84+
* them or none that match, would otherwise be asked again with every answer, without end.
85+
*/
86+
function ask(missing: string[]): void {
87+
const names = missing.map(baseName)
88+
const listed = new Intl.ListFormat('en-GB', { type: 'conjunction' }).format(names)
89+
const one = missing.length === 1
90+
choose.textContent = one ? 'Choose the file' : 'Choose the files'
91+
filesInput.accept = [...new Set(missing.map((path) => `.${kind(path)}`))].join(',')
92+
filesBox.hidden = false
93+
say(chosen.size
94+
? `Still needed: ${listed}.`
95+
: `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.`, 'asking')
96+
const missingNow = names.join('\n')
97+
if (missingNow === told) return
98+
told = missingNow
99+
toParent({ type: 'needs-files', names })
100+
}
101+
102+
/** Files given, by the person or by the parent: the activity is built once none is missing. */
103+
function take(files: File[]): void {
104+
if (!files.length || !wanted.length) return
105+
// Where one file is named, a second choice replaces the first.
106+
if (wanted.length === 1) chosen.clear()
107+
for (const file of files) chosen.set(file.name, file)
108+
void play()
109+
}
110+
111+
async function play(): Promise<void> {
112+
const build = ++builds
113+
const { files, missing } = filesFor(wanted)
114+
if (missing.length) return ask(missing)
115+
filesBox.hidden = true
116+
say('Building the activity in your browser…', 'building')
48117
try {
49-
const result = await buildPackage(parsed.source, { libraries: await openPack(installPack), files: {} })
118+
opened ??= openPack(installPack)
119+
const result = await buildPackage(source, { libraries: await opened, files })
120+
if (build !== builds) return
50121
const name = packageName(String(result.manifest.title ?? ''))
51-
download.href = URL.createObjectURL(result.blob)
122+
if (packageUrl) URL.revokeObjectURL(packageUrl)
123+
packageUrl = URL.createObjectURL(result.blob)
124+
download.href = packageUrl
52125
download.download = name
53126
download.hidden = false
54127
const file = new File([result.blob], name, { type: 'application/zip' })
55128
toParent({ type: 'built', file, title: result.manifest.title, size: sized(result.blob.size) })
56129
say(`“${String(result.manifest.title ?? name)}”, ${sized(result.blob.size)}. Starting it…`, 'building')
130+
playerBox.hidden = false
57131
player.file = file
58132
} catch (error) {
133+
if (build !== builds) return
59134
if (error instanceof SourceError) {
60135
const problems = (error as SourceError & { problems: Problem[] }).problems
61136
return say(`The activity has ${problems.length} problem${problems.length === 1 ? '' : 's'}: open it in the build page to see and fix ${problems.length === 1 ? 'it' : 'them'}.`, 'error')
62137
}
138+
// A pack that could not open is opened again at the next build.
139+
opened = null
63140
say(`It could not be built: ${error instanceof Error ? error.message : error}`, 'error')
64141
}
65142
}
66143

144+
async function start(): Promise<void> {
145+
let text: string | null
146+
try {
147+
text = await sourceFromFragment(location.hash)
148+
} catch {
149+
return say('The link is damaged: its activity cannot be read. Ask the chat for it again.', 'error')
150+
}
151+
if (text === null) return say('The link carries no activity. This page plays the one an AI chat put in its link.', 'error')
152+
const parsed = parseSource(text)
153+
if ('problem' in parsed) return say('The activity in the link cannot be read. Open it in the build page to see why.', 'error')
154+
source = parsed.source
155+
wanted = namedFiles(source)
156+
await play()
157+
}
158+
67159
player.addEventListener('ready', () => say(status.textContent!.replace(/ Starting it…$/, ''), 'ready'))
68160
player.addEventListener('error', (event) => {
69161
if (player.state === 'ready') return
70162
say(`It was built, but does not play: ${(event as unknown as CustomEvent<{ message: string }>).detail.message}`, 'error')
71163
})
72164

73-
void play()
165+
// The file field is hidden, and the button opens it.
166+
choose.addEventListener('click', () => filesInput.click())
167+
filesInput.addEventListener('change', () => {
168+
const files = [...(filesInput.files ?? [])]
169+
filesInput.value = ''
170+
take(files)
171+
})
172+
// Files from the frame's parent, which may hold what the person attached in the chat.
173+
window.addEventListener('message', (event) => {
174+
if (!framed || event.source !== window.parent) return
175+
const message = event.data as { source?: unknown, type?: unknown, files?: unknown } | null
176+
if (message?.source !== 'h5p-play-host' || message.type !== 'files' || !Array.isArray(message.files)) return
177+
take(message.files.filter((file): file is File => file instanceof File))
178+
})
179+
180+
void start()
74181
window.addEventListener('hashchange', () => location.reload())

0 commit comments

Comments
 (0)