diff --git a/apps/demo/demo/player-page.css b/apps/demo/demo/player-page.css
index b24edc10..2b326855 100644
--- a/apps/demo/demo/player-page.css
+++ b/apps/demo/demo/player-page.css
@@ -642,6 +642,69 @@ progress[hidden] { display: none; }
.message.offer:not([hidden]) { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
.offer button[hidden] { display: none; }
+/* ---------------------------------------------------------------- the SCORM page's steps */
+
+/* A step: its number in a disc before its heading, and hidden until the page can reach it. */
+.step[hidden] { display: none; }
+.step h2 { display: flex; align-items: center; gap: 0.6rem; }
+.step-number {
+ display: inline-grid;
+ flex: none;
+ place-items: center;
+ width: 1.75rem;
+ height: 1.75rem;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--accent-ink);
+ font-size: 0.875rem;
+ font-weight: 650;
+ letter-spacing: 0;
+}
+.step-hint { color: var(--muted); font-size: 0.925rem; }
+
+/* A file's row in the review: its name, size and a button to take it out; what its zip will hold,
+ or why none can be written, in a strip whose left edge takes the state's colour as the status
+ strip's does; its title in the LMS; and, with several files, its own zip. */
+.scorm-rows { display: grid; gap: 0.75rem; margin: 0; padding: 0; list-style: none; }
+.scorm-row {
+ padding: 0.85rem 1rem;
+ border: 1px solid var(--line);
+ border-left: 3px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+}
+.scorm-row[data-state="built"] { border-left-color: var(--ok); }
+.scorm-row[data-state="refused"],
+.scorm-row[data-state="failed"] { border-left-color: var(--danger); }
+.scorm-row[data-state="reading"],
+.scorm-row[data-state="building"] { border-left-color: var(--accent); }
+.scorm-row-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.25rem 0.75rem; }
+.scorm-row-name { font-weight: 600; overflow-wrap: anywhere; }
+.scorm-row-size { color: var(--muted); font-size: 0.875rem; font-variant-numeric: tabular-nums; }
+/* A small button beside the name, where the page's own rule draws a large one. */
+button.scorm-row-remove { min-height: 2rem; margin-left: auto; padding: 0.2rem 0.75rem; font-size: 0.85rem; }
+.scorm-row-facts { margin: 0.35rem 0 0; color: var(--muted); font-size: 0.925rem; }
+.scorm-row[data-state="refused"] .scorm-row-facts,
+.scorm-row[data-state="failed"] .scorm-row-facts { color: var(--danger); }
+.scorm-row-title { display: grid; gap: 0.3rem; margin-top: 0.65rem; font-size: 0.85rem; font-weight: 600; }
+.scorm-row-title input {
+ min-width: 0;
+ min-height: 2.5rem;
+ padding: 0.4rem 0.75rem;
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ background: var(--bg);
+ color: inherit;
+ font: inherit;
+ font-size: 0.95rem;
+ font-weight: 400;
+ transition: border-color var(--ease), box-shadow var(--ease);
+}
+.scorm-row-title input:focus-visible { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
+.scorm-row-title input:disabled { opacity: 0.6; }
+.scorm-row-download { display: inline-block; margin-top: 0.6rem; font-weight: 600; }
+.scorm-row-download[hidden] { display: none; }
+
/* ---------------------------------------------------------------- the player's box */
h5p-player {
diff --git a/apps/demo/demo/scorm.html b/apps/demo/demo/scorm.html
index f0eb9cb1..60e1389a 100644
--- a/apps/demo/demo/scorm.html
+++ b/apps/demo/demo/scorm.html
@@ -4,14 +4,14 @@
Convert H5P to SCORM in your browser — h5p-offline-player
-
+
-
+
@@ -19,7 +19,7 @@
-
+
@@ -32,29 +32,49 @@
SCORM
H5P to SCORM
- Drop a .h5p file here, or choose one, and download it as a SCORM 1.2 package
- for your LMS. It is built in your browser with the player this site serves, and nothing is
- uploaded: the package never leaves your computer.
+ Drop .h5p files here, or choose them, check what each zip will hold, and
+ download them as SCORM 1.2 packages for your LMS. They are built in your browser with the
+ player this site serves, and nothing is uploaded: the packages never leave your computer.
+ What each zip will hold, read from the package before anything is built. The title is
+ what the LMS lists the package by; change it here if you like.
+
diff --git a/design/layout.md b/design/layout.md
index 92a34d2d..57d2641c 100644
--- a/design/layout.md
+++ b/design/layout.md
@@ -233,8 +233,9 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st
lib/scorm-core.mjs what the SCORM zip is wherever it is written, and no Node import: the
package read and its parts planned, the entries laid out, the zip written
into a zip.js writer; lib/scorm-browser.mjs, `./scorm/browser`,
- buildScormInPage(): the same zip in a page, from a File, the files
- fetched from the site and the zip a Blob; lib/shared.mjs, EmbedError and
+ planScormInPage() and buildScormInPage(): the same zip in a page, from a
+ File, read and planned first (#137), the files fetched from the site and
+ the zip a Blob; lib/shared.mjs, EmbedError and
the player's file names, for the modules that import no Node (#122)
scorm/ the SCORM package's launch page (index.html, its title, language and
build filled in by the writer), scorm.js, its bridge to the LMS's API,
diff --git a/design/scorm.md b/design/scorm.md
index 8b38fcb6..c0b823bb 100644
--- a/design/scorm.md
+++ b/design/scorm.md
@@ -270,13 +270,15 @@ one row each; an LMS added here gets a row there.
compressor, as one bundled for 1.4 does, gets the one at `base` or a zip without it, whose page
names none and whose bridge writes the state plain, rather than an export that fails for a file
it never had to serve), each part checked against the index's SHA-256 since it came
- over the network, and the zip a `Blob`. The runtime's files are named by a list,
+ over the network, and the zip a `Blob`, in two steps since #137: `planScormInPage` reads and
+ plans, and the plan's `write` fetches and writes (below). The runtime's files are named by a list,
`RUNTIME_FILES`, plus the fonts from its `MANIFEST.json`, since a folder on a server cannot be
listed; `scorm-browser.test.ts` runs the builder in Node, which has `fetch`, `File` and
`crypto.subtle`, against a written site and holds its zip to the command's entry for entry, so a
file the runtime adds shows up there. `site/scorm-page.js` is the page's script,
- `startScormPage()`, which reads `#file`, `#status`, `#download` and `#notice`, and a `#state`
- badge where the page has one; the written site loads it as `scripts/build.mjs` bundles it with
+ `startScormPage()`, which reads `#file`, `#status`, `#download` and `#notice`, a `#state`
+ badge where the page has one, and `#files` and `#build` where it works in steps (below); the
+ written site loads it as `scripts/build.mjs` bundles it with
zip.js and the player's `./plan` (`dist/scorm-page.js`, zip.js's licence in its header, since the
site has no bundler), from `scorm.html`, with the launch page and the bridge copied beside it as
`scorm-launch.html`, `scorm.js` and `lz-string.js` and the player's and the pack's versions in
@@ -293,8 +295,50 @@ one row each; an LMS added here gets a row there.
Decided with the owner that day: SCORM 1.2 only, H5P's result rule kept,
the tested LMSs the supported ones. Canvas, the audience's LMS, runs its SCORM on Rustici's
SCORM Cloud by all accounts and cannot be tested here, since Canvas Free-for-Teacher has no SCORM
- upload. `scorm-page.test.ts` drives the page in Chromium: a chosen file, the download, which is
- the command's zip and plays unpacked, a refusal, and the next file after it.
+ upload.
+- **The page works in steps, and the title is the teacher's** (#137, 2026-11-05). The University
+ of Tennessee's in-browser converter (Nick Pook, MIT, h5p-standalone inside) reviews each package
+ before it builds, lets the title be changed and takes several files; the owner asked for the
+ same here, the build staying ours: their zips, measured on 2026-11-05 under a stand-in for an
+ LMS and in SCORM Cloud, sent no score, no answers and no time, and never resumed. So a page
+ shows what a zip will hold before anything is written, from the plan the build then uses:
+ `planScormInPage` reads
+ the package and plans its parts, and returns the facts, the main library with the version its
+ `preloadedDependencies` give it (`mainLibraryOf`), the title, the size, the parts and their size
+ from the pack's index, with `write`, which fetches the files and writes the zip, as often as
+ asked; `buildScormInPage` is the two at once. A refusal comes at planning, by name, before
+ anything but the pack's index is fetched. **The title** is `title` on both builders and
+ `--title` on the command, cleaned by `scormTitle` as `h5p.json`'s is, an empty one leaving the
+ package's; it goes into the manifest's organisation and item, which the LMS lists, and the
+ launch page's `
`, and not into the build stamp, so a zip written again under another
+ title keeps learners' places, nor into the package, which goes in as exported. **The page**
+ works in steps where it holds `#files`, a list, and `#build`, a button, as both pages here do:
+ ① choose, ② review, ③ download, each step the closest `[data-step]` around them, shown once it
+ can be reached. A file chosen or dropped gets a row (the same file twice, by name, size and date,
+ is one), whose facts sit in a live region (`role="status"`) from the moment the row appears, so
+ that what the reading found is announced. Every row is drawn again on any change, a key typed
+ in a title among them, so the page writes a region's text, and `#status`'s, only when it
+ changes: written again as it was, a region may be read out again, and a test types a title key
+ by key and counts no change to either. `#build` writes the rows one after another, a failure
+ shown in its row while the others go on; `#download` is then the zip, or, for several, one zip
+ holding them all, each stored as it is with its sizes and CRC in its local header (`addStored`,
+ the package's way since #92), while each row links its own; a title changed after a build takes
+ that zip back. A page with only the four elements of before builds the first file at once and
+ shows a refusal in `#notice`, as up to 1.5, since `startScormPage` and its page are covered by
+ docs/compatibility.md and a host's own page has to keep working. Not taken from their page: a
+ contents list, a SCORM Cloud link, an export of the settings, switches for playing offline and
+ for resume, since every zip here carries all it plays and always resumes, and an accessibility
+ check, which would need knowledge of each content type. The SCORM version and the grading
+ options are #138's.
+
+ `scorm-page.test.ts` drives the written site's page in Chromium: a chosen file read into its row
+ and built on Build, the download, which is the command's zip and plays unpacked; three files at
+ once, a refusal in its row beside two that build, a title given, each row's zip and the zip of
+ all, a row taken out, a title changed after the build; files dropped, the same one only once;
+ and a page with only the four elements, which builds at once and refuses in `#notice`.
+ `scorm-browser.test.ts` holds the plan's facts to the command's zip, two writes of one plan
+ under two titles to the same zip but for the manifest and the page, and a title given to the
+ page's builder to the command's `--title`, entry for entry.
`tests/scorm.test.ts` checks the zip, the parts it carries, its stored entries' local headers and
its refusals in Node. In Chromium it plays the unpacked zip under a page that holds the API and
diff --git a/docs/compatibility.md b/docs/compatibility.md
index f7a180d4..e82af203 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -97,9 +97,9 @@ What is covered of the pack itself: the `pack` export, `parts/` with its `index.
question's `cmi.interactions.n`), and what it keeps in `cmi.suspend_data`, which a zip written
by a later version reads back unless the libraries it carries from the pack have changed: 1.5
writes it compressed and still reads what 1.4 wrote plain.
-- **The SCORM page**, `scorm.html` on a written site, and **`buildScormInPage()`** and
- **`startScormPage()`**, with their options and types: the same zip as `buildScorm()`'s, built in
- the browser.
+- **The SCORM page**, `scorm.html` on a written site, and **`planScormInPage()`**,
+ **`buildScormInPage()`** and **`startScormPage()`**, with their options and types: the same zip
+ as `buildScorm()`'s, built in the browser.
A written site is a folder of copies and changes only when it is written again: upgrading is
running the new version of the command and deploying the folder. A SCORM zip likewise, replaced in
diff --git a/packages/embed/README.md b/packages/embed/README.md
index 9cc897c9..2d7d5703 100644
--- a/packages/embed/README.md
+++ b/packages/embed/README.md
@@ -40,6 +40,7 @@ a subdomain shares your site's cookies.
| `--no-libraries` | Leave out the library pack, 13.8 MB in `libraries/`, one archive per library, of which a learner's browser fetches only those a package needs; `libraries=pack` then fetches them from jsDelivr, where allowed |
| `--force` | Write into a non-empty folder, replacing only this tool's files |
| `--scorm [zip]` | Write a SCORM 1.2 package of one `.h5p` instead of the site; see [A SCORM package, for an LMS](#a-scorm-package-for-an-lms) |
+| `--title ` | With `--scorm`, the title the LMS lists the package by. Default: the title in its `h5p.json` |
| `-h`, `--help` / `-v`, `--version` | |
Origins are `https://host.example`, comma or space separated, no path or trailing slash;
@@ -170,11 +171,15 @@ belongs to what it was saved in.
### In the browser
-The site `h5p-embed` writes carries the same converter as a page, `scorm.html`: a `.h5p` chosen
-or dropped on it becomes the same zip, built in the browser from the site's own copies of the
-player, the runtime and the library pack, and offered as a download. Nothing is uploaded and no
-`npx` is needed; the page says which LMSs the zip is checked in and what each needs. The demo
-site has it at [/demo/scorm.html](https://h5p-offline-player.vercel.app/demo/scorm.html).
+The site `h5p-embed` writes carries the same converter as a page, `scorm.html`, in three steps.
+Choose `.h5p` files, or drop them on it; review each one, which shows the main library and its
+version, the size, whether it carries its libraries or how many it takes from the pack, or why it
+cannot be built, and the title the LMS will list it by, which you can change; then build, and
+download each zip, or all of them in one. They are built in the browser from the site's own
+copies of the player, the runtime and the library pack, the same zips as the command's. Nothing
+is uploaded and no `npx` is needed; the page says which LMSs the zip is checked in and what each
+needs. The demo site has it at
+[/demo/scorm.html](https://h5p-offline-player.vercel.app/demo/scorm.html).
### Supported LMSs
@@ -238,9 +243,10 @@ export, which `libraries=pack` then plays from) or `packBase` (the folder of a c
`@missing-elements/h5p-runtime` export, for a bundled element) and `askInOwnFrame` (default
`true`; `false` plays a package from another origin as it is when a same-origin page frames it).
`librariesPack`, the URL of a whole `libraries.h5p`, still works, as a bundle that only fills gaps.
-`buildScorm` from `@missing-elements/h5p-embed/scorm` is `--scorm`: it takes `h5p`, `out` and
-`force`, and returns the zip's path, its title, size, the `libraries` it carries from the pack,
-and `build`, the stamp saved state is kept against. Every entry ships with TypeScript declarations.
+`buildScorm` from `@missing-elements/h5p-embed/scorm` is `--scorm`: it takes `h5p`, `out`,
+`force` and `title`, and returns the zip's path, its title, size, the `libraries` it carries from
+the pack, and `build`, the stamp saved state is kept against. Every entry ships with TypeScript
+declarations.
`buildScormInPage` from `@missing-elements/h5p-embed/scorm/browser` is the same build in a page:
it takes `file`, a `File` or `Blob`; `base`, the folder with the player's three files and
@@ -250,11 +256,17 @@ it takes `file`, a `File` or `Blob`; `base`, the folder with the player's three
beside the player as the written site does, where a page that gives the template and not the
compressor gets the one at `base`, or a zip without it that keeps the saved state plain, as 1.4
did;
-`version` and `packVersion`, for the zip's notice; and `onProgress`. It returns the zip as a
-`Blob`, with its `name`, `title`, `libraries`, `build` and `size`. `startScormPage` from
-`@missing-elements/h5p-embed/scorm-page.js` is the page's script, which reads the page's
-`#file`, `#status`, `#download` and `#notice` (see `site/scorm.html`); the written site loads it
-bundled, with zip.js inside, and a page that bundles imports the source.
+`version` and `packVersion`, for the zip's notice; `title`, as `buildScorm` takes it; and
+`onProgress`. It returns the zip as a `Blob`, with its `name`, `title`, `libraries`, `build` and
+`size`. `planScormInPage`, from the same module, takes the same options and stops before
+anything is written: it reads the package and returns what its zip will hold, its `title`,
+`mainLibrary`, `size`, the `libraries` from the pack and their `librariesSize`, or refuses it as
+the build would, and `write({ title })` then writes the zip, as often as asked. `startScormPage`
+from `@missing-elements/h5p-embed/scorm-page.js` is the page's script, which reads the page's
+`#file`, `#status`, `#download` and `#notice`, and works in steps where the page also holds
+`#files`, the list it puts a row in for each file, and `#build`, the button that builds them (see
+`site/scorm.html`); a page without the two builds the first file at once, as before. The written
+site loads it bundled, with zip.js inside, and a page that bundles imports the source.
```js
import '@missing-elements/h5p-offline-player'
diff --git a/packages/embed/bin/h5p-embed.mjs b/packages/embed/bin/h5p-embed.mjs
index edbaef62..c3e7ab32 100755
--- a/packages/embed/bin/h5p-embed.mjs
+++ b/packages/embed/bin/h5p-embed.mjs
@@ -6,7 +6,7 @@ import { EmbedError, buildSite } from '../lib/build.mjs'
import { buildScorm } from '../lib/scorm.mjs'
const USAGE = `Usage: h5p-embed [folder] [options]
- h5p-embed --scorm [zip] [--force]
+ h5p-embed --scorm [zip] [--title ] [--force]
Writes the H5P embed page as a static site, ready to deploy to a player domain of your own.
The folder defaults to ./h5p-player.
@@ -17,6 +17,8 @@ zip defaults to ./.scorm.zip.
Options:
--scorm write a SCORM package of this .h5p rather than the site
+ --title with --scorm, the title the LMS lists the package by. Default: the
+ title in its h5p.json
--packages play packages, and fetch library bundles, only from these origins
(comma or space separated; this site's own is always allowed). Add
any host a package URL redirects to, and https://cdn.jsdelivr.net for
@@ -39,6 +41,7 @@ try {
allowPositionals: true,
options: {
scorm: { type: 'string' },
+ title: { type: 'string' },
packages: { type: 'string', multiple: true },
ancestors: { type: 'string', multiple: true },
'default-libraries': { type: 'string' },
@@ -75,6 +78,11 @@ const shown = (path) => {
return below === '' ? '.' : below.startsWith('..') ? path : below
}
+if (values.title !== undefined && values.scorm === undefined) {
+ console.error(`h5p-embed: --title only with --scorm, which names the package it titles\n\n${USAGE}`)
+ process.exit(2)
+}
+
// `--scorm=` with no package still means a SCORM package, refused for naming none.
if (values.scorm !== undefined) {
// The site's options shape a site; a SCORM package has no hosts, framers or library sources.
@@ -87,7 +95,8 @@ if (values.scorm !== undefined) {
const zip = await buildScorm({
h5p: values.scorm,
out: positionals[0] ?? `${basename(values.scorm, extname(values.scorm))}.scorm.zip`,
- force: values.force ?? false
+ force: values.force ?? false,
+ title: values.title
})
const count = zip.libraries.length
const supplied = count > 0 ? `, the H5P runtime and ${count} ${count === 1 ? 'library' : 'libraries'} from the library pack, which it does not carry` : ' and the H5P runtime'
diff --git a/packages/embed/lib/scorm-browser.mjs b/packages/embed/lib/scorm-browser.mjs
index 9ce18640..6b893b8b 100644
--- a/packages/embed/lib/scorm-browser.mjs
+++ b/packages/embed/lib/scorm-browser.mjs
@@ -1,6 +1,6 @@
import { BlobWriter, ZipWriter } from '@zip.js/zip.js'
import { packLibrariesIn } from '@missing-elements/h5p-offline-player/plan'
-import { addScormEntries, buildStamp, readPackage, runtimeFiles, scormEntries, scormTitle, sha256Hex } from './scorm-core.mjs'
+import { addScormEntries, buildStamp, mainLibraryOf, readPackage, runtimeFiles, scormEntries, scormTitle, sha256Hex } from './scorm-core.mjs'
import { EmbedError, PLAYER_FILES } from './shared.mjs'
/**
@@ -10,6 +10,10 @@ import { EmbedError, PLAYER_FILES } from './shared.mjs'
* the library pack come from the site the page is on, and the zip comes back as a `Blob` for a
* download link. Nothing is uploaded anywhere. It needs a secure context, https or localhost, for
* `crypto.subtle`.
+ *
+ * In two steps, so that a page can show what a zip will hold before it is written:
+ * `planScormInPage` reads the package and plans the parts of the pack it needs, and the plan's
+ * `write` fetches the files and writes the zip. `buildScormInPage` is both at once.
*/
/**
@@ -26,6 +30,8 @@ import { EmbedError, PLAYER_FILES } from './shared.mjs'
* @property {Blob} file the package, as picked or dropped
* @property {string} [name] its file name, for the zip's name, the title's fallback and the
* messages; a `File`'s own by default
+ * @property {string} [title] the title the LMS lists the zip by, in place of `h5p.json`'s; an
+ * empty one leaves that
* @property {string | URL} [base] the folder that holds the player's three files and
* `frame-assets/`, and, unless `assets` gives them, `scorm-launch.html`, `scorm.js`,
* `lz-string.js`, `embed.css` and `libraries.txt`: this page's own folder by default
@@ -51,13 +57,32 @@ import { EmbedError, PLAYER_FILES } from './shared.mjs'
* @typedef {object} PageScorm
* @property {Blob} blob the zip
* @property {string} name what to call it: the package's name with `.scorm.zip` in place of its extension
- * @property {string} title the package's title, as the LMS lists it
+ * @property {string} title the title the LMS lists it by: the one chosen, else the package's
* @property {string} version the player's version, as given
* @property {string[]} libraries the folders of the libraries the zip carries from the pack
* @property {string} build the build stamp, as `buildScorm` returns it
* @property {number} size the zip's size in bytes
*/
+/**
+ * What `planScormInPage` read of a package: what its zip will hold, known before anything else is
+ * fetched and anything is written.
+ * @typedef {object} PlannedScorm
+ * @property {string} name the package's file name
+ * @property {number} size the package's size in bytes
+ * @property {string} title the title the zip takes unless `write` is given another: `h5p.json`'s,
+ * or the file's name
+ * @property {{ machineName: string, majorVersion?: number, minorVersion?: number } | null} mainLibrary
+ * the package's main library, as `h5p.json` names it, with the version its dependencies give
+ * it; `null` when it names none
+ * @property {string[]} libraries the folders of the libraries the zip will carry from the pack;
+ * none for a package that carries its own
+ * @property {number} librariesSize their archives' size in bytes, as the pack's index gives it
+ * @property {(options?: { title?: string, onProgress?: (progress: ScormProgress) => void }) => Promise} write
+ * fetches the parts, the player and the runtime, and writes the zip, under `title` when one is
+ * given; `onProgress` defaults to the plan's. It can be called again, for another title
+ */
+
/**
* @param {typeof fetch} fetchImpl
* @param {string} url
@@ -81,14 +106,15 @@ async function fetched(fetchImpl, url, what) {
const asBlob = (value) => (value instanceof Blob ? value : new Blob([value]))
/**
- * Builds the SCORM 1.2 zip of a package in a page, and returns it as a `Blob`. Refuses what
- * `buildScorm` refuses, with the same messages, and a part of the pack whose bytes do not match
- * the index, since they came over the network.
+ * Reads a package in a page and plans its SCORM zip: `h5p.json`, and the parts of the pack the
+ * zip will carry, by the player's own plan. Refuses what `buildScorm` refuses before it writes,
+ * with the same messages: a package that needs a library neither it nor the pack has, and a file
+ * that is not a package.
* @param {PageScormOptions} options
- * @returns {Promise}
+ * @returns {Promise}
*/
-export async function buildScormInPage(options) {
- const { file, pack = null, packBase = null, assets = {}, version = 'unknown', packVersion = null, onProgress = () => {}, fetch: fetchImpl = globalThis.fetch } = options ?? {}
+export async function planScormInPage(options) {
+ const { file, pack = null, packBase = null, onProgress = () => {}, fetch: fetchImpl = globalThis.fetch } = options ?? {}
if (!(file instanceof Blob)) throw new TypeError('Give the package as a File or a Blob')
if (!globalThis.crypto?.subtle) {
throw new EmbedError('A page builds SCORM packages in a secure context only, https or localhost: it needs crypto.subtle, which a page has nowhere else.')
@@ -97,13 +123,9 @@ export async function buildScormInPage(options) {
if (typeof name !== 'string' || !name) throw new TypeError("Give the package's name: a Blob has none")
const base = new URL(options.base ?? './', globalThis.location?.href)
if (!base.href.endsWith('/')) base.pathname += '/'
- /** @param {string} path */
- const at = (path) => new URL(path, base).href
// The pack as the page can reach it, held to its shape by the player's own rule; a part's
// record, what the zip's index repeats, is the entry without its address.
- /** @type {import('./scorm-core.mjs').PackPart[]} */
- let parts = []
/** @type {unknown[]} */
let index = []
if (pack) {
@@ -122,7 +144,10 @@ export async function buildScormInPage(options) {
})
onProgress({ step: 'reading' })
+ /** @type {any} */
let manifest
+ /** @type {import('./scorm-core.mjs').PackPart[]} */
+ let parts
try {
;({ manifest, parts } = await readPackage(file, name, library))
} catch (error) {
@@ -132,52 +157,82 @@ export async function buildScormInPage(options) {
}
throw error
}
- const title = scormTitle(manifest, name.replace(/\.[^.]+$/, ''))
-
- onProgress({ step: 'libraries', libraries: parts.length })
- /** @param {string} url @param {string} what */
- const blob = async (url, what) => (await fetched(fetchImpl, url, what)).blob()
- // The compressor came in 1.5, after pages that bundle the launch files were written: such a page
- // that does not give it plays on without it, its state plain, rather than fail for a file it
- // never had to serve.
- const compressor = async () => {
- try {
- return await blob(at('lz-string.js'), "The launch page's compressor")
- } catch (error) {
- if (assets.launch !== undefined && error instanceof EmbedError) return null
- throw error
+ const stem = name.replace(/\.[^.]+$/, '')
+ const planned = scormTitle(manifest, stem)
+
+ /** @type {PlannedScorm['write']} */
+ const write = async ({ title: chosen, onProgress: report = onProgress } = {}) => {
+ const title = scormTitle(manifest, stem, chosen)
+ const { assets = {}, version = 'unknown', packVersion = null } = options
+ /** @param {string} path */
+ const at = (path) => new URL(path, base).href
+
+ report({ step: 'libraries', libraries: parts.length })
+ /** @param {string} url @param {string} what */
+ const blob = async (url, what) => (await fetched(fetchImpl, url, what)).blob()
+ // The compressor came in 1.5, after pages that bundle the launch files were written: such a
+ // page that does not give it plays on without it, its state plain, rather than fail for a file
+ // it never had to serve.
+ const compressor = async () => {
+ try {
+ return await blob(at('lz-string.js'), "The launch page's compressor")
+ } catch (error) {
+ if (assets.launch !== undefined && error instanceof EmbedError) return null
+ throw error
+ }
}
- }
- /** @param {string[]} names @param {(name: string) => string} url @param {string} what */
- const blobs = async (names, url, what) => new Map(await Promise.all(names.map(async (item) => /** @type {[string, Blob]} */ ([item, await blob(url(item), `${what} ${item}`)]))))
- const partBlobs = await blobs(parts.map((part) => part.folder), (folder) => /** @type {import('./scorm-core.mjs').PackPart} */ (parts.find((part) => part.folder === folder)).url, 'The library part')
- // Checked as the player checks a part before it uses one: these bytes came over the network.
- for (const part of parts) {
- const bytes = await /** @type {Blob} */ (partBlobs.get(part.folder)).arrayBuffer()
- if ((await sha256Hex(bytes)) !== part.sha256) {
- throw new EmbedError(`The library part ${part.folder} from ${part.url} does not match the pack's index, so the zip was not written.`)
+ /** @param {string[]} names @param {(name: string) => string} url @param {string} what */
+ const blobs = async (names, url, what) => new Map(await Promise.all(names.map(async (item) => /** @type {[string, Blob]} */ ([item, await blob(url(item), `${what} ${item}`)]))))
+ const partBlobs = await blobs(parts.map((part) => part.folder), (folder) => /** @type {import('./scorm-core.mjs').PackPart} */ (parts.find((part) => part.folder === folder)).url, 'The library part')
+ // Checked as the player checks a part before it uses one: these bytes came over the network.
+ for (const part of parts) {
+ const bytes = await /** @type {Blob} */ (partBlobs.get(part.folder)).arrayBuffer()
+ if ((await sha256Hex(bytes)) !== part.sha256) {
+ throw new EmbedError(`The library part ${part.folder} from ${part.url} does not match the pack's index, so the zip was not written.`)
+ }
}
- }
- const runtimeManifest = await (await fetched(fetchImpl, at('frame-assets/MANIFEST.json'), "The runtime's manifest")).json()
- const files = {
- launch: assets.launch ?? (await (await fetched(fetchImpl, at('scorm-launch.html'), "The launch page's template")).text()),
- bridge: assets.bridge !== undefined ? asBlob(assets.bridge) : await blob(at('scorm.js'), 'The launch page\'s script'),
- lz: assets.lz !== undefined ? asBlob(assets.lz) : await compressor(),
- css: assets.css !== undefined ? asBlob(assets.css) : await blob(at('embed.css'), 'The stylesheet'),
- player: await blobs(PLAYER_FILES, at, "The player's file"),
- runtime: await blobs(runtimeFiles(runtimeManifest), (path) => at(`frame-assets/${path}`), "The runtime's file"),
- pkg: file,
- parts: partBlobs,
- librariesText: parts.length === 0 ? null : assets.libraries !== undefined ? asBlob(assets.libraries) : await blob(at('libraries.txt'), "The pack's licence list")
+ const runtimeManifest = await (await fetched(fetchImpl, at('frame-assets/MANIFEST.json'), "The runtime's manifest")).json()
+ const files = {
+ launch: assets.launch ?? (await (await fetched(fetchImpl, at('scorm-launch.html'), "The launch page's template")).text()),
+ bridge: assets.bridge !== undefined ? asBlob(assets.bridge) : await blob(at('scorm.js'), 'The launch page\'s script'),
+ lz: assets.lz !== undefined ? asBlob(assets.lz) : await compressor(),
+ css: assets.css !== undefined ? asBlob(assets.css) : await blob(at('embed.css'), 'The stylesheet'),
+ player: await blobs(PLAYER_FILES, at, "The player's file"),
+ runtime: await blobs(runtimeFiles(runtimeManifest), (path) => at(`frame-assets/${path}`), "The runtime's file"),
+ pkg: file,
+ parts: partBlobs,
+ librariesText: parts.length === 0 ? null : assets.libraries !== undefined ? asBlob(assets.libraries) : await blob(at('libraries.txt'), "The pack's licence list")
+ }
+
+ // The whole package in memory once, for its hash: `crypto.subtle` takes no stream.
+ const build = await buildStamp(await sha256Hex(await file.arrayBuffer()), parts)
+ const { entries, xml } = scormEntries({ manifest, source: name, title, build, version, packVersion, parts, files })
+
+ report({ step: 'writing' })
+ const zip = new ZipWriter(new BlobWriter('application/zip'), { useWebWorkers: false })
+ await addScormEntries(zip, { entries, xml })
+ const out = await zip.close()
+ return { blob: out, name: `${stem}.scorm.zip`, title, version, libraries: parts.map((part) => part.folder), build, size: out.size }
}
- // The whole package in memory once, for its hash: `crypto.subtle` takes no stream.
- const build = await buildStamp(await sha256Hex(await file.arrayBuffer()), parts)
- const { entries, xml } = scormEntries({ manifest, source: name, title, build, version, packVersion, parts, files })
+ return {
+ name,
+ size: file.size,
+ title: planned,
+ mainLibrary: mainLibraryOf(manifest),
+ libraries: parts.map((part) => part.folder),
+ librariesSize: parts.reduce((sum, part) => sum + part.size, 0),
+ write
+ }
+}
- onProgress({ step: 'writing' })
- const zip = new ZipWriter(new BlobWriter('application/zip'), { useWebWorkers: false })
- await addScormEntries(zip, { entries, xml })
- const out = await zip.close()
- return { blob: out, name: `${name.replace(/\.[^.]+$/, '')}.scorm.zip`, title, version, libraries: parts.map((part) => part.folder), build, size: out.size }
+/**
+ * Builds the SCORM 1.2 zip of a package in a page, and returns it as a `Blob`: `planScormInPage`
+ * and the plan's `write` at once. Refuses what `buildScorm` refuses, with the same messages, and a
+ * part of the pack whose bytes do not match the index, since they came over the network.
+ * @param {PageScormOptions} options
+ * @returns {Promise}
+ */
+export async function buildScormInPage(options) {
+ return (await planScormInPage(options)).write({ title: options?.title })
}
diff --git a/packages/embed/lib/scorm-core.mjs b/packages/embed/lib/scorm-core.mjs
index e3a22ebe..13a856a6 100644
--- a/packages/embed/lib/scorm-core.mjs
+++ b/packages/embed/lib/scorm-core.mjs
@@ -158,15 +158,34 @@ export async function buildStamp(packageSha256, parts) {
}
/**
- * The package's title, as the LMS lists it: `h5p.json`'s, with the control characters XML refuses
- * read as spaces, since a title pasted in can carry one; or the file's name.
+ * The package's title, as the LMS lists it: the one chosen for the zip, by `--title` or on the
+ * page, else `h5p.json`'s, else the file's name; with the control characters XML refuses read as
+ * spaces, since a title pasted in can carry one. A chosen title that is empty, or only spaces,
+ * leaves the default.
* @param {unknown} manifest `h5p.json`, parsed
- * @param {string} fallback
+ * @param {string} fallback the file's name without its extension
+ * @param {unknown} [chosen] the title chosen for the zip
*/
-export function scormTitle(manifest, fallback) {
- const title = /** @type {{ title?: unknown } | null} */ (manifest)?.title
- const named = typeof title === 'string' ? title.replace(/[\x00-\x1f\x7f]+/g, ' ').trim() : ''
- return named || fallback
+export function scormTitle(manifest, fallback, chosen) {
+ /** @param {unknown} value */
+ const text = (value) => (typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f]+/g, ' ').trim() : '')
+ return text(chosen) || text(/** @type {{ title?: unknown } | null} */ (manifest)?.title) || fallback
+}
+
+/**
+ * The package's main library, as `h5p.json` names it, with the version its
+ * `preloadedDependencies` give it; `null` when it names none, and no version when the
+ * dependencies do not list it.
+ * @param {unknown} manifest `h5p.json`, parsed
+ * @returns {{ machineName: string, majorVersion?: number, minorVersion?: number } | null}
+ */
+export function mainLibraryOf(manifest) {
+ const machineName = /** @type {{ mainLibrary?: unknown } | null} */ (manifest)?.mainLibrary
+ if (typeof machineName !== 'string' || !machineName) return null
+ const listed = dependenciesIn(manifest).find((dependency) => dependency.machineName === machineName)
+ const majorVersion = Number(listed?.majorVersion)
+ const minorVersion = Number(listed?.minorVersion)
+ return listed && Number.isInteger(majorVersion) && Number.isInteger(minorVersion) ? { machineName, majorVersion, minorVersion } : { machineName }
}
/**
@@ -331,6 +350,19 @@ export function scormEntries({ manifest, source, title, build, version, packVers
return { entries, xml }
}
+/**
+ * Adds a file that is compressed already as a stored entry. Written into a stream, an entry gets a
+ * data descriptor, and a Java ZipInputStream refuses a stored entry that has one: SCORM Cloud
+ * refused exactly those (#92). Passed through with its size and CRC, it gets a complete local
+ * header instead, and is still streamed, not held.
+ * @param {import('@zip.js/zip.js').ZipWriter} zip
+ * @param {string} name
+ * @param {Blob} blob
+ */
+export async function addStored(zip, name, blob) {
+ await zip.add(name, new BlobReader(blob), { passThrough: true, compressionMethod: 0, uncompressedSize: blob.size, crc32: await crcOf(blob) })
+}
+
/**
* Writes the manifest and the entries into a zip.js writer, which the caller opens on a file or a
* `Blob` and closes.
@@ -346,13 +378,7 @@ export async function addScormEntries(zip, { entries, xml }) {
}
const { name, blob } = entry
// The package, the pack's parts and the fonts are compressed already, so they are stored.
- // Written into a stream, an entry gets a data descriptor, and a Java ZipInputStream refuses
- // a stored entry that has one: SCORM Cloud refused exactly those (#92). Passed through with
- // its size and CRC, it gets a complete local header instead, and is still streamed, not held.
- if (name.endsWith('.h5p') || name.endsWith('.woff2')) {
- await zip.add(name, new BlobReader(blob), { passThrough: true, compressionMethod: 0, uncompressedSize: blob.size, crc32: await crcOf(blob) })
- } else {
- await zip.add(name, new BlobReader(blob), { level: 6 })
- }
+ if (name.endsWith('.h5p') || name.endsWith('.woff2')) await addStored(zip, name, blob)
+ else await zip.add(name, new BlobReader(blob), { level: 6 })
}
}
diff --git a/packages/embed/lib/scorm.mjs b/packages/embed/lib/scorm.mjs
index 01256dde..51e24fbc 100644
--- a/packages/embed/lib/scorm.mjs
+++ b/packages/embed/lib/scorm.mjs
@@ -78,7 +78,8 @@ async function filesUnder(dir) {
* What `buildScorm` wrote, for a summary.
* @typedef {object} BuiltScorm
* @property {string} out the zip, as an absolute path
- * @property {string} title the package's title, as the LMS lists it: `h5p.json`'s, or the file's name
+ * @property {string} title the title the LMS lists the zip by: the one chosen, else `h5p.json`'s, else
+ * the file's name
* @property {string} version the player's version, as its `dist/VERSION` says
* @property {string[]} libraries the folders of the libraries the zip carries from the library
* pack, for a package that does not carry them itself; none for one that does
@@ -97,9 +98,11 @@ async function filesUnder(dir) {
* @param {string} options.h5p the package to wrap
* @param {string} options.out the zip to write
* @param {boolean} [options.force] replace a file already at `out`
+ * @param {string} [options.title] the title the LMS lists the zip by, in place of `h5p.json`'s;
+ * an empty one leaves that
* @returns {Promise}
*/
-export async function buildScorm({ h5p, out, force = false }) {
+export async function buildScorm({ h5p, out, force = false, title: chosen }) {
if (!h5p) throw new EmbedError('No package given.')
if (!out) throw new EmbedError('No output file given.')
const source = resolve(h5p)
@@ -116,7 +119,7 @@ export async function buildScorm({ h5p, out, force = false }) {
// What the package declares and carries, and what the pack adds, read before anything is written.
const { manifest, parts } = await readPackage(await openAsBlob(source), basename(h5p), pack)
- const title = scormTitle(manifest, basename(h5p, extname(h5p)))
+ const title = scormTitle(manifest, basename(h5p, extname(h5p)), chosen)
// The learner's saved place is kept against the libraries too, as the player keeps it against
// the revision: a zip written with others starts learners over, as a refreshed package does.
const build = await buildStamp(await sha256(source), parts)
diff --git a/packages/embed/site/scorm-page.css b/packages/embed/site/scorm-page.css
index c5db057a..bbe1b256 100644
--- a/packages/embed/site/scorm-page.css
+++ b/packages/embed/site/scorm-page.css
@@ -1,4 +1,4 @@
-/* The SCORM page: a column of text with one file input, as plain as the embed page. It comes
+/* The SCORM page: a column of text in three numbered steps, as plain as the embed page. It comes
after embed.css, which has the notice's look and no background of its own. */
body {
padding: 1.5rem 1rem 3rem;
@@ -38,6 +38,142 @@ input[type="file"] {
font: inherit;
}
+button {
+ padding: 0.45rem 1rem;
+ border: 1px solid #b8c0cc;
+ border-radius: 6px;
+ background: #f6f8fa;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+}
+
+button:hover:not(:disabled) {
+ background: #eef1f5;
+}
+
+button:disabled {
+ opacity: 0.55;
+ cursor: default;
+}
+
+/* A step: its number in a disc before its heading. A step the page cannot reach yet is hidden. */
+.step[hidden] {
+ display: none;
+}
+
+.step h2 {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.step-number {
+ display: inline-grid;
+ flex: none;
+ place-items: center;
+ width: 1.6rem;
+ height: 1.6rem;
+ border-radius: 50%;
+ background: #2f6df6;
+ color: #fff;
+ font-size: 0.85rem;
+}
+
+.step-hint {
+ color: #5b6370;
+}
+
+/* A file's row in the review: its name, size and a button to take it out; what its zip will hold,
+ or why none can be written; its title in the LMS; and, with several, its own zip. */
+.scorm-rows {
+ display: grid;
+ gap: 0.6rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.scorm-row {
+ padding: 0.7rem 0.85rem;
+ border: 1px solid #e2e6ec;
+ border-left: 3px solid #c9d0d9;
+ border-radius: 6px;
+}
+
+.scorm-row[data-state="built"] {
+ border-left-color: #1d7a42;
+}
+
+.scorm-row[data-state="refused"],
+.scorm-row[data-state="failed"] {
+ border-left-color: #b4232a;
+}
+
+.scorm-row[data-state="reading"],
+.scorm-row[data-state="building"] {
+ border-left-color: #2f6df6;
+}
+
+.scorm-row-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 0.25rem 0.75rem;
+}
+
+.scorm-row-name {
+ font-weight: 600;
+ overflow-wrap: anywhere;
+}
+
+.scorm-row-size {
+ color: #5b6370;
+ font-size: 0.9em;
+}
+
+.scorm-row-remove {
+ margin-left: auto;
+ padding: 0.2rem 0.65rem;
+ font-size: 0.9em;
+}
+
+.scorm-row-facts {
+ margin: 0.3rem 0 0;
+ color: #5b6370;
+}
+
+.scorm-row[data-state="refused"] .scorm-row-facts,
+.scorm-row[data-state="failed"] .scorm-row-facts {
+ color: #b4232a;
+}
+
+.scorm-row-title {
+ display: grid;
+ gap: 0.25rem;
+ margin-top: 0.5rem;
+ font-size: 0.9em;
+ font-weight: 600;
+}
+
+.scorm-row-title input {
+ padding: 0.4rem 0.6rem;
+ border: 1px solid #b8c0cc;
+ border-radius: 6px;
+ font: inherit;
+ font-weight: 400;
+}
+
+.scorm-row-download {
+ display: inline-block;
+ margin-top: 0.5rem;
+ font-weight: 600;
+}
+
+.scorm-row-download[hidden] {
+ display: none;
+}
+
/* The line that says where the build is, then what it made, with the link to it. */
.status {
display: flex;
diff --git a/packages/embed/site/scorm-page.js b/packages/embed/site/scorm-page.js
index 66cae235..1e8a81ff 100644
--- a/packages/embed/site/scorm-page.js
+++ b/packages/embed/site/scorm-page.js
@@ -1,54 +1,127 @@
/*! @missing-elements/h5p-embed. MIT. */
/**
- * The SCORM page: a `.h5p` picked or dropped becomes a SCORM 1.2 zip, built in the browser by
- * `buildScormInPage` from this site's own copies of the player, the runtime and the library
- * pack, with nothing uploaded anywhere. `startScormPage()` runs it; the site's `scorm-main.js`
- * calls it with what `h5p-embed` wrote into `config.js`, and the demo's `/demo/scorm.html` with
- * its own copies. The page holds `#file`, the input; `#status`, a line that says where the build
- * is and then what it made; `#download`, the link to the zip, hidden until there is one; and
- * `#notice`, for a refusal. A page with a `#state` badge, as the demo's pages have, gets the
- * state's name in it, `idle`, `building`, `ready` or `error`, and as `data-state` on it and on
- * the `.status` strip around `#status`, which its stylesheet colours.
+ * The SCORM page: `.h5p` files picked or dropped become SCORM 1.2 zips, built in the browser by
+ * `planScormInPage` and its `write` from this site's own copies of the player, the runtime and
+ * the library pack, with nothing uploaded anywhere. `startScormPage()` runs it; the site's
+ * `scorm-main.js` calls it with what `h5p-embed` wrote into `config.js`, and the demo's
+ * `/demo/scorm.html` with its own copies.
+ *
+ * The page holds `#file`, the input; `#status`, a line that says where the build is and then what
+ * it made; `#download`, the link to the zip, hidden until there is one; and `#notice`, for a
+ * refusal. A page with a `#state` badge, as the demo's pages have, gets the state's name in it,
+ * `idle`, `building`, `ready` or `error`, and as `data-state` on it and on the `.status` strip
+ * around `#status`, which its stylesheet colours.
+ *
+ * A page that also holds `#files`, a list, and `#build`, a button, as both pages here do, works in
+ * steps. Each file chosen gets a row in the list, which says what its zip will hold, or why none
+ * can be written, and takes the title the LMS lists it by; nothing is written until `#build` is
+ * pressed, which writes the rows one after another; `#download` is then the zip, or, for several,
+ * one zip that holds them all, while each row links its own. The closest `[data-step]` around
+ * each of the two is shown once it can be reached. A page with neither builds the first file it
+ * is given at once, as the page did up to embed 1.5.
*/
-import { buildScormInPage } from '../lib/scorm-browser.mjs'
+import { BlobWriter, ZipWriter } from '@zip.js/zip.js'
+import { addStored } from '../lib/scorm-core.mjs'
+import { buildScormInPage, planScormInPage } from '../lib/scorm-browser.mjs'
import { EmbedError } from '../lib/shared.mjs'
/**
* What `buildScormInPage` is given beside the file: where the player's files and the pack are,
* and the versions for the zip's notice.
- * @typedef {Omit} ScormPageOptions
+ * @typedef {Omit} ScormPageOptions
*/
+/** What a page in steps calls the zip that holds the others. */
+const TOGETHER = 'scorm-packages.zip'
+
/** @param {number} bytes */
const megabytes = (bytes) => `${(bytes / 1_000_000).toFixed(1)} MB`
+/**
+ * A package's size, in kilobytes below a megabyte, where a tenth of one says nothing.
+ * @param {number} bytes
+ */
+const sized = (bytes) => (bytes < 1_000_000 ? `${Math.max(1, Math.round(bytes / 1000))} kB` : megabytes(bytes))
+
/** @param {number} count */
const libraries = (count) => `${count} ${count === 1 ? 'library' : 'libraries'}`
+/** @param {unknown} error */
+const reason = (error) => (error instanceof EmbedError ? error.message : `The zip could not be written: ${error instanceof Error ? error.message : error}`)
+
/**
- * @param {ScormPageOptions} [options]
+ * What a zip is, said in one line.
+ * @param {import('../lib/scorm-browser.mjs').PageScorm} zip
*/
-export function startScormPage(options = {}) {
+const made = (zip) => {
+ const carried = zip.libraries.length ? `, with ${libraries(zip.libraries.length)} from the pack` : ''
+ return `“${zip.title}” as a SCORM 1.2 package${carried}. Build ${zip.build}.`
+}
+
+/**
+ * What a package's zip will hold, as its row says it.
+ * @param {import('../lib/scorm-browser.mjs').PlannedScorm} plan
+ */
+const holds = ({ mainLibrary: main, libraries: parts, librariesSize }) => {
+ const named = !main ? 'no main library named' : main.majorVersion === undefined ? main.machineName : `${main.machineName} ${main.majorVersion}.${main.minorVersion}`
+ return `${named} · ${parts.length === 0 ? 'carries its libraries' : `${libraries(parts.length)} from the pack, ${sized(librariesSize)}`}`
+}
+
+/**
+ * @template {keyof HTMLElementTagNameMap} K
+ * @param {K} tag
+ * @param {string} className
+ * @param {string} [text]
+ * @returns {HTMLElementTagNameMap[K]}
+ */
+const create = (tag, className, text = '') => {
+ const element = document.createElement(tag)
+ element.className = className
+ element.textContent = text
+ return element
+}
+
+/** The elements every SCORM page has, and the two ways of changing them. */
+function common() {
const input = /** @type {HTMLInputElement} */ (document.querySelector('#file'))
const status = /** @type {HTMLElement} */ (document.querySelector('#status'))
const link = /** @type {HTMLAnchorElement} */ (document.querySelector('#download'))
const notice = /** @type {HTMLElement} */ (document.querySelector('#notice'))
const badge = /** @type {HTMLElement | null} */ (document.querySelector('#state'))
const strip = /** @type {HTMLElement | null} */ (status.closest('.status'))
- /** @type {string | null} the last zip's address, let go of when the next one replaces it */
- let last = null
- let busy = false
-
+ // Text is written only when it changes: rewritten as it is, a live region may be read out again.
/** @param {string} text */
const say = (text) => {
- status.textContent = text
+ if (status.textContent !== text) status.textContent = text
}
-
/** @param {'idle' | 'building' | 'ready' | 'error'} state */
const mark = (state) => {
for (const element of [badge, strip]) if (element) element.dataset.state = state
- if (badge) badge.textContent = state
+ if (badge && badge.textContent !== state) badge.textContent = state
}
+ return { input, link, notice, say, mark }
+}
+
+/**
+ * @param {ScormPageOptions} [options]
+ */
+export function startScormPage(options = {}) {
+ const list = document.querySelector('#files')
+ const button = document.querySelector('#build')
+ if (list instanceof HTMLElement && button instanceof HTMLButtonElement) inSteps(options, list, button)
+ else atOnce(options)
+}
+
+/**
+ * The page as it was up to embed 1.5, for a page without `#files` and `#build`: the first file
+ * given is built at once, and a refusal goes to `#notice`.
+ * @param {ScormPageOptions} options
+ */
+function atOnce(options) {
+ const { input, link, notice, say, mark } = common()
+ /** @type {string | null} the last zip's address, let go of when the next one replaces it */
+ let last = null
+ let busy = false
/** @param {File} file */
async function make(file) {
@@ -75,12 +148,11 @@ export function startScormPage(options = {}) {
link.download = zip.name
link.textContent = `Download ${zip.name} (${megabytes(zip.size)})`
link.hidden = false
- const carried = zip.libraries.length ? `, with ${libraries(zip.libraries.length)} from the pack` : ''
- say(`“${zip.title}” as a SCORM 1.2 package${carried}. Build ${zip.build}.`)
+ say(made(zip))
mark('ready')
} catch (error) {
say('')
- notice.textContent = error instanceof EmbedError ? error.message : `The zip could not be written: ${error instanceof Error ? error.message : error}`
+ notice.textContent = reason(error)
notice.hidden = false
mark('error')
} finally {
@@ -103,3 +175,280 @@ export function startScormPage(options = {}) {
if (file) void make(file)
})
}
+
+/**
+ * The page in steps: choose, review, download.
+ * @param {ScormPageOptions} options
+ * @param {HTMLElement} list `#files`
+ * @param {HTMLButtonElement} button `#build`
+ */
+function inSteps(options, list, button) {
+ const { input, link, notice, say, mark } = common()
+ const reviewStep = /** @type {HTMLElement | null} */ (list.closest('[data-step]'))
+ const downloadStep = /** @type {HTMLElement | null} */ (button.closest('[data-step]'))
+ /**
+ * A file chosen on a page in steps, and what became of it.
+ * @typedef {object} Row
+ * @property {File} file
+ * @property {HTMLLIElement} element its row in `#files`
+ * @property {HTMLElement} facts what the zip will hold, or why it cannot be written: a live region
+ * from the start, so that what the reading found is announced
+ * @property {HTMLButtonElement} remove
+ * @property {HTMLInputElement | null} field the title, once the file is read
+ * @property {HTMLAnchorElement} download its own zip, shown when the page has several
+ * @property {import('../lib/scorm-browser.mjs').PlannedScorm | null} plan
+ * @property {string | null} error why it cannot be built, or why its last build failed
+ * @property {(import('../lib/scorm-browser.mjs').PageScorm & { url: string }) | null} zip
+ */
+ /** @type {Row[]} */
+ const rows = []
+ let busy = false
+ /** @type {Row | null} the row being written */
+ let current = null
+ /** Files are read one after another, in the order they came. */
+ let reading = Promise.resolve()
+ /** @type {{ key: string, url: string, size: number } | null} the zip of zips, and which zips it holds */
+ let together = null
+ /** Which offer of `#download` is the latest, so that a slower one that was overtaken lets go. */
+ let offers = 0
+
+ /** @param {Row} row */
+ const forget = (row) => {
+ if (row.zip) URL.revokeObjectURL(row.zip.url)
+ row.zip = null
+ }
+
+ /**
+ * @param {Row} row
+ * @param {boolean} several whether the page has more than one zip to build, so that each row
+ * links its own
+ */
+ const render = (row, several) => {
+ row.element.dataset.state = row === current ? 'building' : row.zip ? 'built' : row.plan ? (row.error ? 'failed' : 'planned') : row.error ? 'refused' : 'reading'
+ // Only when it changes, as with `say`: every row is rendered again on each change to any.
+ const facts = row.error ?? (row.plan ? holds(row.plan) : 'Reading…')
+ if (row.facts.textContent !== facts) row.facts.textContent = facts
+ row.remove.disabled = busy
+ if (row.field) row.field.disabled = busy
+ if (row.zip && several) {
+ row.download.href = row.zip.url
+ row.download.download = row.zip.name
+ row.download.textContent = `Download ${row.zip.name} (${megabytes(row.zip.size)})`
+ }
+ row.download.hidden = !(row.zip && several)
+ }
+
+ /** `#download`: the one zip, or the zip of zips; hidden while there is neither, or while writing. */
+ const offer = async () => {
+ const turn = ++offers
+ const buildable = rows.filter((entry) => entry.plan)
+ const built = buildable.flatMap((entry) => (entry.zip ? [entry.zip] : []))
+ // Which zips the zip of zips would hold now; none while writing, or with fewer than two.
+ const key = !busy && buildable.length > 1 && built.length > 1 ? built.map((zip) => zip.url).join(' ') : null
+ if (together && together.key !== key) {
+ URL.revokeObjectURL(together.url)
+ together = null
+ }
+ link.hidden = true
+ link.removeAttribute('href')
+ if (busy || built.length === 0) return
+ if (buildable.length === 1) {
+ const [zip] = built
+ link.href = zip.url
+ link.download = zip.name
+ link.textContent = `Download ${zip.name} (${megabytes(zip.size)})`
+ link.hidden = false
+ return
+ }
+ // With several, each row links its own, and this is all of them in one.
+ if (key === null) return
+ if (!together) {
+ let blob
+ try {
+ blob = await bundle(built)
+ } catch (error) {
+ if (turn === offers) {
+ notice.textContent = `The zip of all of them could not be written: ${error instanceof Error ? error.message : error}`
+ notice.hidden = false
+ }
+ return
+ }
+ if (turn !== offers) return
+ together = { key, url: URL.createObjectURL(blob), size: blob.size }
+ }
+ link.href = together.url
+ link.download = TOGETHER
+ link.textContent = `Download all ${built.length} as one zip (${megabytes(together.size)})`
+ link.hidden = false
+ }
+
+ /** Everything from the state: the rows, the steps, the button, the strip and its link. */
+ const refresh = () => {
+ const buildable = rows.filter((entry) => entry.plan)
+ const pending = buildable.filter((entry) => !entry.zip)
+ const built = buildable.filter((entry) => entry.zip)
+ const several = buildable.length > 1
+ for (const entry of rows) render(entry, several)
+ if (reviewStep) reviewStep.hidden = rows.length === 0
+ if (downloadStep) downloadStep.hidden = buildable.length === 0
+ const count = pending.length || buildable.length
+ button.textContent = several ? `Build ${count} SCORM ${count === 1 ? 'package' : 'packages'}` : 'Build the SCORM package'
+ button.disabled = busy || pending.length === 0 || rows.some((entry) => !entry.plan && !entry.error)
+ input.disabled = busy
+ if (!busy) {
+ const failed = pending.filter((entry) => entry.error).length
+ const waiting = pending.length - failed
+ const unwritten = failed === 1 ? 'one could not be written, as its row says' : `${failed} could not be written, as their rows say`
+ if (built.length === 0) {
+ mark(failed ? 'error' : 'idle')
+ say(failed ? `${several ? unwritten.charAt(0).toUpperCase() + unwritten.slice(1) : 'The zip could not be written, as its row says'}.` : '')
+ } else if (!several) {
+ mark('ready')
+ say(made(/** @type {NonNullable} */ (built[0].zip)))
+ } else {
+ const notes = [failed ? unwritten : '', waiting ? `${waiting} more to build` : ''].filter(Boolean)
+ const counted = built.length === 1 ? 'One SCORM 1.2 package, with its link above' : `${built.length} SCORM 1.2 packages, each with its link above`
+ mark('ready')
+ say(`${counted}${notes.map((note) => `; ${note}`).join('')}.`)
+ }
+ }
+ return offer()
+ }
+
+ /** @param {File} file */
+ const row = (file) => {
+ const element = create('li', 'scorm-row')
+ const head = create('div', 'scorm-row-head')
+ const remove = create('button', 'scorm-row-remove', 'Remove')
+ remove.type = 'button'
+ remove.setAttribute('aria-label', `Remove ${file.name}`)
+ head.append(create('span', 'scorm-row-name', file.name), create('span', 'scorm-row-size', sized(file.size)), remove)
+ const facts = create('p', 'scorm-row-facts', 'Reading…')
+ facts.setAttribute('role', 'status')
+ const download = create('a', 'scorm-row-download')
+ download.hidden = true
+ element.append(head, facts, download)
+ /** @type {Row} */
+ const entry = { file, element, facts, remove, field: null, download, plan: null, error: null, zip: null }
+ remove.addEventListener('click', () => {
+ const at = rows.indexOf(entry)
+ if (busy || at < 0) return
+ rows.splice(at, 1)
+ forget(entry)
+ element.remove()
+ // Where the row was: the next one's button, the one before it, or the input.
+ const next = rows[at] ?? rows[at - 1]
+ ;(next ? next.remove : input).focus()
+ void refresh()
+ })
+ return entry
+ }
+
+ /** @param {Row} entry */
+ const read = async (entry) => {
+ if (!rows.includes(entry)) return
+ try {
+ const plan = await planScormInPage({ ...options, file: entry.file })
+ entry.plan = plan
+ const label = create('label', 'scorm-row-title', 'Title in the LMS')
+ const field = document.createElement('input')
+ field.type = 'text'
+ field.value = plan.title
+ // Emptied, the field shows what the zip is then called.
+ field.placeholder = plan.title
+ field.setAttribute('aria-label', `Title in the LMS for ${entry.file.name}`)
+ field.addEventListener('input', () => {
+ forget(entry)
+ void refresh()
+ })
+ label.append(field)
+ entry.facts.after(label)
+ entry.field = field
+ } catch (error) {
+ entry.error = reason(error)
+ }
+ if (rows.includes(entry)) void refresh()
+ }
+
+ /** @param {File[]} files */
+ const add = (files) => {
+ if (busy) return
+ notice.hidden = true
+ for (const file of files) {
+ // The same file twice is one row.
+ if (rows.some(({ file: listed }) => listed.name === file.name && listed.size === file.size && listed.lastModified === file.lastModified)) continue
+ const entry = row(file)
+ rows.push(entry)
+ list.append(entry.element)
+ reading = reading.then(() => read(entry))
+ }
+ void refresh()
+ }
+
+ const build = async () => {
+ const queue = rows.filter((entry) => entry.plan && !entry.zip)
+ if (busy || queue.length === 0) return
+ busy = true
+ notice.hidden = true
+ mark('building')
+ for (const [at, entry] of queue.entries()) {
+ current = entry
+ entry.error = null
+ void refresh()
+ /** @param {string} text */
+ const step = (text) => say(queue.length > 1 ? `${entry.file.name}, ${at + 1} of ${queue.length}: ${text}` : text.charAt(0).toUpperCase() + text.slice(1))
+ try {
+ const zip = await /** @type {import('../lib/scorm-browser.mjs').PlannedScorm} */ (entry.plan).write({
+ title: entry.field?.value,
+ onProgress: ({ step: where, libraries: count }) => {
+ if (where === 'libraries') step(count ? `fetching ${libraries(count)} from the pack…` : 'fetching the player…')
+ else if (where === 'writing') step('writing the zip…')
+ }
+ })
+ entry.zip = { ...zip, url: URL.createObjectURL(zip.blob) }
+ } catch (error) {
+ entry.error = reason(error)
+ }
+ }
+ current = null
+ busy = false
+ await refresh()
+ // On to what was made, rather than left on a button that has nothing more to do.
+ const target = !link.hidden ? link : rows.find((entry) => !entry.download.hidden)?.download
+ target?.focus()
+ }
+
+ input.addEventListener('change', () => {
+ const files = [...(input.files ?? [])]
+ // So that the same file, chosen again after a change to it, counts as a change.
+ input.value = ''
+ if (files.length) add(files)
+ })
+ // Files dropped anywhere on the page.
+ document.addEventListener('dragover', (event) => event.preventDefault())
+ document.addEventListener('drop', (event) => {
+ event.preventDefault()
+ const files = [...(event.dataTransfer?.files ?? [])]
+ if (files.length) add(files)
+ })
+ button.addEventListener('click', () => void build())
+ void refresh()
+}
+
+/**
+ * The zips in one, each stored as it is, since each is compressed already; a name taken twice gets
+ * a number.
+ * @param {Array<{ name: string, blob: Blob }>} zips
+ */
+async function bundle(zips) {
+ const zip = new ZipWriter(new BlobWriter('application/zip'), { useWebWorkers: false })
+ const taken = new Set()
+ for (const { name, blob } of zips) {
+ const stem = name.replace(/(\.scorm)?\.zip$/, '')
+ let unique = name
+ for (let n = 2; taken.has(unique); n++) unique = `${stem} (${n})${name.slice(stem.length)}`
+ taken.add(unique)
+ await addStored(zip, unique, blob)
+ }
+ return zip.close()
+}
diff --git a/packages/embed/site/scorm.html b/packages/embed/site/scorm.html
index 21d46b0b..d446b5ab 100644
--- a/packages/embed/site/scorm.html
+++ b/packages/embed/site/scorm.html
@@ -14,19 +14,38 @@
H5P to SCORM
- Choose a .h5p file, or drop it on this page, and download it as a SCORM 1.2
- package for your LMS. Nothing is uploaded: the package is built here, in your browser, with
- the player this site serves.
+ Choose .h5p files, or drop them on this page, check what each zip will hold,
+ and download them as SCORM 1.2 packages for your LMS. Nothing is uploaded: the packages are
+ built here, in your browser, with the player this site serves.
Or drop them anywhere on this page. Each becomes a zip of its own.
+
+
+
+
2 Review
+
+ What each zip will hold, read from the package before anything is built. The title is
+ what the LMS lists the package by; change it here if you like.
+
diff --git a/packages/embed/tests/package-types.ts b/packages/embed/tests/package-types.ts
index 5134f8a8..12f7718a 100644
--- a/packages/embed/tests/package-types.ts
+++ b/packages/embed/tests/package-types.ts
@@ -6,7 +6,7 @@
import { EmbedError, buildSite, type BuiltSite } from '@missing-elements/h5p-embed'
import { startEmbed } from '@missing-elements/h5p-embed/embed.js'
import { buildScorm, type BuiltScorm } from '@missing-elements/h5p-embed/scorm'
-import { buildScormInPage, type PageScorm } from '@missing-elements/h5p-embed/scorm/browser'
+import { buildScormInPage, planScormInPage, type PageScorm, type PlannedScorm } from '@missing-elements/h5p-embed/scorm/browser'
import { startScormPage } from '@missing-elements/h5p-embed/scorm-page.js'
import { pack } from '@missing-elements/h5p-libraries'
import { runtime } from '@missing-elements/h5p-runtime'
@@ -24,7 +24,7 @@ export async function asACallerWould(): Promise {
await buildSite({ folder: 'public/player' })
// One package as a SCORM zip, for an LMS.
- const zip: BuiltScorm = await buildScorm({ h5p: 'course.h5p', out: 'course.scorm.zip', force: true })
+ const zip: BuiltScorm = await buildScorm({ h5p: 'course.h5p', out: 'course.scorm.zip', force: true, title: 'Week 3' })
const build: string = zip.build
const fromPack: string[] = zip.libraries
// @ts-expect-error the package is named `h5p`
@@ -33,10 +33,16 @@ export async function asACallerWould(): Promise {
// The same zip built in a page, from a picked file, with the pack as its package exports it.
const inPage: PageScorm = await buildScormInPage({ file: new Blob([]), name: 'course.h5p', base: 'https://player.example/', pack, version: '1.4.0', onProgress: ({ step }) => step })
const blob: Blob = inPage.blob
+ // Read first, so that a page can say what the zip will hold, and written after, under a title.
+ const plan: PlannedScorm = await planScormInPage({ file: new Blob([]), name: 'course.h5p', pack })
+ const main: string | undefined = plan.mainLibrary?.machineName
+ const retitled: PageScorm = await plan.write({ title: 'Week 3', onProgress: ({ step }) => step })
+ // @ts-expect-error a title is text
+ await plan.write({ title: 3 })
startScormPage({ pack, version: '1.4.0', packVersion: '1.0.1' })
// @ts-expect-error the package is a `file`, not a path
await buildScormInPage({ h5p: 'course.h5p' })
- void [hosts, build, fromPack, blob, parseOrigin, new EmbedError('refused') instanceof Error]
+ void [hosts, build, fromPack, blob, main, retitled, parseOrigin, new EmbedError('refused') instanceof Error]
return site.csp
}
diff --git a/packages/embed/tests/scorm-browser.test.ts b/packages/embed/tests/scorm-browser.test.ts
index c701282e..54829855 100644
--- a/packages/embed/tests/scorm-browser.test.ts
+++ b/packages/embed/tests/scorm-browser.test.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { buildSite } from '../lib/build.mjs'
-import { buildScormInPage, type ScormProgress } from '../lib/scorm-browser.mjs'
+import { buildScormInPage, planScormInPage, type ScormProgress } from '../lib/scorm-browser.mjs'
import { buildScorm } from '../lib/scorm.mjs'
import { EmbedError } from '../lib/shared.mjs'
import { host, type Host } from './helpers/host.js'
@@ -91,6 +91,55 @@ describe('built in a page', () => {
expect(steps).toEqual([{ step: 'reading' }, { step: 'libraries', libraries: command.libraries.length }, { step: 'writing' }])
})
+ it('says what a zip will hold before it is written, and writes it under any title as often as asked', async () => {
+ const steps: ScormProgress[] = []
+ const plan = await planScormInPage({ file: await picked(formulas, 'formulas.h5p'), ...onSite(site), onProgress: (progress) => steps.push(progress) })
+ const command = await buildScorm({ h5p: formulas, out: join(dir, 'formulas.plan.zip') })
+ const index = JSON.parse(await readFile(join(dir, 'site', 'libraries', 'index.json'), 'utf8')) as { libraries: Array<{ folder: string; size: number }> }
+ const sizes = new Map(index.libraries.map((entry) => [entry.folder, entry.size]))
+ expect(plan).toMatchObject({ name: 'formulas.h5p', size: (await readFile(formulas)).length, title: command.title, libraries: command.libraries })
+ expect(plan.mainLibrary).toEqual({ machineName: 'H5P.QuestionSet', majorVersion: 1, minorVersion: expect.any(Number) })
+ expect(plan.librariesSize).toBe(command.libraries.reduce((sum, folder) => sum + (sizes.get(folder) ?? Number.NaN), 0))
+ // Read, and nothing fetched or written yet.
+ expect(steps).toEqual([{ step: 'reading' }])
+
+ const carries = await planScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site) })
+ expect(carries).toMatchObject({ libraries: [], librariesSize: 0, mainLibrary: { machineName: 'H5P.QuestionSet' } })
+
+ // Written twice, under two titles: the same zip but for the title, kept against the same build.
+ const first = await plan.write()
+ const second = await plan.write({ title: ' A title\nof its own ' })
+ expect(first).toMatchObject({ title: command.title, build: command.build, libraries: command.libraries })
+ expect(second).toMatchObject({ title: 'A title of its own', build: command.build })
+ expect(steps).toEqual([{ step: 'reading' }, ...Array(2).fill([{ step: 'libraries', libraries: command.libraries.length }, { step: 'writing' }]).flat()])
+ const firstOut = join(dir, 'formulas.first.zip')
+ const secondOut = join(dir, 'formulas.second.zip')
+ await writeFile(firstOut, new Uint8Array(await first.blob.arrayBuffer()))
+ await writeFile(secondOut, new Uint8Array(await second.blob.arrayBuffer()))
+ const a = await entriesOf(firstOut)
+ const b = await entriesOf(secondOut)
+ expect(b.names).toEqual(a.names)
+ for (const name of a.names) {
+ const same = Buffer.from(await a.bytes(name)).equals(Buffer.from(await b.bytes(name)))
+ expect(same, name).toBe(name !== 'imsmanifest.xml' && name !== 'index.html')
+ }
+ expect((await b.text('imsmanifest.xml')).match(/A title of its own<\/title>/g)).toHaveLength(2)
+ expect(await b.text('index.html')).toContain('A title of its own')
+ await a.close()
+ await b.close()
+ })
+
+ it("writes the command's zip under the command's title, and keeps the package's for a title of spaces", async () => {
+ const titled = await buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site), title: 'Week 3: the quiz' })
+ const out = join(dir, 'quiz.titled.page.zip')
+ await writeFile(out, new Uint8Array(await titled.blob.arrayBuffer()))
+ const command = await buildScorm({ h5p: quiz, out: join(dir, 'quiz.titled.cli.zip'), title: 'Week 3: the quiz' })
+ expect(titled).toMatchObject({ title: 'Week 3: the quiz', build: command.build })
+ expect(command.title).toBe('Week 3: the quiz')
+ await expectSameZip(out, command.out)
+ await expect(buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site), title: ' \t ' })).resolves.toMatchObject({ title: 'Do you know what just happened?' })
+ })
+
it("takes the pack as its package exports it, with the same result", async () => {
const index = JSON.parse(await readFile(join(dir, 'site', 'libraries', 'index.json'), 'utf8')) as { libraries: Array<{ folder: string }> }
const pack = { libraries: index.libraries.map((entry) => ({ ...entry, url: `${site.origin}/libraries/${entry.folder}.h5p` })) }
diff --git a/packages/embed/tests/scorm-page.test.ts b/packages/embed/tests/scorm-page.test.ts
index a5308467..7fb746d8 100644
--- a/packages/embed/tests/scorm-page.test.ts
+++ b/packages/embed/tests/scorm-page.test.ts
@@ -1,7 +1,7 @@
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
-import { chromium, type Browser } from 'playwright'
+import { chromium, type Browser, type Download, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { buildSite } from '../lib/build.mjs'
import { buildScorm } from '../lib/scorm.mjs'
@@ -9,20 +9,48 @@ import { host, type Host } from './helpers/host.js'
import { changedQuiz, entriesOf, formulas, quiz } from './helpers/zip.js'
/**
- * The SCORM page of a written site, driven in Chromium as a teacher uses it: a file chosen, the
- * zip offered and downloaded, and a refusal shown. What the zip holds is `scorm-browser.test.ts`'s
- * to check against the command's; here it is the page's own script, bundled as the site carries
- * it, and the download that reaches the disk.
+ * The SCORM page of a written site, driven in Chromium as a teacher uses it: files chosen or
+ * dropped, each read into a row of the review, a title changed, the zips built and downloaded one
+ * by one and all in one, and a refusal shown beside the files that build. What a zip holds is
+ * `scorm-browser.test.ts`'s to check against the command's; here it is the page's own script,
+ * bundled as the site carries it, and the downloads that reach the disk. A page with only the
+ * elements a page had up to embed 1.5 still builds a file the moment it is chosen.
*/
+/** A host's page as the README described one up to embed 1.5: the input, the line, the link and the notice. */
+const LEGACY = `
+
+
+
+ A page of a host's own
+
+
+
+
+