diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 8b50ccc65..fbb40c77b 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -15,7 +15,7 @@ env:
# renovate: datasource=npm depName=npm
NPM_VERSION: "11"
# renovate: datasource=npm depName=@microbit-foundation/python-editor-v3-microbit registryUrl=https://npm.pkg.github.com
- THEME_VERSION: 0.4.1
+ THEME_VERSION: 0.5.0
jobs:
stages:
diff --git a/AGENTS.md b/AGENTS.md
index a4ad74db9..976f481c4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,8 +5,10 @@
This app uses react-aria-components + Panda CSS via `@microbit/ui`.
Read `../ui/docs/hints.md` before styling/theming/UI work.
The private theme package is the sibling repo
-`../python-editor-v3-microbit` (consumed via a manual `node_modules`
-symlink locally — re-create it after `npm install`).
+`../python-editor-v3-microbit`. Link it with `npm run dev:link-theme`, which
+builds it and symlinks it into `node_modules`; re-run after `npm install`.
+Home page artwork (banner, help cards) lives there and is resolved per file by
+`theme-package/images/*` imports, falling back to `src/deployment/default`.
`@microbit/ui` is consumed as the **published package**, pinned in
`package.json`. To develop against a local `../ui` checkout instead — what you
diff --git a/docs/analytics-events.md b/docs/analytics-events.md
index 0e0eae1f1..ebf8f2f96 100644
--- a/docs/analytics-events.md
+++ b/docs/analytics-events.md
@@ -10,13 +10,18 @@ at the end maps the previous UA-shaped events to their replacements.
Set once on app boot. Auto-attach to every subsequent event for the same user,
available as user-scoped breakdowns in GA4.
-| Name | Values | Set when | Notes |
-| ------------------ | ------------ | -------- | -------------------------------------------------------------- |
-| `webusb_available` | `yes` / `no` | App boot | From `"usb" in navigator`. Same name and values as ml-trainer. |
+| Name | Values | Set when | Notes |
+| ------------------ | -------------------------------------------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `webusb_available` | `yes` / `no` | App boot | From `"usb" in navigator`. Same name and values as ml-trainer. |
+| `project_storage` | `database` / `session_no_indexeddb` / `session_open_failed` / `host` | App boot, once the projects database has opened or failed to | Where the tab keeps its project. `database` is IndexedDB. The two `session_` values are the session-storage fallback: the browser has no IndexedDB, or it has but the database would not open. `host` is iframe controller mode, where the embedding page keeps the project. |
Unlike ml-trainer there is no `webbluetooth_available`: the editor doesn't use
Bluetooth.
+`project_storage` is there to show how many sessions really run without the
+projects database, and why, which decides whether the session-storage fallback
+is worth keeping.
+
## Device events
Same event family and params as ml-trainer so a cross-product device dashboard
@@ -108,26 +113,81 @@ No `destination` param: the editor only downloads. ml-trainer's
### `project_import`
User brought files in. Fires once per drop / picker selection, before the
-files are parsed, so it counts attempts.
-
-| Param | Values |
-| -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
-| `source` | `drop` / `file_picker` (same values as ml-trainer) |
-| `format` | `hex` (replaces the project) / `py` (Python file added to the project) / `other` (any other single file) / `multiple` (more than one file) |
-
-### `project_reset`
+files are parsed, so it counts attempts. A hex always becomes a new project.
+Other files join the open project from the editor and become a new project
+from the home and projects pages.
-User chose Reset project, replacing everything with the starter program. Fires
-when the menu action is chosen, before the confirm dialog. No params.
+| Param | Values |
+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `source` | `drop` / `file_picker` (same values as ml-trainer) |
+| `format` | `hex` / `py` (a single Python file) / `other` (any other single file) / `multiple` (more than one file) |
+| `surface` | `editor` (the Files tab or a drop on the editor) / `home` (the projects row's Import button or a drop on the home page) / `projects` (a drop on the projects page) |
### `project_rename`
User set the project name, from the header or the name-your-project prompt on
-save. No params.
+save, with no params; or from a project card or the projects toolbar, with
+`surface`.
+
+| Param | Values |
+| --------- | --------------------------------------------------------- |
+| `surface` | `home` / `projects` (absent when renamed from the editor) |
+
+## Project management events
+
+The home and projects pages, aligned with ml-trainer's events of the same
+names so one set of custom definitions serves both.
+
+### `project_create`
+
+User named and created a new project from the home page.
+
+| Param | Values |
+| --------- | ------ |
+| `surface` | `home` |
+
+### `project_open`
+
+User opened a project from a card or its menu.
+
+| Param | Values |
+| --------- | ------------------- |
+| `surface` | `home` / `projects` |
+
+### `project_duplicate`
+
+| Param | Values |
+| --------- | ------------------- |
+| `surface` | `home` / `projects` |
+
+### `project_delete`
+
+Fires once for a single delete and once for a multi-select delete, after the
+user confirms.
+
+| Param | Values |
+| --------- | --------------------------------------------------------- |
+| `count` | int (1 for a card's menu; the selection's size otherwise) |
+| `surface` | `home` / `projects` |
+
+### `project_search`
+
+Projects page only. Fires once per intentional search, 400ms after the last
+keystroke, not per keypress. No params.
+
+### `project_sort`
+
+Projects page only. Fires when the user changes the sort field or direction.
+
+| Param | Values |
+| ----------- | ---------------------------------------------- |
+| `field` | `name` / `timestamp` (last modified or opened) |
+| `direction` | `asc` / `desc` |
### `idea_open`
-User opened an idea into the editor.
+User opened an idea as a new project, from the home page idea dialog or the
+editor's Ideas tab.
| Param | Values |
| ----- | -------------------------- |
@@ -166,6 +226,11 @@ Fires once per search session: when results first appear after typing, not
per keystroke (300ms debounce) and not again until results are cleared. No
params. Search terms are deliberately not sent.
+### `ideas_notice_open`
+
+User opened the dialog, from the notice in the Ideas tab, that explains that
+ideas are moving to the home page. No params.
+
## Code snippet events
Moving code from the documentation into the editor. Drag and copy are the
@@ -234,6 +299,7 @@ reading old dashboards.
| Old name | Status |
| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
+| `project_reset` | Removed with the Reset project action (September 2026); replacing a program means importing from the home page. |
| `boot` → `WebUSB-available` | Dropped. Replaced by the `webusb_available` user property. `session_start` auto-fires. |
| `connect` | Replaced by `device_step` (`task: connect`) and `device_success` / `device_failure` / `device_exit`. |
| `disconnect` | Renamed `device_disconnect`; widened with `reason` to also capture unexpected drops. |
diff --git a/docs/tech-overview.md b/docs/tech-overview.md
index 6f42d37ff..b5de4626b 100644
--- a/docs/tech-overview.md
+++ b/docs/tech-overview.md
@@ -14,14 +14,104 @@ The project is bundled using [Vite](https://vitejs.dev/). The test runner is [Vi
We use Prettier to format code. Please set this up to format before committing changes, ideally on save (there's [a VS Code plugin](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)).
-The UI is split into different areas by the [workbench component](../src/workbench/Workbench.tsx). This component manages layout including expand/collapse of the sidebar and simulator and is a good starting point to navigate the codebase. The main areas are:
+The app has three pages: a home page, a projects page and the editor. See [Pages and routing](#pages-and-routing).
-1. The sidebar on the left, with Reference, Ideas, API and Project tabs as well as settings and help menus.
-2. The main editing area with the text editor for the current file, header with the project title and the project action bar with buttons for key interactions. When a micro:bit device is connected over WebUSB, the serial area appears between the text editor and the project actions.
+The editor's UI is split into different areas by the [workbench component](../src/workbench/Workbench.tsx). This component manages layout including expand/collapse of the sidebar and simulator and is a good starting point to navigate the codebase. The main areas are:
+
+1. The sidebar on the left, with Reference, Ideas, API and Files tabs as well as settings and help menus.
+2. The main editing area with the text editor for the current file, a breadcrumb with the project name and the open file, and the project action bar with buttons for key interactions. When a micro:bit device is connected over WebUSB, the serial area appears between the text editor and the project actions.
3. The simulator on the right, with its own serial area and controls.
The branding that you see on the [Foundation deployment](https://python.microbit.org/v/3) is not Open Source and is managed in a private GitHub project. This is swapped in via an alias for `theme-package` in the Vite config.
+## Pages and routing
+
+Routing uses [react-router](https://reactrouter.com/). The routes are set up in [router.tsx](../src/router.tsx) and the URLs are built in [urls.ts](../src/urls.ts).
+
+- The home page is at the app's root and the projects page at `/projects`. Both are in [src/pages](../src/pages) and are built from components in `@microbit/ui-patterns`, which micro:bit CreateAI also uses, so the two apps present projects the same way. Page composition, the banner and the resource cards are specific to this app.
+- The editor is at `/project`, with the sidebar's tab and position in the URL as `/project/:tab/:slug`. The editor used to be at the root, so its old `/:tab/:slug` URLs redirect.
+- There is no project id in the URL. Which project a tab has open is kept in session storage.
+- The editor route's loader chooses the project: the tab's current one, otherwise the most recently used, otherwise a new one with the starter program. The pages don't need a project, so they render without choosing one.
+
+The Foundation's website links to the editor with a program in the URL, as a `#project:` link. [project-link.ts](../src/fs/project-link.ts) reads it once at startup. It becomes a new project when the editor first opens (or replaces the single project where there is no database), and is then removed from the address so that a reload does not open it again. Such links point at the root, so the home page sends the user on to the editor while a link is still waiting to be opened. A link that cannot be read is dropped.
+
+When the editor is embedded in an iframe in controller mode, as micro:bit classroom does, the embedding page owns the project. The editor is then the only page, at the root, and there is no home or projects page.
+
+## Projects and storage
+
+Projects are stored in the browser, in IndexedDB, so a user can have several and come back to them. Nothing is stored on a server.
+
+The pieces:
+
+- [`ProjectsDatabase`](../src/fs/projects-db.ts) is the database, accessed with [idb](https://github.com/jakearchibald/idb). It has a `projects` store (id, name and a timestamp) and a `files` store keyed by project id and file name.
+- [`FileSystem`](../src/fs/fs.ts) is what the editor reads and writes. It keeps an in-memory working copy of the open project and the MicroPython file system used to build a hex file. Its storage sits behind the `FSStorage` interface in [storage.ts](../src/fs/storage.ts).
+- [`IndexedDBFSStorage`](../src/fs/indexeddb-storage.ts) is the `FSStorage` for one project in the database.
+- [`Projects`](../src/project/projects.ts) lists, creates, opens, renames, duplicates and deletes projects, and keeps the file system on the open one. UI components go through it and never touch the database.
+
+### Opening and saving
+
+Opening a project loads its record and all its files in one read, then switches the file system's storage. Loading first means a failed read leaves the previously open project as it was.
+
+Edits are written through as they happen. There is no separate "save" action for browser storage:
+
+- Writes are coalesced per file for 300ms, then flushed as one transaction. The project's timestamp is the time of the edit, so "last modified" does not depend on when the flush ran.
+- Pending writes are also flushed when the page is hidden or unloading. A transaction that waits on a read, or on its requests finishing, does not survive the page unloading. So a flush never reads before it writes, and one from a hidden or unloading page commits explicitly. This is why the storage holds the project's name and writes the whole project record each time, rather than reading the record and updating it.
+- A flush at any other time checks, in the same transaction, that the project still exists.
+- A failed flush is not retried on a timer, which against a full quota would never end. Its edits stay queued and go with the next flush, whatever causes it: a later edit, the page being hidden, or the project being switched. Meanwhile the user sees a toast that stays until dismissed ("Browser storage full" when the quota is exceeded), is warned before closing the tab, and the error is logged once per session.
+
+MicroPython itself is only needed to build a hex file or flash, not to edit. If it fails to load, projects still open and save, and loading is tried again the next time something needs it.
+
+### More than one tab
+
+Tabs tell each other about changes over a `BroadcastChannel`, naming the projects affected:
+
+- Every tab refreshes its list of projects.
+- A tab with a changed project open reloads it, after first saving anything it has outstanding. If that cannot be saved, the tab keeps its own copy rather than lose the edit, and stays out of step until the project is next opened in it or the tab is reloaded.
+- A tab with a deleted project open stops writing it, and if the editor is showing goes to the home page with a message.
+
+### Without IndexedDB, and embedded
+
+If IndexedDB is unavailable, for example in some private browsing modes, the editor falls back to how it worked before projects were stored: one project in session storage, lost when the tab closes. There is no project management, the pages redirect to the editor, and the user is warned before closing a tab with unsaved changes.
+
+In iframe controller mode the embedding page supplies and stores the project, and none of the above applies.
+
+A tab that was open on a version of the editor from before the database has its project in session storage. It is moved into the database once, at startup, and becomes that tab's current project.
+
+### Importing files
+
+A hex file is always a whole program. Other files are added to the open project from the editor, and make a new project from the pages. [project-import.tsx](../src/project/project-import.tsx) handles both.
+
+"Editor" below is the Files tab's Add files button or a drop on the editor.
+
+| Input | Iframe, editor | No IndexedDB, editor | Database, editor | Database, home or projects page |
+| ---------------------------- | ------------------------------------------ | -------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- |
+| One hex | Replaces the project; asks first if edited | Same | New project named after the file; the editor switches to it | New project; the editor opens on it |
+| Hex with other files | Error | Same | Same | Same |
+| `.mpy` | Error | Same | Same | Same |
+| One `.py` script | Added under its own name | Same | Same | New project named after the script, which becomes `main.py` |
+| `main.py` | Replaces `main.py`; asks first | Same | Same | New untitled project with that `main.py` |
+| Several files, or a module | Added; asks before overwriting any | Same | Same | New untitled project; starter `main.py` added if none |
+| Idea from the Ideas tab | Replaces the project; asks first if edited | Same | New project named after the idea | n/a |
+| `#project:` link at startup | Ignored; the host owns the project | Replaces the project | New project | n/a |
+| Host `importproject` message | Replaces the project | n/a | n/a | n/a |
+
+### Design decisions
+
+Some choices that are not obvious from the code:
+
+- **The editor opens straight to code.** `/project` in a new tab opens the most recent project rather than asking the user to pick one. The editor has always been quick to get into, and some users bookmark it.
+- **No project id in the URL.** The tab's project is kept in session storage instead. This may be revisited if projects are ever stored on a server.
+- **Each deployment has its own database.** The database name includes the base path, so deployments that share an origin, such as production and beta, keep separate projects.
+- **No warning before closing a tab.** The editor used to warn when a tab was closed with changes made since the last hex file was loaded or saved, because closing the tab lost them. With the database every edit is already stored, so there is nothing to warn about unless a save has failed. The warning remains where there is no database.
+- **Imports never overwrite silently.** With the database, a hex or an idea makes a new project rather than replacing the open one. Without it there is only one project, so the editor asks before replacing one that has been edited: in micro:bit classroom a student's dropped hex would otherwise replace the teacher's starter program without a word. Adding files that would overwrite existing ones asks first in every mode.
+- **A project changed in another tab is reloaded, not merged.** The last write wins.
+
+Known limits:
+
+- An edit may still be lost if the page unloads in the few milliseconds that an ordinary flush is mid-transaction.
+- Switching project waits for MicroPython if it is still loading, which is only noticeable on a slow first visit.
+- Browsers can evict stored data, for example when the device is short of space. Safari removes it for a site that has not been visited in seven days of browser use.
+
## Connecting to the micro:bit via WebUSB, flashing and hex files
The [device folder](../src/device) contains WebUSB support for the micro:bit using [DAP.js](https://github.com/ARMmbed/dapjs). This includes an implementation of partial flashing which signficiantly speeds up subsequent flashing.
diff --git a/i18n.config.mjs b/i18n.config.mjs
index 46ce8253b..206f007cc 100644
--- a/i18n.config.mjs
+++ b/i18n.config.mjs
@@ -35,7 +35,11 @@ export default defineConfig({
// in the format it was created in.
crowdinFormat: "chrome",
out: "src/messages/ui.{lang}.json",
- packages: ["@microbit/ui", "@microbit/ui-patterns"],
+ packages: [
+ "@microbit/ui",
+ "@microbit/ui-patterns",
+ "@microbit/ui-carousel",
+ ],
},
],
});
diff --git a/lang/ui.ca.json b/lang/ui.ca.json
index 6705b80f0..3ff71cf62 100644
--- a/lang/ui.ca.json
+++ b/lang/ui.ca.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Enrera"
},
- "back-to-main": {
- "defaultMessage": "tornar al codi principal"
- },
"cancel-action": {
"defaultMessage": "Cancel·lar"
},
- "change-files": {
- "defaultMessage": "Canviar fitxers?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Afegeix el fitxer {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "Afegeix el mòdul {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Substitueix el fitxer {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Substitueix el mòdul {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Afegeix el fitxer {target} des de {source} "
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Afegeix el programa principal de {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Substitueix el fitxer {target} per {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Substitueix el programa principal per {source}"
- },
"clear": {
"defaultMessage": "Esborra"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Substitueix tots els fitxers amb els de l'hexadecimal?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Vols substituir tots els fitxers pel programa d'inici per defecte?"
- },
"confirm-replace-title": {
"defaultMessage": "Confirma la substitució del projecte"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Edita el nom del teu projecte"
},
- "edit-project-name-action": {
- "defaultMessage": "Edita el nom del projecte"
- },
"failed-to-build-hex": {
"defaultMessage": "No s'ha pogut crear el fitxer hexadecimal"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Obert"
},
- "open-file-action": {
- "defaultMessage": "Obert"
- },
"open-file-dropped": {
"defaultMessage": "Obre el fitxer quan es deixa anar"
},
- "open-hover": {
- "defaultMessage": "Obre un fitxer hexadecimal o Python o afegeix altres fitxers"
- },
- "options": {
- "defaultMessage": "Opcions"
- },
"parameter-help": {
"defaultMessage": "Ajuda dels paràmetres"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "Capçalera del projecte"
},
- "project-name": {
- "defaultMessage": "Nom del projecte"
- },
"project-name-not-empty": {
"defaultMessage": "El nom del projecte no pot estar buit"
},
- "project-tab": {
- "defaultMessage": "Projecte"
- },
- "project-tab-description": {
- "defaultMessage": "Visualitza, crea, afegeix i edita els fitxers del teu projecte"
- },
"python-powered": {
"defaultMessage": "Fet amb Python"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Substitueix"
},
- "reset-project-action": {
- "defaultMessage": "Restableix el projecte"
- },
- "reset-project-feedback": {
- "defaultMessage": "Restableix el projecte al programa d'inici predeterminat"
- },
- "reset-project-hover": {
- "defaultMessage": "Restableix el projecte al programa inicial predeterminat, descartant el teu treball"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Sense resultats} one {# resultat} other {# resultats}}"
},
diff --git a/lang/ui.de.json b/lang/ui.de.json
index b2048a4dc..fd160ff86 100644
--- a/lang/ui.de.json
+++ b/lang/ui.de.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Zurück"
},
- "back-to-main": {
- "defaultMessage": "zurück zum Hauptcode"
- },
"cancel-action": {
"defaultMessage": "Abbrechen"
},
- "change-files": {
- "defaultMessage": "Dateien ändern?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Datei {name} hinzufügen?"
- },
- "choose-main-add-module": {
- "defaultMessage": "Modul {name} hinzufügen"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Datei {name} ersetzen"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Modul {name} ersetzen"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Datei {target} aus {source} hinzufügen"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Hauptcode aus {source} hinzufügen"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Datei {target} durch {source} ersetzen"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Hauptcode durch {source} ersetzen"
- },
"clear": {
"defaultMessage": "Löschen"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Alle Dateien durch die in der HEX-Datei ersetzen?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Alle Dateien durch den Standard-Startcode ersetzen?"
- },
"confirm-replace-title": {
"defaultMessage": "Zurücksetzen bestätigen"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Bearbeite den Namen deines Projekts"
},
- "edit-project-name-action": {
- "defaultMessage": "Projektname bearbeiten"
- },
"failed-to-build-hex": {
"defaultMessage": "Erstellen der hex-Datei fehlgeschlagen"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Öffnen"
},
- "open-file-action": {
- "defaultMessage": "Öffnen …"
- },
"open-file-dropped": {
"defaultMessage": "Datei nach Ablegen öffnen"
},
- "open-hover": {
- "defaultMessage": "Eine HEX- oder Python-Datei öffnen oder andere Dateien hinzufügen."
- },
- "options": {
- "defaultMessage": "Optionen"
- },
"parameter-help": {
"defaultMessage": "Parameter-Hilfe"
},
@@ -440,18 +395,9 @@
"project-header": {
"defaultMessage": "Projekt-Kopfzeile"
},
- "project-name": {
- "defaultMessage": "Projektname"
- },
"project-name-not-empty": {
"defaultMessage": "Der Projektname darf nicht leer sein"
},
- "project-tab": {
- "defaultMessage": "Projekt"
- },
- "project-tab-description": {
- "defaultMessage": "Anzeigen, Erstellen, Hinzufügen und Bearbeiten der Dateien in deinem Projekt"
- },
"python-powered": {
"defaultMessage": "Python betrieben"
},
@@ -476,15 +422,6 @@
"replace-action-label": {
"defaultMessage": "Ersetzen"
},
- "reset-project-action": {
- "defaultMessage": "Projekt zurücksetzen"
- },
- "reset-project-feedback": {
- "defaultMessage": "Projekt auf den Standard-Startcode zurückgesetzt"
- },
- "reset-project-hover": {
- "defaultMessage": "Setzt das Projekt auf den Standard-Startcode zurück und verwirft deine Arbeit"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Keine Ergebnisse} one {# Ergebnis} other {# Ergebnisse}}"
},
diff --git a/lang/ui.en.json b/lang/ui.en.json
index 853643267..018809bb0 100644
--- a/lang/ui.en.json
+++ b/lang/ui.en.json
@@ -27,10 +27,30 @@
"defaultMessage": "Accessibility",
"description": "Menu item for link to accessibility site"
},
+ "accessibility-resource-title": {
+ "defaultMessage": "Accessibility",
+ "description": "Title of the help card linking to the accessibility statement"
+ },
+ "add-files-action": {
+ "defaultMessage": "Add files…",
+ "description": "Button in the Files tab to add files to the project"
+ },
+ "add-files-hover": {
+ "defaultMessage": "Add Python or other files to your project. A hex file opens as a new project.",
+ "description": "Hover text for the add files button"
+ },
+ "add-files-hover-replace": {
+ "defaultMessage": "Add Python or other files to your project. A hex file replaces all project files.",
+ "description": "Hover text for the add files button when the browser cannot keep more than one project, so opening a hex file replaces the open project"
+ },
"added-change": {
"defaultMessage": "Added file {changeName}",
"description": "Change made to file"
},
+ "all-projects-action": {
+ "defaultMessage": "All projects",
+ "description": "Link beside the home page \"Make it: code it\" row heading leading to all those projects on microbit.org"
+ },
"api-description": {
"defaultMessage": "For usage and examples, see Reference",
"description": "Extended description at the top of the API tab"
@@ -67,49 +87,21 @@
"defaultMessage": "Back",
"description": "Back button text"
},
- "back-to-main": {
- "defaultMessage": "back to the main code",
- "description": "Text button, takes back to main code"
+ "breadcrumb-label": {
+ "defaultMessage": "Breadcrumb",
+ "description": "Accessible name of the breadcrumb above the code editor: Home, the project name and the open file"
},
"cancel-action": {
"defaultMessage": "Cancel",
"description": "Cancel button text"
},
- "change-files": {
- "defaultMessage": "Change files?",
- "description": "Header for dialog of confirmation of files changed"
- },
- "choose-main-add-file": {
- "defaultMessage": "Add file {name}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-add-module": {
- "defaultMessage": "Add module {name}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Replace file {name}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Replace module {name}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Add file {target} from {source}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Add main code from {source}",
- "description": "Shown in load dialog to confirm actions"
+ "choose-file-menu": {
+ "defaultMessage": "{filename}, choose a file",
+ "description": "Accessible name of the open file's name above the editor, which opens a menu of the project's files"
},
- "choose-main-source-replace-file": {
- "defaultMessage": "Replace file {target} with {source}",
- "description": "Shown in load dialog to confirm actions"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Replace main code with {source}",
- "description": "Shown in load dialog to confirm actions"
+ "choose-file-tooltip": {
+ "defaultMessage": "Choose a file",
+ "description": "Tooltip on the file icon above the editor, shown when there's no room for the file name, which opens a menu of the project's files"
},
"clear": {
"defaultMessage": "Clear",
@@ -139,9 +131,13 @@
"defaultMessage": "Replace all files with those in the hex?",
"description": "Confirmation message body for replacing project dialog"
},
- "confirm-replace-reset": {
- "defaultMessage": "Replace all files with the default starter code?",
- "description": "Confirmation message for the reset action"
+ "confirm-replace-files-body": {
+ "defaultMessage": "{count, plural, one {{names} is already in this project and will be replaced.} other {These files are already in this project and will be replaced: {names}}}",
+ "description": "Body of the confirmation shown when added files would overwrite files already in the project. names is a comma-separated list of file names."
+ },
+ "confirm-replace-files-title": {
+ "defaultMessage": "Replace existing files?",
+ "description": "Title of the confirmation shown when added files would overwrite files already in the project"
},
"confirm-replace-title": {
"defaultMessage": "Confirm replace project",
@@ -231,6 +227,10 @@
"defaultMessage": "Create file",
"description": "Button text for action that creates a new blank Python file in the current project"
},
+ "create-project-action": {
+ "defaultMessage": "Create",
+ "description": "Button creating a new project: confirms the dialog naming a new project, and creates one from the home page idea dialog"
+ },
"create-python": {
"defaultMessage": "Create a new Python file in this project",
"description": "Hover and dialog title when creating a new Python file"
@@ -275,9 +275,13 @@
"defaultMessage": "Edit the name of your project",
"description": "Text for user to edit the name of the project"
},
- "edit-project-name-action": {
- "defaultMessage": "Edit project name",
- "description": "Text for user to edit the name of the project"
+ "edit-project-name-crumb": {
+ "defaultMessage": "{name}, edit project name",
+ "description": "Accessible name of the breadcrumb button that shows the project name and opens the rename dialog"
+ },
+ "editor-title": {
+ "defaultMessage": "{projectName} – micro:bit Python Editor",
+ "description": "Heading for screen readers on the editor page: the open project's name, then the name of the app"
},
"failed-to-build-hex": {
"defaultMessage": "Failed to build the hex file",
@@ -319,6 +323,14 @@
"defaultMessage": "The name cannot contain spaces",
"description": "Warning text for new Python file name with whitespace"
},
+ "files-tab": {
+ "defaultMessage": "Files",
+ "description": "Files tab button text. Tab shows the files in the project."
+ },
+ "files-tab-description": {
+ "defaultMessage": "Add Python modules to support micro:bit accessories or organise larger projects",
+ "description": "Files tab description text. Tab shows the files in the project."
+ },
"firmware-update-link": {
"defaultMessage": "You must update your firmware before you can connect to this micro:bit.",
"description": "Text in the firmware update dialog"
@@ -331,6 +343,14 @@
"defaultMessage": "Firmware update required",
"description": "Title for the firmware update dialog"
},
+ "first-lessons-with-python-resource-description": {
+ "defaultMessage": "Move from blocks to text-based coding with six familiar projects",
+ "description": "Description on the teacher resource card for the first lessons unit"
+ },
+ "first-lessons-with-python-resource-title": {
+ "defaultMessage": "First lessons with Python and the micro:bit",
+ "description": "Title of the teacher resource card for the first lessons unit"
+ },
"flash-action": {
"defaultMessage": "Flash",
"description": "Text for flash button"
@@ -363,6 +383,10 @@
"defaultMessage": "Help",
"description": "Help menu label"
},
+ "help-resources-row-title": {
+ "defaultMessage": "Help",
+ "description": "Heading of the home page row of help cards"
+ },
"help-support": {
"defaultMessage": "Help & support",
"description": "Menu item for link to support site"
@@ -383,6 +407,94 @@
"defaultMessage": "Simple",
"description": "Highlight code structure option"
},
+ "home-action": {
+ "defaultMessage": "Home",
+ "description": "Link on the editor logo, the editor breadcrumb and the home page header logo, and button on the projects page, returning to the home page"
+ },
+ "home-page-tooltip": {
+ "defaultMessage": "Go to the home page",
+ "description": "Tooltip on the editor logo and the editor breadcrumb's home icon, which link to the home page"
+ },
+ "homepage-banner-heading": {
+ "defaultMessage": "Python for the BBC micro:bit",
+ "description": "Heading of the banner at the top of the home page"
+ },
+ "homepage-banner-subtitle": {
+ "defaultMessage": "The official text-based coding tool for micro:bit",
+ "description": "Text under the home page banner heading"
+ },
+ "idea-activity-picker-title": {
+ "defaultMessage": "Activity picker",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-clap-lights-title": {
+ "defaultMessage": "Clap lights",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-dice-title": {
+ "defaultMessage": "Dice",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-emotion-badge-title": {
+ "defaultMessage": "Emotion badge",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-frere-jacques-title": {
+ "defaultMessage": "Frère Jacques",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-send-a-smile-title": {
+ "defaultMessage": "Send a smile",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "idea-step-counter-title": {
+ "defaultMessage": "Step counter",
+ "description": "Title of an idea card; matches the idea name in the ideas tab"
+ },
+ "ideas-moving-notice": {
+ "defaultMessage": "Ideas are moving to the Home page. Learn more",
+ "description": "Notice in the ideas tab header; the link opens a dialog explaining the change"
+ },
+ "ideas-moving-questions": {
+ "defaultMessage": "Get in touch through our support site.",
+ "description": "Body of the questions section in the ideas moving dialog; the link opens the support site in a new tab"
+ },
+ "ideas-moving-questions-heading": {
+ "defaultMessage": "Still have questions?",
+ "description": "Section heading in the ideas moving dialog"
+ },
+ "ideas-moving-title": {
+ "defaultMessage": "Ideas are moving to the Home page",
+ "description": "Title of the dialog explaining that ideas are moving out of the editor to the home page"
+ },
+ "ideas-moving-what": {
+ "defaultMessage": "Ideas are now on the Home page too. When you create a project from an idea there, the editor opens with that idea in the sidebar. Later, we will remove the option to browse ideas from the sidebar.",
+ "description": "Body of the what is changing section in the ideas moving dialog"
+ },
+ "ideas-moving-what-heading": {
+ "defaultMessage": "What is changing?",
+ "description": "Section heading in the ideas moving dialog"
+ },
+ "ideas-moving-when": {
+ "defaultMessage": "We will remove the option to browse ideas from the sidebar in mid-2027.",
+ "description": "Body of the when section in the ideas moving dialog"
+ },
+ "ideas-moving-when-heading": {
+ "defaultMessage": "When?",
+ "description": "Section heading in the ideas moving dialog"
+ },
+ "ideas-moving-why": {
+ "defaultMessage": "Ideas are easier to browse on the Home page. Selecting an idea shows you a preview before you start, and the Home page has other resources and activities as well.",
+ "description": "Body of the why section in the ideas moving dialog"
+ },
+ "ideas-moving-why-heading": {
+ "defaultMessage": "Why?",
+ "description": "Section heading in the ideas moving dialog"
+ },
+ "ideas-row-title": {
+ "defaultMessage": "Ideas",
+ "description": "Heading of the home page row of idea cards"
+ },
"ideas-tab": {
"defaultMessage": "Ideas",
"description": "Ideas tab button text. Tab shows programs to give students ideas."
@@ -391,17 +503,45 @@
"defaultMessage": "Try out these projects, modify them and get inspired",
"description": "Ideas tab description text. Tab shows programs to give students ideas."
},
+ "import-file-action": {
+ "defaultMessage": "Import",
+ "description": "Import file action"
+ },
"insert-code-action": {
"defaultMessage": "Insert code"
},
+ "introducing-python-course-resource-description": {
+ "defaultMessage": "Introduces our Python Editor that helps learners to write code for the BBC micro:bit. We will highlight all the great features in our editor that support you and your learners to code the micro:bit successfully using Python",
+ "description": "Description on the teacher resource card for the online course introducing Python and the micro:bit"
+ },
+ "introducing-python-course-resource-title": {
+ "defaultMessage": "Introducing Python & the micro:bit (15 mins)",
+ "description": "Title of the teacher resource card for the online course introducing Python and the micro:bit; matches the resource name"
+ },
"language": {
"defaultMessage": "Language",
"description": "Language option text"
},
+ "learn-more-action": {
+ "defaultMessage": "Learn more",
+ "description": "Home page banner button linking to microbit.org"
+ },
"less-action": {
"defaultMessage": "Less",
"description": "Less button text (showing less content)"
},
+ "level-advanced": {
+ "defaultMessage": "Advanced",
+ "description": "Level of a microbit.org project, shown on its card beside a bars icon; matches microbit.org"
+ },
+ "level-beginner": {
+ "defaultMessage": "Beginner",
+ "description": "Level of a microbit.org project, shown on its card beside a bars icon; matches microbit.org"
+ },
+ "level-intermediate": {
+ "defaultMessage": "Intermediate",
+ "description": "Level of a microbit.org project, shown on its card beside a bars icon; matches microbit.org"
+ },
"load-error-makecode-info": {
"defaultMessage": "This hex file cannot be loaded in the Python Editor. The Python Editor cannot open hex files created with Microsoft MakeCode.",
"description": "Load error message"
@@ -411,7 +551,7 @@
"description": "Load error message"
},
"load-error-mixed": {
- "defaultMessage": "A hex file can only be loaded on its own. It replaces all files in the project.",
+ "defaultMessage": "A hex file can only be imported on its own.",
"description": "Load error message"
},
"load-error-mpy": {
@@ -430,10 +570,94 @@
"defaultMessage": "Loading…",
"description": "Shown on loading indicators"
},
+ "manage-project-files-action": {
+ "defaultMessage": "Manage project files",
+ "description": "Item in the menu of the project's files above the editor; opens the Files tab"
+ },
+ "mici-project-hot-potato-game-description": {
+ "defaultMessage": "Play ‘hot potato’ using a micro:bit!",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-hot-potato-game-title": {
+ "defaultMessage": "Hot potato game",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-indoor-outdoor-thermometer-description": {
+ "defaultMessage": "Sense how warm or cold it is outside",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-indoor-outdoor-thermometer-title": {
+ "defaultMessage": "Indoor-outdoor thermometer",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-maxmin-temperature-logger-description": {
+ "defaultMessage": "Store temperature readings",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-maxmin-temperature-logger-title": {
+ "defaultMessage": "Max-min temperature logger",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-sensitive-step-counter-description": {
+ "defaultMessage": "Make your own step counter with a micro:bit",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-sensitive-step-counter-title": {
+ "defaultMessage": "Sensitive step counter",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-teleporting-duck-description": {
+ "defaultMessage": "Teleport a duck between micro:bits using radio",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-teleporting-duck-title": {
+ "defaultMessage": "Teleporting duck",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-thermometer-description": {
+ "defaultMessage": "Make a simple thermometer with your micro:bit",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-thermometer-title": {
+ "defaultMessage": "Thermometer",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-project-treasure-hunt-description": {
+ "defaultMessage": "Multi-player radio treasure hunt game",
+ "description": "Description on a \"Make it: code it\" project card; matches the microbit.org project listing"
+ },
+ "mici-project-treasure-hunt-title": {
+ "defaultMessage": "Treasure hunt",
+ "description": "Title of a \"Make it: code it\" project card; matches the microbit.org project name"
+ },
+ "mici-projects-row-subtitle": {
+ "defaultMessage": "Quick Python projects to help you get the most out of the micro:bit’s features — and have fun!",
+ "description": "Text under the heading of the home page row of \"Make it: code it\" project cards"
+ },
+ "mici-projects-row-title": {
+ "defaultMessage": "Make it: code it projects",
+ "description": "Heading of the home page row of \"Make it: code it\" project cards from microbit.org"
+ },
+ "microbit-classroom-resource-description": {
+ "defaultMessage": "Run whole class sessions, easily share code with students and save progress",
+ "description": "Description on the teacher resource card for micro:bit classroom"
+ },
+ "microbit-classroom-resource-title": {
+ "defaultMessage": "micro:bit classroom",
+ "description": "Title of the teacher resource card for micro:bit classroom; matches the resource name"
+ },
"microbit-hearts-alt": {
"defaultMessage": "micro:bit board with the 5 by 5 LED grid showing a heart",
"description": "Alt text for micro:bit image in About dialog"
},
+ "microbit-labelling-worksheet-resource-description": {
+ "defaultMessage": "Label the features of the micro:bit on this worksheet",
+ "description": "Description on the teacher resource card for the micro:bit labelling worksheet"
+ },
+ "microbit-labelling-worksheet-resource-title": {
+ "defaultMessage": "micro:bit labelling worksheet",
+ "description": "Title of the teacher resource card for the micro:bit labelling worksheet; matches the resource name"
+ },
"micropython-documentation": {
"defaultMessage": "MicroPython documentation",
"description": "MicroPython documentation menu option text"
@@ -474,6 +698,10 @@
"defaultMessage": "Warning: Only main.py downloaded",
"description": "Title of dialog shown when multiple files are available for download but only the main file downloaded."
},
+ "my-projects-row-title": {
+ "defaultMessage": "My projects",
+ "description": "Heading of the home page row of the user's projects, and of the projects page"
+ },
"name-project": {
"defaultMessage": "Name your project",
"description": "Name your project header"
@@ -490,10 +718,18 @@
"defaultMessage": "We'll add the .py extension for you.",
"description": "Hint shown in the new Python file dialog"
},
+ "new-project-action": {
+ "defaultMessage": "New project",
+ "description": "Home page card creating a new project"
+ },
"next-action": {
"defaultMessage": "Next",
"description": "Next button text"
},
+ "no-projects": {
+ "defaultMessage": "No projects to display",
+ "description": "Shown on the projects page when there are no projects, or none match the search"
+ },
"not-found-checklist-one": {
"defaultMessage": "Is your micro:bit plugged in ? Did you follow these steps?",
"description": "Checklist text in the no micro:bit found dialog"
@@ -526,22 +762,10 @@
"defaultMessage": "Open",
"description": "Open button text"
},
- "open-file-action": {
- "defaultMessage": "Open…",
- "description": "Open file button text"
- },
"open-file-dropped": {
"defaultMessage": "Open file when dropped",
"description": "Aria label for file drop target"
},
- "open-hover": {
- "defaultMessage": "Open a hex or Python file or add other files",
- "description": "Hover text over load button"
- },
- "options": {
- "defaultMessage": "Options",
- "description": "Label for an options menu"
- },
"parameter-help": {
"defaultMessage": "Parameter help",
"description": "Setting label to control whether pop-up documentation for function/method parameters is automatically shown."
@@ -594,25 +818,45 @@
"defaultMessage": "Project actions",
"description": "Aria label for the bar with project actions"
},
+ "project-deleted-elsewhere-description": {
+ "defaultMessage": "The project you had open was deleted in another tab or window.",
+ "description": "Body of the message shown when the project open in the editor has been deleted in another browser tab or window, as the editor returns to the home page"
+ },
+ "project-deleted-elsewhere-title": {
+ "defaultMessage": "Project deleted",
+ "description": "Title of the message shown when the project open in the editor has been deleted in another browser tab or window, as the editor returns to the home page"
+ },
+ "project-files-heading": {
+ "defaultMessage": "Project files",
+ "description": "Heading at the top of the Files tab, which lists the files in the project"
+ },
"project-header": {
"defaultMessage": "Project header",
"description": "Aria label for the project header area"
},
- "project-name": {
- "defaultMessage": "Project name",
- "description": "Text used to indicate the project name"
- },
"project-name-not-empty": {
"defaultMessage": "The project name cannot be empty",
"description": "Validation message for project name"
},
- "project-tab": {
- "defaultMessage": "Project",
- "description": "Project tab button text"
+ "project-storage-tooltip": {
+ "defaultMessage": "Your data is saved in this browser on this device. Clearing your browser's cookies or site data will delete it. It may also be automatically removed by your browser if your device is low on storage.",
+ "description": "Tooltip on the home page projects row heading explaining where projects are stored"
+ },
+ "python-editor-poster-creativity-resource-description": {
+ "defaultMessage": "Use ideas, reference code and the simulator to get creative",
+ "description": "Description on the teacher resource card for the Python Editor creativity poster"
+ },
+ "python-editor-poster-creativity-resource-title": {
+ "defaultMessage": "Python creativity poster",
+ "description": "Title of the teacher resource card for the Python Editor creativity poster; matches the resource name"
},
- "project-tab-description": {
- "defaultMessage": "View, create, add and edit the files in your project",
- "description": "Project tab description"
+ "python-editor-poster-debugging-resource-description": {
+ "defaultMessage": "Spot errors and avoid typing mistakes as you code",
+ "description": "Description on the teacher resource card for the Python Editor debugging poster"
+ },
+ "python-editor-poster-debugging-resource-title": {
+ "defaultMessage": "Python debugging poster",
+ "description": "Title of the teacher resource card for the Python Editor debugging poster; matches the resource name"
},
"python-powered": {
"defaultMessage": "Python powered",
@@ -646,17 +890,21 @@
"defaultMessage": "Replace",
"description": "Action label for replacing project dialog"
},
- "reset-project-action": {
- "defaultMessage": "Reset project",
- "description": "Action to reset the project to its default state"
+ "resource-type-classroom-resource": {
+ "defaultMessage": "Classroom resource",
+ "description": "Small label above a home page teacher resource card's title saying what kind of resource it is, e.g. a poster or worksheet"
+ },
+ "resource-type-professional-development": {
+ "defaultMessage": "Professional development",
+ "description": "Small label above a home page teacher resource card's title saying what kind of resource it is, e.g. a teacher training course"
},
- "reset-project-feedback": {
- "defaultMessage": "Project reset to the default starter code",
- "description": "Confirmation message after resetting the project"
+ "resource-type-teaching-tool": {
+ "defaultMessage": "Teaching tool",
+ "description": "Small label above a home page teacher resource card's title saying what kind of resource it is, e.g. micro:bit classroom"
},
- "reset-project-hover": {
- "defaultMessage": "Resets the project to the default starter code, discarding your work",
- "description": "Reset action hover text"
+ "resource-type-unit-of-work": {
+ "defaultMessage": "Unit of work",
+ "description": "Small label above a home page teacher resource card's title saying what kind of resource it is, e.g. a series of lessons"
},
"results-count": {
"defaultMessage": "{count, plural, =0 {No results} one {# result} other {# results}}",
@@ -1090,10 +1338,26 @@
"defaultMessage": "Start coding",
"description": "Start coding button text"
},
+ "storage-error-other": {
+ "defaultMessage": "Failed to save your project to browser storage",
+ "description": "Toast shown when an IndexedDB storage write fails for an unknown reason"
+ },
+ "storage-error-quota-description": {
+ "defaultMessage": "Your project edit may not be saved.",
+ "description": "Toast description when browser storage quota is exceeded"
+ },
+ "storage-error-quota-title": {
+ "defaultMessage": "Browser storage full",
+ "description": "Toast title when browser storage quota is exceeded"
+ },
"support": {
"defaultMessage": "Support",
"description": "Support menu option text"
},
+ "teacher-resources-row-title": {
+ "defaultMessage": "Teacher resources",
+ "description": "Heading of the home page row of teacher resource cards"
+ },
"terms-of-use": {
"defaultMessage": "Terms of use",
"description": "Terms of use menu option text"
@@ -1134,6 +1398,10 @@
"defaultMessage": "Transfer saved hex file to micro:bit",
"description": "Title for the transfer hex dialog"
},
+ "troubleshooting-resource-title": {
+ "defaultMessage": "Troubleshooting",
+ "description": "Title of the help card linking to the support site"
+ },
"try-again-action": {
"defaultMessage": "Try again",
"description": "Try again button text"
@@ -1166,6 +1434,10 @@
"defaultMessage": "User guide",
"description": "Menu item for link to user guide site"
},
+ "view-all-projects": {
+ "defaultMessage": "View all",
+ "description": "Link and card on the home page leading to the projects page"
+ },
"visit-dot-org": {
"defaultMessage": "visit microbit.org (opens in a new tab)",
"description": "alt text for logo link to .org"
diff --git a/lang/ui.es-ES.json b/lang/ui.es-ES.json
index 772d572d3..a47fe4e85 100644
--- a/lang/ui.es-ES.json
+++ b/lang/ui.es-ES.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Volver"
},
- "back-to-main": {
- "defaultMessage": "volver al código principal"
- },
"cancel-action": {
"defaultMessage": "Cancelar"
},
- "change-files": {
- "defaultMessage": "¿Cambiar archivos?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Añadir archivo {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "Añadir módulo {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Sustituir archivo {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Sustituir módulo {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Añadir archivo {target} de {source}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Añadir código principal de {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Sustituir archivo {target} por {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Sustituir código principal por {source}"
- },
"clear": {
"defaultMessage": "Borrar"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "¿Sustituir todos los archivos por los del HEX?"
},
- "confirm-replace-reset": {
- "defaultMessage": "¿Sustituir todos los archivos por el código de inicio predeterminado?"
- },
"confirm-replace-title": {
"defaultMessage": "¿Sustituir proyecto?"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Edita el nombre del proyecto"
},
- "edit-project-name-action": {
- "defaultMessage": "Editar nombre del proyecto"
- },
"failed-to-build-hex": {
"defaultMessage": "No se ha podido generar el archivo HEX"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Abrir"
},
- "open-file-action": {
- "defaultMessage": "Abrir…"
- },
"open-file-dropped": {
"defaultMessage": "Abrir archivo al soltarlo"
},
- "open-hover": {
- "defaultMessage": "Abre un archivo HEX o Python o añade otros archivos"
- },
- "options": {
- "defaultMessage": "Opciones"
- },
"parameter-help": {
"defaultMessage": "Ayuda con parámetros"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "Cabecera del proyecto"
},
- "project-name": {
- "defaultMessage": "Nombre del proyecto"
- },
"project-name-not-empty": {
"defaultMessage": "El nombre del proyecto no puede estar en blanco"
},
- "project-tab": {
- "defaultMessage": "Proyecto"
- },
- "project-tab-description": {
- "defaultMessage": "Ver, crear, añadir y editar los archivos del proyecto"
- },
"python-powered": {
"defaultMessage": "Funciona con Python"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Sustituir"
},
- "reset-project-action": {
- "defaultMessage": "Restablecer proyecto"
- },
- "reset-project-feedback": {
- "defaultMessage": "Proyecto restablecido al código de inicio predeterminado"
- },
- "reset-project-hover": {
- "defaultMessage": "Restablece el proyecto al código de inicio predeterminado, descartando tu trabajo"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Ningún resultado} one {# resultado} other {# resultados}}"
},
diff --git a/lang/ui.fr.json b/lang/ui.fr.json
index 5b8028e74..666a39465 100644
--- a/lang/ui.fr.json
+++ b/lang/ui.fr.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Précédent"
},
- "back-to-main": {
- "defaultMessage": "revenir au code principal"
- },
"cancel-action": {
"defaultMessage": "Annuler"
},
- "change-files": {
- "defaultMessage": "Changer de fichiers ?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Ajouter le fichier {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "Ajouter le module {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Remplacer le fichier {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Remplacer le module {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Ajouter le fichier {target} depuis {source}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Ajouter le code principal depuis {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Remplacer le fichier {target} par {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Remplacer le code principal par {source}"
- },
"clear": {
"defaultMessage": "Effacer"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Remplacer tous les fichiers par ceux de l’hex ?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Remplacer tous les fichiers avec le code de départ par défaut ?"
- },
"confirm-replace-title": {
"defaultMessage": "Confirmer le remplacement du projet"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Modifier le nom de votre projet"
},
- "edit-project-name-action": {
- "defaultMessage": "Modifier le nom du projet"
- },
"failed-to-build-hex": {
"defaultMessage": "Impossible de créer le fichier hex"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Ouvrir"
},
- "open-file-action": {
- "defaultMessage": "Ouvrir…"
- },
"open-file-dropped": {
"defaultMessage": "Ouvrir le fichier lorsqu’il est déposé"
},
- "open-hover": {
- "defaultMessage": "Ouvrir un fichier hex ou Python, ou ajouter d'autres fichiers"
- },
- "options": {
- "defaultMessage": "Options"
- },
"parameter-help": {
"defaultMessage": "Aide aux paramètres"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "En-tête de projet"
},
- "project-name": {
- "defaultMessage": "Intitulé du projet"
- },
"project-name-not-empty": {
"defaultMessage": "Le nom du projet ne peut pas être vide"
},
- "project-tab": {
- "defaultMessage": "Projet"
- },
- "project-tab-description": {
- "defaultMessage": "Visualiser, créer, ajouter et modifier les fichiers de votre projet"
- },
"python-powered": {
"defaultMessage": "Fonctionne avec Python"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Remplacer"
},
- "reset-project-action": {
- "defaultMessage": "Réinitialiser le projet"
- },
- "reset-project-feedback": {
- "defaultMessage": "Le projet a été réinitialisé au code de départ par défaut"
- },
- "reset-project-hover": {
- "defaultMessage": "Réinitialise le projet au code de départ par défaut, supprimant ainsi votre travail"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Aucun résultat} one {# résultat} other {# résultats}}"
},
diff --git a/lang/ui.ga-IE.json b/lang/ui.ga-IE.json
index f46e54d5c..2e6dd4c03 100644
--- a/lang/ui.ga-IE.json
+++ b/lang/ui.ga-IE.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Ar ais"
},
- "back-to-main": {
- "defaultMessage": "ar ais go dtí an príomhchód"
- },
"cancel-action": {
"defaultMessage": "Cealaigh"
},
- "change-files": {
- "defaultMessage": "Athraigh comhaid?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Cuir comhad {name} leis"
- },
- "choose-main-add-module": {
- "defaultMessage": "Cuir modúl {name} leis"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Ionadaigh comhad {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Ionadaigh modúl {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Cuir comhad {target} ó {source}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Cuir príomhchód ó {source} leis"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Ionadaigh comhad {target} le {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Cuir {source} in ionad an phríomhchóid"
- },
"clear": {
"defaultMessage": "Glan"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Cuir iad siúd sa heics in ionad gach comhad?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Cuir an cód tosaithe réamhshocraithe in ionad gach comhaid?"
- },
"confirm-replace-title": {
"defaultMessage": "Deimhnigh ionadaigh an tionscadal"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Cuir ainm do thionscadail in eagar"
},
- "edit-project-name-action": {
- "defaultMessage": "Cuir ainm an tionscadail in eagar"
- },
"failed-to-build-hex": {
"defaultMessage": "Theip ar an gcomhad heicsidheachúlach a thógáil"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Oscail"
},
- "open-file-action": {
- "defaultMessage": "Oscail…"
- },
"open-file-dropped": {
"defaultMessage": "Oscail comhad nuair a thit sé"
},
- "open-hover": {
- "defaultMessage": "Oscail comhad heicsidheachúlach nó Python nó cuir comhaid eile leis"
- },
- "options": {
- "defaultMessage": "Roghanna"
- },
"parameter-help": {
"defaultMessage": "Cabhair pharaiméadair"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "Ceanntásc an tionscadail"
},
- "project-name": {
- "defaultMessage": "Ainm an tionscadail"
- },
"project-name-not-empty": {
"defaultMessage": "Ní féidir ainm an tionscadail a fholmhú"
},
- "project-tab": {
- "defaultMessage": "Tionscadal"
- },
- "project-tab-description": {
- "defaultMessage": "Amharc ar na comhaid i do thionscadal, iad a chruthú, a chur leis agus a chur in eagar"
- },
"python-powered": {
"defaultMessage": "Python faoi thiomáint"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Ionadaigh"
},
- "reset-project-action": {
- "defaultMessage": "Athshocraigh tionscadal"
- },
- "reset-project-feedback": {
- "defaultMessage": "Athshocraigh an tionscadal go dtí an cód tosaithe réamhshocraithe"
- },
- "reset-project-hover": {
- "defaultMessage": "Athshocraigh an tionscadal chuig an gcód tosaithe réamhshocraithe, ag caitheamh do chuid oibre"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Gan torthaí} one {# toradh} two {# thoradh} few {# torthaí} many {# torthaí} other {# torthaí}}\n"
},
diff --git a/lang/ui.ja.json b/lang/ui.ja.json
index 97ba13beb..81e53f621 100644
--- a/lang/ui.ja.json
+++ b/lang/ui.ja.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "戻る"
},
- "back-to-main": {
- "defaultMessage": "メインコードに戻る"
- },
"cancel-action": {
"defaultMessage": "キャンセル"
},
- "change-files": {
- "defaultMessage": "ファイルを変更しますか?"
- },
- "choose-main-add-file": {
- "defaultMessage": "ファイル {name} を追加"
- },
- "choose-main-add-module": {
- "defaultMessage": "モジュール {name} を追加"
- },
- "choose-main-replace-file": {
- "defaultMessage": "ファイル {name} を置き換え"
- },
- "choose-main-replace-module": {
- "defaultMessage": "モジュール {name} を置き換え"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "{source} からファイル {target} を追加"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "{source} からメインコードを追加"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "ファイル {target} を {source} に置き換え"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "メインコードを {source} に置き換え"
- },
"clear": {
"defaultMessage": "クリア"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "すべてのファイルを hex に置き換えますか?"
},
- "confirm-replace-reset": {
- "defaultMessage": "すべてのファイルをデフォルトのスターターコードに置き換えますか?"
- },
"confirm-replace-title": {
"defaultMessage": "プロジェクトの置き換えを確認"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "プロジェクトの名前を編集"
},
- "edit-project-name-action": {
- "defaultMessage": "プロジェクト名を編集"
- },
"failed-to-build-hex": {
"defaultMessage": "hex ファイルのビルドに失敗しました"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "開く"
},
- "open-file-action": {
- "defaultMessage": "開く…"
- },
"open-file-dropped": {
"defaultMessage": "ドロップ時にファイルを開く"
},
- "open-hover": {
- "defaultMessage": "hex ファイルまたは Python ファイルを開くか、他のファイルを追加する"
- },
- "options": {
- "defaultMessage": "オプション"
- },
"parameter-help": {
"defaultMessage": "パラメータのヘルプ"
},
@@ -440,18 +395,9 @@
"project-header": {
"defaultMessage": "プロジェクトヘッダー"
},
- "project-name": {
- "defaultMessage": "プロジェクト名"
- },
"project-name-not-empty": {
"defaultMessage": "プロジェクト名は空にできません"
},
- "project-tab": {
- "defaultMessage": "プロジェクト"
- },
- "project-tab-description": {
- "defaultMessage": "プロジェクト内のファイルの表示、作成、追加、編集"
- },
"python-powered": {
"defaultMessage": "Python搭載"
},
@@ -476,15 +422,6 @@
"replace-action-label": {
"defaultMessage": "置換"
},
- "reset-project-action": {
- "defaultMessage": "プロジェクトをリセット"
- },
- "reset-project-feedback": {
- "defaultMessage": "プロジェクトがデフォルトのスターターコードにリセットされました"
- },
- "reset-project-hover": {
- "defaultMessage": "プロジェクトをデフォルトのスターターコードにリセットし、作業を破棄します"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {結果なし} other {#件の結果}}"
},
diff --git a/lang/ui.ko.json b/lang/ui.ko.json
index 3e7030dc2..9a340db1e 100644
--- a/lang/ui.ko.json
+++ b/lang/ui.ko.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "뒤로"
},
- "back-to-main": {
- "defaultMessage": "메인 코드로 돌아가기"
- },
"cancel-action": {
"defaultMessage": "취소"
},
- "change-files": {
- "defaultMessage": "파일을 변경하시겠습니까?"
- },
- "choose-main-add-file": {
- "defaultMessage": "{name} 파일 추가"
- },
- "choose-main-add-module": {
- "defaultMessage": "{name} 모듈 추가"
- },
- "choose-main-replace-file": {
- "defaultMessage": "{name} 파일 교체"
- },
- "choose-main-replace-module": {
- "defaultMessage": "{name} 모듈 교체"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "{source}에서 {target} 파일 추가"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "{source}에서 메인 코드 추가"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "{target} 파일을 {source}(으)로 교체"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "메인 코드를 {source}(으)로 교체"
- },
"clear": {
"defaultMessage": "지우기"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "모든 파일을 hex 내 파일로 교체하시겠습니까?"
},
- "confirm-replace-reset": {
- "defaultMessage": "모든 파일을 기본 스타터 코드로 교체하시겠습니까?"
- },
"confirm-replace-title": {
"defaultMessage": "프로젝트 교체 확인"
},
@@ -200,9 +167,6 @@
"edit-name-project-hover": {
"defaultMessage": "프로젝트의 이름을 편집합니다"
},
- "edit-project-name-action": {
- "defaultMessage": "프로젝트 이름 편집"
- },
"failed-to-build-hex": {
"defaultMessage": "hex 파일 빌딩 실패"
},
@@ -389,18 +353,9 @@
"open-action": {
"defaultMessage": "열기"
},
- "open-file-action": {
- "defaultMessage": "열기…"
- },
"open-file-dropped": {
"defaultMessage": "드롭될 때 파일 열기"
},
- "open-hover": {
- "defaultMessage": "Hex 또는 Python 파일을 열거나 다른 파일을 추가하세요"
- },
- "options": {
- "defaultMessage": "옵션"
- },
"parameter-help": {
"defaultMessage": "매개변수 도움말"
},
@@ -437,18 +392,9 @@
"project-header": {
"defaultMessage": "프로젝트 머리글"
},
- "project-name": {
- "defaultMessage": "프로젝트 이름"
- },
"project-name-not-empty": {
"defaultMessage": "프로젝트 이름을 입력해야 합니다"
},
- "project-tab": {
- "defaultMessage": "프로젝트"
- },
- "project-tab-description": {
- "defaultMessage": "프로젝트에서 파일을 확인하고, 생성하고, 추가하고 편집할 수 있습니다"
- },
"python-powered": {
"defaultMessage": "Python powered"
},
@@ -473,15 +419,6 @@
"replace-action-label": {
"defaultMessage": "교체"
},
- "reset-project-action": {
- "defaultMessage": "프로젝트 초기화"
- },
- "reset-project-feedback": {
- "defaultMessage": "프로젝트를 기본 스타터 코드로 초기화합니다."
- },
- "reset-project-hover": {
- "defaultMessage": "프로젝트를 기본 스타터 코드로 초기화하고 작업한 내용을 삭제합니다"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {결과 없음} one {#개의 결과} other {#개의 결과}}"
},
diff --git a/lang/ui.lol.json b/lang/ui.lol.json
index 53220d163..fb3f3982c 100644
--- a/lang/ui.lol.json
+++ b/lang/ui.lol.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "crwdns331384:0crwdne331384:0"
},
- "back-to-main": {
- "defaultMessage": "crwdns331386:0crwdne331386:0"
- },
"cancel-action": {
"defaultMessage": "crwdns331388:0crwdne331388:0"
},
- "change-files": {
- "defaultMessage": "crwdns331390:0crwdne331390:0"
- },
- "choose-main-add-file": {
- "defaultMessage": "crwdns331392:0{name}crwdne331392:0"
- },
- "choose-main-add-module": {
- "defaultMessage": "crwdns331394:0{name}crwdne331394:0"
- },
- "choose-main-replace-file": {
- "defaultMessage": "crwdns331396:0{name}crwdne331396:0"
- },
- "choose-main-replace-module": {
- "defaultMessage": "crwdns331398:0{name}crwdne331398:0"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "crwdns331400:0{target}crwdnd331400:0{source}crwdne331400:0"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "crwdns331402:0{source}crwdne331402:0"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "crwdns331404:0{target}crwdnd331404:0{source}crwdne331404:0"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "crwdns331406:0{source}crwdne331406:0"
- },
"clear": {
"defaultMessage": "crwdns331408:0crwdne331408:0"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "crwdns331420:0crwdne331420:0"
},
- "confirm-replace-reset": {
- "defaultMessage": "crwdns331422:0crwdne331422:0"
- },
"confirm-replace-title": {
"defaultMessage": "crwdns331424:0crwdne331424:0"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "crwdns331484:0crwdne331484:0"
},
- "edit-project-name-action": {
- "defaultMessage": "crwdns331486:0crwdne331486:0"
- },
"failed-to-build-hex": {
"defaultMessage": "crwdns331488:0crwdne331488:0"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "crwdns331610:0crwdne331610:0"
},
- "open-file-action": {
- "defaultMessage": "crwdns331612:0crwdne331612:0"
- },
"open-file-dropped": {
"defaultMessage": "crwdns331614:0crwdne331614:0"
},
- "open-hover": {
- "defaultMessage": "crwdns331616:0crwdne331616:0"
- },
- "options": {
- "defaultMessage": "crwdns331618:0crwdne331618:0"
- },
"parameter-help": {
"defaultMessage": "crwdns331620:0crwdne331620:0"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "crwdns331640:0crwdne331640:0"
},
- "project-name": {
- "defaultMessage": "crwdns331642:0crwdne331642:0"
- },
"project-name-not-empty": {
"defaultMessage": "crwdns331644:0crwdne331644:0"
},
- "project-tab": {
- "defaultMessage": "crwdns331646:0crwdne331646:0"
- },
- "project-tab-description": {
- "defaultMessage": "crwdns331648:0crwdne331648:0"
- },
"python-powered": {
"defaultMessage": "crwdns331650:0crwdne331650:0"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "crwdns331664:0crwdne331664:0"
},
- "reset-project-action": {
- "defaultMessage": "crwdns331666:0crwdne331666:0"
- },
- "reset-project-feedback": {
- "defaultMessage": "crwdns331668:0crwdne331668:0"
- },
- "reset-project-hover": {
- "defaultMessage": "crwdns331670:0crwdne331670:0"
- },
"results-count": {
"defaultMessage": "crwdns331672:0count={count}crwdne331672:0"
},
diff --git a/lang/ui.nl.json b/lang/ui.nl.json
index 84692e481..1530acc09 100644
--- a/lang/ui.nl.json
+++ b/lang/ui.nl.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Terug"
},
- "back-to-main": {
- "defaultMessage": "terug naar de hoofdcode"
- },
"cancel-action": {
"defaultMessage": "Annuleren"
},
- "change-files": {
- "defaultMessage": "Bestanden wijzigen?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Voeg bestand {name} toe"
- },
- "choose-main-add-module": {
- "defaultMessage": "Module {name} toevoegen"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Vervang bestand {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Vervang module {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Bestand {target} van {source} toevoegen"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Voeg hoofdcode toe van {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Vervang bestand {target} door {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Vervang hoofdcode door {source}"
- },
"clear": {
"defaultMessage": "Verwijderen"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Alle bestanden vervangen door bestanden in de hex?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Alle bestanden vervangen door de standaard startcode?"
- },
"confirm-replace-title": {
"defaultMessage": "Vervanging bevestigen"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Wijzig de naam van je project"
},
- "edit-project-name-action": {
- "defaultMessage": "Project naam bewerken"
- },
"failed-to-build-hex": {
"defaultMessage": "Het maken van het hex bestand is mislukt"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Open"
},
- "open-file-action": {
- "defaultMessage": "Open…"
- },
"open-file-dropped": {
"defaultMessage": "Open bestand wanneer gedropt"
},
- "open-hover": {
- "defaultMessage": "Open een hex of Python bestand of voeg andere bestanden toe"
- },
- "options": {
- "defaultMessage": "Opties"
- },
"parameter-help": {
"defaultMessage": "Hulp parameter"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "Project koptekst"
},
- "project-name": {
- "defaultMessage": "Projectnaam"
- },
"project-name-not-empty": {
"defaultMessage": "De projectnaam kan niet leeg zijn"
},
- "project-tab": {
- "defaultMessage": "Project"
- },
- "project-tab-description": {
- "defaultMessage": "Bekijk, aanmaken, toevoegen en bewerken van de bestanden in je project"
- },
"python-powered": {
"defaultMessage": "Python actief"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Vervangen"
},
- "reset-project-action": {
- "defaultMessage": "Reset project"
- },
- "reset-project-feedback": {
- "defaultMessage": "Project opnieuw instellen op de standaard startcode"
- },
- "reset-project-hover": {
- "defaultMessage": "Reset het project naar de standaard start code, waarmee je jouw werk weggooit"
- },
"results-count": {
"defaultMessage": "{count, plural, =0{# results} one{# result} other{# results}}"
},
diff --git a/lang/ui.pl.json b/lang/ui.pl.json
index 519b35994..30d2f415b 100644
--- a/lang/ui.pl.json
+++ b/lang/ui.pl.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Wróć"
},
- "back-to-main": {
- "defaultMessage": "wróć do głównego kodu"
- },
"cancel-action": {
"defaultMessage": "Anuluj"
},
- "change-files": {
- "defaultMessage": "Zmienić pliki?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Dodaj plik {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "Dodaj moduł {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Zastąp plik {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Zastąp moduł {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Dodaj plik {target} z {source}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Dodaj kod główny z {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Zastąp plik {target} z {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Zastąp kod główny z {source}"
- },
"clear": {
"defaultMessage": "Wyczyść"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Zastąpić wszystkie pliki tymi z hex?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Zastąpić wszystkie pliki domyślnym kodem startowym?"
- },
"confirm-replace-title": {
"defaultMessage": "Potwierdź zastąpienie projektu"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Edytuj nazwę swojego projektu"
},
- "edit-project-name-action": {
- "defaultMessage": "Edytuj nazwę projektu"
- },
"failed-to-build-hex": {
"defaultMessage": "Nie udało się utworzyć pliku hex"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Otwórz"
},
- "open-file-action": {
- "defaultMessage": "Otwórz…"
- },
"open-file-dropped": {
"defaultMessage": "Otwórz plik po upuszczeniu"
},
- "open-hover": {
- "defaultMessage": "Otwórz plik hex lub Pythona lub dodaj inne pliki"
- },
- "options": {
- "defaultMessage": "Opcje"
- },
"parameter-help": {
"defaultMessage": "Pomoc dot. parametru"
},
@@ -446,18 +401,9 @@
"project-header": {
"defaultMessage": "Nagłówek projektu"
},
- "project-name": {
- "defaultMessage": "Nazwa projektu"
- },
"project-name-not-empty": {
"defaultMessage": "Nazwa projektu nie może być pusta"
},
- "project-tab": {
- "defaultMessage": "Projekt"
- },
- "project-tab-description": {
- "defaultMessage": "Przejrzyj, utwórz, dodaj i edytuj pliki w projekcie"
- },
"python-powered": {
"defaultMessage": "Obsługiwany przez Python"
},
@@ -482,15 +428,6 @@
"replace-action-label": {
"defaultMessage": "Zastąp"
},
- "reset-project-action": {
- "defaultMessage": "Resetuj projekt"
- },
- "reset-project-feedback": {
- "defaultMessage": "Reset projektu do domyślnego kodu startowego"
- },
- "reset-project-hover": {
- "defaultMessage": "Resetuje projekt do domyślnego kodu startowego, odrzucając Twoją pracę"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Brak wyników} one {# wynik} few {# wyników} many {# wyników} other {# wyników}}"
},
diff --git a/lang/ui.pt-BR.json b/lang/ui.pt-BR.json
index 5e2a869ac..bb8f9f6e9 100644
--- a/lang/ui.pt-BR.json
+++ b/lang/ui.pt-BR.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "Voltar"
},
- "back-to-main": {
- "defaultMessage": "voltar ao código principal"
- },
"cancel-action": {
"defaultMessage": "Cancelar"
},
- "change-files": {
- "defaultMessage": "Alterar arquivos?"
- },
- "choose-main-add-file": {
- "defaultMessage": "Adicionar arquivo {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "Adicionar módulo {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "Substituir arquivo {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "Substituir módulo {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "Adicionar arquivo {target} de {source}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "Adicionar código principal de {source}"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "Substituir arquivo {target} por {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "Substituir código principal por {source}"
- },
"clear": {
"defaultMessage": "Limpar"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "Substituir todos os arquivos pelos contidos no hex?"
},
- "confirm-replace-reset": {
- "defaultMessage": "Substituir todos os arquivos pelo código inicial padrão?"
- },
"confirm-replace-title": {
"defaultMessage": "Confirmar substituição do projeto"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "Edite o nome do seu projeto"
},
- "edit-project-name-action": {
- "defaultMessage": "Editar nome do projeto"
- },
"failed-to-build-hex": {
"defaultMessage": "Falha ao construir o arquivo hexadecimal"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "Abrir"
},
- "open-file-action": {
- "defaultMessage": "Abrir…"
- },
"open-file-dropped": {
"defaultMessage": "Abrir arquivo ao soltá-lo"
},
- "open-hover": {
- "defaultMessage": "Abra um arquivo hex ou Python ou adicione outros arquivos\n"
- },
- "options": {
- "defaultMessage": "Opções"
- },
"parameter-help": {
"defaultMessage": "Ajuda sobre parâmetros"
},
@@ -440,18 +395,9 @@
"project-header": {
"defaultMessage": "Cabeçalho do projeto"
},
- "project-name": {
- "defaultMessage": "Nome do projeto"
- },
"project-name-not-empty": {
"defaultMessage": "O nome do projeto não pode estar vazio"
},
- "project-tab": {
- "defaultMessage": "Projeto"
- },
- "project-tab-description": {
- "defaultMessage": "Visualize, crie, adicione e edite os arquivos no seu projeto"
- },
"python-powered": {
"defaultMessage": "Desenvolvido com Python"
},
@@ -476,15 +422,6 @@
"replace-action-label": {
"defaultMessage": "Substituir"
},
- "reset-project-action": {
- "defaultMessage": "Redefinir projeto"
- },
- "reset-project-feedback": {
- "defaultMessage": "Projeto redefinido para o código inicial padrão"
- },
- "reset-project-hover": {
- "defaultMessage": "Redefine o projeto para o código inicial padrão, descartando seu trabalho"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {Nenhum resultado} one {# resultado} other {# resultados}}"
},
diff --git a/lang/ui.zh-CN.json b/lang/ui.zh-CN.json
index 94cca82ed..3e2dd04f5 100644
--- a/lang/ui.zh-CN.json
+++ b/lang/ui.zh-CN.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "返回"
},
- "back-to-main": {
- "defaultMessage": "返回主代码"
- },
"cancel-action": {
"defaultMessage": "取消"
},
- "change-files": {
- "defaultMessage": "更改文件?"
- },
- "choose-main-add-file": {
- "defaultMessage": "添加文件 {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "添加模块 {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "替换文件 {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "替换模块 {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "从 {source} 添加文件 {target}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "从 {source} 添加主代码"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "将文件 {target} 替换为 {source}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "用 {source} 替换主代码"
- },
"clear": {
"defaultMessage": "清除"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "将所有文件替换成 hex 文件?"
},
- "confirm-replace-reset": {
- "defaultMessage": "用默认启动代码替换所有文件?"
- },
"confirm-replace-title": {
"defaultMessage": "确认替换项目"
},
@@ -203,9 +170,6 @@
"edit-name-project-hover": {
"defaultMessage": "编辑您项目的名称"
},
- "edit-project-name-action": {
- "defaultMessage": "编辑项目名称"
- },
"failed-to-build-hex": {
"defaultMessage": "无法创建 hex 文件"
},
@@ -392,18 +356,9 @@
"open-action": {
"defaultMessage": "打开"
},
- "open-file-action": {
- "defaultMessage": "打开…"
- },
"open-file-dropped": {
"defaultMessage": "放下时打开文件"
},
- "open-hover": {
- "defaultMessage": "打开一 份 hex 或 Python 文件,或添加其他文件"
- },
- "options": {
- "defaultMessage": "选项"
- },
"parameter-help": {
"defaultMessage": "参数帮助"
},
@@ -440,18 +395,9 @@
"project-header": {
"defaultMessage": "项目标题"
},
- "project-name": {
- "defaultMessage": "项目名称"
- },
"project-name-not-empty": {
"defaultMessage": "项目名称不能为空"
},
- "project-tab": {
- "defaultMessage": "项目"
- },
- "project-tab-description": {
- "defaultMessage": "查看、创建、添加和编辑您项目中的文件"
- },
"python-powered": {
"defaultMessage": "Python 驱动"
},
@@ -476,15 +422,6 @@
"replace-action-label": {
"defaultMessage": "替换"
},
- "reset-project-action": {
- "defaultMessage": "重置项目"
- },
- "reset-project-feedback": {
- "defaultMessage": "项目重置为默认启动代码"
- },
- "reset-project-hover": {
- "defaultMessage": "将项目重置为默认启动代码,放弃您的工作"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {No results} other {# results}}"
},
diff --git a/lang/ui.zh-TW.json b/lang/ui.zh-TW.json
index 63548e9a8..fdd8eb7b2 100644
--- a/lang/ui.zh-TW.json
+++ b/lang/ui.zh-TW.json
@@ -47,39 +47,9 @@
"back-action": {
"defaultMessage": "返回"
},
- "back-to-main": {
- "defaultMessage": "返回主程式碼"
- },
"cancel-action": {
"defaultMessage": "取消"
},
- "change-files": {
- "defaultMessage": "是否要變更檔案?"
- },
- "choose-main-add-file": {
- "defaultMessage": "新增檔案 {name}"
- },
- "choose-main-add-module": {
- "defaultMessage": "新增模組 {name}"
- },
- "choose-main-replace-file": {
- "defaultMessage": "取代檔案 {name}"
- },
- "choose-main-replace-module": {
- "defaultMessage": "取代模組 {name}"
- },
- "choose-main-source-add-file": {
- "defaultMessage": "從 {source} 新增檔案 {target}"
- },
- "choose-main-source-add-main-code": {
- "defaultMessage": "從 {source} 新增主程式碼"
- },
- "choose-main-source-replace-file": {
- "defaultMessage": "用 {source} 取代檔案 {target}"
- },
- "choose-main-source-replace-main-code": {
- "defaultMessage": "用 {source} 取代主程式碼"
- },
"clear": {
"defaultMessage": "清除"
},
@@ -101,9 +71,6 @@
"confirm-replace-body": {
"defaultMessage": "是否要用 hex 取代所有檔案?"
},
- "confirm-replace-reset": {
- "defaultMessage": "是否要用預設起始程式碼來取代所有檔案?"
- },
"confirm-replace-title": {
"defaultMessage": "確認取代專案"
},
@@ -200,9 +167,6 @@
"edit-name-project-hover": {
"defaultMessage": "編輯您的專案名稱"
},
- "edit-project-name-action": {
- "defaultMessage": "編輯專案名稱"
- },
"failed-to-build-hex": {
"defaultMessage": "無法組建 HEX 檔案"
},
@@ -389,18 +353,9 @@
"open-action": {
"defaultMessage": "開啟"
},
- "open-file-action": {
- "defaultMessage": "開啟..."
- },
"open-file-dropped": {
"defaultMessage": "放置時開啟檔案"
},
- "open-hover": {
- "defaultMessage": "開啟 Hex 或 Python 檔案,或是新增其他檔案"
- },
- "options": {
- "defaultMessage": "選項"
- },
"parameter-help": {
"defaultMessage": "參數說明"
},
@@ -437,18 +392,9 @@
"project-header": {
"defaultMessage": "專案標頭"
},
- "project-name": {
- "defaultMessage": "專案名稱"
- },
"project-name-not-empty": {
"defaultMessage": "專案名稱不可為空白"
},
- "project-tab": {
- "defaultMessage": "專案"
- },
- "project-tab-description": {
- "defaultMessage": "檢視、建立、新增和編輯專案中的檔案"
- },
"python-powered": {
"defaultMessage": "已啟動 Python"
},
@@ -473,15 +419,6 @@
"replace-action-label": {
"defaultMessage": "取代"
},
- "reset-project-action": {
- "defaultMessage": "重設專案"
- },
- "reset-project-feedback": {
- "defaultMessage": "專案重設為預設起始程式碼"
- },
- "reset-project-hover": {
- "defaultMessage": "將專案重設為預設起始程式碼,放棄您的工作"
- },
"results-count": {
"defaultMessage": "{count, plural, =0 {沒有結果} one {# 個結果} other {# 個結果}}"
},
diff --git a/package-lock.json b/package-lock.json
index 51ef7a6bd..d05b36267 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,7 +20,8 @@
"@microbit/microbit-connection": "^1.0.0",
"@microbit/microbit-fs": "^0.11.0",
"@microbit/micropython-microbit-stubs": "^1.0.1",
- "@microbit/ui": "^0.6.2",
+ "@microbit/ui": "^0.6.3",
+ "@microbit/ui-carousel": "^0.5.0",
"@microbit/ui-patterns": "^0.8.0",
"@sanity/block-content-to-react": "^3.0.0",
"@sanity/image-url": "^1.0.1",
@@ -29,6 +30,7 @@
"crelt": "^1.0.5",
"dompurify": "^3.2.5",
"file-saver": "^2.0.5",
+ "idb": "^8.0.3",
"lunr": "^2.3.9",
"lunr-languages": "^1.14.0",
"lzma": "^2.3.2",
@@ -43,6 +45,7 @@
"react-intl": "^12.1.5",
"react-router": "^7.18.3",
"style-mod": "^4.1.4",
+ "swiper": "^14.2.0",
"vscode-jsonrpc": "^10.0.0",
"vscode-languageserver-protocol": "^3.16.0",
"xterm": "4.19.0",
@@ -70,6 +73,7 @@
"@vitejs/plugin-react": "^5.1.4",
"ejs": "^7.0.2",
"eslint": "^10.9.1",
+ "fake-indexeddb": "^6.2.5",
"jsdom": "^30.1.3",
"playwright": "^1.58.2",
"prettier": "2.3.2",
@@ -3644,6 +3648,20 @@
"react-intl": "^6.6.8 || ^7.0.0 || ^10.1.14 || ^12.0.0"
}
},
+ "node_modules/@microbit/ui-carousel": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@microbit/ui-carousel/-/ui-carousel-0.5.0.tgz",
+ "integrity": "sha512-2cqJmUOWNVXvLyYGpz8u+KeZDRz4dOsSW3bsopz6QaSgtNLYfx4/Ll0LhJPZDcXjPWGBXh1DN5FCwRurCpAcpw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@microbit/ui": "^0.6.0",
+ "@pandacss/dev": "^2.4.0",
+ "react": "^18.3.1 || ^19.0.0",
+ "react-aria": "^3.50.0",
+ "react-intl": "^6.6.8 || ^7.0.0 || ^10.1.14 || ^12.0.0",
+ "swiper": "^14.0.0"
+ }
+ },
"node_modules/@microbit/ui-patterns": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/@microbit/ui-patterns/-/ui-patterns-0.8.0.tgz",
@@ -8191,6 +8209,16 @@
"node": ">=12.0.0"
}
},
+ "node_modules/fake-indexeddb": {
+ "version": "6.2.8",
+ "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.8.tgz",
+ "integrity": "sha512-mpVW/HLUqwKXJ6F/s0hMgdK1eQfM4ncTHDioNGHWL0WKV3VcZCoZq1NKgboBbAge07aRCO7L48yziKssL59XEQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -8851,10 +8879,9 @@
}
},
"node_modules/idb": {
- "version": "7.1.1",
- "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz",
- "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
- "dev": true,
+ "version": "8.0.4",
+ "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.4.tgz",
+ "integrity": "sha512-jd0ITCrN+Zah4J7R/Z2jnR3W7A4BXDAjmo62MwWuSjxCiueUAf7X5rbodEdidWzeknwXHmLpdZkoiiCppNi30Q==",
"license": "ISC"
},
"node_modules/ignore": {
@@ -11369,6 +11396,25 @@
"node": ">=8"
}
},
+ "node_modules/swiper": {
+ "version": "14.4.0",
+ "resolved": "https://registry.npmjs.org/swiper/-/swiper-14.4.0.tgz",
+ "integrity": "sha512-6axnAuBsttFJe0gwsM5tT203/Bts0vcI+FwIX6dqFE4pUFVW6qrdRprNFQVxOYMW7V0S6A/KIqJ6JaPpNN2MCw==",
+ "funding": [
+ {
+ "type": "custom",
+ "url": "https://sponsors.nolimits4web.com"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nolimits4web"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4.7.0"
+ }
+ },
"node_modules/temp-dir": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz",
@@ -12270,6 +12316,13 @@
"workbox-core": "7.4.1"
}
},
+ "node_modules/workbox-background-sync/node_modules/idb": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz",
+ "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/workbox-broadcast-update": {
"version": "7.4.1",
"resolved": "https://registry.npmjs.org/workbox-broadcast-update/-/workbox-broadcast-update-7.4.1.tgz",
@@ -12436,6 +12489,13 @@
"workbox-core": "7.4.1"
}
},
+ "node_modules/workbox-expiration/node_modules/idb": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz",
+ "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/workbox-google-analytics": {
"version": "7.4.1",
"resolved": "https://registry.npmjs.org/workbox-google-analytics/-/workbox-google-analytics-7.4.1.tgz",
diff --git a/package.json b/package.json
index 747d6a64b..fd1430f43 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,8 @@
"@microbit/microbit-connection": "^1.0.0",
"@microbit/microbit-fs": "^0.11.0",
"@microbit/micropython-microbit-stubs": "^1.0.1",
- "@microbit/ui": "^0.6.2",
+ "@microbit/ui": "^0.6.3",
+ "@microbit/ui-carousel": "^0.5.0",
"@microbit/ui-patterns": "^0.8.0",
"@sanity/block-content-to-react": "^3.0.0",
"@sanity/image-url": "^1.0.1",
@@ -34,6 +35,7 @@
"crelt": "^1.0.5",
"dompurify": "^3.2.5",
"file-saver": "^2.0.5",
+ "idb": "^8.0.3",
"lunr": "^2.3.9",
"lunr-languages": "^1.14.0",
"lzma": "^2.3.2",
@@ -48,6 +50,7 @@
"react-intl": "^12.1.5",
"react-router": "^7.18.3",
"style-mod": "^4.1.4",
+ "swiper": "^14.2.0",
"vscode-jsonrpc": "^10.0.0",
"vscode-languageserver-protocol": "^3.16.0",
"xterm": "4.19.0",
@@ -75,6 +78,7 @@
"@vitejs/plugin-react": "^5.1.4",
"ejs": "^7.0.2",
"eslint": "^10.9.1",
+ "fake-indexeddb": "^6.2.5",
"jsdom": "^30.1.3",
"playwright": "^1.58.2",
"prettier": "2.3.2",
@@ -111,7 +115,8 @@
"ci": "npm run typecheck && npm run lint && npm run test && npm run i18n:tidy -- --check && npm run build",
"deploy": "website-deploy-s3",
"invalidate": "invalidate-cloudfront-distribution",
- "dev:link-ui": "rm -rf node_modules/@microbit/ui node_modules/@microbit/ui-patterns node_modules/@microbit/i18n-tools && ln -s ../../../ui/packages/ui node_modules/@microbit/ui && ln -s ../../../ui/packages/ui-patterns node_modules/@microbit/ui-patterns && ln -s ../../../ui/packages/i18n-tools node_modules/@microbit/i18n-tools && ln -sf ../@microbit/i18n-tools/bin/microbit-i18n.mjs node_modules/.bin/microbit-i18n && rm -rf styled-system node_modules/.vite && npm run panda",
+ "dev:link-ui": "rm -rf node_modules/@microbit/ui node_modules/@microbit/ui-patterns node_modules/@microbit/ui-carousel node_modules/@microbit/i18n-tools && ln -s ../../../ui/packages/ui node_modules/@microbit/ui && ln -s ../../../ui/packages/ui-patterns node_modules/@microbit/ui-patterns && ln -s ../../../ui/packages/ui-carousel node_modules/@microbit/ui-carousel && ln -s ../../../ui/packages/i18n-tools node_modules/@microbit/i18n-tools && ln -sf ../@microbit/i18n-tools/bin/microbit-i18n.mjs node_modules/.bin/microbit-i18n && rm -rf styled-system node_modules/.vite && npm run panda",
+ "dev:link-theme": "rm -rf node_modules/@microbit-foundation/python-editor-v3-microbit && mkdir -p node_modules/@microbit-foundation && ln -s ../../../python-editor-v3-microbit node_modules/@microbit-foundation/python-editor-v3-microbit && npm run build --prefix ../python-editor-v3-microbit && rm -rf styled-system node_modules/.vite && npm run panda",
"i18n:compile": "microbit-i18n compile",
"i18n:tidy": "microbit-i18n tidy",
"i18n:download": "microbit-i18n download",
diff --git a/panda.config.ts b/panda.config.ts
index 674ab1fc1..3429a99ef 100644
--- a/panda.config.ts
+++ b/panda.config.ts
@@ -61,6 +61,7 @@ export default defineConfig({
// broken non-recipe styling — check the resolved node_modules path.
"./node_modules/@microbit/ui/src/**/*.{ts,tsx}",
"./node_modules/@microbit/ui-patterns/src/**/*.{ts,tsx}",
+ "./node_modules/@microbit/ui-carousel/src/**/*.{ts,tsx}",
],
outdir: "styled-system",
});
diff --git a/src/App.tsx b/src/App.tsx
index 37a7bae50..e9baa5d36 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,8 +5,9 @@
*/
import { SharedUIProvider, ToastProvider } from "@microbit/ui";
import { polyfill } from "mobile-drag-drop";
-import { useEffect, useMemo } from "react";
+import { useEffect } from "react";
import "./App.css";
+import { deferred } from "./common/deferred";
import { DialogProvider } from "./common/use-dialogs";
import VisualViewPortCSSVariables from "./common/VisualViewportCSSVariables";
import { deployment, useDeployment } from "./deployment";
@@ -22,15 +23,24 @@ import SearchProvider from "./documentation/search/search-hooks";
import { ActiveEditorProvider } from "./editor/active-editor-hooks";
import { FileSystem } from "./fs/fs";
import { FileSystemProvider } from "./fs/fs-hooks";
-import { createHost } from "./fs/host";
+import {
+ openProjectsDatabase,
+ reportProjectStorageMode,
+} from "./fs/current-project";
+import { createHost, IframeHost } from "./fs/host";
+import { parseProjectLink, PendingProjectLink } from "./fs/project-link";
+import { FSStorage } from "./fs/storage";
+import { IframeModeProvider } from "./iframe-mode-hooks";
+import { Projects } from "./project/projects";
+import { ProjectsProvider } from "./project/projects-hooks";
import { fetchMicroPython } from "./micropython/micropython";
import { LanguageServerClientProvider } from "./language-server/language-server-hooks";
import { logDeviceStatusChange } from "./logging/analytics";
import { LoggingProvider } from "./logging/logging-hooks";
import TranslationProvider from "./messages/TranslationProvider";
-import ProjectDropTarget from "./project/ProjectDropTarget";
import { RouterProvider } from "react-router/dom";
import { createRouter } from "./router";
+import StorageErrorToast from "./project/storage-error-toast";
import SessionSettingsProvider from "./settings/session-settings";
import SettingsProvider from "./settings/settings";
import BeforeUnloadDirtyCheck from "./workbench/BeforeUnloadDirtyCheck";
@@ -47,18 +57,49 @@ const device: MicrobitUSBConnection = isMockDeviceMode()
? new MockDeviceConnection()
: createUSBConnection({ logging });
-const host = createHost(logging);
+// The database opens at boot; the project the editor shows is chosen when
+// the editor route loads, so the pages need not pick one.
+const projectStorage = deferred();
+const linkResult = parseProjectLink(window.location.href);
+if (linkResult.status === "unreadable") {
+ // Nothing will consume it, so it has no use in the address.
+ const { pathname, search } = window.location;
+ window.history.replaceState(null, "", pathname + search);
+}
+const projectLink = new PendingProjectLink(
+ linkResult.status === "ok" ? linkResult.link : undefined
+);
+const host = createHost(logging, projectLink, projectStorage.promise);
+const iframeMode = host instanceof IframeHost;
const fs = new FileSystem(logging, host, fetchMicroPython);
+const projects = iframeMode
+ ? undefined
+ : new Projects(
+ fs,
+ logging,
+ openProjectsDatabase(logging),
+ projectStorage,
+ projectLink
+ );
-// If this fails then we retry on access.
+// If this fails then we retry on access. Until a project is opened this
+// waits on the storage, so only in iframe mode does it run straight away.
fs.initializeInBackground();
+// Created once here: a browser router starts running its loaders as soon as
+// it exists, and React's development-mode double render would make two.
+const router = createRouter({ projects });
+
const App = () => {
useEffect(() => {
logging.setUserProperty(
"webusb_available",
"usb" in navigator ? "yes" : "no"
);
+ if (iframeMode) {
+ // Otherwise reported when the projects database opens, or fails to.
+ reportProjectStorageMode(logging, "host");
+ }
const statusListener = (event: ConnectionStatusChange) =>
logDeviceStatusChange(logging, event);
device.addEventListener("status", statusListener);
@@ -75,46 +116,48 @@ const App = () => {
const deployment = useDeployment();
const { ConsentProvider } = deployment.compliance;
- const router = useMemo(() => createRouter(), []);
return (
<>
-
-
-
- {/* Inside TranslationProvider: SharedUIProvider passes the app
+
+
+
+
+ {/* Inside TranslationProvider: SharedUIProvider passes the app
locale to react-aria for its built-in strings, and the
toast region's close label and status announcements are
react-intl messages. */}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
>
);
diff --git a/src/RootLayout.tsx b/src/RootLayout.tsx
index 918edb8d8..168e47aeb 100644
--- a/src/RootLayout.tsx
+++ b/src/RootLayout.tsx
@@ -6,6 +6,8 @@
import { ErrorBoundary, UnexpectedErrorPage } from "@microbit/ui-patterns";
import { useCallback } from "react";
import { Outlet } from "react-router";
+import StorageVersionErrorPage from "./fs/StorageVersionErrorPage";
+import { useStorageVersionError } from "./fs/storage-status";
import { useDeployment } from "./deployment";
import { useLogging } from "./logging/logging-hooks";
@@ -20,6 +22,7 @@ const RootLayout = () => {
(error: unknown) => logging.error("Uncaught render error", error),
[logging]
);
+ const storageVersionError = useStorageVersionError();
return (
{
)}
>
-
+ {storageVersionError ? : }
);
};
diff --git a/src/common/AreaHeading.tsx b/src/common/AreaHeading.tsx
index 63b9a9904..c253c01a3 100644
--- a/src/common/AreaHeading.tsx
+++ b/src/common/AreaHeading.tsx
@@ -10,14 +10,17 @@ import { Box } from "styled-system/jsx";
interface AreaHeadingProps {
name: string;
description: ReactNode;
+ /** Rendered below the description. */
+ children?: ReactNode;
}
-const AreaHeading = ({ name, description }: AreaHeadingProps) => (
+const AreaHeading = ({ name, description, children }: AreaHeadingProps) => (
{name}
{description}
+ {children}
);
diff --git a/src/common/FileDropTarget.tsx b/src/common/FileDropTarget.tsx
index e818f910e..3e34ea3fc 100644
--- a/src/common/FileDropTarget.tsx
+++ b/src/common/FileDropTarget.tsx
@@ -6,9 +6,9 @@
import { ReactNode, useCallback, useState } from "react";
import { RiFolderOpenLine } from "react-icons/ri";
import { useIntl } from "react-intl";
-import { Box, Center } from "styled-system/jsx";
+import { Box, BoxProps, Center } from "styled-system/jsx";
-interface FileDropTargetProps {
+interface FileDropTargetProps extends BoxProps {
children: ReactNode;
onFileDrop: (files: File[]) => void;
"data-testid"?: string;
@@ -16,11 +16,15 @@ interface FileDropTargetProps {
/**
* An area that handles multiple dropped files.
+ *
+ * The drop overlay covers this element's box, so size it to the content it
+ * wraps: the editor fills its parent, the pages grow with their content.
*/
const FileDropTarget = ({
children,
onFileDrop,
"data-testid": dataTestId,
+ ...props
}: FileDropTargetProps) => {
const [dragOver, setDragOver] = useState(false);
@@ -56,7 +60,7 @@ const FileDropTarget = ({
data-testid={dataTestId}
onDragOver={handleDragOver}
position="relative"
- height="100%"
+ {...props}
>
{dragOver && (
{
+ promise: Promise;
+ resolve: (value: T) => void;
+}
+
+export const deferred = (): Deferred => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
diff --git a/src/deployment/default/images/accessibility.svg b/src/deployment/default/images/accessibility.svg
new file mode 100644
index 000000000..b55922589
--- /dev/null
+++ b/src/deployment/default/images/accessibility.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/src/deployment/default/images/banner-background.svg b/src/deployment/default/images/banner-background.svg
new file mode 100644
index 000000000..625fd367a
--- /dev/null
+++ b/src/deployment/default/images/banner-background.svg
@@ -0,0 +1 @@
+
diff --git a/src/deployment/default/images/first-lessons-python.svg b/src/deployment/default/images/first-lessons-python.svg
new file mode 100644
index 000000000..b55922589
--- /dev/null
+++ b/src/deployment/default/images/first-lessons-python.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/src/deployment/default/images/hot-potato-game.jpg b/src/deployment/default/images/hot-potato-game.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/hot-potato-game.jpg differ
diff --git a/src/deployment/default/images/idea-activity-picker.png b/src/deployment/default/images/idea-activity-picker.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-activity-picker.png differ
diff --git a/src/deployment/default/images/idea-clap-lights.png b/src/deployment/default/images/idea-clap-lights.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-clap-lights.png differ
diff --git a/src/deployment/default/images/idea-dice.png b/src/deployment/default/images/idea-dice.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-dice.png differ
diff --git a/src/deployment/default/images/idea-emotion-badge.png b/src/deployment/default/images/idea-emotion-badge.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-emotion-badge.png differ
diff --git a/src/deployment/default/images/idea-frere-jacques.png b/src/deployment/default/images/idea-frere-jacques.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-frere-jacques.png differ
diff --git a/src/deployment/default/images/idea-send-a-smile.png b/src/deployment/default/images/idea-send-a-smile.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-send-a-smile.png differ
diff --git a/src/deployment/default/images/idea-step-counter.png b/src/deployment/default/images/idea-step-counter.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/idea-step-counter.png differ
diff --git a/src/deployment/default/images/indoor-outdoor-thermometer.png b/src/deployment/default/images/indoor-outdoor-thermometer.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/indoor-outdoor-thermometer.png differ
diff --git a/src/deployment/default/images/introducing-python-course.png b/src/deployment/default/images/introducing-python-course.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/introducing-python-course.png differ
diff --git a/src/deployment/default/images/maxmin-temperature-logger.png b/src/deployment/default/images/maxmin-temperature-logger.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/maxmin-temperature-logger.png differ
diff --git a/src/deployment/default/images/microbit-classroom.png b/src/deployment/default/images/microbit-classroom.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/microbit-classroom.png differ
diff --git a/src/deployment/default/images/microbit-labelling-worksheet.jpg b/src/deployment/default/images/microbit-labelling-worksheet.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/microbit-labelling-worksheet.jpg differ
diff --git a/src/deployment/default/images/python-editor-poster-creativity.jpg b/src/deployment/default/images/python-editor-poster-creativity.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/python-editor-poster-creativity.jpg differ
diff --git a/src/deployment/default/images/python-editor-poster-debugging.jpg b/src/deployment/default/images/python-editor-poster-debugging.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/python-editor-poster-debugging.jpg differ
diff --git a/src/deployment/default/images/sensitive-step-counter.jpg b/src/deployment/default/images/sensitive-step-counter.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/sensitive-step-counter.jpg differ
diff --git a/src/deployment/default/images/teleporting-duck.jpg b/src/deployment/default/images/teleporting-duck.jpg
new file mode 100644
index 000000000..32975ea49
Binary files /dev/null and b/src/deployment/default/images/teleporting-duck.jpg differ
diff --git a/src/deployment/default/images/thermometer.png b/src/deployment/default/images/thermometer.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/thermometer.png differ
diff --git a/src/deployment/default/images/treasure-hunt.png b/src/deployment/default/images/treasure-hunt.png
new file mode 100644
index 000000000..667d5f01d
Binary files /dev/null and b/src/deployment/default/images/treasure-hunt.png differ
diff --git a/src/deployment/default/images/troubleshooting.svg b/src/deployment/default/images/troubleshooting.svg
new file mode 100644
index 000000000..b55922589
--- /dev/null
+++ b/src/deployment/default/images/troubleshooting.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/src/deployment/default/images/user-guide.svg b/src/deployment/default/images/user-guide.svg
new file mode 100644
index 000000000..b55922589
--- /dev/null
+++ b/src/deployment/default/images/user-guide.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/src/deployment/default/index.tsx b/src/deployment/default/index.tsx
index 550713d65..6200d6203 100644
--- a/src/deployment/default/index.tsx
+++ b/src/deployment/default/index.tsx
@@ -3,10 +3,72 @@
*
* SPDX-License-Identifier: MIT
*/
-import { BrandConfigFactory } from "..";
+import { BrandConfigFactory, LogoProps } from "..";
+
+// Inline styles rather than Panda, matching the private brand package,
+// which is resolved from node_modules outside Panda's extraction scope.
+const AppLogo = ({ h, color }: LogoProps) => (
+
+ Python Editor
+
+);
+
+// The sidebar header sizes these from their width alone, so a logo without
+// intrinsic height leaves the link that wraps it unclickable.
+const squareLogo = (
+
+
+
+ Py
+
+
+);
+
+const horizontalLogo = (
+
+
+ Python Editor
+
+
+);
const defaultBrandFactory: BrandConfigFactory = () => ({
product: "python-editor",
+ AppLogo,
+ squareLogo,
+ horizontalLogo,
// This isn't ideal as it's the branded version. You can just remove the field to remove the welcome dialog.
welcomeVideoYouTubeId: "mREwMW69qKc",
});
diff --git a/src/deployment/default/panda-preset.ts b/src/deployment/default/panda-preset.ts
index e6503036b..672611094 100644
--- a/src/deployment/default/panda-preset.ts
+++ b/src/deployment/default/panda-preset.ts
@@ -78,8 +78,8 @@ export const appPreset = definePreset({
semanticTokens: {
colors: {
// Sidebar chrome: Container `sidebar-header` bg + the Tabs `sidebar`
- // variant. OSS is flat black; the private preset uses brand colours /
- // a gradient (see the private panda-preset).
+ // variant. OSS is flat black; the private preset uses brand colours
+ // (see the private panda-preset).
sidebarHeaderBg: { value: "black" },
sidebarTablistBg: { value: "black" },
sidebarTabSelectedText: { value: "black" },
@@ -124,6 +124,14 @@ export const appPreset = definePreset({
},
},
},
+ conditions: {
+ extend: {
+ // Short screens (e.g. 1366x768 Chromebooks); reduces card heights and
+ // spacing in the home page projects row. Matches ml-trainer so the
+ // cards are the same size.
+ shortHeight: "@media (max-height: 800px)",
+ },
+ },
});
export default appPreset;
diff --git a/src/deployment/index.ts b/src/deployment/index.ts
index 2271263e9..0822e7896 100644
--- a/src/deployment/index.ts
+++ b/src/deployment/index.ts
@@ -3,7 +3,7 @@
*
* SPDX-License-Identifier: MIT
*/
-import React, { ReactNode, use } from "react";
+import React, { ComponentType, ReactNode, use } from "react";
import { createStubCompliance } from "../compliance/stub";
import { createWebCompliance } from "../compliance/web";
import { Logger } from "../logging/logger";
@@ -29,6 +29,13 @@ export interface BrandConfig {
welcomeVideoYouTubeId?: string;
squareLogo?: ReactNode;
horizontalLogo?: ReactNode;
+ /**
+ * Product wordmark for the page header, e.g. "Python Editor". Draws in
+ * currentColor. Same shape as ml-trainer's so the brand packages match.
+ */
+ AppLogo?: ComponentType;
+ /** Organisation logo shown before the wordmark, e.g. the micro:bit logo. */
+ OrgLogo?: ComponentType;
supportLink?: string;
guideLink?: string;
@@ -37,6 +44,18 @@ export interface BrandConfig {
termsOfUseLink?: string;
privacyPolicyLink?: string;
translationLink?: string;
+ /**
+ * Name shown after the copyright symbol in the home page footer. Omit it
+ * and no copyright line is shown.
+ */
+ copyrightHolder?: string;
+}
+
+export interface LogoProps {
+ /** CSS height, e.g. "20px". */
+ h?: string;
+ /** CSS color; the logos draw in currentColor. */
+ color?: string;
}
export type BrandConfigFactory = (env: Record) => BrandConfig;
diff --git a/src/documentation/common/DocumentationContent.tsx b/src/documentation/common/DocumentationContent.tsx
index 2fd23cb81..47ba4207b 100644
--- a/src/documentation/common/DocumentationContent.tsx
+++ b/src/documentation/common/DocumentationContent.tsx
@@ -43,6 +43,11 @@ interface DocumentationContextValue {
parentSlug?: string;
toolkitType?: string;
title?: string;
+ /**
+ * Links to Reference and API, which navigate the editor's sidebar. False
+ * outside the editor, where they show as plain text.
+ */
+ editorLinks?: boolean;
}
const DocumentationContext = React.createContext({});
@@ -63,10 +68,16 @@ const useCodeEmbedContext = () => {
return { parentSlug, toolkitType, title };
};
+const useEditorLinks = () => use(DocumentationContext).editorLinks !== false;
+
const DocumentationApiLinkMark = (
props: SerializerMarkProps
) => {
const [, setState] = useRouterState();
+ const editorLinks = useEditorLinks();
+ if (!editorLinks) {
+ return <>{props.children}>;
+ }
return (
) => {
const [state, setState] = useRouterState();
+ const editorLinks = useEditorLinks();
+ if (!editorLinks) {
+ return <>{props.children}>;
+ }
return (
{
- const previousAnchor = usePrevious(anchor);
- return !previousAnchor && anchor
- ? "forward"
- : previousAnchor && !anchor
- ? "back"
- : "none";
+ const id = anchor?.id;
+ const [last, setLast] = useState<{
+ id: string | undefined;
+ direction: AnimationDirection;
+ }>({ id, direction: "none" });
+ if (last.id !== id) {
+ const direction: AnimationDirection =
+ !last.id && id ? "forward" : last.id && !id ? "back" : "none";
+ setLast({ id, direction });
+ return direction;
+ }
+ return last.direction;
};
diff --git a/src/documentation/ideas/IdeasDocumentation.tsx b/src/documentation/ideas/IdeasDocumentation.tsx
index 24939aeaa..154c64a8d 100644
--- a/src/documentation/ideas/IdeasDocumentation.tsx
+++ b/src/documentation/ideas/IdeasDocumentation.tsx
@@ -3,10 +3,11 @@
*
* SPDX-License-Identifier: MIT
*/
-import { Link, Text } from "@microbit/ui";
-import { CSSProperties, ReactNode, useCallback, useRef } from "react";
+import { Button, Icon, Link, Text } from "@microbit/ui";
+import { CSSProperties, ReactNode, useCallback, useRef, useState } from "react";
+import { RiInformationLine } from "react-icons/ri";
import { FormattedMessage, useIntl } from "react-intl";
-import { Box, Grid, Stack } from "styled-system/jsx";
+import { Box, Grid, HStack, Stack } from "styled-system/jsx";
import AreaHeading from "../../common/AreaHeading";
import {
docStylesClass,
@@ -26,7 +27,11 @@ import DocumentationContent, {
} from "../common/DocumentationContent";
import ImageWithFallback from "../common/ImageWithFallback";
import { isV2Only } from "../common/model";
+import { useProjectsDatabaseActive } from "../../fs/storage-status";
+import { useIframeMode } from "../../iframe-mode-hooks";
+import { useLogging } from "../../logging/logging-hooks";
import IdeaCard from "./IdeaCard";
+import IdeasMovingDialog from "./IdeasMovingDialog";
import { Idea } from "./model";
import OfflineImageFallback from "../OfflineImageFallback";
import { microbitOrgMiciProjectsUrl } from "../../external-links";
@@ -149,7 +154,9 @@ const ActiveLevel = ({
+ >
+
+
}
>
{
+ const [isOpen, setIsOpen] = useState(false);
+ const learnMoreRef = useRef(null);
+ const logging = useLogging();
+ const iframeMode = useIframeMode();
+ const projectsDatabaseActive = useProjectsDatabaseActive();
+ if (iframeMode || !projectsDatabaseActive) {
+ // There is no home page for the ideas to move to.
+ return null;
+ }
+ return (
+ // Top-aligned so the icon stays on the first line when the text wraps.
+
+ {/* One line of the text high, to centre the icon on the first line. */}
+
+
+
+
+ (
+ {
+ logging.event({ type: "ideas_notice_open" });
+ setIsOpen(true);
+ }}
+ >
+ {chunks}
+
+ ),
+ }}
+ />
+
+ setIsOpen(false)}
+ finalFocusRef={learnMoreRef}
+ />
+
+ );
+};
+
export default IdeasDocumentation;
diff --git a/src/documentation/ideas/IdeasMovingDialog.tsx b/src/documentation/ideas/IdeasMovingDialog.tsx
new file mode 100644
index 000000000..0e474ae6c
--- /dev/null
+++ b/src/documentation/ideas/IdeasMovingDialog.tsx
@@ -0,0 +1,105 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ Button,
+ Link,
+ Modal,
+ ModalBody,
+ ModalCloseButton,
+ ModalFooter,
+ ModalHeader,
+ Text,
+} from "@microbit/ui";
+import { ReactNode, RefObject } from "react";
+import { FormattedMessage } from "react-intl";
+import { Stack } from "styled-system/jsx";
+import { useDeployment } from "../../deployment";
+
+const sections = [
+ { heading: "ideas-moving-what-heading", body: "ideas-moving-what" },
+ { heading: "ideas-moving-why-heading", body: "ideas-moving-why" },
+ { heading: "ideas-moving-when-heading", body: "ideas-moving-when" },
+] as const;
+
+interface IdeasMovingDialogProps {
+ isOpen: boolean;
+ onClose: () => void;
+ finalFocusRef?: RefObject;
+}
+
+const IdeasMovingDialog = ({
+ isOpen,
+ onClose,
+ finalFocusRef,
+}: IdeasMovingDialogProps) => {
+ const { supportLink } = useDeployment();
+ return (
+
+
+
+
+
+
+
+ {sections.map(({ heading, body }) => (
+ }>
+
+
+ ))}
+ {supportLink && (
+ }
+ >
+ (
+
+ {chunks}
+
+ ),
+ }}
+ />
+
+ )}
+
+
+
+
+
+
+
+
+ );
+};
+
+const Section = ({
+ heading,
+ children,
+}: {
+ heading: ReactNode;
+ children: ReactNode;
+}) => (
+
+
+ {heading}
+
+ {children}
+
+);
+
+export default IdeasMovingDialog;
diff --git a/src/documentation/ideas/idea-code.ts b/src/documentation/ideas/idea-code.ts
new file mode 100644
index 000000000..8a1b74488
--- /dev/null
+++ b/src/documentation/ideas/idea-code.ts
@@ -0,0 +1,19 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { PortableText } from "../../common/sanity";
+import { Idea } from "./model";
+
+const isCode = (
+ block: PortableText[number]
+): block is { _type: "python"; main: string } => block._type === "python";
+
+/** The idea's program: its content's first code block. */
+export const ideaCode = (idea: Idea): string | undefined =>
+ idea.content?.find(isCode)?.main;
+
+/** The idea's content without its code, for showing beside the code. */
+export const withoutCode = (content: PortableText | undefined): PortableText =>
+ (content ?? []).filter((block) => !isCode(block));
diff --git a/src/e2e/accessibility.test.ts b/src/e2e/accessibility.test.ts
index d39bed3aa..906f1fe7a 100644
--- a/src/e2e/accessibility.test.ts
+++ b/src/e2e/accessibility.test.ts
@@ -83,7 +83,7 @@ test.describe("accessibility scans", () => {
});
test("create file dialog", async ({ app }) => {
- await app.switchTab("Project");
+ await app.switchTab("Files");
await app.page.getByRole("button", { name: "Create file" }).click();
const name = app.page.getByLabel("Name*");
await name.waitFor();
@@ -94,11 +94,17 @@ test.describe("accessibility scans", () => {
});
test("file actions menu", async ({ app }) => {
- await app.switchTab("Project");
+ await app.switchTab("Files");
await app.projectTab.openFileActionsMenu("main.py");
await app.expectNoNewAccessibilityViolations();
});
+ test("breadcrumb file menu", async ({ app }) => {
+ await app.page.getByRole("button", { name: /choose a file/ }).click();
+ await app.page.getByRole("menuitemradio").first().waitFor();
+ await app.expectNoNewAccessibilityViolations();
+ });
+
test("search results", async ({ app }) => {
await app.search("loop");
await app.page.getByRole("dialog").getByRole("link").first().waitFor();
diff --git a/src/e2e/app-test-fixtures.ts b/src/e2e/app-test-fixtures.ts
index 2d84dda53..7e5077e77 100644
--- a/src/e2e/app-test-fixtures.ts
+++ b/src/e2e/app-test-fixtures.ts
@@ -1,20 +1,36 @@
import { test as base } from "@playwright/test";
-import { App } from "./app.js";
+import { App, baseUrl } from "./app.js";
+import { HomePage } from "./home-page.js";
+import { ProjectsPage } from "./projects-page.js";
type MyFixtures = {
app: App;
+ homePage: HomePage;
+ projectsPage: ProjectsPage;
};
-export const test = base.extend({
- app: async ({ page, context }, use) => {
- const app = new App(page, context);
+type Options = {
+ /** Hide IndexedDB so the editor falls back to session storage. */
+ noIndexedDB: boolean;
+ /** Open the editor before the test. Off for tests that embed it. */
+ autoGoto: boolean;
+};
+
+export const test = base.extend({
+ noIndexedDB: [false, { option: true }],
+ autoGoto: [true, { option: true }],
+ // On the context rather than the app fixture: the compliance notice is a
+ // modal dialog that hides the page from the accessibility tree, so a test
+ // that only drives the pages needs the cookie just as much as one that
+ // drives the editor.
+ context: async ({ context, noIndexedDB }, use) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await context.addCookies([
{
// See corresponding code in App.tsx.
name: "mockDevice",
value: "1",
- url: app.baseUrl,
+ url: baseUrl,
},
// Don't show compliance notice for Foundation builds
{
@@ -26,10 +42,31 @@ export const test = base.extend({
functional: true,
})
),
- url: app.baseUrl,
+ url: baseUrl,
},
]);
- await app.goto();
+ if (noIndexedDB) {
+ await context.addInitScript(() => {
+ // The getter lives on the prototype so an own property is needed.
+ Object.defineProperty(window, "indexedDB", {
+ value: undefined,
+ configurable: true,
+ });
+ });
+ }
+ await use(context);
+ },
+ app: async ({ page, context, autoGoto }, use) => {
+ const app = new App(page, context);
+ if (autoGoto) {
+ await app.goto();
+ }
await use(app);
},
+ homePage: async ({ page }, use) => {
+ await use(new HomePage(page));
+ },
+ projectsPage: async ({ page }, use) => {
+ await use(new ProjectsPage(page));
+ },
});
diff --git a/src/e2e/app.ts b/src/e2e/app.ts
index 2af7cb65d..866d76b57 100644
--- a/src/e2e/app.ts
+++ b/src/e2e/app.ts
@@ -18,63 +18,30 @@ import { readFileSync } from "fs";
import { DeviceErrorCode } from "@microbit/microbit-connection";
import { expectNoNewViolations } from "./axe.js";
-export enum LoadDialogType {
- CONFIRM,
- REPLACE,
- CONFIRM_BUT_LOAD_AS_MODULE,
- NONE,
-}
-
export interface BrowserDownload {
filename: string;
data: Buffer;
}
// E2E_PORT points the suite at a server on another port.
-const baseUrl = `http://localhost:${process.env.E2E_PORT ?? "3000"}`;
+export const baseUrl = `http://localhost:${process.env.E2E_PORT ?? "3000"}`;
-interface UrlOptions {
+// We didn't use BASE_URL here as CRA seems to set it to "" before running jest.
+// Maybe can be changed since the Vite upgrade.
+const basePath = process.env.E2E_BASE_URL ?? "/";
+
+export interface UrlOptions {
flags?: Flag[];
fragment?: string;
language?: string;
+ /** Iframe controller mode, as embedded by classroom. */
+ controller?: boolean;
}
interface SaveOptions {
waitForDownload: boolean;
}
-class LoadDialog {
- private confirmButton: Locator;
- private replaceButton: Locator;
- private optionsButton: Locator;
- private type: LoadDialogType;
-
- constructor(public readonly page: Page, type: LoadDialogType) {
- this.type = type;
- this.confirmButton = this.page.getByRole("button", { name: "Confirm" });
- this.replaceButton = this.page.getByRole("button", { name: "Replace" });
- this.optionsButton = this.page.getByRole("button", {
- name: "Options",
- exact: true,
- });
- }
-
- async submit() {
- switch (this.type) {
- case LoadDialogType.CONFIRM:
- return await this.confirmButton.click();
- case LoadDialogType.REPLACE:
- return await this.replaceButton.click();
- case LoadDialogType.CONFIRM_BUT_LOAD_AS_MODULE:
- await this.optionsButton.click();
- await this.page.getByText(/^(Add|Replace) file .+\.py$/).click();
- return await this.confirmButton.click();
- default:
- return;
- }
- }
-}
-
class FileActionsMenu {
public saveButton: Locator;
public editButton: Locator;
@@ -102,8 +69,8 @@ class ProjectTabPanel {
private openButton: Locator;
constructor(public readonly page: Page) {
this.openButton = this.page
- .getByRole("tabpanel", { name: "Project" })
- .getByTestId("open");
+ .getByRole("tabpanel", { name: "Files" })
+ .getByTestId("add-files");
}
async openFileActionsMenu(filename: string) {
@@ -281,7 +248,7 @@ export class App {
}
async goto(options: UrlOptions = {}) {
- await this.page.goto(optionsToURL(options));
+ await this.page.goto(editorUrl(options));
// Wait for the page to be loaded
await this.editor.waitFor();
}
@@ -291,7 +258,7 @@ export class App {
}
async setProjectName(projectName: string): Promise {
- await this.page.getByRole("button", { name: "Edit project name" }).click();
+ await this.page.getByRole("button", { name: /edit project name/i }).click();
await this.page.getByLabel("Name*").fill(projectName);
await this.page.getByRole("button", { name: "Confirm" }).click();
}
@@ -339,12 +306,12 @@ export class App {
}
}
- async switchTab(tabName: "Project" | "API" | "Reference" | "Ideas") {
+ async switchTab(tabName: "Files" | "API" | "Reference" | "Ideas") {
await this.page.getByRole("tab", { name: tabName }).click();
}
async createNewFile(name: string): Promise {
- await this.switchTab("Project");
+ await this.switchTab("Files");
await this.page.getByRole("button", { name: "Create file" }).click();
await this.page.getByLabel("Name*").fill(name);
await this.page
@@ -352,12 +319,6 @@ export class App {
.click();
}
- async resetProject(): Promise {
- await this.switchTab("Project");
- await this.page.getByRole("button", { name: "Reset project" }).click();
- await this.page.getByRole("button", { name: "Replace" }).click();
- }
-
async expectEditorContainText(match: RegExp | string) {
// Scroll to the top of code text area
await this.editorTextArea.click();
@@ -366,32 +327,33 @@ export class App {
}
async expectProjectFiles(expected: string[]): Promise {
- await this.switchTab("Project");
- await expect(this.page.getByRole("listitem")).toHaveText(expected);
+ await this.switchTab("Files");
+ await expect(
+ this.page.getByRole("tabpanel", { name: "Files" }).getByRole("listitem")
+ ).toHaveText(expected);
}
- async loadFiles(
- filePathFromProjectRoot: string,
- options: { acceptDialog?: LoadDialogType } = {}
- ) {
- await this.switchTab("Project");
+ /** Adds files from the Files tab; a hex opens as a new project. */
+ async loadFiles(filePathFromProjectRoot: string) {
+ await this.switchTab("Files");
await this.projectTab.chooseFile(filePathFromProjectRoot);
-
- if (options.acceptDialog !== undefined) {
- const loadDialog = new LoadDialog(this.page, options.acceptDialog);
- await loadDialog.submit();
- }
}
+ /**
+ * Drops a file on a drop target. The default is the editor's; the home and
+ * projects pages have their own.
+ */
async dropFile(
filePathFromProjectRoot: string,
- options: { acceptDialog?: LoadDialogType } = {}
+ target: string = "project-drop-target"
) {
const filePath = getAbsoluteFilePath(filePathFromProjectRoot);
const filename = getFilename(filePathFromProjectRoot);
- // Wait for page to load
- await this.saveButton.waitFor();
+ if (target === "project-drop-target") {
+ // Wait for page to load
+ await this.saveButton.waitFor();
+ }
// Playwright drag and drop file method taken from
// https://github.com/microsoft/playwright/issues/10667#issuecomment-998397241
@@ -408,17 +370,25 @@ export class App {
// Drag file over target area to reveal drop zone
await this.page
- .getByTestId("project-drop-target")
+ .getByTestId(target)
.dispatchEvent("dragover", { dataTransfer });
- const dropZone = this.page.getByTestId("project-drop-target-overlay");
+ const dropZone = this.page.getByTestId(`${target}-overlay`);
await dropZone.waitFor();
await dropZone.dispatchEvent("drop", { dataTransfer });
+ }
- if (options.acceptDialog !== undefined) {
- const loadDialog = new LoadDialog(this.page, options.acceptDialog);
- await loadDialog.submit();
- }
+ /** No drop overlay left showing after a drop. */
+ async expectNoDropOverlay(): Promise {
+ await expect(this.page.locator('[data-testid$="-overlay"]')).toHaveCount(0);
+ }
+
+ /** Answers the open confirmation dialog. */
+ async answerDialog(buttonName: string): Promise {
+ await this.page
+ .getByRole("alertdialog")
+ .getByRole("button", { name: buttonName })
+ .click();
}
async expectAlertText(title: string, description?: string): Promise {
@@ -429,19 +399,19 @@ export class App {
}
async isDeleteFileOptionDisabled(filename: string) {
- await this.switchTab("Project");
+ await this.switchTab("Files");
const fileOptionMenu = await this.projectTab.openFileActionsMenu(filename);
return await fileOptionMenu.deleteButton.isDisabled();
}
async isEditFileOptionDisabled(filename: string) {
- await this.switchTab("Project");
+ await this.switchTab("Files");
const fileOptionMenu = await this.projectTab.openFileActionsMenu(filename);
return await fileOptionMenu.editButton.isDisabled();
}
async editFile(filename: string): Promise {
- await this.switchTab("Project");
+ await this.switchTab("Files");
const fileOptionMenu = await this.projectTab.openFileActionsMenu(filename);
await fileOptionMenu.editButton.click();
}
@@ -486,7 +456,7 @@ export class App {
}
async deleteFile(filename: string) {
- await this.switchTab("Project");
+ await this.switchTab("Files");
const fileOptionMenu = await this.projectTab.openFileActionsMenu(filename);
await fileOptionMenu.delete();
}
@@ -500,19 +470,28 @@ export class App {
await this.page.getByRole("button", { name: "Close" }).click();
}
- async closeAndExpectBeforeUnloadDialogVisible(
- visible: boolean
- ): Promise {
- if (visible) {
- this.page.on("dialog", async (dialog) => {
- expect(dialog.type() === "beforeunload").toEqual(visible);
-
- // Though https://playwright.dev/docs/api/class-page#page-event-dialog
- // says that dialog.dismiss() is needed otherwise the page will freeze,
- // in practice, it appears that the dialog is dismissed automatically.
- });
- }
+ async closeWithoutBeforeUnloadPrompt(): Promise {
+ expect(await this.closeAndCollectDialogs()).not.toContain("beforeunload");
+ }
+
+ async closeAndExpectBeforeUnloadPrompt(): Promise {
+ expect(await this.closeAndCollectDialogs()).toContain("beforeunload");
+ }
+
+ /**
+ * Playwright accepts a beforeunload dialog itself if nobody listens, so
+ * listen to see it. Any dialog is handled before the page can close.
+ */
+ private async closeAndCollectDialogs(): Promise {
+ const dialogs: string[] = [];
+ this.page.on("dialog", async (dialog) => {
+ dialogs.push(dialog.type());
+ await dialog.accept();
+ });
+ const closed = this.page.waitForEvent("close");
await this.page.close({ runBeforeUnload: true });
+ await closed;
+ return dialogs;
}
async expectDocumentationTopLevelHeading(
@@ -770,11 +749,23 @@ export class App {
}
async expectFocusOnLoad(): Promise {
- const link = this.page.getByLabel(
- "visit microbit.org (opens in a new tab)"
- );
+ // The logo's home link leads the sidebar header.
await this.page.keyboard.press("Tab");
- await expect(link).toBeFocused();
+ await expect(this.homeLink).toBeFocused();
+ }
+
+ private get homeLink() {
+ // The logo's, ahead of the sidebar's own home link.
+ return this.page.getByRole("link", { name: "Home" }).first();
+ }
+
+ /**
+ * Follows the sidebar logo to the home page. Only available with the
+ * projects database active outside iframe mode; otherwise the logo links
+ * to microbit.org.
+ */
+ async goHome(): Promise {
+ await this.homeLink.click();
}
async assertFocusOnSidebar(): Promise {
@@ -823,12 +814,38 @@ export const getFilename = (filePath: string) => {
return filename;
};
-const getAbsoluteFilePath = (filePathFromProjectRoot: string) => {
+export const getAbsoluteFilePath = (filePathFromProjectRoot: string) => {
const dir = path.dirname(fileURLToPath(import.meta.url));
return path.join(dir.replace("src/e2e", ""), filePathFromProjectRoot);
};
-const optionsToURL = (options: UrlOptions): string => {
+export const editorUrl = (options: UrlOptions = {}): string =>
+ // In controller mode the editor is the only page and stays at the root.
+ appUrl(options.controller ? "" : "project", options);
+
+export const homeUrl = (options: UrlOptions = {}): string =>
+ appUrl("", options);
+
+export const projectsPageUrl = (options: UrlOptions = {}): string =>
+ appUrl("projects", options);
+
+/**
+ * @param path The page's path within the app, without a leading slash.
+ */
+/**
+ * Matches a page's URL, wherever the app is deployed. The base URL's trailing
+ * slash is optional: the app's own links to the home page are without it.
+ *
+ * @param path The page's path within the app, without a leading slash.
+ */
+export const appUrlPattern = (path: string = ""): RegExp => {
+ const prefix = (baseUrl + basePath + path).replace(/\/$/, "");
+ return new RegExp(
+ `^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/?([?#]|$)`
+ );
+};
+
+export const appUrl = (path: string, options: UrlOptions = {}): string => {
const flags = new Set([
"none",
"noWelcome",
@@ -841,11 +858,13 @@ const optionsToURL = (options: UrlOptions): string => {
if (options.language) {
params.push(["l", options.language]);
}
+ if (options.controller) {
+ params.push(["controller", "1"]);
+ }
return (
baseUrl +
- // We didn't use BASE_URL here as CRA seems to set it to "" before running jest.
- // Maybe can be changed since the Vite upgrade.
- (process.env.E2E_BASE_URL ?? "/") +
+ basePath +
+ path +
"?" +
new URLSearchParams(params).toString() +
(options.fragment ?? "")
diff --git a/src/e2e/documentation.test.ts b/src/e2e/documentation.test.ts
index a3da31044..8aab254c3 100644
--- a/src/e2e/documentation.test.ts
+++ b/src/e2e/documentation.test.ts
@@ -3,6 +3,7 @@
*
* SPDX-License-Identifier: MIT
*/
+import { expect } from "@playwright/test";
import { test } from "./app-test-fixtures.js";
test.describe("documentation", () => {
@@ -79,6 +80,28 @@ test.describe("documentation", () => {
);
});
+ test("Ideas tab explains that ideas are moving to the home page", async ({
+ app,
+ }) => {
+ await app.switchTab("Ideas");
+ await expect(
+ app.page.getByText("Ideas are moving to the Home page.")
+ ).toBeVisible();
+ await app.expectNoNewAccessibilityViolations();
+
+ const learnMore = app.page.getByRole("button", { name: "Learn more" });
+ await learnMore.click();
+ const dialog = app.page.getByRole("dialog");
+ await expect(
+ dialog.getByRole("heading", { name: "Ideas are moving to the Home page" })
+ ).toBeVisible();
+ await app.expectNoNewAccessibilityViolations();
+
+ await app.page.keyboard.press("Escape");
+ await expect(dialog).toBeHidden();
+ await expect(learnMore).toBeFocused();
+ });
+
test("Select an idea", async ({ app }) => {
const ideaName = "Emotion badge";
await app.switchTab("Ideas");
diff --git a/src/e2e/edits.test.ts b/src/e2e/edits.test.ts
index 356dcf528..55f3f0782 100644
--- a/src/e2e/edits.test.ts
+++ b/src/e2e/edits.test.ts
@@ -7,25 +7,29 @@ import { test } from "./app-test-fixtures.js";
test.describe("edits", () => {
test("doesn't prompt on close if no edits made", async ({ app }) => {
- await app.closeAndExpectBeforeUnloadDialogVisible(false);
+ await app.closeWithoutBeforeUnloadPrompt();
});
- test("prompts on close if file edited", async ({ app }) => {
+ test("doesn't prompt on close if file edited, as the project is saved", async ({
+ app,
+ }) => {
await app.typeInEditor("A change!");
await app.expectEditorContainText(/A change/);
- await app.closeAndExpectBeforeUnloadDialogVisible(true);
+ await app.closeWithoutBeforeUnloadPrompt();
});
- test("prompts on close if project name edited", async ({ app }) => {
+ test("doesn't prompt on close if project name edited, as the project is saved", async ({
+ app,
+ }) => {
const name = "idiosyncratic ruminant";
await app.setProjectName(name);
await app.expectProjectName(name);
- await app.closeAndExpectBeforeUnloadDialogVisible(true);
+ await app.closeWithoutBeforeUnloadPrompt();
});
- test("retains text across a reload via session storage", async ({ app }) => {
+ test("retains text across a reload", async ({ app }) => {
await app.typeInEditor("A change!");
await app.expectEditorContainText(/A change/);
@@ -33,4 +37,20 @@ test.describe("edits", () => {
await app.expectEditorContainText(/A change/);
});
+
+ test("retains text across a reload straight after typing", async ({
+ app,
+ }) => {
+ // Writes are coalesced for a few hundred milliseconds, so this relies on
+ // the pending ones being flushed as the page unloads. The clock is held
+ // so the write cannot land by its timer first. It can only be held at a
+ // time the page has not reached, hence the margin.
+ await app.page.clock.install();
+ await app.page.clock.pauseAt(Date.now() + 1000);
+ await app.editorTextArea.fill("A change!");
+ await app.page.reload();
+ await app.page.clock.resume();
+
+ await app.expectEditorContainText(/A change/);
+ });
});
diff --git a/src/e2e/home-page.ts b/src/e2e/home-page.ts
new file mode 100644
index 000000000..6c2134a6e
--- /dev/null
+++ b/src/e2e/home-page.ts
@@ -0,0 +1,132 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect, Locator, Page } from "@playwright/test";
+import { appUrlPattern, getAbsoluteFilePath, homeUrl } from "./app.js";
+import { expectNoNewViolations } from "./axe.js";
+
+/**
+ * The modal dialog rather than a menu popover, which also has the dialog
+ * role. Modals render on a section; popovers are divs.
+ */
+export const modalDialog = (page: Page): Locator =>
+ page.getByRole("dialog").and(page.locator("section"));
+
+/**
+ * The project cards and their menus, shared by the home and projects pages.
+ */
+export class ProjectCards {
+ constructor(public readonly page: Page) {}
+
+ card(name: string): Locator {
+ return this.page.getByRole("button", { name, exact: true });
+ }
+
+ async open(name: string): Promise {
+ await this.card(name).click();
+ }
+
+ async expectVisible(name: string): Promise {
+ await expect(this.card(name)).toBeVisible();
+ }
+
+ async expectNotVisible(name: string): Promise {
+ await expect(this.card(name)).toBeHidden();
+ }
+
+ async openMenu(name: string): Promise {
+ await this.page
+ .getByRole("button", { name: `${name} actions menu`, exact: true })
+ .click();
+ }
+
+ async menuOpen(name: string): Promise {
+ await this.openMenu(name);
+ await this.page.getByRole("menuitem", { name: "Open" }).click();
+ }
+
+ async menuRename(name: string, newName: string): Promise {
+ await this.openMenu(name);
+ await this.page.getByRole("menuitem", { name: "Rename" }).click();
+ await this.fillNameDialog(newName, "Rename");
+ }
+
+ async menuDuplicate(name: string, newName: string): Promise {
+ await this.openMenu(name);
+ await this.page.getByRole("menuitem", { name: "Duplicate" }).click();
+ await this.fillNameDialog(newName, "Duplicate");
+ }
+
+ async menuDelete(name: string): Promise {
+ await this.openMenu(name);
+ await this.page.getByRole("menuitem", { name: "Delete" }).click();
+ await this.confirmDelete();
+ }
+
+ async fillNameDialog(newName: string, confirmLabel: string): Promise {
+ const dialog = modalDialog(this.page);
+ await expect(dialog).toBeVisible();
+ const nameInput = dialog.getByRole("textbox");
+ await nameInput.fill(newName);
+ await dialog.getByRole("button", { name: confirmLabel }).click();
+ await expect(dialog).toBeHidden();
+ }
+
+ async confirmDelete(): Promise {
+ const dialog = this.page.getByRole("alertdialog");
+ await expect(dialog).toBeVisible();
+ // "Delete", or "Delete N projects" for a selection.
+ await dialog.getByRole("button", { name: /^Delete/ }).click();
+ await expect(dialog).toBeHidden();
+ }
+}
+
+export class HomePage {
+ public cards: ProjectCards;
+ private projectsHeading: Locator;
+
+ constructor(public readonly page: Page) {
+ this.cards = new ProjectCards(page);
+ this.projectsHeading = page.getByRole("heading", { name: "My projects" });
+ }
+
+ async goto(): Promise {
+ await this.page.goto(homeUrl());
+ await this.expectOnPage();
+ }
+
+ async expectOnPage(): Promise {
+ await expect(this.projectsHeading).toBeVisible();
+ await expect(this.page).toHaveURL(appUrlPattern());
+ }
+
+ async expectNoNewAccessibilityViolations(): Promise {
+ await expectNoNewViolations(this.page);
+ }
+
+ /** Creates a project, accepting the default name unless one is given. */
+ async newProject(name?: string): Promise {
+ await this.page.getByRole("button", { name: "New project" }).click();
+ if (name !== undefined) {
+ await this.cards.fillNameDialog(name, "Create");
+ } else {
+ await modalDialog(this.page)
+ .getByRole("button", { name: "Create" })
+ .click();
+ }
+ }
+
+ /** Imports a file from the projects row as a new project. */
+ async importFile(filePathFromProjectRoot: string): Promise {
+ const fileChooserPromise = this.page.waitForEvent("filechooser");
+ await this.page.getByRole("button", { name: "Import" }).click();
+ const fileChooser = await fileChooserPromise;
+ await fileChooser.setFiles(getAbsoluteFilePath(filePathFromProjectRoot));
+ }
+
+ async viewAllProjects(): Promise {
+ await this.page.getByRole("link", { name: "View all" }).click();
+ }
+}
diff --git a/src/e2e/home.test.ts b/src/e2e/home.test.ts
new file mode 100644
index 000000000..744a6d4f1
--- /dev/null
+++ b/src/e2e/home.test.ts
@@ -0,0 +1,217 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect } from "@playwright/test";
+import { appUrlPattern } from "./app.js";
+import { test } from "./app-test-fixtures.js";
+import { modalDialog } from "./home-page.js";
+
+test.describe("home page", () => {
+ // The app fixture sets up the context; these tests start from home.
+ test.use({ autoGoto: false });
+
+ test("shows the banner and the resource rows", async ({ homePage }) => {
+ await homePage.goto();
+ await expect(
+ homePage.page.getByRole("heading", {
+ name: "Python for the BBC micro:bit",
+ })
+ ).toBeVisible();
+ for (const row of [
+ "Ideas",
+ "Teacher resources",
+ "Make it: code it projects",
+ "Help",
+ ]) {
+ await expect(
+ homePage.page.getByRole("heading", { name: row, exact: true })
+ ).toBeVisible();
+ }
+ await homePage.expectNoNewAccessibilityViolations();
+ });
+
+ test("creates a project and opens it in the editor", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Night light");
+
+ await app.expectProjectName("Night light");
+ await expect(app.page).toHaveURL(appUrlPattern("project"));
+ await app.expectEditorContainText("from microbit import");
+ });
+
+ test("opens an idea from its dialog as a project showing the idea", async ({
+ app,
+ homePage,
+ }) => {
+ const ideaName = "Emotion badge";
+ await homePage.goto();
+ await homePage.page.getByRole("button", { name: ideaName }).click();
+ const dialog = homePage.page.getByRole("dialog");
+ await expect(
+ dialog.getByRole("heading", { name: ideaName, exact: true })
+ ).toBeVisible();
+ const create = dialog.getByRole("button", { name: "Create", exact: true });
+ // Enabled once the idea's code has loaded.
+ await expect(create).toBeEnabled();
+ await homePage.expectNoNewAccessibilityViolations();
+
+ await create.click();
+
+ await expect(app.page).toHaveURL(
+ appUrlPattern("project/ideas/emotion-badge")
+ );
+ await app.expectProjectName(ideaName);
+ await expect(
+ app.page.getByRole("tab", { name: "Ideas", selected: true })
+ ).toBeVisible();
+ await app.expectDocumentationTopLevelHeading(ideaName);
+ await app.expectEditorContainText("from microbit import");
+ });
+
+ test("returns home from the editor with the project listed", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Night light");
+ await app.expectProjectName("Night light");
+
+ await app.goHome();
+
+ await homePage.expectOnPage();
+ await homePage.cards.expectVisible("Night light");
+ });
+
+ test("reopens a project from its card with the edits kept", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Night light");
+ await app.expectProjectName("Night light");
+ await app.typeInEditor("# a change");
+ await app.expectEditorContainText("# a change");
+ await app.goHome();
+ await homePage.expectOnPage();
+ await homePage.newProject("Other");
+ await app.expectProjectName("Other");
+ await app.goHome();
+ await homePage.expectOnPage();
+
+ await homePage.cards.open("Night light");
+
+ await app.expectProjectName("Night light");
+ await app.expectEditorContainText("# a change");
+ });
+
+ // The helpers above pass straight through these states.
+ test("scans a project card, its menu and dialogs", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.page.getByRole("button", { name: "New project" }).click();
+ await expect(modalDialog(homePage.page)).toBeVisible();
+ await homePage.expectNoNewAccessibilityViolations();
+ await homePage.cards.fillNameDialog("Night light", "Create");
+ await app.expectProjectName("Night light");
+ await app.goHome();
+ await homePage.cards.expectVisible("Night light");
+ await homePage.expectNoNewAccessibilityViolations();
+
+ await homePage.cards.openMenu("Night light");
+ const rename = homePage.page.getByRole("menuitem", { name: "Rename" });
+ await expect(rename).toBeVisible();
+ await homePage.expectNoNewAccessibilityViolations();
+
+ await rename.click();
+ await expect(modalDialog(homePage.page)).toBeVisible();
+ await homePage.expectNoNewAccessibilityViolations();
+ await homePage.page.keyboard.press("Escape");
+ await expect(modalDialog(homePage.page)).toBeHidden();
+
+ await homePage.cards.openMenu("Night light");
+ await homePage.page.getByRole("menuitem", { name: "Delete" }).click();
+ await expect(homePage.page.getByRole("alertdialog")).toBeVisible();
+ await homePage.expectNoNewAccessibilityViolations();
+ });
+
+ test("renames, duplicates and deletes from the card menu", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Night light");
+ await app.expectProjectName("Night light");
+ await app.goHome();
+ await homePage.expectOnPage();
+
+ await homePage.cards.menuRename("Night light", "Day light");
+ await homePage.cards.expectVisible("Day light");
+ await homePage.cards.expectNotVisible("Night light");
+
+ await homePage.cards.menuDuplicate("Day light", "Copy of Day light");
+ await homePage.cards.expectVisible("Copy of Day light");
+ await homePage.cards.expectVisible("Day light");
+
+ await homePage.cards.menuDelete("Day light");
+ await homePage.cards.expectNotVisible("Day light");
+ await homePage.cards.expectVisible("Copy of Day light");
+ });
+
+ test("imports a hex as a new project", async ({ app, homePage }) => {
+ await homePage.goto();
+ await homePage.importFile("testData/1.0.1.hex");
+
+ await app.expectProjectName("1.0.1");
+ await app.expectEditorContainText(/PASS1/);
+ await app.goHome();
+ await homePage.cards.expectVisible("1.0.1");
+ });
+
+ test("imports a Python script as a new project named after it", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.importFile("testData/samplefile.py");
+
+ await app.expectProjectName("samplefile");
+ await app.expectProjectFiles(["main.py"]);
+ });
+
+ test("a dropped hex opens as a new project with no overlay left", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await app.dropFile("testData/1.0.1.hex", "home-drop-target");
+
+ await app.expectProjectName("1.0.1");
+ await app.expectNoDropOverlay();
+ });
+
+ test("keeps projects across a reload", async ({ app, homePage }) => {
+ await homePage.goto();
+ await homePage.newProject("Night light");
+ await app.expectProjectName("Night light");
+ await app.goHome();
+ await homePage.expectOnPage();
+
+ await homePage.page.reload();
+
+ await homePage.expectOnPage();
+ await homePage.cards.expectVisible("Night light");
+ });
+
+ test("links to the projects page", async ({ homePage, projectsPage }) => {
+ await homePage.goto();
+ await homePage.viewAllProjects();
+ await projectsPage.expectOnPage();
+ });
+});
diff --git a/src/e2e/iframe.test.ts b/src/e2e/iframe.test.ts
new file mode 100644
index 000000000..a96b46523
--- /dev/null
+++ b/src/e2e/iframe.test.ts
@@ -0,0 +1,155 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect, FrameLocator, Page } from "@playwright/test";
+import { editorUrl } from "./app.js";
+import { test } from "./app-test-fixtures.js";
+
+interface EditorMessage {
+ type: "pyeditor";
+ action: string;
+ project?: { files: Record };
+}
+
+const hostCode = "display.scroll('from the host')";
+
+/**
+ * The host page is served by intercepting a request for it and is defined
+ * here, in the tests, so it is never part of the app.
+ */
+const hostPage = (editorSrc: string) => `
+Iframe host harness
+
+
+`;
+
+const hostUrl = new URL("e2e-iframe-host.html", editorUrl()).href;
+
+const openEmbeddedEditor = async (page: Page): Promise => {
+ await page.route(hostUrl, (route) =>
+ route.fulfill({
+ contentType: "text/html",
+ body: hostPage(editorUrl({ controller: true })),
+ })
+ );
+ await page.goto(hostUrl);
+ const frame = page.frameLocator("iframe[name='editor']");
+ await frame.getByTestId("editor").waitFor();
+ return frame;
+};
+
+const editorText = (frame: FrameLocator) =>
+ frame.getByTestId("editor").getByRole("textbox");
+
+// fill() on the CodeMirror contenteditable sometimes inserts rather than
+// replaces, so select everything first.
+const replaceEditorText = async (
+ page: Page,
+ frame: FrameLocator,
+ text: string
+) => {
+ await editorText(frame).click();
+ await page.keyboard.press(
+ process.platform === "darwin" ? "Meta+a" : "Control+a"
+ );
+ await page.keyboard.type(text);
+};
+
+// Set by the host harness page. Evaluate callbacks run in the page, so the
+// cast has to be repeated inside each rather than shared.
+const receivedActions = (page: Page) =>
+ page.evaluate(() =>
+ (window as unknown as { messages: EditorMessage[] }).messages.map(
+ (m) => m.action
+ )
+ );
+
+const lastSavedMain = (page: Page) =>
+ page.evaluate(() => {
+ const { messages } = window as unknown as { messages: EditorMessage[] };
+ const saves = messages.filter((m) => m.action === "workspacesave");
+ const encoded = saves[saves.length - 1]?.project?.files["main.py"];
+ return encoded === undefined ? undefined : atob(encoded);
+ });
+
+/**
+ * Controller mode, as embedded by classroom: the host owns the project and
+ * there is no storage or project management in the editor.
+ */
+test.describe("iframe controller mode", () => {
+ test.use({ autoGoto: false });
+
+ test("loads the host's project and reports back edits", async ({ app }) => {
+ const frame = await openEmbeddedEditor(app.page);
+
+ await expect(editorText(frame)).toContainText("from the host");
+ expect(await receivedActions(app.page)).toEqual([
+ "workspacesync",
+ "workspaceloaded",
+ ]);
+
+ await replaceEditorText(app.page, frame, "display.scroll('edited')");
+ await expect
+ .poll(() => lastSavedMain(app.page))
+ .toEqual("display.scroll('edited')");
+ });
+
+ test("replaces the project when the host imports one", async ({ app }) => {
+ const frame = await openEmbeddedEditor(app.page);
+ await expect(editorText(frame)).toContainText("from the host");
+
+ await app.page.evaluate(() => {
+ const editor = document.querySelector("iframe")!.contentWindow!;
+ editor.postMessage(
+ {
+ type: "pyeditor",
+ action: "importproject",
+ project: "display.scroll('imported')",
+ },
+ "*"
+ );
+ });
+
+ await expect(editorText(frame)).toContainText("imported");
+ });
+
+ test("prompts on close if file edited, as the host may not have saved", async ({
+ app,
+ }) => {
+ const frame = await openEmbeddedEditor(app.page);
+ await expect(editorText(frame)).toContainText("from the host");
+
+ await replaceEditorText(app.page, frame, "display.scroll('edited')");
+ await expect(editorText(frame)).toContainText("edited");
+
+ await app.closeAndExpectBeforeUnloadPrompt();
+ });
+
+ test("does not say ideas are moving, as there is no home page", async ({
+ app,
+ }) => {
+ const frame = await openEmbeddedEditor(app.page);
+ await frame.getByRole("tab", { name: "Ideas" }).click();
+ await expect(
+ frame.getByRole("heading", { name: "Ideas", exact: true })
+ ).toBeVisible();
+ await expect(
+ frame.getByRole("button", { name: "Learn more" })
+ ).toBeHidden();
+ });
+});
diff --git a/src/e2e/migration.test.ts b/src/e2e/migration.test.ts
deleted file mode 100644
index 8bae53368..000000000
--- a/src/e2e/migration.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { test } from "./app-test-fixtures.js";
-
-const heartMigrationFragment =
- "#project:XQAAgACRAAAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOM4sSAXBT95G3en+tghrYmE+YJp6EiYgzA9ThKkyShWq2UdvmCzqxoNfYc1wlmTqlNv/Piaz3WoSe3flvr/ItyLl0aolQlEpv4LA8A=";
-
-const sunlightSensorMigrationFragment =
- "#project:XQAAgAByAQAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOW6kOsIEMK7SL0Qco7jgsHFKZXfjv/XcHWvXG9qyz1a/a3NUulFDj/FDJxVAIV+WZLpRoo4E6MbW70FOgIfBPWP2hDVsojpoLc7ZfKI8SHxv54FSfB5bkbzaAKO+8CO73t6Odtv691JGjJ9MExFighY6GxyM/DoNInDDpAjFeaqCWrYdwENX7ZVM3we8f4swI71tL28N7sg588aB//A78AA";
-
-test.describe("migration", () => {
- test("Loads the project from the URL", async ({ app }) => {
- await app.goto({ fragment: heartMigrationFragment });
- await app.page.reload();
- await app.expectProjectName("Hearts");
- await app.expectEditorContainText(
- "from microbit import *display.show(Image.HEART)"
- );
-
- // Regression test: Check that we can switch to a different migration in the same session.
- // Previously we ignored the migration because we already had content in session storage.
- await app.goto({
- fragment: sunlightSensorMigrationFragment,
- });
- await app.page.reload();
- // wait for page to load
- await app.saveButton.waitFor();
- await app.expectEditorContainText("display.read_light_level");
- });
-});
diff --git a/src/e2e/multiple-files.test.ts b/src/e2e/multiple-files.test.ts
index c00a80a20..5ee055509 100644
--- a/src/e2e/multiple-files.test.ts
+++ b/src/e2e/multiple-files.test.ts
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: MIT
*/
import { expect } from "@playwright/test";
-import { LoadDialogType } from "./app.js";
import { test } from "./app-test-fixtures.js";
test.describe("multiple-files", () => {
@@ -31,23 +30,18 @@ test.describe("multiple-files", () => {
});
test("Copes with non-main file being updated", async ({ app }) => {
- await app.loadFiles("testData/usermodule.py", {
- acceptDialog: LoadDialogType.CONFIRM_BUT_LOAD_AS_MODULE,
- });
+ await app.loadFiles("testData/usermodule.py");
await app.editFile("usermodule.py");
await app.expectEditorContainText(/b_works/);
- await app.loadFiles("testData/updated/usermodule.py", {
- acceptDialog: LoadDialogType.CONFIRM_BUT_LOAD_AS_MODULE,
- });
+ await app.loadFiles("testData/updated/usermodule.py");
+ await app.answerDialog("Replace");
await app.expectEditorContainText(/c_works/);
});
test("Shows warning for third-party module", async ({ app }) => {
- await app.loadFiles("testData/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/module.py");
await app.editFile("module.py");
await app.expectThirdPartModuleWarning("a", "1.0.0");
@@ -58,16 +52,13 @@ test.describe("multiple-files", () => {
await app.toggleSettingThirdPartyModuleEditing();
}
- await app.loadFiles("testData/updated/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/updated/module.py");
+ await app.answerDialog("Replace");
await app.expectThirdPartModuleWarning("a", "1.1.0");
});
test("Copes with currently open file being deleted", async ({ app }) => {
- await app.loadFiles("testData/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/module.py");
await app.editFile("module.py");
await app.deleteFile("module.py");
await app.expectEditorContainText(/Hello/);
diff --git a/src/e2e/open.test.ts b/src/e2e/open.test.ts
index fb55d8b10..723be8ef7 100644
--- a/src/e2e/open.test.ts
+++ b/src/e2e/open.test.ts
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: MIT
*/
import { expect } from "@playwright/test";
-import { LoadDialogType } from "./app.js";
import { test } from "./app-test-fixtures.js";
test.describe("open", () => {
@@ -17,19 +16,31 @@ test.describe("open", () => {
);
});
- test("Loads a Python file", async ({ app }) => {
- await app.loadFiles("testData/samplefile.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ test("Adds a Python file to the project", async ({ app }) => {
+ await app.loadFiles("testData/samplefile.py");
- await app.expectAlertText("Updated file main.py");
+ await app.expectAlertText("Added file samplefile.py");
+ await app.expectProjectFiles(["main.py", "samplefile.py"]);
await app.expectProjectName("Untitled project");
});
+ test("Asks before replacing a file with the same name", async ({ app }) => {
+ await app.loadFiles("testData/samplefile.py");
+ await app.expectAlertText("Added file samplefile.py");
+
+ await app.loadFiles("testData/samplefile.py");
+ await app.expectDialog("Replace existing files?");
+ await app.answerDialog("Cancel");
+ await app.expectProjectFiles(["main.py", "samplefile.py"]);
+
+ await app.loadFiles("testData/samplefile.py");
+ await app.expectDialog("Replace existing files?");
+ await app.answerDialog("Replace");
+ await app.expectAlertText("Updated file samplefile.py");
+ });
+
test("Correctly handles a hex that's actually Python", async ({ app }) => {
- await app.loadFiles("testData/not-a-hex.hex", {
- acceptDialog: LoadDialogType.NONE,
- });
+ await app.loadFiles("testData/not-a-hex.hex");
await app.expectAlertText(
"Cannot load file",
@@ -39,31 +50,38 @@ test.describe("open", () => {
);
});
- test("Loads a v1.0.1 hex file", async ({ app }) => {
+ test("Opens a v1.0.1 hex file as a new project", async ({
+ app,
+ homePage,
+ }) => {
+ await app.typeInEditor("# Keep me");
await app.loadFiles("testData/1.0.1.hex");
await app.expectEditorContainText(/PASS1/);
await app.expectProjectName("1.0.1");
+
+ // The previous project is untouched.
+ await app.goHome();
+ await homePage.cards.expectVisible("1.0.1");
+ await homePage.cards.open("Untitled project");
+ await app.expectEditorContainText("# Keep me");
});
- test("Loads a v0.9 hex file", async ({ app }) => {
+ test("Opens a v0.9 hex file as a new project", async ({ app }) => {
await app.loadFiles("testData/0.9.hex");
await app.expectEditorContainText(/PASS2/);
await app.expectProjectName("0.9");
});
- test("Loads via drag and drop", async ({ app }) => {
+ test("Opens a hex via drag and drop", async ({ app }) => {
await app.dropFile("testData/1.0.1.hex");
await app.expectProjectName("1.0.1");
- // await app.findVisibleEditorContents(/PASS1/);
});
test("Correctly handles an mpy file", async ({ app }) => {
- await app.loadFiles("testData/samplempyfile.mpy", {
- acceptDialog: LoadDialogType.NONE,
- });
+ await app.loadFiles("testData/samplempyfile.mpy");
await app.expectAlertText(
"Cannot load file",
@@ -74,9 +92,7 @@ test.describe("open", () => {
test("Correctly handles a file with an invalid extension", async ({
app,
}) => {
- await app.loadFiles("testData/sampletxtfile.txt", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/sampletxtfile.txt");
expect(await app.isEditFileOptionDisabled("sampletxtfile.txt")).toEqual(
true
@@ -86,60 +102,12 @@ test.describe("open", () => {
test("Correctly imports modules with the 'magic comment' in the filesystem.", async ({
app,
}) => {
- await app.loadFiles("testData/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/module.py");
await app.expectAlertText("Added file module.py");
- await app.loadFiles("testData/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/module.py");
+ await app.answerDialog("Replace");
await app.expectAlertText("Updated file module.py");
});
-
- test("Warns before load if you have changes", async ({ app }) => {
- await app.typeInEditor("# Different text");
- await app.loadFiles("testData/1.0.1.hex", {
- acceptDialog: LoadDialogType.REPLACE,
- });
- await app.expectEditorContainText(/PASS1/);
- await app.expectProjectName("1.0.1");
- });
-
- test("No warn before load if you save hex", async ({ app }) => {
- await app.setProjectName("Avoid dialog");
- await app.typeInEditor("# Different text");
- await app.save();
- await app.closeDialog("Project saved");
-
- // No dialog accepted
- await app.loadFiles("testData/1.0.1.hex");
- await app.expectEditorContainText(/PASS1/);
- });
-
- test("No warn before load if you save main file", async ({ app }) => {
- await app.setProjectName("Avoid dialog");
- await app.typeInEditor("# Different text");
- await app.savePythonScript();
-
- // No dialog accepted
- await app.loadFiles("testData/1.0.1.hex");
- await app.expectEditorContainText(/PASS1/);
- });
-
- test("Warn before load if you save main file only and you have others", async ({
- app,
- }) => {
- await app.setProjectName("Avoid dialog");
- await app.typeInEditor("# Different text");
- await app.createNewFile("another");
- await app.savePythonScript();
- await app.closeDialog("Warning: Only main.py downloaded");
-
- await app.loadFiles("testData/1.0.1.hex", {
- acceptDialog: LoadDialogType.REPLACE,
- });
- await app.expectEditorContainText(/PASS1/);
- });
});
diff --git a/src/e2e/project-link.test.ts b/src/e2e/project-link.test.ts
new file mode 100644
index 000000000..be968cbf4
--- /dev/null
+++ b/src/e2e/project-link.test.ts
@@ -0,0 +1,35 @@
+/**
+ * (c) 2021, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { test } from "./app-test-fixtures.js";
+import {
+ heartProjectLinkFragment,
+ sunlightSensorProjectLinkFragment,
+} from "./project-links.js";
+
+test.describe("project link", () => {
+ test("Loads the project from the URL", async ({ app, homePage }) => {
+ await app.goto({ fragment: heartProjectLinkFragment });
+ await app.page.reload();
+ await app.expectProjectName("Hearts");
+ await app.expectEditorContainText(
+ "from microbit import *display.show(Image.HEART)"
+ );
+
+ // Regression test: Check that we can open a different project link in the same session.
+ // Previously we ignored the link because we already had content in session storage.
+ await app.goto({
+ fragment: sunlightSensorProjectLinkFragment,
+ });
+ await app.page.reload();
+ // wait for page to load
+ await app.saveButton.waitFor();
+ await app.expectEditorContainText("display.read_light_level");
+
+ // Each link made a project rather than replacing the last.
+ await app.goHome();
+ await homePage.cards.expectVisible("Hearts");
+ });
+});
diff --git a/src/e2e/project-links.ts b/src/e2e/project-links.ts
new file mode 100644
index 000000000..c25302212
--- /dev/null
+++ b/src/e2e/project-links.ts
@@ -0,0 +1,15 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+
+// #project: links as microbit.org makes them, for tests that open one.
+
+/** A project named "Hearts" that shows a heart. */
+export const heartProjectLinkFragment =
+ "#project:XQAAgACRAAAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOM4sSAXBT95G3en+tghrYmE+YJp6EiYgzA9ThKkyShWq2UdvmCzqxoNfYc1wlmTqlNv/Piaz3WoSe3flvr/ItyLl0aolQlEpv4LA8A=";
+
+/** A project that reads the light level. */
+export const sunlightSensorProjectLinkFragment =
+ "#project:XQAAgAByAQAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOW6kOsIEMK7SL0Qco7jgsHFKZXfjv/XcHWvXG9qyz1a/a3NUulFDj/FDJxVAIV+WZLpRoo4E6MbW70FOgIfBPWP2hDVsojpoLc7ZfKI8SHxv54FSfB5bkbzaAKO+8CO73t6Odtv691JGjJ9MExFighY6GxyM/DoNInDDpAjFeaqCWrYdwENX7ZVM3we8f4swI71tL28N7sg588aB//A78AA";
diff --git a/src/e2e/projects-page.ts b/src/e2e/projects-page.ts
new file mode 100644
index 000000000..fa0a1d4a8
--- /dev/null
+++ b/src/e2e/projects-page.ts
@@ -0,0 +1,127 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect, Locator, Page } from "@playwright/test";
+import { appUrlPattern, projectsPageUrl } from "./app.js";
+import { expectNoNewViolations } from "./axe.js";
+import { ProjectCards } from "./home-page.js";
+
+export class ProjectsPage {
+ public cards: ProjectCards;
+ private heading: Locator;
+ private searchInput: Locator;
+ private toolbar: Locator;
+
+ constructor(public readonly page: Page) {
+ this.cards = new ProjectCards(page);
+ this.heading = page.getByRole("heading", { name: "My projects" });
+ this.searchInput = page.getByRole("searchbox", { name: "Search" });
+ // Two toolbars are in the DOM, for wide and narrow layouts; only one is
+ // shown, so act on the visible one.
+ this.toolbar = page
+ .getByRole("group", { name: "Selection actions" })
+ .locator("visible=true");
+ }
+
+ async goto(): Promise {
+ await this.page.goto(projectsPageUrl());
+ await this.expectOnPage();
+ }
+
+ async expectOnPage(): Promise {
+ await expect(this.heading).toBeVisible();
+ await expect(this.page).toHaveURL(appUrlPattern("projects"));
+ }
+
+ async expectNoNewAccessibilityViolations(): Promise {
+ await expectNoNewViolations(this.page);
+ }
+
+ async goHome(): Promise {
+ await this.page.getByRole("button", { name: "Home" }).click();
+ }
+
+ async expectProjectCount(count: number): Promise {
+ await expect(this.page.getByRole("checkbox")).toHaveCount(count);
+ }
+
+ async expectNoProjects(): Promise {
+ await expect(this.page.getByText("No projects to display")).toBeVisible();
+ }
+
+ async expectProjectOrder(names: string[]): Promise {
+ const checkboxes = this.page.getByRole("checkbox");
+ await expect(checkboxes).toHaveCount(names.length);
+ for (let i = 0; i < names.length; i++) {
+ await expect(checkboxes.nth(i)).toHaveAccessibleName(
+ `Select ${names[i]}`
+ );
+ }
+ }
+
+ async search(query: string): Promise {
+ await this.searchInput.fill(query);
+ }
+
+ async clearSearch(): Promise {
+ await this.page.getByRole("button", { name: "Clear" }).click();
+ }
+
+ async select(name: string): Promise {
+ const checkbox = this.page.getByRole("checkbox", {
+ name: `Select ${name}`,
+ exact: true,
+ });
+ await checkbox.check({ force: true });
+ await expect(checkbox).toBeChecked();
+ }
+
+ async expectToolbarVisible(): Promise {
+ await expect(this.toolbar).toBeVisible();
+ }
+
+ async expectToolbarHidden(): Promise {
+ await expect(
+ this.page.getByRole("group", { name: "Selection actions" })
+ ).toHaveCount(0);
+ }
+
+ async expectToolbarButtons(names: string[]): Promise {
+ const buttons = this.toolbar.getByRole("button");
+ await expect(buttons).toHaveCount(names.length);
+ for (const name of names) {
+ await expect(this.toolbar.getByRole("button", { name })).toBeVisible();
+ }
+ }
+
+ async toolbarRename(newName: string): Promise {
+ await this.toolbar.getByRole("button", { name: "Rename" }).click();
+ await this.cards.fillNameDialog(newName, "Rename");
+ }
+
+ async toolbarDuplicate(newName: string): Promise {
+ await this.toolbar.getByRole("button", { name: "Duplicate" }).click();
+ await this.cards.fillNameDialog(newName, "Duplicate");
+ }
+
+ async toolbarDelete(): Promise {
+ await this.toolbar.getByRole("button", { name: /^Delete/ }).click();
+ await this.cards.confirmDelete();
+ }
+
+ async toolbarClear(): Promise {
+ await this.toolbar.getByRole("button", { name: "Clear" }).click();
+ }
+
+ async sortBy(field: "Name" | "Last modified"): Promise {
+ await this.page
+ .getByRole("combobox", { name: "Sort projects" })
+ .selectOption({ label: field });
+ }
+
+ async toggleSortDirection(): Promise {
+ await this.page.getByRole("button", { name: /order$/ }).click();
+ }
+}
diff --git a/src/e2e/projects.test.ts b/src/e2e/projects.test.ts
new file mode 100644
index 000000000..8558f63f5
--- /dev/null
+++ b/src/e2e/projects.test.ts
@@ -0,0 +1,166 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect } from "@playwright/test";
+import { App } from "./app.js";
+import { test } from "./app-test-fixtures.js";
+import { HomePage } from "./home-page.js";
+
+test.describe("projects page", () => {
+ test.use({ autoGoto: false });
+
+ test("shows a message when there are no projects", async ({
+ projectsPage,
+ }) => {
+ await projectsPage.goto();
+ await projectsPage.expectNoProjects();
+ await projectsPage.expectToolbarHidden();
+ await projectsPage.expectNoNewAccessibilityViolations();
+ });
+
+ test("goes back home", async ({ homePage, projectsPage }) => {
+ await projectsPage.goto();
+ await projectsPage.goHome();
+ await homePage.expectOnPage();
+ });
+
+ test.describe("with projects", () => {
+ test.beforeEach(async ({ app, homePage, projectsPage }) => {
+ await homePage.goto();
+ for (const name of ["Alpha", "Beta"]) {
+ await homePage.newProject(name);
+ await app.expectProjectName(name);
+ await app.goHome();
+ await homePage.expectOnPage();
+ }
+ await projectsPage.goto();
+ await projectsPage.expectProjectCount(2);
+ });
+
+ test("lists most recent first and sorts by name", async ({
+ projectsPage,
+ }) => {
+ await projectsPage.expectProjectOrder(["Beta", "Alpha"]);
+ await projectsPage.expectNoNewAccessibilityViolations();
+ await projectsPage.sortBy("Name");
+ await projectsPage.expectProjectOrder(["Alpha", "Beta"]);
+ await projectsPage.toggleSortDirection();
+ await projectsPage.expectProjectOrder(["Beta", "Alpha"]);
+ });
+
+ test("searches by name", async ({ projectsPage }) => {
+ await projectsPage.search("alp");
+ await projectsPage.expectProjectOrder(["Alpha"]);
+ await projectsPage.search("nothing here");
+ await projectsPage.expectNoProjects();
+ await projectsPage.clearSearch();
+ await projectsPage.expectProjectCount(2);
+ });
+
+ test("a dropped hex becomes a new project open in the editor", async ({
+ app,
+ projectsPage,
+ }) => {
+ await app.dropFile("testData/1.0.1.hex", "projects-drop-target");
+ await app.expectProjectName("1.0.1");
+ await app.expectNoDropOverlay();
+ await app.goHome();
+ await projectsPage.goto();
+ await projectsPage.expectProjectCount(3);
+ });
+
+ test("a dropped Python file becomes a new project", async ({
+ app,
+ projectsPage,
+ }) => {
+ await app.dropFile("testData/samplefile.py", "projects-drop-target");
+ await app.expectProjectName("samplefile");
+ await app.expectProjectFiles(["main.py"]);
+ await projectsPage.goto();
+ await projectsPage.expectProjectCount(3);
+ });
+
+ test("opens a project from its menu", async ({ app, projectsPage }) => {
+ await projectsPage.cards.menuOpen("Alpha");
+ await app.expectProjectName("Alpha");
+ });
+
+ test("renames, duplicates and deletes from the toolbar", async ({
+ projectsPage,
+ }) => {
+ await projectsPage.select("Alpha");
+ await projectsPage.expectToolbarVisible();
+ await projectsPage.expectToolbarButtons([
+ "Rename",
+ "Duplicate",
+ "Delete",
+ "Clear",
+ ]);
+ await projectsPage.expectNoNewAccessibilityViolations();
+
+ await projectsPage.toolbarRename("Gamma");
+ await projectsPage.cards.expectVisible("Gamma");
+
+ await projectsPage.toolbarDuplicate("Gamma copy");
+ await projectsPage.expectProjectCount(3);
+
+ await projectsPage.toolbarClear();
+ await projectsPage.expectToolbarHidden();
+
+ await projectsPage.select("Gamma");
+ await projectsPage.select("Gamma copy");
+ await projectsPage.expectToolbarButtons(["Delete 2 projects", "Clear"]);
+ await projectsPage.toolbarDelete();
+ await projectsPage.expectProjectOrder(["Beta"]);
+ });
+
+ test("deletes the open project and the editor moves on", async ({
+ app,
+ projectsPage,
+ }) => {
+ // Beta was created last, so it is the tab's open project.
+ await projectsPage.cards.menuDelete("Beta");
+ await projectsPage.expectProjectOrder(["Alpha"]);
+
+ await app.goto();
+ await app.expectProjectName("Alpha");
+ });
+ });
+});
+
+test.describe("projects across tabs", () => {
+ test.use({ autoGoto: false });
+
+ test("a project deleted in another tab sends the editor home", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Shared");
+ await app.expectProjectName("Shared");
+
+ // Session storage is per tab, so a new tab at the editor opens the most
+ // recent project: the same one.
+ const otherPage = await app.context.newPage();
+ const otherApp = new App(otherPage, app.context);
+ await otherApp.goto();
+ await otherApp.expectProjectName("Shared");
+
+ await app.goHome();
+ await homePage.cards.menuDelete("Shared");
+
+ const otherHomePage = new HomePage(otherPage);
+ await otherHomePage.expectOnPage();
+ await expect(
+ otherPage.getByText(
+ "The project you had open was deleted in another tab or window."
+ )
+ ).toBeVisible();
+ await otherHomePage.expectNoNewAccessibilityViolations();
+ await expect(
+ otherPage.getByText("Failed to save your project")
+ ).toBeHidden();
+ });
+});
diff --git a/src/e2e/reset.test.ts b/src/e2e/reset.test.ts
deleted file mode 100644
index 2ccfd9cea..000000000
--- a/src/e2e/reset.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { test } from "./app-test-fixtures.js";
-
-test.describe("reset", () => {
- test("sets language via URL", async ({ app }) => {
- await app.setProjectName("My project");
- await app.selectAllInEditor();
- await app.typeInEditor("# Not the default starter code");
- await app.createNewFile("testing");
-
- await app.resetProject();
-
- // Everything's back to normal.
- await app.expectProjectName("Untitled project");
- await app.expectEditorContainText("from microbit import");
- await app.expectProjectFiles(["main.py"]);
- });
-});
diff --git a/src/e2e/routing.test.ts b/src/e2e/routing.test.ts
new file mode 100644
index 000000000..553674e23
--- /dev/null
+++ b/src/e2e/routing.test.ts
@@ -0,0 +1,90 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect } from "@playwright/test";
+import { appUrl, appUrlPattern, homeUrl } from "./app.js";
+import { test } from "./app-test-fixtures.js";
+import { heartProjectLinkFragment } from "./project-links.js";
+
+test.describe("routing", () => {
+ test.use({ autoGoto: false });
+
+ test("redirects the editor's old documentation URLs", async ({ app }) => {
+ await app.page.goto(appUrl("reference/display"));
+ await expect(app.page).toHaveURL(
+ appUrlPattern("project/reference/display")
+ );
+ await expect(
+ app.page.getByRole("tab", { name: "Reference" })
+ ).toHaveAttribute("aria-selected", "true");
+ });
+
+ test("shows not found for an unknown page", async ({ app }) => {
+ await app.page.goto(appUrl("nonsense/whatever/else"));
+ await expect(
+ app.page.getByRole("heading", { name: "Page not found" })
+ ).toBeVisible();
+ });
+
+ // microbit.org links carry the v2 editor's #import: prefix; the editor's
+ // own share links are bare.
+ for (const [name, fragment] of [
+ ["a #project:", heartProjectLinkFragment],
+ ["an #import:", "#import:" + heartProjectLinkFragment],
+ ]) {
+ test(`${name} link at the root opens the program in the editor`, async ({
+ app,
+ }) => {
+ await app.page.goto(homeUrl({ fragment }));
+ await expect(app.page).toHaveURL(appUrlPattern("project"));
+ await app.expectProjectName("Hearts");
+ await app.expectEditorContainText("display.show(Image.HEART)");
+ // Or a reload would open it again as another project.
+ expect(new URL(app.page.url()).hash).toEqual("");
+ });
+ }
+
+ // A link that cannot be read has no project to open. It must not stay in
+ // the address, where it would keep sending the home page to the editor.
+ for (const [name, fragment] of [
+ ["#project:", "#project:notvalid"],
+ ["#import:", "#import:#project:notvalid"],
+ ]) {
+ test(`an unreadable ${name} link at the root is dropped`, async ({
+ app,
+ homePage,
+ }) => {
+ await app.page.goto(homeUrl({ fragment }));
+ await homePage.expectOnPage();
+ expect(new URL(app.page.url()).hash).toEqual("");
+ });
+ }
+
+ test("an unreadable #project: link at the editor is dropped, and Home works", async ({
+ app,
+ homePage,
+ }) => {
+ await app.goto({ fragment: "#project:notvalid" });
+ expect(new URL(app.page.url()).hash).toEqual("");
+
+ await app.goHome();
+ await homePage.expectOnPage();
+ });
+
+ test("a new tab at the editor opens the most recent project", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.newProject("Most recent");
+ await app.expectProjectName("Most recent");
+
+ // Session storage is per tab, so a new page has no current project.
+ const other = await app.context.newPage();
+ const otherApp = new (await import("./app.js")).App(other, app.context);
+ await otherApp.goto();
+ await otherApp.expectProjectName("Most recent");
+ });
+});
diff --git a/src/e2e/save.test.ts b/src/e2e/save.test.ts
index cf2b3d074..941774a41 100644
--- a/src/e2e/save.test.ts
+++ b/src/e2e/save.test.ts
@@ -5,7 +5,6 @@
*/
import { expect } from "@playwright/test";
import fs from "fs";
-import { LoadDialogType } from "./app.js";
import { test } from "./app-test-fixtures.js";
test.describe("save", () => {
@@ -31,10 +30,8 @@ test.describe("save", () => {
}) => {
// Set the project name to avoid calling the edit project name input dialog.
await app.setProjectName("not default name");
- await app.loadFiles("testData/too-large.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
- await app.expectEditorContainText(/# Filler/);
+ await app.loadFiles("testData/too-large.py");
+ await app.expectAlertText("Added file too-large.py");
await app.save({ waitForDownload: false });
await app.expectAlertText(
@@ -60,9 +57,7 @@ test.describe("save", () => {
app,
}) => {
await app.setProjectName("not default name");
- await app.loadFiles("testData/module.py", {
- acceptDialog: LoadDialogType.CONFIRM,
- });
+ await app.loadFiles("testData/module.py");
await app.savePythonScript();
await app.expectDialog("Warning: Only main.py downloaded");
});
diff --git a/src/e2e/session-migration.test.ts b/src/e2e/session-migration.test.ts
new file mode 100644
index 000000000..9e68c88a8
--- /dev/null
+++ b/src/e2e/session-migration.test.ts
@@ -0,0 +1,82 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect, Page } from "@playwright/test";
+import { test } from "./app-test-fixtures.js";
+import { heartProjectLinkFragment } from "./project-links.js";
+
+/**
+ * The editor used to be at the app's root and kept its one project in
+ * session storage. A tab left open across the upgrade reloads at the same
+ * address, which is now the home page.
+ */
+test.describe(
+ "session storage project from before the projects database",
+ () => {
+ test.use({ autoGoto: false });
+
+ test.beforeEach(async ({ context }) => {
+ await context.addInitScript(() => {
+ // Once per tab, as the old editor would have left it: an init script
+ // runs on every load, and the migration removes these.
+ if (!sessionStorage.getItem("seeded")) {
+ sessionStorage.setItem("seeded", "true");
+ sessionStorage.setItem("fs/files/main.py", btoa("# from before"));
+ sessionStorage.setItem("fs/meta/projectName", "Before the upgrade");
+ sessionStorage.setItem("fs/meta/dirty", "true");
+ }
+ });
+ });
+
+ const sessionProjectKeys = (page: Page) =>
+ page.evaluate(() =>
+ Object.keys(sessionStorage).filter((key) => key.startsWith("fs/"))
+ );
+
+ test("is listed when the tab reloads at the root, and opens", async ({
+ app,
+ homePage,
+ }) => {
+ await homePage.goto();
+ await homePage.cards.expectVisible("Before the upgrade");
+ expect(await sessionProjectKeys(app.page)).toEqual([]);
+
+ // Not lost by making something else first.
+ await homePage.newProject("Another");
+ await app.expectProjectName("Another");
+ await app.goHome();
+ await homePage.cards.open("Before the upgrade");
+ await app.expectProjectName("Before the upgrade");
+ await app.expectEditorContainText("# from before");
+ });
+
+ test("is listed on the projects page too", async ({ projectsPage }) => {
+ await projectsPage.goto();
+ await projectsPage.cards.expectVisible("Before the upgrade");
+ });
+
+ test("is listed beside the project from a #project: link, which opens", async ({
+ app,
+ homePage,
+ }) => {
+ await app.goto({ fragment: heartProjectLinkFragment });
+ await app.expectProjectName("Hearts");
+ expect(await sessionProjectKeys(app.page)).toEqual([]);
+
+ await app.goHome();
+ await homePage.cards.expectVisible("Hearts");
+ await homePage.cards.expectVisible("Before the upgrade");
+ });
+
+ test("still opens straight away at the editor's new address", async ({
+ app,
+ }) => {
+ await app.goto();
+ await app.expectProjectName("Before the upgrade");
+ await app.expectEditorContainText("# from before");
+ expect(await sessionProjectKeys(app.page)).toEqual([]);
+ });
+ }
+);
diff --git a/src/e2e/storage-errors.test.ts b/src/e2e/storage-errors.test.ts
new file mode 100644
index 000000000..13f575c1c
--- /dev/null
+++ b/src/e2e/storage-errors.test.ts
@@ -0,0 +1,203 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { expect } from "@playwright/test";
+import { App, homeUrl } from "./app.js";
+import { test } from "./app-test-fixtures.js";
+import { heartProjectLinkFragment } from "./project-links.js";
+
+/**
+ * Without IndexedDB the editor keeps the project in session storage, as it
+ * did before the projects database, so closing the tab loses it and the
+ * before-unload prompt is back.
+ */
+test.describe("storage fallback", () => {
+ test.use({ noIndexedDB: true });
+
+ test("doesn't prompt on close if no edits made", async ({ app }) => {
+ await app.closeWithoutBeforeUnloadPrompt();
+ });
+
+ test("prompts on close if file edited", async ({ app }) => {
+ await app.typeInEditor("A change!");
+ await app.expectEditorContainText(/A change/);
+
+ await app.closeAndExpectBeforeUnloadPrompt();
+ });
+
+ test("prompts on close if project name edited", async ({ app }) => {
+ const name = "idiosyncratic ruminant";
+ await app.setProjectName(name);
+ await app.expectProjectName(name);
+
+ await app.closeAndExpectBeforeUnloadPrompt();
+ });
+
+ test("replaces the project with a hex without asking if not edited", async ({
+ app,
+ }) => {
+ await app.loadFiles("testData/1.0.1.hex");
+ await app.expectProjectName("1.0.1");
+ });
+
+ test("asks before a hex replaces an edited project", async ({ app }) => {
+ await app.typeInEditor("A change!");
+ await app.expectEditorContainText(/A change/);
+
+ await app.loadFiles("testData/1.0.1.hex");
+ await app.expectDialog("Confirm replace project");
+ await app.answerDialog("Cancel");
+ await app.expectEditorContainText(/A change/);
+
+ await app.loadFiles("testData/1.0.1.hex");
+ await app.answerDialog("Replace");
+ await app.expectProjectName("1.0.1");
+ await app.expectEditorContainText(/PASS1/);
+ });
+
+ test("does not say ideas are moving, as there is no home page", async ({
+ app,
+ }) => {
+ await app.switchTab("Ideas");
+ await app.expectDocumentationTopLevelHeading("Ideas");
+ await expect(
+ app.page.getByRole("button", { name: "Learn more" })
+ ).toBeHidden();
+ });
+
+ test("opens a #project: link at the root in the editor", async ({ app }) => {
+ await app.page.goto(homeUrl({ fragment: heartProjectLinkFragment }));
+ await app.expectProjectName("Hearts");
+ await app.expectEditorContainText("display.show(Image.HEART)");
+ expect(new URL(app.page.url()).hash).toEqual("");
+ });
+
+ test("retains text across a reload via session storage", async ({ app }) => {
+ await app.typeInEditor("A change!");
+ await app.expectEditorContainText(/A change/);
+
+ await app.page.reload();
+
+ await app.expectEditorContainText(/A change/);
+ });
+});
+
+/**
+ * Makes the next IndexedDB put throw, then restores it, or with `every`
+ * makes them all throw. The first put in a project flush is the project
+ * record, so this fails the whole flush.
+ */
+const injectWriteError = async (
+ app: App,
+ errorName: "QuotaExceededError" | "UnknownError",
+ { every = false }: { every?: boolean } = {}
+) => {
+ await app.page.evaluate(
+ ({ errorName, every }) => {
+ const original = IDBObjectStore.prototype.put;
+ IDBObjectStore.prototype.put = function () {
+ if (!every) {
+ IDBObjectStore.prototype.put = original;
+ }
+ throw new DOMException(`Simulated ${errorName}`, errorName);
+ };
+ },
+ { errorName, every }
+ );
+};
+
+/**
+ * A failed write to the projects database keeps the edit in the editor and
+ * shows a persistent toast, as ml-trainer does.
+ */
+test.describe("storage write errors", () => {
+ test("shows the storage full toast on a quota error", async ({ app }) => {
+ await injectWriteError(app, "QuotaExceededError");
+ await app.typeInEditor("A change!");
+
+ await expect(app.page.getByText("Browser storage full")).toBeVisible();
+ await expect(
+ app.page.getByText("Your project edit may not be saved.")
+ ).toBeVisible();
+ await expect(
+ app.page.getByText("An unexpected error occurred")
+ ).toBeHidden();
+ await app.expectEditorContainText(/A change/);
+ });
+
+ test("shows a generic toast on another write error", async ({ app }) => {
+ await injectWriteError(app, "UnknownError");
+ await app.typeInEditor("A change!");
+
+ await expect(
+ app.page.getByText("Failed to save your project to browser storage")
+ ).toBeVisible();
+ await expect(
+ app.page.getByText("An unexpected error occurred")
+ ).toBeHidden();
+ });
+
+ test("warns before closing while an edit has not saved", async ({ app }) => {
+ await injectWriteError(app, "UnknownError", { every: true });
+ await app.typeInEditor("A change!");
+ await expect(
+ app.page.getByText("Failed to save your project to browser storage")
+ ).toBeVisible();
+
+ await app.closeAndExpectBeforeUnloadPrompt();
+ });
+
+ test("does not warn once a later save has succeeded", async ({ app }) => {
+ // Only the first save fails. typeInEditor's last keys are typed slowly
+ // enough to be saved again, successfully, after it.
+ await injectWriteError(app, "UnknownError");
+ await app.typeInEditor("A change!");
+ await expect(
+ app.page.getByText("Failed to save your project to browser storage")
+ ).toBeVisible();
+ // Past the storage's flush delay, so the last save has finished.
+ await app.page.waitForTimeout(600);
+
+ await app.closeWithoutBeforeUnloadPrompt();
+ });
+});
+
+/**
+ * Makes the next IndexedDB get throw, then restores it. Opening a project
+ * reads its record with one, so this fails the load.
+ */
+const injectReadError = async (app: App) => {
+ await app.page.evaluate(() => {
+ const original = IDBObjectStore.prototype.get;
+ IDBObjectStore.prototype.get = function () {
+ IDBObjectStore.prototype.get = original;
+ throw new DOMException("Simulated UnknownError", "UnknownError");
+ };
+ });
+};
+
+/**
+ * A failed read from the projects database is reported on the page the user
+ * is left on, and the project is still there to open.
+ */
+test.describe("storage read errors", () => {
+ test("reports a failed load on going back to the editor from the home page", async ({
+ app,
+ homePage,
+ }) => {
+ await app.goHome();
+ await homePage.expectOnPage();
+
+ await injectReadError(app);
+ await app.page.goBack();
+
+ await expect(
+ app.page.getByText("An unexpected error occurred")
+ ).toBeVisible();
+ await homePage.expectOnPage();
+ await homePage.cards.open("Untitled project");
+ await app.expectEditorContainText("from microbit import");
+ });
+});
diff --git a/src/editor/ActiveFileInfo.tsx b/src/editor/ActiveFileInfo.tsx
deleted file mode 100644
index 2cd29705a..000000000
--- a/src/editor/ActiveFileInfo.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { Button, Text } from "@microbit/ui";
-import { FormattedMessage } from "react-intl";
-import { HStack } from "styled-system/jsx";
-import { MAIN_FILE } from "../fs/fs";
-
-interface ActiveFileInfoProps {
- filename: string;
- onSelectedFileChanged: (filename: string) => void;
-}
-
-/**
- * Current file info.
- *
- * We offer an additional route back to editing the main document
- * when the user is editing another document.
- */
-const ActiveFileInfo = ({
- filename,
- onSelectedFileChanged,
-}: ActiveFileInfoProps) => {
- return (
-
- {filename !== MAIN_FILE && (
- <>
-
- {filename}
-
- —
- onSelectedFileChanged(MAIN_FILE)}
- >
-
-
- >
- )}
-
- );
-};
-
-export default ActiveFileInfo;
diff --git a/src/editor/EditorArea.tsx b/src/editor/EditorArea.tsx
index 996a73127..dedb9ef38 100644
--- a/src/editor/EditorArea.tsx
+++ b/src/editor/EditorArea.tsx
@@ -12,10 +12,9 @@ import { widthXl } from "../common/media-queries";
import HideSplitViewButton from "../common/SplitView/HideSplitViewButton";
import { topBarHeight } from "../deployment/misc";
import ZoomControls from "../editor/ZoomControls";
-import ProjectNameEditable from "../project/ProjectNameEditable";
import { WorkbenchSelection } from "../workbench/use-selection";
-import ActiveFileInfo from "./ActiveFileInfo";
import EditorContainer from "./EditorContainer";
+import ProjectBreadcrumb from "./ProjectBreadcrumb";
import UndoRedoControls from "./UndoRedoControls";
interface EditorAreaProps {
@@ -57,18 +56,11 @@ const EditorArea = ({
height: topBarHeight,
}}
>
-
-
-
+
{!simulatorShown && (
void;
+}
+
+/**
+ * Home, the project name (which renames it) and the open file (a menu of
+ * the project's files).
+ */
+const ProjectBreadcrumb = ({
+ filename,
+ onSelectedFileChanged,
+}: ProjectBreadcrumbProps) => {
+ const intl = useIntl();
+ const containerRef = useRef(null);
+ const measureRefs = useRef<(HTMLDivElement | null)[]>([]);
+ const [squeeze, setSqueeze] = useState(0);
+
+ // Hidden copies give the width each step needs, so the step is chosen in
+ // one go as the space changes rather than by trying each in turn.
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ const copies = measureRefs.current;
+ if (!container || copies.some((copy) => !copy)) {
+ return;
+ }
+ const update = () => {
+ const available = container.clientWidth;
+ const fits = copies.findIndex((copy) => copy!.scrollWidth <= available);
+ setSqueeze((fits === -1 ? 4 : fits) as Squeeze);
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ [container, ...copies].forEach((element) => observer.observe(element!));
+ return () => observer.disconnect();
+ }, []);
+
+ const crumbs = { filename, onSelectedFileChanged };
+ return (
+
+
+ {/* Clips the copies, which can be wider than the space, here rather
+ than on the crumbs, whose focus rings it would cut off. */}
+
+ {measuredSqueezes.map((step) => (
+ {
+ measureRefs.current[step] = element;
+ }}
+ >
+
+
+ ))}
+
+
+ );
+};
+
+/** Out of sight and out of the tab order and accessibility tree. */
+const Measure = ({
+ ref,
+ children,
+}: {
+ ref: React.Ref;
+ children: React.ReactNode;
+}) => (
+
+ {children}
+
+);
+
+interface CrumbsProps extends ProjectBreadcrumbProps {
+ squeeze: Squeeze;
+ /** The crumbs on screen, rather than a copy measured for fit. */
+ shown?: boolean;
+}
+
+const Crumbs = ({
+ filename,
+ onSelectedFileChanged,
+ squeeze,
+ shown,
+}: CrumbsProps) => {
+ const projectsDatabaseActive = useProjectsDatabaseActive();
+ const iframeMode = useIframeMode();
+ const hasHome = projectsDatabaseActive && !iframeMode;
+ return (
+ // role="list" because Safari drops list semantics without list markers.
+
+ {hasHome && (
+
+
+
+
+ )}
+
+
+
+
+
+ = 2}
+ shown={shown}
+ />
+
+
+ );
+};
+
+/** A crumb with the separator that follows it. */
+const CrumbItem = ({
+ flexShrink = 0,
+ children,
+}: {
+ flexShrink?: 0 | 1;
+ children: React.ReactNode;
+}) => (
+
+ {children}
+
+);
+
+/**
+ * Shared by every crumb so they read alike: one size and colour, and the
+ * hover covers icon and text together.
+ */
+const crumbClass = css({
+ gap: "1.5",
+ px: "2",
+ fontSize: "xl",
+ fontWeight: "normal",
+ // As alpha rather than opacity, which would fade the icons too.
+ color: "gray.700/80",
+ whiteSpace: "nowrap",
+});
+
+const crumbIconClass = css({ flexShrink: 0, color: "brand.500" });
+
+const HomeCrumb = ({ showLabel }: { showLabel: boolean }) => {
+ const intl = useIntl();
+ return (
+ // Only for the icon alone; the label says it otherwise.
+
+
+
+
+ {showLabel && }
+
+
+
+ );
+};
+
+/** The project name, which opens the rename dialog. */
+const ProjectCrumb = ({
+ truncate,
+ iconOnly,
+ shown,
+}: {
+ /** Whether the name truncates with an ellipsis. */
+ truncate: boolean;
+ /** Just the pencil, without the name. */
+ iconOnly: boolean;
+ shown?: boolean;
+}) => {
+ const intl = useIntl();
+ const { name } = useProject();
+ const actions = useProjectActions();
+ return (
+
+ actions.editProjectName()}
+ // Literals so Panda can extract both.
+ css={{ flexShrink: truncate ? 1 : 0 }}
+ >
+
+ {!iconOnly && (
+
+ {name}
+
+ )}
+
+
+ );
+};
+
+interface FileCrumbProps extends ProjectBreadcrumbProps {
+ /** Just the files icon, without the name, when space is short. */
+ iconOnly: boolean;
+ shown?: boolean;
+}
+
+/**
+ * Set when a file is chosen from the menu.
+ * The editor area, and so this crumb, is re-created for the new file, so
+ * the new trigger takes focus.
+ */
+const pendingFocus = { trigger: false };
+
+/**
+ * The open file, as a menu of the project's files and a way to the Files
+ * tab.
+ */
+const FileCrumb = ({
+ filename,
+ onSelectedFileChanged,
+ iconOnly,
+ shown,
+}: FileCrumbProps) => {
+ const intl = useIntl();
+ const { files } = useProject();
+ const showSidebarPanel = useShowSidebarPanel();
+ const triggerRef = useRef(null);
+ useEffect(() => {
+ if (shown && pendingFocus.trigger) {
+ pendingFocus.trigger = false;
+ // After the closing menu's own attempt to restore focus.
+ requestAnimationFrame(() => triggerRef.current?.focus());
+ }
+ }, [shown]);
+ const chooseFile = (name: string) => {
+ if (name !== filename) {
+ pendingFocus.trigger = true;
+ onSelectedFileChanged(name);
+ }
+ };
+ // The menu keeps focus inside it while open, then returns it to this
+ // trigger as it closes. So focus is passed on to the Files panel from
+ // the trigger's focus event, before it's painted there. The panel is
+ // shown directly: a router change would wait on the route's loader.
+ const manageFilesPending = useRef(false);
+ const manageFiles = useCallback(() => {
+ manageFilesPending.current = true;
+ // Long enough for the menu's exit animation. Should focus never come
+ // back, a later visit to the trigger isn't sent away.
+ setTimeout(() => {
+ manageFilesPending.current = false;
+ }, 1000);
+ }, []);
+ const handleTriggerFocus = useCallback(() => {
+ if (manageFilesPending.current) {
+ manageFilesPending.current = false;
+ showSidebarPanel("files");
+ }
+ }, [showSidebarPanel]);
+ return (
+
+ {/* Only for the icon alone; the name shows otherwise. */}
+
+
+
+ {!iconOnly && (
+
+ {filename}
+
+ )}
+
+
+
+
+ {/* Separate sections so only the files are options. VoiceOver
+ doesn't give positions ("1 of 2") within sections. */}
+
+ {files.map((file) => (
+ chooseFile(file.name)}
+ >
+ {file.name}
+
+ ))}
+
+
+
+ }
+ onAction={manageFiles}
+ >
+
+
+
+
+
+ );
+};
+
+const Separator = () => (
+
+);
+
+export default ProjectBreadcrumb;
diff --git a/src/environment.ts b/src/environment.ts
index 92ad85ded..48c3efe6a 100644
--- a/src/environment.ts
+++ b/src/environment.ts
@@ -8,3 +8,10 @@ export const version = import.meta.env.VITE_VERSION || "local";
export type Stage = "local" | "REVIEW" | "STAGING" | "PRODUCTION";
export const stage = (import.meta.env.VITE_STAGE || "local") as Stage;
+
+/**
+ * Stages real users reach. Development affordances (like offering to clear
+ * an incompatible projects database) are for the others.
+ */
+export const isPublicFacingStage = (s: Stage = stage): boolean =>
+ s === "STAGING" || s === "PRODUCTION";
diff --git a/src/external-links.ts b/src/external-links.ts
index f5e7dcfe2..ac53079d9 100644
--- a/src/external-links.ts
+++ b/src/external-links.ts
@@ -28,3 +28,23 @@ export const microbitOrgMiciProjectsUrl = (languageId: string) =>
`https://microbit.org/${langPath(
languageId
)}projects/make-it-code-it/?filters=python`;
+
+/** A "make it: code it" project, opened for the Python editor. */
+export const microbitOrgProjectUrl = (slug: string, languageId: string) =>
+ `https://microbit.org/${langPath(
+ languageId
+ )}projects/make-it-code-it/${encodeURIComponent(slug)}/?editor=python`;
+
+export const microbitOrgCodeAiPythonUrl =
+ "https://microbit.org/code-ai/#python";
+
+export const microbitOrgLessonUrl = (slug: string) =>
+ `https://microbit.org/teach/lessons/${encodeURIComponent(slug)}/`;
+
+export const microbitOrgClassroomResourceUrl = (slug: string) =>
+ `https://microbit.org/teach/classroom-resources/${encodeURIComponent(slug)}/`;
+
+export const introducingPythonCourseUrl =
+ "https://microbit.thinkific.com/courses/introducing-python-micro-bit";
+
+export const microbitClassroomUrl = "https://classroom.microbit.org/";
diff --git a/src/flags.ts b/src/flags.ts
index 20a4a9073..0e6509d68 100644
--- a/src/flags.ts
+++ b/src/flags.ts
@@ -61,9 +61,10 @@ export type Flag =
*/
| "translate";
-interface FlagMetadata {
+// Exposed for testing.
+export interface FlagMetadata {
defaultOnStages: Stage[];
- name: Flag;
+ name: F;
}
const allFlags: FlagMetadata[] = [
@@ -73,7 +74,7 @@ const allFlags: FlagMetadata[] = [
{ name: "dndDebug", defaultOnStages: [] },
{ name: "noLang", defaultOnStages: [] },
{ name: "translate", defaultOnStages: [] },
- { name: "noWelcome", defaultOnStages: ["local", "REVIEW"] },
+ { name: "noWelcome", defaultOnStages: ["local"] },
{
name: "pwa",
defaultOnStages: ["REVIEW", "STAGING", "PRODUCTION"],
@@ -83,8 +84,17 @@ const allFlags: FlagMetadata[] = [
type Flags = Record;
-// Exposed for testing.
-export const flagsForParams = (stage: Stage, params: URLSearchParams) => {
+/**
+ * Resolves flag values from the stage, query params and local storage.
+ *
+ * The flag metadata is a parameter so tests can exercise the resolution
+ * rules without depending on the real flag defaults.
+ */
+export const flagsForParams = (
+ stage: Stage,
+ params: URLSearchParams,
+ flagMetadata: FlagMetadata[] = allFlags as FlagMetadata[]
+): Record => {
const enableFlags = new Set(params.getAll("flag"));
try {
localStorage
@@ -100,15 +110,15 @@ export const flagsForParams = (stage: Stage, params: URLSearchParams) => {
? true
: undefined;
return Object.fromEntries(
- allFlags.map((f) => [
+ flagMetadata.map((f) => [
f.name,
isEnabled(f, stage, allFlagsDefault, enableFlags.has(f.name)),
])
- ) as Flags;
+ ) as Record;
};
const isEnabled = (
- f: FlagMetadata,
+ f: FlagMetadata,
stage: Stage,
allFlagsDefault: boolean | undefined,
thisFlagOn: boolean
diff --git a/src/fs/StorageVersionErrorPage.tsx b/src/fs/StorageVersionErrorPage.tsx
new file mode 100644
index 000000000..a63750f3c
--- /dev/null
+++ b/src/fs/StorageVersionErrorPage.tsx
@@ -0,0 +1,56 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Button, Text } from "@microbit/ui";
+import { ErrorPage } from "@microbit/ui-patterns";
+import {
+ getCurrentProjectId,
+ sessionStorageIfPossible,
+} from "./current-project";
+import { databaseName } from "./projects-db";
+
+const deleteDatabase = (name: string) =>
+ new Promise((resolve, reject) => {
+ const request = indexedDB.deleteDatabase(name);
+ request.onsuccess = () => resolve();
+ request.onerror = () =>
+ reject(request.error ?? new Error("deleteDatabase failed"));
+ });
+
+/**
+ * Shown on non-public stages when the projects database was created by an
+ * incompatible build. Review builds share one database, so this is expected
+ * to happen there now and then; the fix is to start again.
+ *
+ * Deliberately untranslated: it never appears on a public deployment.
+ */
+const StorageVersionErrorPage = () => {
+ const handleClearAndReload = async () => {
+ try {
+ await deleteDatabase(databaseName());
+ } catch {
+ // Best effort; the reload will show this page again if it failed.
+ }
+ const session = sessionStorageIfPossible();
+ if (session && getCurrentProjectId(session)) {
+ session.removeItem("currentProjectId");
+ }
+ window.location.reload();
+ };
+ return (
+
+
+ The project storage format has changed in this pre-release version and
+ the old data is not supported. Clearing removes every project stored by
+ review builds in this browser.
+
+
+ Clear data and reload
+
+
+ );
+};
+
+export default StorageVersionErrorPage;
diff --git a/src/fs/current-project.test.ts b/src/fs/current-project.test.ts
new file mode 100644
index 000000000..72d07e89b
--- /dev/null
+++ b/src/fs/current-project.test.ts
@@ -0,0 +1,233 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import "fake-indexeddb/auto";
+import { renderHook } from "@testing-library/react";
+import { vi } from "vitest";
+import { MockLogging } from "../logging/mock";
+import {
+ chooseProject,
+ getCurrentProjectId,
+ migrateSessionProject,
+ openProjectsDatabase,
+ setCurrentProjectId,
+} from "./current-project";
+import { MAIN_FILE } from "./fs";
+import { testProjectLink } from "./project-link-test-data";
+import { databaseName, ProjectsDatabase } from "./projects-db";
+import { SessionStorageFSStorage } from "./storage";
+import {
+ hasStorageVersionError,
+ resetStorageStatus,
+ useProjectsDatabaseActive,
+} from "./storage-status";
+
+const deleteDatabase = () =>
+ new Promise((resolve, reject) => {
+ const request = indexedDB.deleteDatabase(databaseName());
+ request.onsuccess = () => resolve();
+ request.onerror = () =>
+ reject(request.error ?? new Error("deleteDatabase failed"));
+ });
+
+const encode = (text: string) => new TextEncoder().encode(text);
+const isActive = () =>
+ renderHook(() => useProjectsDatabaseActive()).result.current;
+
+describe("openProjectsDatabase", () => {
+ let logging: MockLogging;
+ beforeEach(async () => {
+ await deleteDatabase();
+ logging = new MockLogging();
+ resetStorageStatus();
+ });
+
+ it("opens the database and reports it active", async () => {
+ const db = await openProjectsDatabase(logging);
+ expect(db).toBeInstanceOf(ProjectsDatabase);
+ expect(isActive()).toEqual(true);
+ expect(logging.userProperties.project_storage).toEqual("database");
+ db!.close();
+ });
+
+ it("gives up and logs when the database cannot be opened", async () => {
+ vi.spyOn(ProjectsDatabase, "open").mockRejectedValueOnce(
+ new Error("blocked")
+ );
+ expect(await openProjectsDatabase(logging)).toBeUndefined();
+ expect(logging.errors[0].message).toMatch(/using session storage/);
+ expect(isActive()).toEqual(false);
+ expect(logging.userProperties.project_storage).toEqual(
+ "session_open_failed"
+ );
+ });
+
+ it("gives up quietly on an incompatible database on public stages", async () => {
+ vi.spyOn(ProjectsDatabase, "open").mockRejectedValueOnce(
+ new DOMException("nope", "VersionError")
+ );
+ expect(await openProjectsDatabase(logging, true)).toBeUndefined();
+ expect(hasStorageVersionError()).toEqual(false);
+ expect(logging.errors).toHaveLength(1);
+ });
+
+ it("reports an incompatible database for clearing on non-public stages", async () => {
+ vi.spyOn(ProjectsDatabase, "open").mockRejectedValueOnce(
+ new DOMException("nope", "VersionError")
+ );
+ expect(await openProjectsDatabase(logging, false)).toBeUndefined();
+ expect(logging.errors).toEqual([]);
+ expect(hasStorageVersionError()).toEqual(true);
+ expect(logging.userProperties.project_storage).toEqual(
+ "session_open_failed"
+ );
+ });
+
+ it("gives up without IndexedDB", async () => {
+ const original = globalThis.indexedDB;
+ Object.defineProperty(globalThis, "indexedDB", {
+ value: undefined,
+ configurable: true,
+ });
+ try {
+ expect(await openProjectsDatabase(logging)).toBeUndefined();
+ expect(logging.userProperties.project_storage).toEqual(
+ "session_no_indexeddb"
+ );
+ } finally {
+ Object.defineProperty(globalThis, "indexedDB", {
+ value: original,
+ configurable: true,
+ });
+ }
+ });
+});
+
+describe("chooseProject", () => {
+ let counter = 0;
+ let db: ProjectsDatabase;
+ beforeEach(async () => {
+ sessionStorage.clear();
+ db = await ProjectsDatabase.open(`choose-${Date.now()}-${counter++}`);
+ });
+ afterEach(() => db.close());
+
+ it("creates a project with the starter program when there is nothing", async () => {
+ const id = await chooseProject(db, sessionStorage);
+ expect(getCurrentProjectId(sessionStorage)).toEqual(id);
+ expect((await db.list()).map((p) => p.id)).toEqual([id]);
+ expect(await db.fileNames(id)).toEqual([MAIN_FILE]);
+ });
+
+ it("reopens the tab's current project and marks it most recent", async () => {
+ await db.create({ id: "old", name: "Old", timestamp: 1 }, {});
+ await db.create({ id: "cur", name: "Cur", timestamp: 2 }, {});
+ await db.touch("old", 3);
+ setCurrentProjectId(sessionStorage, "cur");
+
+ expect(await chooseProject(db, sessionStorage)).toEqual("cur");
+ expect((await db.mostRecent())?.id).toEqual("cur");
+ });
+
+ it("opens the most recent project when the tab has none", async () => {
+ await db.create({ id: "old", name: "Old", timestamp: 1 }, {});
+ await db.create({ id: "recent", name: "Recent", timestamp: 2 }, {});
+
+ expect(await chooseProject(db, sessionStorage)).toEqual("recent");
+ expect(getCurrentProjectId(sessionStorage)).toEqual("recent");
+ });
+
+ it("falls back to the most recent when the tab's project is gone", async () => {
+ await db.create({ id: "recent", name: "Recent", timestamp: 2 }, {});
+ setCurrentProjectId(sessionStorage, "deleted");
+
+ expect(await chooseProject(db, sessionStorage)).toEqual("recent");
+ });
+
+ it("makes a #project: link a new project ahead of everything", async () => {
+ await db.create({ id: "cur", name: "Cur", timestamp: 2 }, {});
+ setCurrentProjectId(sessionStorage, "cur");
+ const id = await chooseProject(db, sessionStorage, testProjectLink);
+
+ expect(id).not.toEqual("cur");
+ expect(getCurrentProjectId(sessionStorage)).toEqual(id);
+ expect((await db.get(id))?.name).toEqual("Hearts");
+ expect(new TextDecoder().decode(await db.file(id, MAIN_FILE))).toMatch(
+ /display.show\(Image.HEART\)/
+ );
+ });
+});
+
+describe("migrateSessionProject", () => {
+ let db: ProjectsDatabase;
+ beforeEach(async () => {
+ sessionStorage.clear();
+ db = await ProjectsDatabase.open(`migrate-${Date.now()}-${Math.random()}`);
+ });
+ afterEach(() => {
+ db.close();
+ });
+
+ const leaveSessionProject = async () => {
+ const legacy = new SessionStorageFSStorage(sessionStorage);
+ await legacy.write("main.py", encode("# mine"));
+ await legacy.write("helper.py", encode("# helper"));
+ await legacy.setProjectName("My project");
+ return legacy;
+ };
+
+ it("does nothing when session storage has no project", async () => {
+ setCurrentProjectId(sessionStorage, "current");
+ expect(await migrateSessionProject(db, sessionStorage)).toBeUndefined();
+ expect(await migrateSessionProject(db, undefined)).toBeUndefined();
+ expect(await db.list()).toEqual([]);
+ expect(getCurrentProjectId(sessionStorage)).toEqual("current");
+ });
+
+ it("moves the project and makes it the tab's current project", async () => {
+ const legacy = await leaveSessionProject();
+ sessionStorage.setItem("unrelated", "kept");
+ // As when the tab has been to another deployment on the same origin.
+ setCurrentProjectId(sessionStorage, "from-elsewhere");
+
+ const id = await migrateSessionProject(db, sessionStorage);
+
+ expect((await db.get(id!))?.name).toEqual("My project");
+ expect(await db.fileNames(id!)).toEqual(["helper.py", "main.py"]);
+ expect(Array.from((await db.file(id!, "main.py"))!)).toEqual(
+ Array.from(encode("# mine"))
+ );
+ expect(await legacy.ls()).toEqual([]);
+ expect(sessionStorage.getItem("unrelated")).toEqual("kept");
+ expect(getCurrentProjectId(sessionStorage)).toEqual(id);
+ // Only once.
+ expect(await migrateSessionProject(db, sessionStorage)).toBeUndefined();
+ });
+
+ it("is then what the editor opens, ahead of a more recent project", async () => {
+ await leaveSessionProject();
+ const id = await migrateSessionProject(db, sessionStorage);
+ await db.create(
+ { id: "newer", name: "Newer", timestamp: Date.now() + 1000 },
+ {}
+ );
+
+ expect(await chooseProject(db, sessionStorage)).toEqual(id);
+ });
+
+ it("leaves the session copy for another try if the write fails", async () => {
+ const legacy = await leaveSessionProject();
+ setCurrentProjectId(sessionStorage, "current");
+ vi.spyOn(db, "create").mockRejectedValueOnce(new Error("Simulated"));
+
+ await expect(migrateSessionProject(db, sessionStorage)).rejects.toThrow(
+ "Simulated"
+ );
+
+ expect((await legacy.ls()).sort()).toEqual(["helper.py", "main.py"]);
+ expect(await legacy.projectName()).toEqual("My project");
+ expect(getCurrentProjectId(sessionStorage)).toEqual("current");
+ });
+});
diff --git a/src/fs/current-project.ts b/src/fs/current-project.ts
new file mode 100644
index 000000000..571e2dca0
--- /dev/null
+++ b/src/fs/current-project.ts
@@ -0,0 +1,202 @@
+/**
+ * Which project the editor opens, and its storage.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { toByteArray } from "base64-js";
+import { isPublicFacingStage } from "../environment";
+import { Logging } from "../logging/logging";
+import { generateId } from "./fs-util";
+import { MAIN_FILE } from "./fs";
+import { defaultInitialProject } from "./initial-project";
+import { ProjectLink } from "./project-link";
+import { ProjectsDatabase } from "./projects-db";
+import { SessionStorageFSStorage } from "./storage";
+import {
+ reportProjectsDatabaseActive,
+ reportStorageVersionError,
+} from "./storage-status";
+
+/**
+ * The open project is per tab, as the whole project used to be.
+ */
+const currentProjectKey = "currentProjectId";
+
+export const getCurrentProjectId = (
+ session: Storage | undefined
+): string | undefined => session?.getItem(currentProjectKey) ?? undefined;
+
+export const setCurrentProjectId = (
+ session: Storage | undefined,
+ id: string | undefined
+): void => {
+ if (id === undefined) {
+ session?.removeItem(currentProjectKey);
+ } else {
+ session?.setItem(currentProjectKey, id);
+ }
+};
+
+export const sessionStorageIfPossible = (): Storage | undefined => {
+ try {
+ return window.sessionStorage;
+ } catch {
+ // SecurityError in some embedding scenarios (issue 736) and no window in
+ // tests; either way there is nothing to read.
+ return undefined;
+ }
+};
+
+/**
+ * Where a tab keeps its project, as the project_storage user property.
+ *
+ * It is there to answer one question: how many sessions really run without
+ * the projects database, and why. That decides whether the session-storage
+ * fallback earns its keep.
+ */
+export type ProjectStorageMode =
+ | "database"
+ | "session_no_indexeddb"
+ | "session_open_failed"
+ // Iframe controller mode: the embedding page keeps the project.
+ | "host";
+
+export const reportProjectStorageMode = (
+ logging: Logging,
+ mode: ProjectStorageMode
+): void => logging.setUserProperty("project_storage", mode);
+
+/**
+ * Opens the projects database, or explains why not.
+ *
+ * Without IndexedDB (unavailable, blocked, or an incompatible database) the
+ * result is undefined and the editor falls back to session storage, which is
+ * what it used before. On non-public stages an incompatible database is
+ * reported for the UI to offer clearing it instead, since review builds share
+ * one database.
+ */
+export const openProjectsDatabase = async (
+ logging: Logging,
+ publicFacing: boolean = isPublicFacingStage()
+): Promise => {
+ if (typeof indexedDB === "undefined") {
+ reportProjectStorageMode(logging, "session_no_indexeddb");
+ return undefined;
+ }
+ try {
+ const db = await ProjectsDatabase.open();
+ reportProjectsDatabaseActive();
+ reportProjectStorageMode(logging, "database");
+ return db;
+ } catch (e) {
+ reportProjectStorageMode(logging, "session_open_failed");
+ if (isVersionError(e) && !publicFacing) {
+ reportStorageVersionError(e);
+ } else {
+ logging.error("Projects database unavailable, using session storage", e);
+ }
+ return undefined;
+ }
+};
+
+/**
+ * The files of a new project: the starter program.
+ */
+export const defaultProjectFiles = (): Record =>
+ Object.fromEntries(
+ Object.entries(defaultInitialProject.files).map(([name, base64]) => [
+ name,
+ toByteArray(base64),
+ ])
+ );
+
+/**
+ * The files of a project shared as a #project: link.
+ */
+export const projectLinkFiles = (
+ link: ProjectLink
+): Record => ({
+ [MAIN_FILE]: new TextEncoder().encode(link.source),
+});
+
+/**
+ * Decides which project the editor opens and marks it most recent.
+ *
+ * In order: a new project from the #project: link the app booted with; the
+ * project the tab already has open, which includes one that
+ * migrateSessionProject brought in; the most recently used project, so a
+ * straight-to-editor bookmark keeps working; otherwise a new project.
+ */
+export const chooseProject = async (
+ db: ProjectsDatabase,
+ session: Storage | undefined,
+ link?: ProjectLink
+): Promise => {
+ if (link) {
+ const id = generateId();
+ await db.create(
+ { id, name: link.meta.name, timestamp: Date.now() },
+ projectLinkFiles(link)
+ );
+ setCurrentProjectId(session, id);
+ return id;
+ }
+ const current = getCurrentProjectId(session);
+ if (current && (await db.get(current))) {
+ await db.touch(current);
+ return current;
+ }
+ const recent = await db.mostRecent();
+ if (recent) {
+ await db.touch(recent.id);
+ setCurrentProjectId(session, recent.id);
+ return recent.id;
+ }
+ const id = generateId();
+ await db.create(
+ { id, name: undefined, timestamp: Date.now() },
+ defaultProjectFiles()
+ );
+ setCurrentProjectId(session, id);
+ return id;
+};
+
+/**
+ * Moves the single project that the editor kept in session storage, before
+ * the projects database, into the database, and makes it the tab's current
+ * project, which is what it was. The session storage copy is removed so
+ * this happens once. If the database write fails it is left for another
+ * try.
+ *
+ * Only an earlier version of the app, or this one without the database,
+ * writes a project to session storage, so once this has run for a page
+ * load there is nothing more to find.
+ *
+ * @returns The new project's id, or undefined if there was none to move.
+ */
+export const migrateSessionProject = async (
+ db: ProjectsDatabase,
+ session: Storage | undefined
+): Promise => {
+ const legacy = session && new SessionStorageFSStorage(session);
+ if (!legacy || (await legacy.ls()).length === 0) {
+ return undefined;
+ }
+ const files: Record = {};
+ for (const name of await legacy.ls()) {
+ files[name] = await legacy.read(name);
+ }
+ const id = generateId();
+ await db.create(
+ { id, name: await legacy.projectName(), timestamp: Date.now() },
+ files
+ );
+ await legacy.removeAll();
+ setCurrentProjectId(session, id);
+ return id;
+};
+
+const isVersionError = (e: unknown): boolean =>
+ e instanceof DOMException && e.name === "VersionError";
diff --git a/src/fs/fs-util.ts b/src/fs/fs-util.ts
index 6e85f0c00..a6b331fdc 100644
--- a/src/fs/fs-util.ts
+++ b/src/fs/fs-util.ts
@@ -93,3 +93,7 @@ export const extractModuleData = (code: string): ModuleData | undefined => {
export const generateId = () =>
Math.random().toString(36).substring(2) +
Math.random().toString(36).substring(2);
+
+// Here rather than in fs.ts so initial-project.ts can name the file without
+// importing the file system, which imports the initial project back.
+export const MAIN_FILE = "main.py";
diff --git a/src/fs/fs.test.ts b/src/fs/fs.test.ts
index baa8cc299..49a7d7286 100644
--- a/src/fs/fs.test.ts
+++ b/src/fs/fs.test.ts
@@ -20,6 +20,7 @@ import {
} from "./fs";
import { DefaultHost } from "./host";
import { defaultInitialProject } from "./initial-project";
+import { InMemoryFSStorage } from "./storage";
const hexes = [
fs.readFileSync("src/micropython/microbit-micropython-v1.hex", {
@@ -147,9 +148,11 @@ describe("Filesystem", () => {
await ufs.write("other.txt", "content", VersionAction.INCREMENT);
const originalId = ufs.project.id;
- await ufs.replaceWithHexContents(
+ await ufs.replaceWithFiles(
"new project name",
- await fsp.readFile("testData/1.0.1.hex", { encoding: "ascii" })
+ await ufs.filesFromHex(
+ await fsp.readFile("testData/1.0.1.hex", { encoding: "ascii" })
+ )
);
expect(await asString(ufs.read(MAIN_FILE))).toMatch(/PASS1/);
@@ -159,6 +162,28 @@ describe("Filesystem", () => {
expect(ufs.project.id === originalId).toEqual(false);
});
+ it("reads the appended script of an old hex as main.py", async () => {
+ const files = await ufs.filesFromHex(
+ await fsp.readFile("testData/0.9.hex", { encoding: "ascii" })
+ );
+ expect(Object.keys(files)).toEqual([MAIN_FILE]);
+ expect(new TextDecoder().decode(files[MAIN_FILE])).toMatch(/PASS2/);
+ });
+
+ it("rejects a hex with no Python", async () => {
+ await expect(ufs.filesFromHex(hexes[1])).rejects.toThrow(
+ "No appended code found in the hex file"
+ );
+ });
+
+ it("reading a hex leaves the open project alone", async () => {
+ await ufs.initialize();
+ await ufs.filesFromHex(
+ await fsp.readFile("testData/1.0.1.hex", { encoding: "ascii" })
+ );
+ expect(await asString(ufs.read(MAIN_FILE))).not.toMatch(/PASS1/);
+ });
+
it("can order files ascendingly according to their file names", async () => {
await ufs.initialize();
@@ -178,9 +203,11 @@ describe("Filesystem", () => {
await ufs.setProjectName("new name");
expect(ufs.dirty).toEqual(true);
- await ufs.replaceWithHexContents(
+ await ufs.replaceWithFiles(
"different name",
- await fsp.readFile("testData/1.0.1.hex", { encoding: "ascii" })
+ await ufs.filesFromHex(
+ await fsp.readFile("testData/1.0.1.hex", { encoding: "ascii" })
+ )
);
expect(ufs.dirty).toEqual(false);
@@ -295,5 +322,186 @@ describe("fs - diff", () => {
});
});
+describe("Filesystem switchStorage", () => {
+ const logging = new ConsoleLogging();
+ const host = new DefaultHost();
+ const encode = (text: string) => new TextEncoder().encode(text);
+
+ const otherProject = async () => {
+ const storage = new InMemoryFSStorage("Other project");
+ await storage.write(MAIN_FILE, encode("# other main"));
+ await storage.write("helper.py", encode("# helper"));
+ await storage.markDirty();
+ return storage;
+ };
+
+ it("presents the new storage's files, name and dirty flag", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ const events: Project[] = [];
+ ufs.addEventListener("project_updated", (e) => {
+ events.push(e.project);
+ });
+
+ const storage = await otherProject();
+ await ufs.switchStorage(storage);
+
+ expect(ufs.project.name).toEqual("Other project");
+ expect(ufs.project.files.map((f) => f.name)).toEqual([
+ MAIN_FILE,
+ "helper.py",
+ ]);
+ expect(await asString(ufs.read(MAIN_FILE))).toEqual("# other main");
+ expect(ufs.dirty).toEqual(true);
+ expect(events).toHaveLength(1);
+ });
+
+ it("bumps versions so editors reload the same-named file", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ const before = ufs.project.files.find((f) => f.name === MAIN_FILE)!;
+
+ await ufs.switchStorage(await otherProject());
+
+ const after = ufs.project.files.find((f) => f.name === MAIN_FILE)!;
+ expect(after.version).toBeGreaterThan(before.version);
+ });
+
+ it("gives the project a new id", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ const before = ufs.project.id;
+ await ufs.switchStorage(await otherProject());
+ expect(ufs.project.id).not.toEqual(before);
+ });
+
+ it("refills the hex file system from the new storage", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ await ufs.switchStorage(await otherProject());
+
+ const stats = await ufs.statistics();
+ expect(stats.files).toEqual(2);
+ expect(await ufs.toHexForSave()).toContain(":");
+ });
+
+ it("directs later writes and removes to the new storage only", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ const storage = await otherProject();
+ await ufs.switchStorage(storage);
+
+ await ufs.write("new.py", "# new", VersionAction.INCREMENT);
+ await ufs.remove("helper.py");
+
+ expect(await storage.ls()).toEqual([MAIN_FILE, "new.py"]);
+ const original = await new DefaultHost().createStorage(logging).ls();
+ expect(original).not.toContain("new.py");
+ });
+
+ it("waits for an in-flight initialisation", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ const initializing = ufs.initialize();
+ await ufs.switchStorage(await otherProject());
+ await initializing;
+
+ expect(ufs.project.name).toEqual("Other project");
+ expect(await asString(ufs.read(MAIN_FILE))).toEqual("# other main");
+ expect((await ufs.statistics()).files).toEqual(2);
+ });
+
+ it("tries initialisation again after each failure, not only the first", async () => {
+ let failures = 2;
+ let attempts = 0;
+ const ufs = new FileSystem(logging, host, async () => {
+ attempts++;
+ if (failures-- > 0) {
+ throw new Error("Simulated MicroPython load failure");
+ }
+ return fsMicroPythonSource();
+ });
+ // Fails in the background, then again when something needs it.
+ await ufs.initializeInBackground();
+ await expect(ufs.toHexForSave()).rejects.toThrow(/Simulated/);
+ await expect(ufs.toHexForSave()).rejects.toThrow(/Simulated/);
+
+ expect(typeof (await ufs.toHexForSave())).toEqual("string");
+ expect(attempts).toEqual(3);
+ });
+
+ it("switches after a failed initialisation, which a retry builds from the new storage", async () => {
+ let fail = true;
+ const ufs = new FileSystem(logging, host, async () => {
+ if (fail) {
+ fail = false;
+ throw new Error("Simulated MicroPython load failure");
+ }
+ return fsMicroPythonSource();
+ });
+ await ufs.initializeInBackground();
+
+ await ufs.switchStorage(await otherProject());
+
+ expect(ufs.project.name).toEqual("Other project");
+ expect((await ufs.statistics()).files).toEqual(2);
+ });
+});
+
+describe("Filesystem reloadStorage", () => {
+ const logging = new ConsoleLogging();
+ const host = new DefaultHost();
+ const encode = (text: string) => new TextEncoder().encode(text);
+
+ const project = async (files: Record) => {
+ const storage = new InMemoryFSStorage("Project");
+ for (const [name, text] of Object.entries(files)) {
+ await storage.write(name, encode(text));
+ }
+ return storage;
+ };
+
+ const versions = (ufs: FileSystem) =>
+ Object.fromEntries(ufs.project.files.map((f) => [f.name, f.version]));
+
+ it("keeps the project id and bumps only changed and added files", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ await ufs.switchStorage(
+ await project({ [MAIN_FILE]: "# main", "helper.py": "# helper" })
+ );
+ const id = ufs.project.id;
+ const before = versions(ufs);
+
+ await ufs.reloadStorage(
+ await project({
+ [MAIN_FILE]: "# main",
+ "helper.py": "# helper changed",
+ "added.py": "# added",
+ })
+ );
+
+ expect(ufs.project.id).toEqual(id);
+ const after = versions(ufs);
+ expect(after[MAIN_FILE]).toEqual(before[MAIN_FILE]);
+ expect(after["helper.py"]).toBeGreaterThan(before["helper.py"]);
+ expect(after["added.py"]).toBeDefined();
+ expect(await asString(ufs.read("helper.py"))).toEqual("# helper changed");
+ expect((await ufs.statistics()).files).toEqual(3);
+ });
+
+ it("drops removed files", async () => {
+ const ufs = new FileSystem(logging, host, fsMicroPythonSource);
+ await ufs.initialize();
+ await ufs.switchStorage(
+ await project({ [MAIN_FILE]: "# main", "helper.py": "# helper" })
+ );
+
+ await ufs.reloadStorage(await project({ [MAIN_FILE]: "# main" }));
+
+ expect(ufs.project.files.map((f) => f.name)).toEqual([MAIN_FILE]);
+ expect((await ufs.statistics()).files).toEqual(1);
+ });
+});
+
const asString = async (f: Promise) =>
new TextDecoder().decode((await f).data);
diff --git a/src/fs/fs.ts b/src/fs/fs.ts
index c032246fb..f60a9a2ac 100644
--- a/src/fs/fs.ts
+++ b/src/fs/fs.ts
@@ -7,6 +7,7 @@ import {
getIntelHexAppendedScript,
microbitBoardId,
MicropythonFsHex,
+ IntelHexWithId,
} from "@microbit/microbit-fs";
import { fromByteArray, toByteArray } from "base64-js";
import { sortBy } from "../common/sort-util";
@@ -14,14 +15,17 @@ import { lineNumFromUint8Array } from "../common/text-util";
import { FlashDataError, BoardVersion } from "@microbit/microbit-connection";
import { Logging } from "../logging/logging";
import { MicroPythonSource } from "../micropython/micropython";
-import { extractModuleData, generateId } from "./fs-util";
+import { extractModuleData, generateId, MAIN_FILE } from "./fs-util";
import { Host } from "./host";
-import { PythonProject } from "./initial-project";
+import { defaultInitialProject, PythonProject } from "./initial-project";
import { FSStorage } from "./storage";
import { TypedEventTarget } from "../common/events";
const commonFsSize = 20 * 1024;
+const bytesEqual = (a: Uint8Array, b: Uint8Array): boolean =>
+ a.length === b.length && a.every((byte, i) => byte === b[i]);
+
export interface FileVersion {
name: string;
version: number;
@@ -151,7 +155,7 @@ class EventMap {
"file_text_updated": TextEditEvent;
}
-export const MAIN_FILE = "main.py";
+export { MAIN_FILE };
export const isNameLengthValid = (filename: string): boolean =>
// This length is enforced by the underlying FS so we check it in the UI ahead of time.
@@ -160,8 +164,9 @@ export const isNameLengthValid = (filename: string): boolean =>
/**
* The MicroPython file system adapted for convienient use from the UI.
*
- * For now we store contents backed by session storage so they're only
- * persistent over a browser refresh or Chrome tab restore.
+ * Contents are held in memory and mirrored to the host's persistent storage:
+ * the current project in the IndexedDB projects database, or session storage where
+ * that is unavailable.
*
* We version files in a way that's designed to make UI updates simple.
* If a UI action updates a file (e.g. load from disk) then we bump its version.
@@ -209,14 +214,15 @@ export class FileSystem extends TypedEventTarget {
async initializeInBackground() {
// It's been observed that this can be slow after the fetch on low-end devices,
// so it might be good to move the FS work to a worker if we can't make it fast.
- this.initialize().catch((_) => {
- this.initializing = undefined;
+ this.initialize().catch(() => {
+ // Whatever next needs the file system tries again.
});
}
/**
- * We remember this so we can tell whether the user has edited
- * the project since for stats generation.
+ * The project the host supplied, if it initialized one this session, so
+ * stats can tell whether the user has edited it. Projects from the
+ * projects database never come this way.
*/
private cachedInitialProject: PythonProject | undefined;
@@ -226,26 +232,32 @@ export class FileSystem extends TypedEventTarget {
}
if (!this.initializing) {
this.initializing = (async () => {
- this._dirty = await this.storage.isDirty();
- if (await this.host.shouldReinitializeProject(this.storage)) {
- // Do this ASAP to unblock the editor.
- this.cachedInitialProject = await this.host.createInitialProject();
- if (this.cachedInitialProject.projectName) {
- await this.setProjectName(this.cachedInitialProject.projectName);
- }
- for (const key in this.cachedInitialProject.files) {
- const content = toByteArray(this.cachedInitialProject.files[key]);
- await this.write(key, content, VersionAction.INCREMENT);
+ try {
+ this._dirty = await this.storage.isDirty();
+ if (await this.host.shouldReinitializeProject(this.storage)) {
+ // Do this ASAP to unblock the editor.
+ this.cachedInitialProject = await this.host.createInitialProject();
+ if (this.cachedInitialProject.projectName) {
+ await this.setProjectName(this.cachedInitialProject.projectName);
+ }
+ for (const key in this.cachedInitialProject.files) {
+ const content = toByteArray(this.cachedInitialProject.files[key]);
+ await this.write(key, content, VersionAction.INCREMENT);
+ }
+ this.host.notifyReady(this);
+ } else {
+ await this.notify();
}
- this.host.notifyReady(this);
- } else {
- await this.notify();
- }
- const fs = await this.createInternalFileSystem();
- await this.initializeFsFromStorage(fs);
- this.fs = fs;
- this.initializing = undefined;
+ const fs = await this.createInternalFileSystem();
+ await this.initializeFsFromStorage(fs);
+ this.fs = fs;
+ } finally {
+ // On failure too, or every later call would be handed this
+ // attempt's failure rather than trying again, for instance once
+ // the network is back.
+ this.initializing = undefined;
+ }
await this.notify();
})();
}
@@ -253,6 +265,55 @@ export class FileSystem extends TypedEventTarget {
return this.fs!;
}
+ /**
+ * Switch to a different backing storage, typically another project.
+ *
+ * The new storage is the record from here on: reads, writes and the hex
+ * file system all reflect it. Versions of files present in the new storage
+ * are bumped so editors showing a same-named file reload it.
+ */
+ async switchStorage(storage: FSStorage): Promise {
+ // A failed initialisation is retried later, from the new storage.
+ await this.initializing?.catch(() => undefined);
+ this.project = { ...this.project, id: generateId() };
+ return this.adoptStorage(storage, await storage.ls());
+ }
+
+ /**
+ * Switch to storage holding a later copy of the open project, such as
+ * another tab has saved. Unlike switchStorage the project keeps its id and
+ * only files whose content differs are bumped, so the selected file and
+ * editors showing other files are left alone.
+ */
+ async reloadStorage(storage: FSStorage): Promise {
+ await this.initializing?.catch(() => undefined);
+ const changed: string[] = [];
+ for (const name of await storage.ls()) {
+ const before = (await this.storage.exists(name))
+ ? await this.storage.read(name)
+ : undefined;
+ if (!before || !bytesEqual(before, await storage.read(name))) {
+ changed.push(name);
+ }
+ }
+ return this.adoptStorage(storage, changed);
+ }
+
+ private async adoptStorage(
+ storage: FSStorage,
+ changed: string[]
+ ): Promise {
+ this.storage = storage;
+ this._dirty = await storage.isDirty();
+ if (this.fs) {
+ await this.initializeFsFromStorage(this.fs);
+ }
+ for (const name of changed) {
+ this.incrementFileVersion(name);
+ }
+ return this.notify();
+ }
+
/**
* Update the project name.
*
@@ -354,34 +415,50 @@ export class FileSystem extends TypedEventTarget {
}
async replaceWithMultipleFiles(project: PythonProject): Promise {
+ const files = Object.fromEntries(
+ Object.entries(project.files).map(([name, base64]) => [
+ name,
+ toByteArray(base64),
+ ])
+ );
+ await this.replaceWithFiles(project.projectName, files);
+ }
+
+ /**
+ * Replace the project's files and name. For the single implicit project
+ * of the iframe and session-storage cases; with the projects database an
+ * import becomes a new project instead.
+ */
+ async replaceWithFiles(
+ projectName: string | undefined,
+ files: Record
+ ): Promise {
const fs = await this.initialize();
fs.ls().forEach((f) => fs.remove(f));
- for (const key in project.files) {
- const content = toByteArray(project.files[key]);
- fs.write(key, content);
+ for (const [name, content] of Object.entries(files)) {
+ fs.write(name, content);
}
- await this.replaceCommon(project.projectName);
+ await this.replaceCommon(projectName);
}
- async replaceWithHexContents(
- projectName: string,
- hex: string
- ): Promise {
- const fs = await this.initialize();
+ /**
+ * The files in a hex saved by the editor, or the script appended to a hex
+ * by older editors as main.py. Throws if there is neither.
+ *
+ * Uses a separate file system so the open project is untouched.
+ */
+ async filesFromHex(hex: string): Promise> {
+ const fs = await this.createInternalFileSystem();
try {
- fs.importFilesFromHex(hex, {
- overwrite: true,
- formatFirst: true,
- });
+ fs.importFilesFromHex(hex, { overwrite: true, formatFirst: true });
} catch {
const code = getIntelHexAppendedScript(hex);
if (!code) {
throw new Error("No appended code found in the hex file");
}
- fs.ls().forEach((f) => fs.remove(f));
- fs.write(MAIN_FILE, code);
+ return { [MAIN_FILE]: new TextEncoder().encode(code) };
}
- await this.replaceCommon(projectName);
+ return Object.fromEntries(fs.ls().map((f) => [f, fs.readBytes(f)]));
}
async replaceCommon(projectName?: string): Promise {
@@ -419,8 +496,9 @@ export class FileSystem extends TypedEventTarget {
storageUsed: fs.getStorageUsed(),
lines: lineNumFromUint8Array(currentMainFile),
defaultMain:
- this.cachedInitialProject?.files[MAIN_FILE] ===
- fromByteArray(currentMainFile),
+ (this.cachedInitialProject ?? defaultInitialProject).files[
+ MAIN_FILE
+ ] === fromByteArray(currentMainFile),
magicModules: numMagicModules,
};
}
@@ -507,9 +585,16 @@ export class FileSystem extends TypedEventTarget {
}
}
+ private microPython: Promise | undefined;
+
private createInternalFileSystem = async () => {
- const microPython = await this.microPythonSource();
- return new MicropythonFsHex(microPython, {
+ // Fetched once for the open project and any hex imports; a failed fetch
+ // is forgotten so the next attempt retries it.
+ this.microPython ??= this.microPythonSource().catch((e) => {
+ this.microPython = undefined;
+ throw e;
+ });
+ return new MicropythonFsHex(await this.microPython, {
maxFsSize: commonFsSize,
});
};
diff --git a/src/fs/host-default.test.ts b/src/fs/host-default.test.ts
index 2853c2e27..005b94948 100644
--- a/src/fs/host-default.test.ts
+++ b/src/fs/host-default.test.ts
@@ -5,13 +5,14 @@
import { fromByteArray } from "base64-js";
import { MAIN_FILE } from "./fs";
import { DefaultHost } from "./host";
+import { PendingProjectLink } from "./project-link";
import { defaultInitialProject } from "./initial-project";
-import { testMigrationUrl } from "./migration-test-data";
+import { testProjectLink } from "./project-link-test-data";
describe("DefaultHost", () => {
- it("uses migration if available", async () => {
+ it("uses the project link if there is one", async () => {
const project = await new DefaultHost(
- testMigrationUrl
+ new PendingProjectLink(testProjectLink)
).createInitialProject();
expect(project).toEqual({
files: {
@@ -25,7 +26,7 @@ describe("DefaultHost", () => {
});
});
it("otherwise uses defaults", async () => {
- const project = await new DefaultHost("").createInitialProject();
+ const project = await new DefaultHost().createInitialProject();
expect(project).toEqual(defaultInitialProject);
});
});
diff --git a/src/fs/host.ts b/src/fs/host.ts
index 37480617f..4f7028608 100644
--- a/src/fs/host.ts
+++ b/src/fs/host.ts
@@ -11,13 +11,8 @@ import {
PythonProject,
projectFilesToBase64,
} from "./initial-project";
-import { parseMigrationFromUrl } from "./migration";
-import {
- FSStorage,
- InMemoryFSStorage,
- SessionStorageFSStorage,
- SplitStrategyStorage,
-} from "./storage";
+import { PendingProjectLink } from "./project-link";
+import { DeferredFSStorage, FSStorage, InMemoryFSStorage } from "./storage";
const messages = {
type: "pyeditor",
@@ -37,38 +32,44 @@ export interface Host {
}
export class DefaultHost implements Host {
- constructor(private url: string = "") {}
+ /**
+ * @param projectLink The #project: link at boot, if the projects session
+ * has not already made a project of it.
+ * @param projectStorage The project's storage, once one is opened. Until
+ * then the file system waits. Without one the project stays in memory.
+ */
+ constructor(
+ private projectLink: PendingProjectLink = new PendingProjectLink(),
+ private projectStorage?: Promise
+ ) {}
- createStorage(logging: Logging): FSStorage {
- return new SplitStrategyStorage(
- new InMemoryFSStorage(undefined),
- SessionStorageFSStorage.create(),
- logging
- );
+ createStorage(_logging: Logging): FSStorage {
+ return this.projectStorage
+ ? new DeferredFSStorage(this.projectStorage)
+ : new InMemoryFSStorage(undefined);
}
async shouldReinitializeProject(storage: FSStorage): Promise {
- const migration = parseMigrationFromUrl(this.url);
- if (migration) {
- return true;
- }
- return !(await storage.exists(MAIN_FILE));
+ // Waits for the project's storage, by which time the projects session
+ // has taken a #project: link if it is going to.
+ const hasMain = await storage.exists(MAIN_FILE);
+ return this.projectLink.pending || !hasMain;
}
async createInitialProject(): Promise {
- const migrationParseResult = parseMigrationFromUrl(this.url);
- if (migrationParseResult) {
- const { migration, postMigrationUrl } = migrationParseResult;
- const project = {
+ const link = this.projectLink.take();
+ if (link) {
+ // The path may have changed since boot (the root redirects to the
+ // editor), so strip the hash from the current URL rather than using
+ // the parsed one.
+ const { pathname, search } = window.location;
+ window.history.replaceState(null, "", pathname + search);
+ return {
files: projectFilesToBase64({
- [MAIN_FILE]: migration.source,
+ [MAIN_FILE]: link.source,
}),
- projectName: migration.meta.name,
+ projectName: link.meta.name,
};
- // Remove the migration information from the URL so that a refresh
- // will reload from storage not remigrate.
- window.history.replaceState(null, "", postMigrationUrl);
- return project;
}
return defaultInitialProject;
}
@@ -147,12 +148,16 @@ export class IframeHost implements Host {
}
}
-export const createHost = (logging: Logging): Host => {
+export const createHost = (
+ logging: Logging,
+ projectLink: PendingProjectLink,
+ projectStorage: Promise
+): Host => {
const iframeHost = getControllerHost(logging);
if (iframeHost) {
return new IframeHost(iframeHost, window);
}
- return new DefaultHost(window.location.href);
+ return new DefaultHost(projectLink, projectStorage);
};
const getControllerHost = (logging: Logging): Window | undefined => {
diff --git a/src/fs/indexeddb-storage.test.ts b/src/fs/indexeddb-storage.test.ts
new file mode 100644
index 000000000..e808a6553
--- /dev/null
+++ b/src/fs/indexeddb-storage.test.ts
@@ -0,0 +1,277 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import "fake-indexeddb/auto";
+import { vi } from "vitest";
+import { IndexedDBFSStorage } from "./indexeddb-storage";
+import { ProjectsDatabase } from "./projects-db";
+import { commonStorageTests } from "./storage-tests";
+
+let counter = 0;
+const uniqueName = () => `test-${Date.now()}-${counter++}`;
+const projectId = "p1";
+const contents = (files: Record) =>
+ Object.fromEntries(
+ Object.entries(files).map(([name, data]) => [name, Array.from(data)])
+ );
+
+const openWithProject = async () => {
+ const db = await ProjectsDatabase.open(uniqueName());
+ await db.create({ id: projectId, name: undefined, timestamp: 1 }, {});
+ return db;
+};
+
+describe("IndexedDBFSStorage", () => {
+ let db: ProjectsDatabase;
+ let storage: IndexedDBFSStorage;
+ let errors: unknown[];
+ let changes: number;
+ beforeEach(async () => {
+ db = await openWithProject();
+ errors = [];
+ changes = 0;
+ storage = new IndexedDBFSStorage(
+ db,
+ { id: projectId, name: undefined, timestamp: 1 },
+ (e) => errors.push(e),
+ () => changes++,
+ 20
+ );
+ });
+ afterEach(async () => {
+ await storage.dispose();
+ db.close();
+ });
+
+ commonStorageTests(() => storage);
+
+ it("coalesces writes into one transaction after the delay", async () => {
+ const save = vi.spyOn(db, "save");
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.write("main.py", new Uint8Array([2]));
+ await storage.write("other.py", new Uint8Array([3]));
+ await storage.setProjectName("Renamed");
+ expect(save).not.toHaveBeenCalled();
+
+ await new Promise((resolve) => setTimeout(resolve, 40));
+
+ expect(save).toHaveBeenCalledTimes(1);
+ expect(contents(await db.files(projectId))).toEqual({
+ "main.py": [2],
+ "other.py": [3],
+ });
+ expect((await db.get(projectId))?.name).toEqual("Renamed");
+ });
+
+ it("does not track the dirty flag", async () => {
+ const save = vi.spyOn(db, "save");
+ await storage.markDirty();
+ await storage.flush();
+ expect(await storage.isDirty()).toEqual(false);
+ expect(save).not.toHaveBeenCalled();
+ });
+
+ it("reports each successful flush for cross-tab sync", async () => {
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ await storage.flush();
+ expect(changes).toEqual(1);
+ });
+
+ it("a remove after a write in the same batch wins", async () => {
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.remove("main.py");
+ await storage.flush();
+ expect(contents(await db.files(projectId))).toEqual({});
+ });
+
+ it("bumps the project timestamp when it flushes changes", async () => {
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ expect((await db.get(projectId))?.timestamp).toBeGreaterThan(1);
+ });
+
+ it("issues its writes at once when the page is hidden", async () => {
+ const save = vi.spyOn(db, "save");
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.remove("old.py");
+ await storage.setProjectName("Renamed");
+ Object.defineProperty(document, "visibilityState", {
+ value: "hidden",
+ configurable: true,
+ });
+ document.dispatchEvent(new Event("visibilitychange"));
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ // Before the event handler returns: an unloading page gets no later
+ // chance.
+ expect(save).toHaveBeenCalledWith(
+ { id: projectId, name: "Renamed", timestamp: expect.any(Number) },
+ { writes: { "main.py": new Uint8Array([1]) }, deletes: ["old.py"] },
+ { urgent: true }
+ );
+
+ await storage.flush();
+ expect(contents(await db.files(projectId))).toEqual({ "main.py": [1] });
+ expect((await db.get(projectId))?.name).toEqual("Renamed");
+ expect(changes).toEqual(1);
+ });
+
+ it("flushes on pagehide whatever the visibility", async () => {
+ const save = vi.spyOn(db, "save");
+ await storage.write("main.py", new Uint8Array([1]));
+ window.dispatchEvent(new Event("pagehide"));
+ expect(save).toHaveBeenCalledTimes(1);
+
+ await storage.flush();
+ expect(contents(await db.files(projectId))).toEqual({ "main.py": [1] });
+ });
+
+ it("keeps the later of two flushes that overlap", async () => {
+ await storage.write("main.py", new Uint8Array([1]));
+ const first = storage.flush();
+ await storage.write("main.py", new Uint8Array([2]));
+ await storage.flush({ urgent: true });
+ await first;
+ expect(contents(await db.files(projectId))).toEqual({ "main.py": [2] });
+ expect(errors).toEqual([]);
+ });
+
+ it("reports a failure to announce a change and carries on", async () => {
+ const failing = new IndexedDBFSStorage(
+ db,
+ { id: projectId, name: undefined, timestamp: 1 },
+ (e) => errors.push(e),
+ () => {
+ throw new Error("channel closed");
+ },
+ 20
+ );
+ await failing.write("main.py", new Uint8Array([1]));
+ await failing.flush();
+ expect(errors).toHaveLength(1);
+
+ await failing.write("main.py", new Uint8Array([2]));
+ expect(Array.from(await failing.read("main.py"))).toEqual([2]);
+ await failing.dispose();
+ });
+
+ it("adopts a name saved elsewhere unless it has an unsaved rename", async () => {
+ await storage.write("main.py", new Uint8Array([1]));
+ storage.adoptName("Renamed elsewhere");
+ await storage.flush();
+ expect((await db.get(projectId))?.name).toEqual("Renamed elsewhere");
+
+ await storage.setProjectName("Renamed here");
+ storage.adoptName("Renamed elsewhere again");
+ await storage.flush();
+ expect((await db.get(projectId))?.name).toEqual("Renamed here");
+ });
+
+ it("has unsaved changes after a failed flush, until the next succeeds", async () => {
+ expect(storage.hasUnsavedChanges).toEqual(false);
+ vi.spyOn(db, "save").mockRejectedValueOnce(new Error("Simulated"));
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ expect(storage.hasUnsavedChanges).toEqual(true);
+
+ // Saving anything saves what failed too.
+ await storage.write("other.py", new Uint8Array([2]));
+ await storage.flush();
+ expect(storage.hasUnsavedChanges).toEqual(false);
+ expect(contents(await db.files(projectId))).toEqual({
+ "main.py": [1],
+ "other.py": [2],
+ });
+ });
+
+ it("does not retry a failed flush until something else flushes", async () => {
+ const save = vi
+ .spyOn(db, "save")
+ .mockRejectedValueOnce(new Error("Simulated"));
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(save).toHaveBeenCalledTimes(1);
+
+ // As when the project is switched.
+ await storage.dispose();
+ expect(save).toHaveBeenCalledTimes(2);
+ expect(contents(await db.files(projectId))).toEqual({ "main.py": [1] });
+ });
+
+ it("sends the newer content if a file changes again after a failed flush", async () => {
+ vi.spyOn(db, "save").mockRejectedValueOnce(new Error("Simulated"));
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ await storage.write("main.py", new Uint8Array([2]));
+ await storage.remove("old.py");
+ await storage.flush();
+ expect(contents(await db.files(projectId))).toEqual({ "main.py": [2] });
+ expect(storage.hasUnsavedChanges).toEqual(false);
+ });
+
+ it("does not write back a project deleted elsewhere", async () => {
+ await db.delete(projectId);
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ expect(errors).toHaveLength(1);
+ expect(await db.get(projectId)).toBeUndefined();
+ expect(contents(await db.files(projectId))).toEqual({});
+
+ // Nor later: an urgent flush does not check the project exists, so what
+ // that flush carried must not be kept for it.
+ window.dispatchEvent(new Event("pagehide"));
+ await storage.flush();
+ expect(await db.get(projectId)).toBeUndefined();
+ expect(contents(await db.files(projectId))).toEqual({});
+ expect(storage.hasUnsavedChanges).toEqual(false);
+ });
+
+ it("stamps the project with its latest edit, even after failed flushes", async () => {
+ const now = vi.spyOn(Date, "now");
+ vi.spyOn(db, "save").mockRejectedValueOnce(new Error("Simulated"));
+ now.mockReturnValue(100);
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+
+ now.mockReturnValue(5000);
+ await storage.write("other.py", new Uint8Array([2]));
+ await storage.flush();
+ now.mockRestore();
+
+ expect((await db.get(projectId))?.timestamp).toEqual(5000);
+ });
+
+ it("writes nothing once abandoned", async () => {
+ const save = vi.spyOn(db, "save");
+ await storage.write("main.py", new Uint8Array([1]));
+ storage.abandon();
+ await storage.write("other.py", new Uint8Array([2]));
+ window.dispatchEvent(new Event("pagehide"));
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ expect(save).not.toHaveBeenCalled();
+ expect(errors).toEqual([]);
+ });
+
+ it("reports a failed flush rather than throwing, and keeps its changes for the next", async () => {
+ vi.spyOn(db, "save").mockRejectedValueOnce(
+ new DOMException("full", "QuotaExceededError")
+ );
+ await storage.write("main.py", new Uint8Array([1]));
+ await storage.flush();
+ expect(errors).toHaveLength(1);
+ expect((errors[0] as DOMException).name).toEqual("QuotaExceededError");
+
+ await storage.write("other.py", new Uint8Array([2]));
+ await storage.flush();
+ expect(contents(await db.files(projectId))).toEqual({
+ "main.py": [1],
+ "other.py": [2],
+ });
+ });
+});
diff --git a/src/fs/indexeddb-storage.ts b/src/fs/indexeddb-storage.ts
new file mode 100644
index 000000000..b1443e823
--- /dev/null
+++ b/src/fs/indexeddb-storage.ts
@@ -0,0 +1,279 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ FileChanges,
+ NoSuchProjectError,
+ ProjectMeta,
+ ProjectsDatabase,
+} from "./projects-db";
+import { FSStorage } from "./storage";
+
+const defaultFlushDelayMs = 300;
+
+/**
+ * File system storage for one project in the IndexedDB projects database.
+ *
+ * Intended as the secondary of a SplitStrategyStorage, so reads are rare and
+ * writes arrive on every keystroke. Writes are coalesced per file and flushed
+ * as one transaction after a short delay, and when the page is hidden or
+ * unloading. Reads flush first so they always see the latest write.
+ *
+ * A flush never reads: see ProjectsDatabase.save for why. So this holds the
+ * project's name, the one part of its record that a flush does not itself
+ * decide, from when the project is opened. Another tab changing it is told
+ * to this one by Projects, which opens the project afresh.
+ *
+ * Failures never propagate: a failed flush is reported through onError. Its
+ * changes stay queued and go with the next flush, whatever causes that: a
+ * later edit, the page being hidden, or the project being switched. There
+ * is no retry of its own, which against a full quota would never end.
+ *
+ * The dirty flag is not stored: it exists to warn before work is lost, and
+ * a project in the database outlives the tab.
+ */
+export class IndexedDBFSStorage implements FSStorage {
+ private readonly projectId: string;
+ private name: string | undefined;
+ // The name was set here and has not been flushed yet.
+ private nameUnsaved = false;
+ // Changes not yet known to be in the database. An entry stays here while
+ // a flush carrying it is in flight, and after one that fails.
+ private pendingWrites = new Map();
+ // There is something that no flush has yet been sent for, or that one
+ // failed to save.
+ private needsFlush = false;
+ // When the latest change was made. The project's "last modified" is the
+ // edit, not the flush, which may come later than another project's.
+ private lastChange = 0;
+ private timer: ReturnType | undefined;
+ private flushing: Promise = Promise.resolve();
+ private abandoned = false;
+ private lastFlushFailed = false;
+ private readonly handleVisibilityChange = () => {
+ if (document.visibilityState === "hidden") {
+ void this.flush({ urgent: true });
+ }
+ };
+ // Not every browser reports the page as hidden by the time of pagehide.
+ private readonly handlePageHide = () => void this.flush({ urgent: true });
+
+ /**
+ * @param project The project's record as it is in the database now.
+ * @param onError Reports a failed flush; its changes go with the next.
+ * @param onChange Called after a successful flush, for cross-tab sync.
+ */
+ constructor(
+ private db: ProjectsDatabase,
+ project: ProjectMeta,
+ private onError: (e: unknown) => void,
+ private onChange: () => void = () => {},
+ private flushDelayMs: number = defaultFlushDelayMs
+ ) {
+ this.projectId = project.id;
+ this.name = project.name;
+ if (typeof document !== "undefined") {
+ document.addEventListener(
+ "visibilitychange",
+ this.handleVisibilityChange
+ );
+ window.addEventListener("pagehide", this.handlePageHide);
+ }
+ }
+
+ /**
+ * Flushes and stops listening. The database connection is shared with
+ * the projects list and stays open.
+ */
+ async dispose(): Promise {
+ this.stopListening();
+ await this.flush();
+ }
+
+ /**
+ * For a project that has been deleted: drops what is pending and ignores
+ * writes from here on, so that an editor still showing the project cannot
+ * write it back.
+ */
+ abandon(): void {
+ this.abandoned = true;
+ this.stopListening();
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ this.pendingWrites = new Map();
+ this.needsFlush = false;
+ this.lastFlushFailed = false;
+ }
+
+ /**
+ * True while the last flush failed, so that closing the tab now would
+ * lose what it carried. Each flush sends everything still unsaved, so the
+ * next one to succeed clears this.
+ */
+ get hasUnsavedChanges(): boolean {
+ return this.lastFlushFailed;
+ }
+
+ /**
+ * Takes the project's name as another tab has saved it. A flush writes
+ * the name held here, so without this one that is still to come would
+ * undo the other tab's rename. A rename made here and not yet flushed is
+ * kept: it is the later of the two.
+ */
+ adoptName(name: string | undefined): void {
+ if (!this.nameUnsaved) {
+ this.name = name;
+ }
+ }
+
+ private stopListening(): void {
+ if (typeof document !== "undefined") {
+ document.removeEventListener(
+ "visibilitychange",
+ this.handleVisibilityChange
+ );
+ window.removeEventListener("pagehide", this.handlePageHide);
+ }
+ }
+
+ async ls(): Promise {
+ await this.flush();
+ return this.db.fileNames(this.projectId);
+ }
+
+ async exists(filename: string): Promise {
+ await this.flush();
+ return (await this.db.file(this.projectId, filename)) !== undefined;
+ }
+
+ async read(filename: string): Promise {
+ await this.flush();
+ const data = await this.db.file(this.projectId, filename);
+ if (data === undefined) {
+ throw new Error(`No such file ${filename}`);
+ }
+ return data;
+ }
+
+ async write(name: string, content: Uint8Array): Promise {
+ this.pendingWrites.set(name, content);
+ this.schedule();
+ }
+
+ async remove(name: string): Promise {
+ this.pendingWrites.set(name, null);
+ this.schedule();
+ }
+
+ async clear(): Promise {
+ for (const name of await this.ls()) {
+ this.pendingWrites.set(name, null);
+ }
+ this.name = undefined;
+ this.nameUnsaved = true;
+ this.schedule();
+ await this.flush();
+ }
+
+ async setProjectName(projectName: string | undefined): Promise {
+ this.name = projectName;
+ this.nameUnsaved = true;
+ this.schedule();
+ }
+
+ async projectName(): Promise {
+ return this.name;
+ }
+
+ async markDirty(): Promise {}
+
+ async clearDirty(): Promise {}
+
+ async isDirty(): Promise {
+ return false;
+ }
+
+ private schedule(): void {
+ if (this.abandoned) {
+ this.pendingWrites = new Map();
+ return;
+ }
+ this.needsFlush = true;
+ this.lastChange = Date.now();
+ if (this.timer === undefined) {
+ this.timer = setTimeout(() => void this.flush(), this.flushDelayMs);
+ }
+ }
+
+ /**
+ * Writes everything pending in one transaction. Safe to call at any time.
+ *
+ * The transaction's requests are issued before this returns, which an
+ * urgent flush needs to stand a chance as the page unloads, and it runs
+ * after those of earlier flushes, so the latest content is what is kept.
+ * An earlier flush that is still in flight when the page unloads is not
+ * helped by a later urgent one: only the urgent one commits explicitly.
+ *
+ * @param urgent The page may be about to go away; see
+ * ProjectsDatabase.save.
+ * @returns A promise that resolves when this flush and those before it
+ * have finished, whether or not they succeeded.
+ */
+ flush({ urgent = false }: { urgent?: boolean } = {}): Promise {
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ if (this.abandoned || !this.needsFlush) {
+ return this.flushing;
+ }
+ const project: ProjectMeta = {
+ id: this.projectId,
+ name: this.name,
+ timestamp: this.lastChange,
+ };
+ const sent = new Map(this.pendingWrites);
+ const files: FileChanges = { writes: {}, deletes: [] };
+ for (const [name, data] of sent) {
+ if (data === null) {
+ files.deletes.push(name);
+ } else {
+ files.writes[name] = data;
+ }
+ }
+ this.needsFlush = false;
+ const saved = this.db
+ .save(project, files, { urgent })
+ .then(
+ () => {
+ for (const [name, data] of sent) {
+ // Unless it has been changed again since.
+ if (this.pendingWrites.get(name) === data) {
+ this.pendingWrites.delete(name);
+ }
+ }
+ if (this.name === project.name) {
+ this.nameUnsaved = false;
+ }
+ this.lastFlushFailed = false;
+ },
+ (e) => {
+ if (e instanceof NoSuchProjectError) {
+ // Nothing queued must be sent again: an urgent flush does not
+ // check the project exists and would write part of it back.
+ this.abandon();
+ } else if (!this.abandoned) {
+ // So that the next flush, whatever causes it, sends this again.
+ this.needsFlush = true;
+ this.lastFlushFailed = true;
+ }
+ throw e;
+ }
+ )
+ .then(() => this.onChange())
+ .catch((e) => this.onError(e));
+ const earlier = this.flushing;
+ this.flushing = earlier.then(() => saved);
+ return this.flushing;
+ }
+}
diff --git a/src/fs/initial-project.ts b/src/fs/initial-project.ts
index 49b2d3b9c..d05e5c346 100644
--- a/src/fs/initial-project.ts
+++ b/src/fs/initial-project.ts
@@ -5,7 +5,7 @@
*/
import { fromByteArray } from "base64-js";
-import { MAIN_FILE } from "./fs";
+import { MAIN_FILE } from "./fs-util";
/**
* We can now initialize a project with multiple files.
diff --git a/src/fs/migration.test.ts b/src/fs/migration.test.ts
deleted file mode 100644
index ac2c23d9d..000000000
--- a/src/fs/migration.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { isMigration, parseMigrationFromUrl } from "./migration";
-import { testMigrationUrl } from "./migration-test-data";
-
-describe("parseMigrationFromUrl", () => {
- it("parses valid URL", () => {
- const migration = parseMigrationFromUrl(testMigrationUrl);
- expect(migration).toEqual({
- migration: {
- meta: {
- cloudId: "microbit.org",
- comment: "",
- editor: "python",
- name: "Hearts",
- },
- source: `from microbit import *\r\ndisplay.show(Image.HEART)`,
- },
- postMigrationUrl: "http://localhost:3000/",
- });
- });
- it("undefined for nonsense", () => {
- const migration = parseMigrationFromUrl(
- "https://python.microbit.org/v/2#import:#project:=XQAAgACRAAAAAAAAAAA9iImmlGSt1R="
- );
- expect(migration).toEqual(undefined);
- });
- it("undefined for no project on URL", () => {
- const migration = parseMigrationFromUrl(
- "https://python.microbit.org/v/2#import:#notAProject:XQAAgACRAAAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOM4sSAXBT95G3en+tghrYmE+YJp6EiYgzA9ThKkyShWq2UdvmCzqxoNfYc1wlmTqlNv/Piaz3WoSe3flvr/ItyLl0aolQlEpv4LA8A="
- );
- expect(migration).toEqual(undefined);
- });
- it("isMigration checks fields", () => {
- expect(isMigration({})).toEqual(false);
- expect(isMigration({ meta: { name: "foo" } })).toEqual(false);
- expect(isMigration({ meta: {}, source: "" })).toEqual(false);
- expect(isMigration({ meta: { name: "foo" }, source: "" })).toEqual(true);
- });
-});
diff --git a/src/fs/migration.ts b/src/fs/migration.ts
deleted file mode 100644
index 8a494813a..000000000
--- a/src/fs/migration.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { toByteArray } from "base64-js";
-
-import lzma from "lzma/src/lzma-d";
-
-// LZMA isn't a proper module.
-// When bundled it assigns to window. At dev time it works via the above import.
-const LZMA =
- typeof window !== "undefined" && (window as any).LZMA
- ? (window as any).LZMA
- : lzma.LZMA;
-
-// There are other fields that we don't use.
-export interface Migration {
- meta: {
- name: string;
- };
- source: string;
-}
-
-export const isMigration = (v: any): v is Migration =>
- !!v &&
- typeof v === "object" &&
- !!v.meta &&
- typeof v.meta === "object" &&
- typeof v.meta?.name === "string" &&
- typeof v.source === "string";
-
-interface MigrationParseResult {
- migration: Migration;
- postMigrationUrl: string;
-}
-
-export const parseMigrationFromUrl = (
- url: string
-): MigrationParseResult | undefined => {
- const parts = url.split("#project:");
- const urlPart = parts[1];
- try {
- if (urlPart) {
- const bytes = toByteArray(urlPart);
- const json = JSON.parse(LZMA.decompress(bytes));
- if (isMigration(json)) {
- let postMigrationUrl = parts[0];
- // This was previously stripped off by the versioner but for now do it ourselves:
- postMigrationUrl = postMigrationUrl.replace(/#import:$/, "");
- return { migration: json, postMigrationUrl };
- }
- }
- } catch {
- // Ultimate source is from the URL so we need to be robust to tampering.
- }
- return undefined;
-};
diff --git a/src/fs/migration-test-data.ts b/src/fs/project-link-test-data.ts
similarity index 50%
rename from src/fs/migration-test-data.ts
rename to src/fs/project-link-test-data.ts
index 134a6e561..527754233 100644
--- a/src/fs/migration-test-data.ts
+++ b/src/fs/project-link-test-data.ts
@@ -1,4 +1,12 @@
+import { ProjectLink } from "./project-link";
+
// The heart project.
-export const testMigrationUrl =
+export const testProjectLinkUrl =
// origin needs to match jest's testUrl
"http://localhost:3000/#import:#project:XQAAgACRAAAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOM4sSAXBT95G3en+tghrYmE+YJp6EiYgzA9ThKkyShWq2UdvmCzqxoNfYc1wlmTqlNv/Piaz3WoSe3flvr/ItyLl0aolQlEpv4LA8A=";
+
+/** What testProjectLinkUrl carries, less the fields we don't use. */
+export const testProjectLink: ProjectLink = {
+ meta: { name: "Hearts" },
+ source: `from microbit import *\r\ndisplay.show(Image.HEART)`,
+};
diff --git a/src/fs/project-link.test.ts b/src/fs/project-link.test.ts
new file mode 100644
index 000000000..311669d48
--- /dev/null
+++ b/src/fs/project-link.test.ts
@@ -0,0 +1,63 @@
+/**
+ * (c) 2021, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ isProjectLink,
+ parseProjectLink,
+ PendingProjectLink,
+} from "./project-link";
+import { testProjectLink, testProjectLinkUrl } from "./project-link-test-data";
+
+describe("parseProjectLink", () => {
+ it("parses valid URL", () => {
+ const result = parseProjectLink(testProjectLinkUrl);
+ expect(result).toEqual({
+ status: "ok",
+ link: {
+ meta: {
+ cloudId: "microbit.org",
+ comment: "",
+ editor: "python",
+ name: "Hearts",
+ },
+ source: `from microbit import *\r\ndisplay.show(Image.HEART)`,
+ },
+ });
+ });
+ it("says a link it cannot read is unreadable", () => {
+ const result = parseProjectLink(
+ "https://python.microbit.org/v/2#import:#project:=XQAAgACRAAAAAAAAAAA9iImmlGSt1R="
+ );
+ expect(result).toEqual({ status: "unreadable" });
+ });
+ it("says so when the URL has no project link", () => {
+ const result = parseProjectLink(
+ "https://python.microbit.org/v/2#import:#notAProject:XQAAgACRAAAAAAAAAAA9iImmlGSt1R++5LD+ZJ36cRz46B+lhYtNRoWF0nijpaVyZlK7ACfSpeoQpgfk21st4ty06R4PEOM4sSAXBT95G3en+tghrYmE+YJp6EiYgzA9ThKkyShWq2UdvmCzqxoNfYc1wlmTqlNv/Piaz3WoSe3flvr/ItyLl0aolQlEpv4LA8A="
+ );
+ expect(result).toEqual({ status: "none" });
+ });
+ it("isProjectLink checks fields", () => {
+ expect(isProjectLink({})).toEqual(false);
+ expect(isProjectLink({ meta: { name: "foo" } })).toEqual(false);
+ expect(isProjectLink({ meta: {}, source: "" })).toEqual(false);
+ expect(isProjectLink({ meta: { name: "foo" }, source: "" })).toEqual(true);
+ });
+});
+
+describe("PendingProjectLink", () => {
+ it("hands its link out once", () => {
+ const pending = new PendingProjectLink(testProjectLink);
+ expect(pending.pending).toEqual(true);
+ expect(pending.take()).toEqual(testProjectLink);
+ expect(pending.pending).toEqual(false);
+ expect(pending.take()).toBeUndefined();
+ });
+
+ it("has nothing to hand out without one", () => {
+ const pending = new PendingProjectLink();
+ expect(pending.pending).toEqual(false);
+ expect(pending.take()).toBeUndefined();
+ });
+});
diff --git a/src/fs/project-link.ts b/src/fs/project-link.ts
new file mode 100644
index 000000000..4204c00f3
--- /dev/null
+++ b/src/fs/project-link.ts
@@ -0,0 +1,83 @@
+/**
+ * (c) 2021, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { toByteArray } from "base64-js";
+
+import lzma from "lzma/src/lzma-d";
+
+// LZMA isn't a proper module.
+// When bundled it assigns to window. At dev time it works via the above import.
+const LZMA =
+ typeof window !== "undefined" && (window as any).LZMA
+ ? (window as any).LZMA
+ : lzma.LZMA;
+
+// There are other fields that we don't use.
+export interface ProjectLink {
+ meta: {
+ name: string;
+ };
+ source: string;
+}
+
+export const isProjectLink = (v: any): v is ProjectLink =>
+ !!v &&
+ typeof v === "object" &&
+ !!v.meta &&
+ typeof v.meta === "object" &&
+ typeof v.meta?.name === "string" &&
+ typeof v.source === "string";
+
+/**
+ * What a URL has by way of a #project: link: none, one, or something after
+ * the marker that cannot be read as one.
+ */
+export type ProjectLinkResult =
+ | { status: "none" }
+ | { status: "ok"; link: ProjectLink }
+ | { status: "unreadable" };
+
+/**
+ * Reads the #project: link in a URL. On microbit.org links it sits behind
+ * the v2 editor's #import: prefix, so it isn't always the whole hash.
+ */
+export const parseProjectLink = (url: string): ProjectLinkResult => {
+ const encoded = url.split("#project:")[1];
+ if (encoded === undefined) {
+ return { status: "none" };
+ }
+ try {
+ const json = JSON.parse(LZMA.decompress(toByteArray(encoded)));
+ if (isProjectLink(json)) {
+ return { status: "ok", link: json };
+ }
+ } catch {
+ // Ultimate source is from the URL so we need to be robust to tampering.
+ }
+ return { status: "unreadable" };
+};
+
+/**
+ * The #project: link the app booted with, if any, handed out once.
+ *
+ * With the projects database the link becomes a new project when the editor
+ * chooses one; without it the host writes the program into the single
+ * implicit project. Whichever runs first takes it. The taker also sees to
+ * removing the hash from the URL, so a reload opens what is stored rather
+ * than importing again.
+ */
+export class PendingProjectLink {
+ constructor(private link?: ProjectLink) {}
+
+ get pending(): boolean {
+ return this.link !== undefined;
+ }
+
+ take(): ProjectLink | undefined {
+ const link = this.link;
+ this.link = undefined;
+ return link;
+ }
+}
diff --git a/src/fs/projects-db.test.ts b/src/fs/projects-db.test.ts
new file mode 100644
index 000000000..e8ba8c6d8
--- /dev/null
+++ b/src/fs/projects-db.test.ts
@@ -0,0 +1,199 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import "fake-indexeddb/auto";
+import { openDB } from "idb";
+import {
+ databaseName,
+ NoSuchProjectError,
+ ProjectMeta,
+ ProjectsDatabase,
+} from "./projects-db";
+
+let counter = 0;
+const uniqueName = () => `test-${Date.now()}-${counter++}`;
+
+const meta = (id: string, timestamp: number, name = id): ProjectMeta => ({
+ id,
+ name,
+ timestamp,
+});
+const bytes = (...values: number[]) => new Uint8Array(values);
+// Typed arrays read back through fake-indexeddb under jsdom belong to another
+// realm, so compare contents rather than objects.
+const contents = (files: Record) =>
+ Object.fromEntries(
+ Object.entries(files).map(([name, data]) => [name, Array.from(data)])
+ );
+
+describe("databaseName", () => {
+ it("is namespaced by the base path so production and beta stay apart", () => {
+ expect(databaseName("local", "/")).toEqual("python-editor");
+ expect(databaseName("PRODUCTION", "/v/3/")).toEqual("python-editor/v/3");
+ expect(databaseName("STAGING", "/v/beta/")).toEqual("python-editor/v/beta");
+ });
+
+ it("is shared by every review build", () => {
+ expect(databaseName("REVIEW", "/some-branch/")).toEqual(
+ "python-editor-review"
+ );
+ expect(databaseName("REVIEW", "/another/")).toEqual("python-editor-review");
+ });
+});
+
+describe("ProjectsDatabase", () => {
+ let db: ProjectsDatabase;
+ beforeEach(async () => {
+ db = await ProjectsDatabase.open(uniqueName());
+ });
+ afterEach(() => db.close());
+
+ it("starts empty", async () => {
+ expect(await db.list()).toEqual([]);
+ expect(await db.mostRecent()).toBeUndefined();
+ });
+
+ it("creates projects with files and lists them most recent first", async () => {
+ await db.create(meta("a", 1), { "main.py": bytes(1) });
+ await db.create(meta("b", 2), { "main.py": bytes(2), "x.py": bytes(3) });
+ expect((await db.list()).map((p) => p.id)).toEqual(["b", "a"]);
+ expect(await db.mostRecent()).toEqual(meta("b", 2));
+ expect(contents(await db.files("b"))).toEqual({
+ "main.py": [2],
+ "x.py": [3],
+ });
+ expect(await db.fileNames("a")).toEqual(["main.py"]);
+ expect(Array.from((await db.file("a", "main.py"))!)).toEqual([1]);
+ expect(await db.file("a", "nope.py")).toBeUndefined();
+ });
+
+ it("update changes the given fields of a project's record", async () => {
+ await db.create(meta("a", 1, "before"), { "main.py": bytes(1) });
+ await db.update("a", { name: "renamed" });
+ expect(await db.get("a")).toEqual(meta("a", 1, "renamed"));
+ await db.update("a", { timestamp: 5 });
+ expect(await db.get("a")).toEqual(meta("a", 5, "renamed"));
+ });
+
+ it("update refuses a project that does not exist", async () => {
+ await expect(db.update("missing", { name: "x" })).rejects.toThrow(
+ /No such project missing/
+ );
+ });
+
+ it("save writes the record and file changes together", async () => {
+ await db.create(meta("a", 1), { "main.py": bytes(1), "old.py": bytes(9) });
+ await db.save(meta("a", 5, "renamed"), {
+ writes: { "main.py": bytes(2), "new.py": bytes(3) },
+ deletes: ["old.py"],
+ });
+ expect(await db.get("a")).toEqual(meta("a", 5, "renamed"));
+ expect(contents(await db.files("a"))).toEqual({
+ "main.py": [2],
+ "new.py": [3],
+ });
+ });
+
+ it("save refuses a project that no longer exists and writes nothing", async () => {
+ await expect(
+ db.save(meta("gone", 1), { writes: { "main.py": bytes(1) }, deletes: [] })
+ ).rejects.toBeInstanceOf(NoSuchProjectError);
+ expect(await db.get("gone")).toBeUndefined();
+ expect(contents(await db.files("gone"))).toEqual({});
+ });
+
+ it("save rejects rather than throws when the connection has closed", async () => {
+ await db.create(meta("a", 1), {});
+ db.close();
+ let result: Promise | undefined;
+ expect(() => {
+ result = db.save(meta("a", 2), { writes: {}, deletes: [] });
+ }).not.toThrow();
+ await expect(result).rejects.toThrow();
+ });
+
+ it("an urgent save issues its writes without waiting to check", async () => {
+ await db.create(meta("a", 1), { "main.py": bytes(1) });
+ await db.save(
+ meta("a", 5),
+ { writes: { "main.py": bytes(2) }, deletes: [] },
+ { urgent: true }
+ );
+ expect(await db.get("a")).toEqual(meta("a", 5));
+ expect(contents(await db.files("a"))).toEqual({ "main.py": [2] });
+ });
+
+ it("leaves no unhandled rejection when a request in a transaction fails", async () => {
+ await db.create(meta("a", 1), {});
+ const unhandled: unknown[] = [];
+ const listener = (reason: unknown) => unhandled.push(reason);
+ process.on("unhandledRejection", listener);
+ // The next put fails as a request, as a put can when storage is full,
+ // rather than as a call: it adds a key that already exists.
+ const put = IDBObjectStore.prototype.put;
+ IDBObjectStore.prototype.put = function (this: IDBObjectStore, value) {
+ IDBObjectStore.prototype.put = put;
+ return this.add(value);
+ };
+
+ await expect(db.create(meta("a", 2), {})).rejects.toThrow();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ process.off("unhandledRejection", listener);
+ expect(unhandled).toEqual([]);
+ expect(await db.get("a")).toEqual(meta("a", 1));
+ });
+
+ it("touch makes a project the most recent", async () => {
+ await db.create(meta("a", 1), {});
+ await db.create(meta("b", 2), {});
+ await db.touch("a", 3);
+ expect((await db.mostRecent())?.id).toEqual("a");
+ });
+
+ it("duplicates a project's files under new metadata", async () => {
+ await db.create(meta("a", 1), { "main.py": bytes(1) });
+ await db.duplicate("a", meta("b", 2, "copy"));
+ expect(await db.get("b")).toEqual(meta("b", 2, "copy"));
+ expect(contents(await db.files("b"))).toEqual({ "main.py": [1] });
+ });
+
+ it("deletes a project and its files", async () => {
+ await db.create(meta("a", 1), { "main.py": bytes(1), "x.py": bytes(2) });
+ await db.create(meta("b", 2), { "main.py": bytes(3) });
+ await db.delete("a");
+ expect((await db.list()).map((p) => p.id)).toEqual(["b"]);
+ expect(contents(await db.files("a"))).toEqual({});
+ expect(contents(await db.files("b"))).toEqual({ "main.py": [3] });
+ });
+
+ it("rejects a database created by an incompatible version", async () => {
+ const name = uniqueName();
+ // Same version number, different stores: what a future schema change
+ // that forgot to bump the version would look like from an old build.
+ const other = await openDB(name, 1, {
+ upgrade(db) {
+ db.createObjectStore("something-else");
+ },
+ });
+ other.close();
+ await expect(ProjectsDatabase.open(name)).rejects.toMatchObject({
+ name: "VersionError",
+ });
+ });
+
+ it("loads a project's metadata and files together", async () => {
+ const db = await ProjectsDatabase.open(uniqueName());
+ await db.create(meta("a", 1), { "main.py": bytes(1), "x.py": bytes(2) });
+ await db.create(meta("b", 2), { "main.py": bytes(3) });
+
+ const loaded = await db.load("a");
+
+ expect(loaded?.meta).toEqual(meta("a", 1));
+ expect(contents(loaded!.files)).toEqual({ "main.py": [1], "x.py": [2] });
+ expect(await db.load("missing")).toBeUndefined();
+ db.close();
+ });
+});
diff --git a/src/fs/projects-db.ts b/src/fs/projects-db.ts
new file mode 100644
index 000000000..c81eff3c7
--- /dev/null
+++ b/src/fs/projects-db.ts
@@ -0,0 +1,326 @@
+/**
+ * The projects database in IndexedDB.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { DBSchema, IDBPDatabase, openDB, unwrap } from "idb";
+import { baseUrl } from "../base";
+import { Stage, stage as currentStage } from "../environment";
+
+/**
+ * Project metadata. Deliberately holds no file content so listing is cheap.
+ */
+export interface ProjectMeta {
+ id: string;
+ name: string | undefined;
+ /** Last modified or opened, for ordering by recency. */
+ timestamp: number;
+}
+
+/** A project as listed on the pages: its metadata plus what it contains. */
+export interface ProjectListEntry extends ProjectMeta {
+ fileNames: string[];
+}
+
+/**
+ * A file belonging to a project, keyed by [projectId, name]: a file's name
+ * is its identity within a project.
+ */
+export interface FileRecord {
+ projectId: string;
+ name: string;
+ data: Uint8Array;
+}
+
+/** A project's metadata and the content of its files. */
+export interface ProjectContent {
+ meta: ProjectMeta;
+ files: Record;
+}
+
+/**
+ * Changes to a project's files.
+ */
+export interface FileChanges {
+ writes: Record;
+ deletes: string[];
+}
+
+/** The project has been deleted, most likely in another tab. */
+export class NoSuchProjectError extends Error {
+ constructor(id: string) {
+ super(`No such project ${id}`);
+ this.name = "NoSuchProjectError";
+ }
+}
+
+const PROJECTS = "projects";
+const FILES = "files";
+const stores = [PROJECTS, FILES] as const;
+
+interface Schema extends DBSchema {
+ [PROJECTS]: {
+ key: string;
+ value: ProjectMeta;
+ };
+ [FILES]: {
+ key: [string, string];
+ value: FileRecord;
+ indexes: { projectId: string };
+ };
+}
+
+const DB_VERSION = 1;
+
+/**
+ * Deployments share an origin, so the database name includes the base path
+ * to keep production's and beta's libraries apart. Review builds all share
+ * one: they are internal, and a project made on one branch is useful on the
+ * next. When a schema change breaks it, StorageVersionErrorPage offers to
+ * clear it.
+ */
+export const databaseName = (
+ stage: Stage = currentStage,
+ base: string = baseUrl
+): string => {
+ if (stage === "REVIEW") {
+ return "python-editor-review";
+ }
+ return base === "/"
+ ? "python-editor"
+ : `python-editor${base.replace(/\/$/, "")}`;
+};
+
+/**
+ * idb gives every transaction a promise of its completion, tx.done. A method
+ * that awaits a request and throws when it fails never reaches its own
+ * `await tx.done`, and the transaction's rejection would then be unhandled:
+ * one more error report for a failure the caller has already been given.
+ * This marks it handled. Awaiting tx.done still rejects.
+ */
+const handled = }>(tx: T): T => {
+ tx.done.catch(() => {});
+ return tx;
+};
+
+export class ProjectsDatabase {
+ private constructor(private db: IDBPDatabase) {}
+
+ /**
+ * Opens the database, creating it if needed.
+ *
+ * @throws a VersionError DOMException if the database exists but lacks the
+ * expected stores, which means a newer version of the app created it.
+ */
+ static async open(name: string = databaseName()): Promise {
+ const db = await openDB(name, DB_VERSION, {
+ upgrade(db) {
+ db.createObjectStore(PROJECTS, { keyPath: "id" });
+ const files = db.createObjectStore(FILES, {
+ keyPath: ["projectId", "name"],
+ });
+ files.createIndex("projectId", "projectId");
+ },
+ });
+ for (const store of stores) {
+ if (!db.objectStoreNames.contains(store)) {
+ db.close();
+ throw new DOMException(
+ `Database ${name} has no ${store} store; it was created by an incompatible version of the app`,
+ "VersionError"
+ );
+ }
+ }
+ return new ProjectsDatabase(db);
+ }
+
+ close(): void {
+ this.db.close();
+ }
+
+ /** All projects, most recent first. */
+ async list(): Promise {
+ const all = await this.db.getAll(PROJECTS);
+ return all.sort((a, b) => b.timestamp - a.timestamp);
+ }
+
+ /**
+ * All projects with their file names, most recent first. One transaction
+ * over both stores so the list is consistent and costs two reads, not one
+ * per project.
+ */
+ async listWithFileNames(): Promise {
+ const tx = this.db.transaction(stores, "readonly");
+ const [projects, fileKeys] = await Promise.all([
+ tx.objectStore(PROJECTS).getAll(),
+ tx.objectStore(FILES).getAllKeys(),
+ tx.done,
+ ]);
+ const filesByProject = new Map();
+ for (const [projectId, name] of fileKeys) {
+ const names = filesByProject.get(projectId) ?? [];
+ names.push(name);
+ filesByProject.set(projectId, names);
+ }
+ return projects
+ .sort((a, b) => b.timestamp - a.timestamp)
+ .map((p) => ({ ...p, fileNames: filesByProject.get(p.id) ?? [] }));
+ }
+
+ async get(id: string): Promise {
+ return this.db.get(PROJECTS, id);
+ }
+
+ async mostRecent(): Promise {
+ return (await this.list())[0];
+ }
+
+ /** A project and its files, in one transaction so they match. */
+ async load(id: string): Promise {
+ const tx = this.db.transaction(stores, "readonly");
+ const [meta, records] = await Promise.all([
+ tx.objectStore(PROJECTS).get(id),
+ tx.objectStore(FILES).index("projectId").getAll(id),
+ tx.done,
+ ]);
+ return (
+ meta && {
+ meta,
+ files: Object.fromEntries(records.map((r) => [r.name, r.data])),
+ }
+ );
+ }
+
+ async files(id: string): Promise> {
+ const records = await this.db.getAllFromIndex(FILES, "projectId", id);
+ return Object.fromEntries(records.map((r) => [r.name, r.data]));
+ }
+
+ async fileNames(id: string): Promise {
+ const keys = await this.db.getAllKeysFromIndex(FILES, "projectId", id);
+ return keys.map(([, name]) => name);
+ }
+
+ async file(id: string, name: string): Promise {
+ return (await this.db.get(FILES, [id, name]))?.data;
+ }
+
+ /** Creates a project and its files atomically. */
+ async create(
+ meta: ProjectMeta,
+ files: Record
+ ): Promise {
+ const tx = handled(this.db.transaction(stores, "readwrite"));
+ await tx.objectStore(PROJECTS).put(meta);
+ const fileStore = tx.objectStore(FILES);
+ for (const [name, data] of Object.entries(files)) {
+ await fileStore.put({ projectId: meta.id, name, data });
+ }
+ await tx.done;
+ }
+
+ /**
+ * Changes a project's record, keeping the fields not given. For changes
+ * made from the pages; the open project is written by save().
+ */
+ async update(
+ id: string,
+ changes: Partial>
+ ): Promise {
+ const tx = handled(this.db.transaction(PROJECTS, "readwrite"));
+ const existing = await tx.store.get(id);
+ if (!existing) {
+ throw new NoSuchProjectError(id);
+ }
+ await tx.store.put({ ...existing, ...changes, id });
+ await tx.done;
+ }
+
+ /**
+ * Writes a project's record and file changes in one transaction.
+ *
+ * Every request is issued before this returns and none depends on a read,
+ * because a write that waits for a read is lost when the page unloads: an
+ * unloading page gets no further turns of the event loop. The caller
+ * supplies the whole record for the same reason.
+ *
+ * @param urgent The page may be about to go away, so commit at once
+ * rather than when the requests have finished. This gives up the check
+ * that the project still exists, which needs the result of a read, so a
+ * project deleted in the meantime is written back.
+ * @throws NoSuchProjectError if the project no longer exists (unless
+ * urgent), leaving nothing written.
+ */
+ save(
+ project: ProjectMeta,
+ { writes, deletes }: FileChanges,
+ { urgent = false }: { urgent?: boolean } = {}
+ ): Promise {
+ return new Promise((resolve, reject) => {
+ // The plain transaction, not idb's wrapper: its promise of completion
+ // would be an unhandled rejection on the abort below. Opened in here
+ // so that failing to, as when the browser has closed the connection,
+ // is a rejection like any other failure.
+ const tx = unwrap(this.db).transaction(stores, "readwrite");
+ let missing = false;
+ tx.oncomplete = () => resolve();
+ tx.onabort = () =>
+ reject(
+ missing
+ ? new NoSuchProjectError(project.id)
+ : tx.error ?? new DOMException("Transaction aborted", "AbortError")
+ );
+ try {
+ const projects = tx.objectStore(PROJECTS);
+ if (!urgent) {
+ const existing = projects.getKey(project.id);
+ existing.onsuccess = () => {
+ if (existing.result === undefined) {
+ missing = true;
+ tx.abort();
+ }
+ };
+ }
+ projects.put(project);
+ const fileStore = tx.objectStore(FILES);
+ for (const [name, data] of Object.entries(writes)) {
+ fileStore.put({ projectId: project.id, name, data });
+ }
+ for (const name of deletes) {
+ fileStore.delete([project.id, name]);
+ }
+ // Missing from Safari before 15, where the transaction commits once
+ // its requests finish, if the page lasts that long.
+ if (urgent && "commit" in tx) {
+ tx.commit();
+ }
+ } catch (e) {
+ // A request that could not even be made, such as data that cannot
+ // be stored. Without this the requests before it would commit.
+ tx.abort();
+ throw e;
+ }
+ });
+ }
+
+ /** Marks a project as the most recent. */
+ async touch(id: string, timestamp: number = Date.now()): Promise {
+ await this.update(id, { timestamp });
+ }
+
+ async duplicate(sourceId: string, meta: ProjectMeta): Promise {
+ await this.create(meta, await this.files(sourceId));
+ }
+
+ async delete(id: string): Promise {
+ const tx = handled(this.db.transaction(stores, "readwrite"));
+ await tx.objectStore(PROJECTS).delete(id);
+ const fileStore = tx.objectStore(FILES);
+ for (const key of await fileStore.index("projectId").getAllKeys(id)) {
+ await fileStore.delete(key);
+ }
+ await tx.done;
+ }
+}
diff --git a/src/fs/storage-status.ts b/src/fs/storage-status.ts
new file mode 100644
index 000000000..37b301efd
--- /dev/null
+++ b/src/fs/storage-status.ts
@@ -0,0 +1,52 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { useSyncExternalStore } from "react";
+
+// The storage opens at module load, before React mounts, so the outcome is
+// held here for the UI to read rather than passed through props.
+let versionError: unknown;
+let projectsDatabaseActive = false;
+const listeners = new Set<() => void>();
+
+const notify = () => listeners.forEach((listener) => listener());
+
+/**
+ * Records that the projects database was created by an incompatible version
+ * of the app. Only used on non-public stages, where the fix is to clear it.
+ */
+export const reportStorageVersionError = (error: unknown): void => {
+ versionError = error;
+ notify();
+};
+
+/**
+ * Records that the open project is in the projects database, which outlives
+ * the tab. Not reported for the session-storage fallback or in iframe mode,
+ * where closing the tab still loses the work.
+ */
+export const reportProjectsDatabaseActive = (): void => {
+ projectsDatabaseActive = true;
+ notify();
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+};
+
+export const hasStorageVersionError = (): boolean => versionError !== undefined;
+
+export const useStorageVersionError = (): unknown =>
+ useSyncExternalStore(subscribe, () => versionError);
+
+export const useProjectsDatabaseActive = (): boolean =>
+ useSyncExternalStore(subscribe, () => projectsDatabaseActive);
+
+/** For tests. */
+export const resetStorageStatus = (): void => {
+ versionError = undefined;
+ projectsDatabaseActive = false;
+};
diff --git a/src/fs/storage-tests.ts b/src/fs/storage-tests.ts
new file mode 100644
index 000000000..99a8f3c98
--- /dev/null
+++ b/src/fs/storage-tests.ts
@@ -0,0 +1,71 @@
+/**
+ * Behaviour every FSStorage implementation must have. Not a test file itself;
+ * each implementation's test calls it.
+ *
+ * (c) 2021, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { FSStorage } from "./storage";
+
+export const commonStorageTests = (storage: () => FSStorage) => {
+ it("is empty", async () => {
+ expect(await storage().ls()).toEqual([]);
+ });
+
+ it("stores project name", async () => {
+ await storage().setProjectName("foo");
+ expect(await storage().projectName()).toEqual("foo");
+ });
+
+ it("stores files", async () => {
+ await storage().write("test1.py", new Uint8Array([1]));
+ await storage().write("test2.py", new Uint8Array([2]));
+
+ expect(await storage().ls()).toEqual(["test1.py", "test2.py"]);
+ expect(await storage().exists("test1.py")).toEqual(true);
+ expect(await storage().exists("testX.py")).toEqual(false);
+ expect(Array.from(await storage().read("test1.py"))).toEqual([1]);
+ expect(Array.from(await storage().read("test2.py"))).toEqual([2]);
+ });
+
+ it("throws trying to read a non-existent file", async () => {
+ await expect(() => storage().read("test1.py")).rejects.toThrow(
+ /No such file test1.py/
+ );
+ });
+
+ it("removes files", async () => {
+ await storage().write("test1.py", new Uint8Array([1]));
+ await storage().write("test2.py", new Uint8Array([2]));
+
+ await storage().remove("test1.py");
+
+ expect(await storage().exists("test1.py")).toEqual(false);
+ expect(await storage().ls()).toEqual(["test2.py"]);
+ });
+
+ it("clears", async () => {
+ await storage().write("test1.py", new Uint8Array([1]));
+ await storage().write("test2.py", new Uint8Array([2]));
+
+ await storage().clear();
+
+ expect(await storage().exists("test1.py")).toEqual(false);
+ expect(await storage().exists("test2.py")).toEqual(false);
+ expect(await storage().ls()).toEqual([]);
+ });
+};
+
+/**
+ * For storage that lives no longer than the tab and so tracks the dirty flag.
+ */
+export const dirtyFlagTests = (storage: () => FSStorage) => {
+ it("stores dirty flag", async () => {
+ expect(await storage().isDirty()).toEqual(false);
+ await storage().markDirty();
+ expect(await storage().isDirty()).toEqual(true);
+ await storage().clearDirty();
+ expect(await storage().isDirty()).toEqual(false);
+ });
+};
diff --git a/src/fs/storage.test.ts b/src/fs/storage.test.ts
index afbb52d1c..670f53bd0 100644
--- a/src/fs/storage.test.ts
+++ b/src/fs/storage.test.ts
@@ -3,80 +3,26 @@
*
* SPDX-License-Identifier: MIT
*/
+import { vi } from "vitest";
import { ConsoleLogging } from "../deployment/default/logging";
import { MockLogging } from "../logging/mock";
import {
- FSStorage,
+ DeferredFSStorage,
InMemoryFSStorage,
SessionStorageFSStorage,
SplitStrategyStorage,
} from "./storage";
+import { commonStorageTests, dirtyFlagTests } from "./storage-tests";
const projectName = "projectName";
-const commonStorageTests = (storage: FSStorage) => {
- it("is empty", async () => {
- expect(await storage.ls()).toEqual([]);
- });
-
- it("stores project name", async () => {
- await storage.setProjectName("foo");
- expect(await storage.projectName()).toEqual("foo");
- });
-
- it("stores dirty flag", async () => {
- expect(await storage.isDirty()).toEqual(false);
- await storage.markDirty();
- expect(await storage.isDirty()).toEqual(true);
- await storage.clearDirty();
- expect(await storage.isDirty()).toEqual(false);
- });
-
- it("stores files", async () => {
- await storage.write("test1.py", new Uint8Array([1]));
- await storage.write("test2.py", new Uint8Array([2]));
-
- expect(await storage.ls()).toEqual(["test1.py", "test2.py"]);
- expect(await storage.exists("test1.py")).toEqual(true);
- expect(await storage.exists("testX.py")).toEqual(false);
- expect(await storage.read("test1.py")).toEqual(new Uint8Array([1]));
- expect(await storage.read("test2.py")).toEqual(new Uint8Array([2]));
- });
-
- it("throws trying to read a non-existent file", async () => {
- await expect(() => storage.read("test1.py")).rejects.toThrow(
- /No such file test1.py/
- );
- });
-
- it("removes files", async () => {
- await storage.write("test1.py", new Uint8Array([1]));
- await storage.write("test2.py", new Uint8Array([2]));
-
- await storage.remove("test1.py");
-
- expect(await storage.exists("test1.py")).toEqual(false);
- expect(await storage.ls()).toEqual(["test2.py"]);
- });
-
- it("clears", async () => {
- await storage.write("test1.py", new Uint8Array([1]));
- await storage.write("test2.py", new Uint8Array([2]));
-
- await storage.clear();
-
- expect(await storage.exists("test1.py")).toEqual(false);
- expect(await storage.exists("test2.py")).toEqual(false);
- expect(await storage.ls()).toEqual([]);
- });
-};
-
describe("SessionStorageFSStorage", () => {
const storage = new SessionStorageFSStorage(sessionStorage);
beforeEach(() => {
sessionStorage.clear();
});
- commonStorageTests(storage);
+ commonStorageTests(() => storage);
+ dirtyFlagTests(() => storage);
});
describe("InMemoryFSStorage", () => {
@@ -84,7 +30,19 @@ describe("InMemoryFSStorage", () => {
beforeEach(() => {
storage.clear();
});
- commonStorageTests(storage);
+ commonStorageTests(() => storage);
+ dirtyFlagTests(() => storage);
+});
+
+describe("DeferredFSStorage", () => {
+ const storage = new DeferredFSStorage(
+ Promise.resolve(new InMemoryFSStorage(projectName))
+ );
+ beforeEach(() => {
+ storage.clear();
+ });
+ commonStorageTests(() => storage);
+ dirtyFlagTests(() => storage);
});
describe("SplitStrategyStorage", () => {
@@ -98,7 +56,8 @@ describe("SplitStrategyStorage", () => {
storage.clear();
sessionStorage.clear();
});
- commonStorageTests(storage);
+ commonStorageTests(() => storage);
+ dirtyFlagTests(() => storage);
it("initializes from session storage", async () => {
const memory = new InMemoryFSStorage(projectName);
@@ -139,4 +98,24 @@ describe("SplitStrategyStorage", () => {
expect(await session.ls()).toEqual([]);
expect(await memory.ls()).toEqual(["test1.py", "test2.py", "test3.py"]);
});
+
+ it("never clears a preloaded secondary", async () => {
+ const memory = new InMemoryFSStorage(projectName);
+ const record = new InMemoryFSStorage(projectName);
+ await record.write("test1.py", new Uint8Array([1]));
+ const clear = vi.spyOn(record, "clear");
+ vi.spyOn(record, "write").mockRejectedValue(new Error("Simulated"));
+
+ const log = new MockLogging();
+ const split = new SplitStrategyStorage(memory, record, log, {
+ preloaded: true,
+ });
+ await split.write("test2.py", new Uint8Array([2]));
+
+ expect(log.errors[0].message).toEqual(
+ "Abandoning secondary storage due to error"
+ );
+ expect(clear).not.toHaveBeenCalled();
+ expect(await record.ls()).toEqual(["test1.py"]);
+ });
});
diff --git a/src/fs/storage.ts b/src/fs/storage.ts
index 90ed81333..e526a8c34 100644
--- a/src/fs/storage.ts
+++ b/src/fs/storage.ts
@@ -23,8 +23,10 @@ export interface FSStorage {
projectName(): Promise;
clear(): Promise;
/**
- * We persist the dirty flag so that we know whether the user
- * had previously made changes after a restore from storage.
+ * Whether the user has changed the project since the last hex save, used
+ * to warn before their work is lost. Storage that lives no longer than the
+ * tab persists it so the warning survives a reload; storage that outlives
+ * the tab has nothing to warn about and always reports false.
*/
markDirty(): Promise;
clearDirty(): Promise;
@@ -169,6 +171,18 @@ export class SessionStorageFSStorage implements FSStorage {
this.storage.clear();
}
+ /**
+ * Removes the file system's keys and nothing else: session storage also
+ * holds session settings.
+ */
+ async removeAll(): Promise {
+ for (const key of Object.keys(this.storage)) {
+ if (key.startsWith(fsFilesPrefix) || key.startsWith(fsMetadataPrefix)) {
+ this.storage.removeItem(key);
+ }
+ }
+ }
+
async markDirty(): Promise {
this.storage.setItem(dirtyKey, "true");
}
@@ -180,26 +194,81 @@ export class SessionStorageFSStorage implements FSStorage {
}
}
+/**
+ * Storage that arrives later. Every operation waits for it and then goes
+ * straight through, so its errors reach the caller untouched.
+ */
+export class DeferredFSStorage implements FSStorage {
+ constructor(private storage: Promise) {}
+
+ async ls() {
+ return (await this.storage).ls();
+ }
+ async exists(filename: string) {
+ return (await this.storage).exists(filename);
+ }
+ async read(filename: string) {
+ return (await this.storage).read(filename);
+ }
+ async write(filename: string, content: Uint8Array) {
+ return (await this.storage).write(filename, content);
+ }
+ async remove(filename: string) {
+ return (await this.storage).remove(filename);
+ }
+ async setProjectName(projectName: string | undefined) {
+ return (await this.storage).setProjectName(projectName);
+ }
+ async projectName() {
+ return (await this.storage).projectName();
+ }
+ async clear() {
+ return (await this.storage).clear();
+ }
+ async markDirty() {
+ return (await this.storage).markDirty();
+ }
+ async clearDirty() {
+ return (await this.storage).clearDirty();
+ }
+ async isDirty() {
+ return (await this.storage).isDirty();
+ }
+}
+
/**
* Reads from primary.
*
* Writes to both.
*
- * If write errors occur it clears primary and discontinues use.
+ * If the secondary errors it stops using it, clearing it first unless
+ * preloaded.
*/
export class SplitStrategyStorage implements FSStorage {
private initialized: Promise;
+ private secondary: FSStorage | undefined;
+ /**
+ * @param secondary The persistent copy, or a promise of one for storage
+ * that takes time to open. Every operation waits for it.
+ * @param options.preloaded The primary already holds the secondary's
+ * content, so it isn't read back. The secondary is then the source of
+ * truth and is never cleared.
+ */
constructor(
private primary: FSStorage,
- private secondary: FSStorage | undefined,
- private log: Logging
+ secondary: FSStorage | undefined | Promise,
+ private log: Logging,
+ private options: { preloaded?: boolean } = {}
) {
- this.initialized = secondary
- ? this.secondaryErrorHandle(async () => {
- await initializeFromStorage(secondary, primary);
- })
- : Promise.resolve();
+ this.initialized = Promise.resolve(secondary).then((resolved) => {
+ this.secondary = resolved;
+ return resolved && !options.preloaded
+ ? this.secondaryErrorHandle(async () => {
+ await initializeFromStorage(resolved, primary);
+ })
+ : undefined;
+ });
}
async ls() {
@@ -265,14 +334,16 @@ export class SplitStrategyStorage implements FSStorage {
try {
await action(this.secondary);
} catch (e1) {
- try {
- await this.secondary.clear();
- } catch (e2) {
- // Not much we can do.
- this.log.error(
- "Failed to clear secondary storage in error scenario",
- e2
- );
+ if (!this.options.preloaded) {
+ try {
+ await this.secondary.clear();
+ } catch (e2) {
+ // Not much we can do.
+ this.log.error(
+ "Failed to clear secondary storage in error scenario",
+ e2
+ );
+ }
}
// Avoid all future errors this session.
this.log.error("Abandoning secondary storage due to error", e1);
diff --git a/src/iframe-mode-hooks.tsx b/src/iframe-mode-hooks.tsx
new file mode 100644
index 000000000..e455f1e98
--- /dev/null
+++ b/src/iframe-mode-hooks.tsx
@@ -0,0 +1,16 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { createContext, use } from "react";
+
+const IframeModeContext = createContext(false);
+
+/**
+ * Whether the app is embedded in controller mode (classroom). The embedding
+ * page then owns the project and there are no pages besides the editor.
+ */
+export const IframeModeProvider = IframeModeContext.Provider;
+
+export const useIframeMode = (): boolean => use(IframeModeContext);
diff --git a/src/pages/ActionCard.tsx b/src/pages/ActionCard.tsx
new file mode 100644
index 000000000..feac4a599
--- /dev/null
+++ b/src/pages/ActionCard.tsx
@@ -0,0 +1,65 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ Card,
+ CardBody,
+ darkSurface,
+ Icon,
+ LinkBox,
+ LinkOverlayButton,
+ VStack,
+} from "@microbit/ui";
+import { ReactNode } from "react";
+import { IconType } from "react-icons";
+
+interface ActionCardProps {
+ onClick: () => void;
+ icon: IconType;
+ children: ReactNode;
+}
+
+/**
+ * A card-sized button among the project cards, for creating a project or
+ * seeing them all.
+ */
+const ActionCard = ({ onClick, icon, children }: ActionCardProps) => (
+
+
+
+
+
+
+ {children}
+
+
+
+
+
+);
+
+export default ActionCard;
diff --git a/src/pages/BackArrow.tsx b/src/pages/BackArrow.tsx
new file mode 100644
index 000000000..0eff1193c
--- /dev/null
+++ b/src/pages/BackArrow.tsx
@@ -0,0 +1,27 @@
+/**
+ * (c) 2024, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { css } from "styled-system/css";
+
+/** Back arrow glyph, sized like an icon (1em, currentColor). */
+const BackArrow = () => (
+
+
+
+);
+
+export default BackArrow;
diff --git a/src/pages/DefaultPageLayout.tsx b/src/pages/DefaultPageLayout.tsx
new file mode 100644
index 000000000..c64f1bad4
--- /dev/null
+++ b/src/pages/DefaultPageLayout.tsx
@@ -0,0 +1,127 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Box, Button, darkSurface, HStack, VStack } from "@microbit/ui";
+import { css } from "styled-system/css";
+import { ReactNode } from "react";
+import { FormattedMessage, useIntl } from "react-intl";
+import { Link as RouterLink, useNavigate } from "react-router";
+import { styled } from "styled-system/jsx";
+import { useDeployment } from "../deployment";
+import { flags } from "../flags";
+import SettingsMenu from "../settings/SettingsMenu";
+import { createHomePageUrl } from "../urls";
+import HelpMenu from "../workbench/HelpMenu";
+import BackArrow from "./BackArrow";
+import PageReleaseNotice from "./PageReleaseNotice";
+
+interface DefaultPageLayoutProps {
+ children: ReactNode;
+ /** A back-to-home button in place of the branding. */
+ backToHome?: boolean;
+}
+
+/**
+ * Organisation logo, divider, product wordmark, as ml-trainer's header.
+ * Sizes are the prototype's; the OSS build has only the wordmark.
+ */
+const Branding = () => {
+ const intl = useIntl();
+ const { AppLogo, OrgLogo } = useDeployment();
+ return (
+
+ {/* Decorative: the link is named by its label. */}
+
+ {OrgLogo ? (
+ <>
+
+
+ >
+ ) : null}
+ {AppLogo ? : null}
+
+
+ );
+};
+
+// The pages copy ml-trainer's header, whose buttons are the base preset's
+// lg size with a 24px icon. This app's dense preset shrinks lg to 42px
+// and the icon to 18px, so the sizes are pinned here. See the dense preset
+// discussion in docs/home-page.md.
+const headerButtonCss = { h: "48px", minW: "48px", fontSize: "24px" };
+
+const BackToHomeButton = () => {
+ const navigate = useNavigate();
+ return (
+ }
+ onPress={() => void navigate(createHomePageUrl())}
+ >
+
+
+ );
+};
+
+/**
+ * Full-height page with the brand header and a scrolling body, for the
+ * pages outside the editor.
+ */
+const DefaultPageLayout = ({
+ children,
+ backToHome = false,
+}: DefaultPageLayoutProps) => (
+
+
+ {backToHome ? : }
+
+
+
+
+
+ {flags.betaNotice && }
+
+ {children}
+
+
+);
+
+export default DefaultPageLayout;
diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx
new file mode 100644
index 000000000..9ebc55e1e
--- /dev/null
+++ b/src/pages/HomePage.tsx
@@ -0,0 +1,302 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ Button,
+ Icon,
+ IconButton,
+ Text,
+ TooltipButton,
+ useBreakpointValue,
+ VisuallyHidden,
+ VStack,
+} from "@microbit/ui";
+import { css } from "styled-system/css";
+import { CarouselRow } from "@microbit/ui-carousel";
+import { NameProjectDialog, ProjectCard } from "@microbit/ui-patterns";
+import { ChangeEvent, useCallback, useRef, useState } from "react";
+import {
+ RiAddLine,
+ RiFolderOpenLine,
+ RiInformationLine,
+ RiUpload2Line,
+} from "react-icons/ri";
+import { FormattedMessage, useIntl } from "react-intl";
+import { Link as RouterLink, useNavigate } from "react-router";
+import FileDropTarget from "../common/FileDropTarget";
+import { useDeployment } from "../deployment";
+import { microbitOrgMiciProjectsUrl } from "../external-links";
+import { useSettings } from "../settings/settings";
+import { createProjectsPageUrl } from "../urls";
+import ActionCard from "./ActionCard";
+import DefaultPageLayout from "./DefaultPageLayout";
+import IdeaDialog from "./IdeaDialog";
+import ProjectIcon from "./ProjectIcon";
+import HomepageBanner from "./HomepageBanner";
+import HomepageFooter from "./HomepageFooter";
+import {
+ useImportProjectFiles,
+ usePageProjects,
+ useProjectPageActions,
+ useReportCreateProjectFailure,
+ useReportOpenFailure,
+} from "./project-page-actions";
+import {
+ createHelpCards,
+ createLessonCards,
+ createMiciProjectCards,
+ createIdeaCards,
+} from "./resource-cards";
+
+const numCardsDisplayed = 10;
+
+const projectsRowClassName = css({ _shortHeight: { py: 4 } });
+
+const HomePage = () => {
+ const intl = useIntl();
+ const [{ languageId }] = useSettings();
+ const brand = useDeployment();
+ const [selectedIdea, setSelectedIdea] = useState<{
+ slug: string;
+ title: string;
+ }>();
+ const selectIdea = useCallback(
+ (slug: string, title: string) => setSelectedIdea({ slug, title }),
+ []
+ );
+ const importFiles = useImportProjectFiles("home");
+ const handleDrop = useCallback(
+ (files: File[]) => void importFiles(files, "drop"),
+ [importFiles]
+ );
+ useReportCreateProjectFailure();
+ useReportOpenFailure();
+ return (
+
+ {selectedIdea && (
+ setSelectedIdea(undefined)}
+ />
+ )}
+
+
+ {intl.formatMessage({ id: "app-title" })}
+
+
+
+ }
+ navigation
+ />
+ }
+ navigation
+ />
+ }
+ subtitle={ }
+ actions={
+
+
+
+ }
+ navigation
+ />
+ }
+ navigation
+ />
+
+
+
+ );
+};
+
+const ProjectsRow = () => {
+ const tooltipPlacement = useBreakpointValue<"bottom" | "right">({
+ base: "bottom",
+ sm: "right",
+ });
+ const projects = usePageProjects();
+ const { actions, open, create } = useProjectPageActions("home", projects);
+ const cards = [
+ ,
+ ...projects.slice(0, numCardsDisplayed).map((project) => (
+
+
+
+ )),
+ ...(projects.length > numCardsDisplayed
+ ? [ ]
+ : []),
+ ];
+ return (
+ <>
+ {actions.dialogs}
+ }
+ titleSuffix={
+
+
+
+
+
+ }
+ >
+
+
+ }
+ actions={[
+ ,
+ ,
+ ]}
+ navigation
+ />
+ >
+ );
+};
+
+const NewProjectCard = ({
+ onCreate,
+}: {
+ onCreate: (name: string) => Promise;
+}) => {
+ const intl = useIntl();
+ const [isOpen, setIsOpen] = useState(false);
+ const close = useCallback(() => setIsOpen(false), []);
+ const handleSave = useCallback(
+ (name: string) => {
+ setIsOpen(false);
+ void onCreate(name);
+ },
+ [onCreate]
+ );
+ return (
+ <>
+ }
+ />
+ setIsOpen(true)} icon={RiAddLine}>
+
+
+ >
+ );
+};
+
+/**
+ * Chooses files to import as a new project. Icon only where the row's
+ * heading leaves no room for the label.
+ */
+const ImportProjectButton = () => {
+ const intl = useIntl();
+ const importFiles = useImportProjectFiles("home");
+ const inputRef = useRef(null);
+ const choose = useCallback(() => inputRef.current?.click(), []);
+ const handleChange = useCallback(
+ (e: ChangeEvent) => {
+ const files = Array.from(e.target.files ?? []);
+ // Clear the input so choosing the same file again triggers a change.
+ e.target.value = "";
+ if (files.length > 0) {
+ void importFiles(files, "file_picker");
+ }
+ },
+ [importFiles]
+ );
+ const label = intl.formatMessage({ id: "import-file-action" });
+ return (
+ <>
+
+
+
+
+ }
+ onPress={choose}
+ css={{ display: { base: "none", sm: "inline-flex" } }}
+ >
+ {label}
+
+ >
+ );
+};
+
+const ViewAllProjectsCard = () => {
+ const navigate = useNavigate();
+ return (
+ void navigate(createProjectsPageUrl())}
+ icon={RiFolderOpenLine}
+ >
+
+
+ );
+};
+
+/** A text link beside a row heading. */
+const rowLinkClassName = css({
+ color: "brand.700",
+ fontWeight: "semibold",
+ borderRadius: "md",
+ px: 2,
+ py: 1,
+ textDecoration: "none",
+ _hover: { textDecoration: "underline" },
+ _focusVisible: { focusRing: "outline" },
+});
+
+const ViewAllProjectsLink = () => (
+
+
+
+);
+
+export default HomePage;
diff --git a/src/pages/HomepageBanner.tsx b/src/pages/HomepageBanner.tsx
new file mode 100644
index 000000000..825733a27
--- /dev/null
+++ b/src/pages/HomepageBanner.tsx
@@ -0,0 +1,79 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ darkSurface,
+ Heading,
+ HStack,
+ LinkButton,
+ Text,
+ VStack,
+} from "@microbit/ui";
+import { FormattedMessage } from "react-intl";
+import bannerBackground from "theme-package/images/banner-background.svg";
+import { microbitOrgCodeAiPythonUrl } from "../external-links";
+
+// Landscape phones.
+const shortHeight = "@media (max-height: 700px)";
+
+const HomepageBanner = () => {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default HomepageBanner;
diff --git a/src/pages/HomepageFooter.tsx b/src/pages/HomepageFooter.tsx
new file mode 100644
index 000000000..ffbb16cab
--- /dev/null
+++ b/src/pages/HomepageFooter.tsx
@@ -0,0 +1,79 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Button, HStack, Link, Text } from "@microbit/ui";
+import { FormattedMessage } from "react-intl";
+import { styled } from "styled-system/jsx";
+import { useDeployment } from "../deployment";
+
+const fontSize = { base: "sm", sm: "md" };
+
+/**
+ * Copyright and legal links, as ml-trainer's footer without its app store
+ * badges.
+ */
+const HomepageFooter = () => {
+ const { copyrightHolder, privacyPolicyLink, termsOfUseLink, compliance } =
+ useDeployment();
+ return (
+
+
+ {copyrightHolder && (
+
+ © {copyrightHolder}
+
+ )}
+ {compliance.manageCookies && (
+
+
+
+ )}
+ {privacyPolicyLink && (
+
+
+
+ )}
+ {termsOfUseLink && (
+
+
+
+ )}
+
+
+ );
+};
+
+export default HomepageFooter;
diff --git a/src/pages/IdeaDialog.tsx b/src/pages/IdeaDialog.tsx
new file mode 100644
index 000000000..8400384a4
--- /dev/null
+++ b/src/pages/IdeaDialog.tsx
@@ -0,0 +1,124 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ Button,
+ Modal,
+ ModalBody,
+ ModalCloseButton,
+ ModalFooter,
+ ModalHeader,
+ Text,
+} from "@microbit/ui";
+import { useEffect, useRef, useState } from "react";
+import { FormattedMessage } from "react-intl";
+import { Box, Grid, Stack } from "styled-system/jsx";
+import { docStylesClass } from "../common/documentation-styles";
+import Spinner from "../common/Spinner";
+import { useDocumentation } from "../documentation/documentation-hooks";
+import DocumentationContent, {
+ DocumentationContextProvider,
+} from "../documentation/common/DocumentationContent";
+import { ideaCode, withoutCode } from "../documentation/ideas/idea-code";
+import HighlightedCode from "../editor/codemirror/HighlightedCode";
+import { useCreateProjectFailure, useOpenIdea } from "./project-page-actions";
+
+interface IdeaDialogProps {
+ slug: string;
+ /** The idea's name, shown before its content loads and given to the project. */
+ title: string;
+ onClose: () => void;
+}
+
+/**
+ * An idea from the home page: text explaining it beside its program, and a
+ * way to open it as a new project.
+ */
+const IdeaDialog = ({ slug, title, onClose }: IdeaDialogProps) => {
+ const { ideas } = useDocumentation();
+ const openIdea = useOpenIdea();
+ // Router state, and so the editor replacing this dialog, renders in a
+ // transition that further clicks can delay, so the ref guards the create
+ // and local state shows it. Both clear on failure only, to allow a retry.
+ const creatingRef = useRef(false);
+ const [isCreating, setIsCreating] = useState(false);
+ const failure = useCreateProjectFailure();
+ useEffect(() => {
+ creatingRef.current = false;
+ setIsCreating(false);
+ }, [failure]);
+ const idea =
+ ideas.status === "ok"
+ ? ideas.content.find((idea) => idea.slug.current === slug)
+ : undefined;
+ const code = idea && ideaCode(idea);
+ const handleCreate = () => {
+ if (code === undefined || creatingRef.current) {
+ return;
+ }
+ creatingRef.current = true;
+ setIsCreating(true);
+ void openIdea(title, slug, code);
+ };
+ return (
+
+
+
+ {title}
+
+
+
+ {/* Always rendered, so the code stays in the right-hand column. */}
+
+ {idea && (
+ // Without the code, which is beside it, and with links to
+ // Reference and API as text: they need the editor.
+
+
+
+ )}
+
+
+ {ideas.status === "loading" ? (
+
+ ) : code !== undefined ? (
+
+ ) : (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default IdeaDialog;
diff --git a/src/pages/LevelIndicator.tsx b/src/pages/LevelIndicator.tsx
new file mode 100644
index 000000000..bc6a5ecc2
--- /dev/null
+++ b/src/pages/LevelIndicator.tsx
@@ -0,0 +1,87 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { FormattedMessage } from "react-intl";
+import { css } from "styled-system/css";
+
+/** A microbit.org project's level, as the main site has it. */
+export type Level = "beginner" | "intermediate" | "advanced";
+
+/** How many of the bars are filled, less one. */
+const levelNumber: Record = {
+ beginner: 0,
+ intermediate: 1,
+ advanced: 2,
+};
+
+const levelMessageId: Record = {
+ beginner: "level-beginner",
+ intermediate: "level-intermediate",
+ advanced: "level-advanced",
+};
+
+const color = "#999999";
+
+/** Rising bars, filled up to the level. Copied from microbit.org. */
+const LevelImage = ({ value }: { value: Level }) => {
+ const level = levelNumber[value];
+ return (
+
+
+ = 2 ? color : undefined}
+ />
+ = 1 ? color : undefined}
+ />
+ = 0 ? color : undefined}
+ />
+
+
+ );
+};
+
+/**
+ * A project's level with microbit.org's bars icon. No typography here; the
+ * caller decides it. Not mirrored for right-to-left as the main site is: this
+ * app has no right-to-left languages.
+ */
+const LevelIndicator = ({ value }: { value: Level }) => (
+ // Baseline alignment sits the text on the icon's bottom edge.
+
+
+
+
+
+
+);
+
+export default LevelIndicator;
diff --git a/src/pages/PageReleaseNotice.tsx b/src/pages/PageReleaseNotice.tsx
new file mode 100644
index 000000000..5a9392378
--- /dev/null
+++ b/src/pages/PageReleaseNotice.tsx
@@ -0,0 +1,90 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Button, darkSurface, LinkButton, Text } from "@microbit/ui";
+import { useState } from "react";
+import { RiArrowRightLine, RiFeedbackLine } from "react-icons/ri";
+import { styled } from "styled-system/jsx";
+import FeedbackForm from "../workbench/FeedbackForm";
+
+/**
+ * The beta notice as a band under the page header, as ml-trainer shows it.
+ * The editor keeps its own, shorter one at the foot of the sidebar. Both are
+ * English only: they only show on non-public stages.
+ */
+const PageReleaseNotice = () => {
+ const [feedbackOpen, setFeedbackOpen] = useState(false);
+ return (
+ <>
+ setFeedbackOpen(false)}
+ />
+
+
+
+ Beta
+
+
+ This is a beta version and is subject to change without notice
+
+
+
+ }
+ variant="link"
+ size="sm"
+ css={{ color: "white", fontWeight: "bold" }}
+ onPress={() => setFeedbackOpen(true)}
+ >
+ Feedback
+
+ }
+ size="sm"
+ css={{
+ bg: "white",
+ border: 0,
+ color: "brand.700",
+ _hover: { bg: "white", color: "brand.700" },
+ }}
+ href="https://python.microbit.org/v/3"
+ >
+ Go to the current editor
+
+
+
+ >
+ );
+};
+
+export default PageReleaseNotice;
diff --git a/src/pages/ProjectIcon.tsx b/src/pages/ProjectIcon.tsx
new file mode 100644
index 000000000..0d0c8eb3c
--- /dev/null
+++ b/src/pages/ProjectIcon.tsx
@@ -0,0 +1,37 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Box } from "@microbit/ui";
+import PythonLogo from "../common/PythonLogo";
+
+interface ProjectIconProps {
+ /**
+ * The projects page cards carry a selection checkbox in the top-left
+ * corner, so the glyph drops below it rather than sharing the corner.
+ */
+ hasCheckbox?: boolean;
+ /** Smaller on short viewports, for the home page carousel. */
+ short?: boolean;
+}
+
+/** The picture on a project card: the Python logo in the top-left corner. */
+const ProjectIcon = ({ hasCheckbox = false, short }: ProjectIconProps) => (
+
+
+
+);
+
+export default ProjectIcon;
diff --git a/src/pages/ProjectsPage.tsx b/src/pages/ProjectsPage.tsx
new file mode 100644
index 000000000..dda44cfb9
--- /dev/null
+++ b/src/pages/ProjectsPage.tsx
@@ -0,0 +1,256 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ Box,
+ Flex,
+ Grid,
+ Heading,
+ HStack,
+ Slide,
+ Stack,
+ Text,
+ useBreakpointValue,
+ VStack,
+} from "@microbit/ui";
+import { css, cx } from "styled-system/css";
+import {
+ defaultSortDirection,
+ ProjectCard,
+ ProjectSearchInput,
+ ProjectSortDirection,
+ ProjectSortField,
+ ProjectSortInput,
+ ProjectsToolbar,
+ ProjectsToolbarHandle,
+ rankProjects,
+ sortProjects,
+ useProjectSelection,
+} from "@microbit/ui-patterns";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { FormattedMessage, useIntl } from "react-intl";
+import FileDropTarget from "../common/FileDropTarget";
+import { useLogging } from "../logging/logging-hooks";
+import DefaultPageLayout from "./DefaultPageLayout";
+import ProjectIcon from "./ProjectIcon";
+import {
+ PageProject,
+ usePageProjects,
+ useProjectPageActions,
+ useImportProjectFiles,
+} from "./project-page-actions";
+
+const fileNames = (project: PageProject) => project.fileNames;
+
+const ProjectsPage = () => {
+ const projects = usePageProjects();
+ const logging = useLogging();
+ const intl = useIntl();
+ const mobileIconOnly = useBreakpointValue({ base: true, md: false });
+
+ const selection = useProjectSelection(projects);
+ const { selectedIds } = selection;
+ const { actions, open } = useProjectPageActions(
+ "projects",
+ projects,
+ selectedIds
+ );
+
+ const [field, setField] = useState("timestamp");
+ const [direction, setDirection] = useState("desc");
+ const handleFieldChange = (next: ProjectSortField) => {
+ const nextDirection = defaultSortDirection(next);
+ setField(next);
+ setDirection(nextDirection);
+ logging.event({
+ type: "project_sort",
+ detail: { field: next, direction: nextDirection },
+ });
+ };
+ const toggleDirection = () => {
+ const next = direction === "asc" ? "desc" : "asc";
+ setDirection(next);
+ logging.event({ type: "project_sort", detail: { field, direction: next } });
+ };
+
+ const importFiles = useImportProjectFiles("projects");
+ const handleDrop = useCallback(
+ (files: File[]) => void importFiles(files, "drop"),
+ [importFiles]
+ );
+
+ const [query, setQuery] = useState("");
+ const handleQueryChange = useCallback(
+ (value: string) => {
+ if (value.trim()) {
+ selection.clear();
+ }
+ setQuery(value);
+ },
+ [selection]
+ );
+ // One project_search per intentional search, not per keystroke.
+ useEffect(() => {
+ if (!query.trim()) {
+ return;
+ }
+ const handle = setTimeout(() => {
+ logging.event({ type: "project_search" });
+ }, 400);
+ return () => clearTimeout(handle);
+ }, [logging, query]);
+
+ const shown = useMemo(
+ () =>
+ query.trim()
+ ? rankProjects(projects, query, fileNames)
+ : sortProjects(projects, field, direction, intl.locale),
+ [direction, field, intl.locale, projects, query]
+ );
+
+ const desktopToolbarRef = useRef(null);
+ const mobileToolbarRef = useRef(null);
+ const handleSkipToToolbar = useCallback(() => {
+ if (!desktopToolbarRef.current?.focus()) {
+ mobileToolbarRef.current?.focus();
+ }
+ }, []);
+
+ return (
+ <>
+ {actions.dialogs}
+
+
+
+
+
+
+
+
+
+ {selection.hasSelection && (
+
+
+
+ )}
+
+
+ {shown.length > 0 ? (
+
+ {shown.map((project) => (
+
+
+
+
+
+ ))}
+
+ ) : (
+
+
+
+
+
+ )}
+
+
+
+
+
+
+
+
+
+ >
+ );
+};
+
+export default ProjectsPage;
diff --git a/src/pages/ResourceCard.tsx b/src/pages/ResourceCard.tsx
new file mode 100644
index 000000000..dd9f0d543
--- /dev/null
+++ b/src/pages/ResourceCard.tsx
@@ -0,0 +1,146 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import {
+ AspectRatio,
+ Box,
+ Heading,
+ Image,
+ LinkBox,
+ LinkOverlay,
+ LinkOverlayButton,
+ Text,
+ VStack,
+} from "@microbit/ui";
+import { ReactNode } from "react";
+import LevelIndicator, { Level } from "./LevelIndicator";
+
+type ResourceCardProps = {
+ /** A 2:1 image area instead of 4:3. */
+ wide?: boolean;
+ /** Spacing scale units around the image, for artwork without a margin. */
+ imagePadding?: number;
+ /** `cover` crops photos to the card; `contain` keeps artwork whole. */
+ imageFit?: "cover" | "contain";
+ imgSrc: string;
+ title: ReactNode;
+ /**
+ * A small label above the title saying what kind of resource it is, e.g.
+ * "Unit of work".
+ */
+ resourceType?: ReactNode;
+ /** A line under the title saying what the resource is. */
+ description?: ReactNode;
+ level?: Level;
+} & (
+ | { /** A page on another site. */ url: string; onClick?: undefined }
+ | { /** An action within the app. */ onClick: () => void; url?: undefined }
+);
+
+/**
+ * A card linking to a resource on another site, or doing something in the app.
+ */
+const ResourceCard = ({
+ wide,
+ imagePadding,
+ imageFit = "cover",
+ imgSrc,
+ url,
+ onClick,
+ title,
+ resourceType,
+ description,
+ level,
+}: ResourceCardProps) => (
+
+
+
+
+
+
+
+
+ {resourceType !== undefined && (
+
+ {resourceType}
+
+ )}
+
+ {onClick ? (
+
+ {title}
+
+ ) : (
+
+ {title}
+
+ )}
+
+ {(description !== undefined || level) && (
+ // As microbit.org's CardContent: the body sits at the bottom with
+ // a fixed-height description, so the spare space in a stretched
+ // card goes under the title and descriptions line up across a row.
+
+ {description !== undefined && (
+
+ {description}
+
+ )}
+ {level && (
+
+
+
+ )}
+
+ )}
+
+
+
+);
+
+export default ResourceCard;
diff --git a/src/pages/project-page-actions.tsx b/src/pages/project-page-actions.tsx
new file mode 100644
index 000000000..4c6cd4160
--- /dev/null
+++ b/src/pages/project-page-actions.tsx
@@ -0,0 +1,288 @@
+/**
+ * What the project cards and toolbar do on the home and projects pages.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { ProjectSummary, useProjectActions } from "@microbit/ui-patterns";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useIntl } from "react-intl";
+import {
+ ActionFunctionArgs,
+ redirect,
+ useFetcher,
+ useFetchers,
+ useLocation,
+ useNavigate,
+ useNavigation,
+} from "react-router";
+import useActionFeedback from "../common/use-action-feedback";
+import { MAIN_FILE } from "../fs/fs";
+import { useLogging } from "../logging/logging-hooks";
+import { useProjectImporter } from "../project/project-hooks";
+import { ImportSource } from "../project/project-import";
+import { Projects } from "../project/projects";
+import { useProjectList, useProjects } from "../project/projects-hooks";
+import {
+ isQuotaExceededError,
+ useShowStorageError,
+} from "../project/storage-error-toast";
+import { RouterState } from "../router-hooks";
+import { createEditorUrl, routerPathFromUrl } from "../urls";
+
+/** Which page an action happened on, for analytics. */
+export type ProjectSurface = "home" | "projects";
+
+export interface PageProject extends ProjectSummary {
+ fileNames: string[];
+}
+
+/** Shared by every create, so pages can see one in progress. */
+const createProjectFetcherKey = "create-project";
+
+/** The editor route's action result when creating a project fails. */
+interface CreateProjectFailure {
+ error: unknown;
+}
+
+/** What the editor route's action reads from its form. */
+interface CreateProjectFields {
+ name: string;
+ /** main.py, e.g. an idea's program, instead of the default. */
+ code?: string;
+}
+
+/**
+ * The editor route's action: creates a project from the form and opens the
+ * editor on it at the same URL. Part of the navigation, so the router knows
+ * a create is in progress until the editor is showing.
+ */
+export const createProjectAction =
+ (projects: Projects) =>
+ async ({
+ request,
+ }: ActionFunctionArgs): Promise => {
+ const form = await request.formData();
+ const field = (key: string) => {
+ const value = form.get(key);
+ return typeof value === "string" ? value : undefined;
+ };
+ const name = field("name") ?? "";
+ const code = field("code");
+ try {
+ if (code !== undefined) {
+ await projects.createFromFiles(name, {
+ [MAIN_FILE]: new TextEncoder().encode(code),
+ });
+ } else {
+ await projects.create(name);
+ }
+ } catch (error) {
+ return { error };
+ }
+ return redirect(routerPathFromUrl(request.url));
+ };
+
+/**
+ * The projects as the shared components want them: every one has a name.
+ * Held while a create is in progress, so the new card doesn't show in the
+ * moment before the page gives way to the editor.
+ */
+export const usePageProjects = (): PageProject[] => {
+ const list = useProjectList();
+ const creating = useFetchers().some(
+ (f) => f.key === createProjectFetcherKey && f.state !== "idle"
+ );
+ const navigating = useNavigation().state !== "idle";
+ const [shownList, setShownList] = useState(list);
+ if (!creating && !navigating && shownList !== list) {
+ setShownList(list);
+ }
+ const intl = useIntl();
+ const untitled = intl.formatMessage({ id: "untitled-project" });
+ return useMemo(
+ () => shownList.map((p) => ({ ...p, name: p.name ?? untitled })),
+ [shownList, untitled]
+ );
+};
+
+/** Reports a failed storage action as a toast. */
+const useReportError = () => {
+ const actionFeedback = useActionFeedback();
+ const showStorageError = useShowStorageError();
+ return useCallback(
+ (e: unknown) => {
+ if (isQuotaExceededError(e)) {
+ showStorageError(e);
+ } else {
+ actionFeedback.unexpectedError(e);
+ }
+ },
+ [actionFeedback, showStorageError]
+ );
+};
+
+/** Reports a project the editor failed to load before redirecting here. */
+export const useReportOpenFailure = () => {
+ const projects = useProjects();
+ const reportError = useReportError();
+ // The redirect can land on this page while it is already showing, so
+ // check on every arrival, not just when it mounts.
+ const { key } = useLocation();
+ useEffect(() => {
+ const failure = projects.takeOpenFailure();
+ if (failure !== undefined) {
+ reportError(failure);
+ }
+ }, [projects, reportError, key]);
+};
+
+/** Runs a storage action, reporting failures as toasts. */
+const useAttempt = () => {
+ const reportError = useReportError();
+ return useCallback(
+ async (action: () => Promise) => {
+ try {
+ await action();
+ } catch (e) {
+ reportError(e);
+ }
+ },
+ [reportError]
+ );
+};
+
+/** Creates a project and opens the editor on it. */
+export const useCreateProject = (surface: ProjectSurface) => {
+ const logging = useLogging();
+ const submit = useSubmitCreateProject();
+ return useCallback(
+ async (name: string) => {
+ logging.event({ type: "project_create", detail: { surface } });
+ await submit({ name });
+ },
+ [logging, submit, surface]
+ );
+};
+
+/**
+ * Opens an idea as a new project with its program in main.py, showing the
+ * idea in the Ideas tab beside the editor.
+ */
+export const useOpenIdea = () => {
+ const logging = useLogging();
+ const submit = useSubmitCreateProject();
+ return useCallback(
+ async (name: string, slug: string, code: string) => {
+ logging.event({ type: "idea_open", detail: { id: slug } });
+ await submit({ name, code }, { tab: "ideas", slug: { id: slug } });
+ },
+ [logging, submit]
+ );
+};
+
+/** The last failed create's result, a new object for each failure. */
+export const useCreateProjectFailure = () =>
+ useFetcher({ key: createProjectFetcherKey }).data;
+
+/**
+ * Reports a failed create as a toast. Every create shares one fetcher, so
+ * call this once per page, not per submitter, or each one shows the toast.
+ */
+export const useReportCreateProjectFailure = () => {
+ const reportError = useReportError();
+ const failure = useCreateProjectFailure();
+ useEffect(() => {
+ if (failure) {
+ reportError(failure.error);
+ }
+ }, [failure, reportError]);
+};
+
+/**
+ * Submits to the editor route's action (createProjectAction). Failures are
+ * reported by useReportCreateProjectFailure.
+ */
+const useSubmitCreateProject = () => {
+ const { submit } = useFetcher({
+ key: createProjectFetcherKey,
+ });
+ return useCallback(
+ (fields: CreateProjectFields, state?: RouterState) =>
+ submit(
+ {
+ name: fields.name,
+ ...(fields.code !== undefined && { code: fields.code }),
+ },
+ { method: "post", action: createEditorUrl(state) }
+ ),
+ [submit]
+ );
+};
+
+export const useProjectPageActions = (
+ surface: ProjectSurface,
+ projects: PageProject[],
+ selectedIds?: string[]
+) => {
+ const store = useProjects();
+ const logging = useLogging();
+ const navigate = useNavigate();
+ const attempt = useAttempt();
+ const create = useCreateProject(surface);
+
+ const actions = useProjectActions({
+ projects,
+ selectedIds,
+ onRename: (id, name) =>
+ attempt(async () => {
+ logging.event({ type: "project_rename", detail: { surface } });
+ await store.rename(id, name);
+ }),
+ onDuplicate: (id, name) =>
+ attempt(async () => {
+ logging.event({ type: "project_duplicate", detail: { surface } });
+ await store.duplicate(id, name);
+ }),
+ onDelete: (ids) =>
+ attempt(async () => {
+ logging.event({
+ type: "project_delete",
+ detail: { surface, count: ids.length },
+ });
+ await store.delete(ids);
+ }),
+ });
+
+ const open = useCallback(
+ (id: string) =>
+ attempt(async () => {
+ logging.event({ type: "project_open", detail: { surface } });
+ await store.open(id);
+ await navigate(createEditorUrl());
+ }),
+ [attempt, logging, navigate, store, surface]
+ );
+
+ return { actions, open, create };
+};
+
+/**
+ * Imports files from the home or projects page as a new project and opens
+ * the editor on it. Errors are reported as toasts by the importer.
+ */
+export const useImportProjectFiles = (
+ surface: ProjectSurface
+): ((files: File[], source: ImportSource) => Promise) => {
+ const importer = useProjectImporter();
+ const navigate = useNavigate();
+ return useCallback(
+ async (files: File[], source: ImportSource) => {
+ if (await importer.importAsNewProject(files, source, surface)) {
+ await navigate(createEditorUrl());
+ }
+ },
+ [importer, navigate, surface]
+ );
+};
diff --git a/src/pages/resource-cards.tsx b/src/pages/resource-cards.tsx
new file mode 100644
index 000000000..bf9bd5308
--- /dev/null
+++ b/src/pages/resource-cards.tsx
@@ -0,0 +1,277 @@
+/**
+ * The cards linking to microbit.org and the support site from the home page.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { IntlShape } from "react-intl";
+import accessibilityImage from "theme-package/images/accessibility.svg";
+import firstLessonsImage from "theme-package/images/first-lessons-python.svg";
+import ideaEmotionBadge from "theme-package/images/idea-emotion-badge.png";
+import ideaStepCounter from "theme-package/images/idea-step-counter.png";
+import ideaActivityPicker from "theme-package/images/idea-activity-picker.png";
+import ideaSendASmile from "theme-package/images/idea-send-a-smile.png";
+import ideaDice from "theme-package/images/idea-dice.png";
+import ideaClapLights from "theme-package/images/idea-clap-lights.png";
+import ideaFrereJacques from "theme-package/images/idea-frere-jacques.png";
+import hotPotatoGame from "theme-package/images/hot-potato-game.jpg";
+import indoorOutdoorThermometer from "theme-package/images/indoor-outdoor-thermometer.png";
+import introducingPythonCourseImage from "theme-package/images/introducing-python-course.png";
+import labellingWorksheetImage from "theme-package/images/microbit-labelling-worksheet.jpg";
+import microbitClassroomImage from "theme-package/images/microbit-classroom.png";
+import posterCreativityImage from "theme-package/images/python-editor-poster-creativity.jpg";
+import posterDebuggingImage from "theme-package/images/python-editor-poster-debugging.jpg";
+import maxminTemperatureLogger from "theme-package/images/maxmin-temperature-logger.png";
+import sensitiveStepCounter from "theme-package/images/sensitive-step-counter.jpg";
+import teleportingDuck from "theme-package/images/teleporting-duck.jpg";
+import thermometer from "theme-package/images/thermometer.png";
+import treasureHunt from "theme-package/images/treasure-hunt.png";
+import troubleshootingImage from "theme-package/images/troubleshooting.svg";
+import userGuideImage from "theme-package/images/user-guide.svg";
+import { BrandConfig } from "../deployment";
+import {
+ introducingPythonCourseUrl,
+ microbitClassroomUrl,
+ microbitOrgClassroomResourceUrl,
+ microbitOrgLessonUrl,
+ microbitOrgProjectUrl,
+} from "../external-links";
+import { Level } from "./LevelIndicator";
+import ResourceCard from "./ResourceCard";
+
+interface Idea {
+ titleId: string;
+ /** The idea's slug in the CMS. */
+ slug: string;
+ imgSrc: string;
+}
+
+const ideas: Idea[] = [
+ {
+ titleId: "idea-emotion-badge-title",
+ slug: "emotion-badge",
+ imgSrc: ideaEmotionBadge,
+ },
+ {
+ titleId: "idea-step-counter-title",
+ slug: "step-counter",
+ imgSrc: ideaStepCounter,
+ },
+ {
+ titleId: "idea-activity-picker-title",
+ slug: "activity-picker",
+ imgSrc: ideaActivityPicker,
+ },
+ {
+ titleId: "idea-send-a-smile-title",
+ slug: "send-a-smile",
+ imgSrc: ideaSendASmile,
+ },
+ { titleId: "idea-dice-title", slug: "dice", imgSrc: ideaDice },
+ {
+ titleId: "idea-clap-lights-title",
+ slug: "clap-lights",
+ imgSrc: ideaClapLights,
+ },
+ {
+ titleId: "idea-frere-jacques-title",
+ slug: "frère-jacques",
+ imgSrc: ideaFrereJacques,
+ },
+];
+
+/** Idea cards show the idea, by slug, for the user to open or not. */
+export const createIdeaCards = (
+ intl: IntlShape,
+ onSelect: (slug: string, title: string) => void
+) =>
+ ideas.map((idea) => (
+
+ onSelect(idea.slug, intl.formatMessage({ id: idea.titleId }))
+ }
+ imgSrc={idea.imgSrc}
+ />
+ ));
+
+interface MiciProject {
+ titleId: string;
+ descriptionId: string;
+ level: Level;
+ /** The "make it: code it" project's slug on microbit.org. */
+ slug: string;
+ imgSrc: string;
+}
+
+const miciProjects: MiciProject[] = [
+ {
+ titleId: "mici-project-thermometer-title",
+ descriptionId: "mici-project-thermometer-description",
+ level: "beginner",
+ slug: "thermometer",
+ imgSrc: thermometer,
+ },
+ {
+ titleId: "mici-project-sensitive-step-counter-title",
+ descriptionId: "mici-project-sensitive-step-counter-description",
+ level: "beginner",
+ slug: "sensitive-step-counter",
+ imgSrc: sensitiveStepCounter,
+ },
+ {
+ titleId: "mici-project-treasure-hunt-title",
+ descriptionId: "mici-project-treasure-hunt-description",
+ level: "intermediate",
+ slug: "treasure-hunt",
+ imgSrc: treasureHunt,
+ },
+ {
+ titleId: "mici-project-maxmin-temperature-logger-title",
+ descriptionId: "mici-project-maxmin-temperature-logger-description",
+ level: "advanced",
+ slug: "maxmin-temperature-logger",
+ imgSrc: maxminTemperatureLogger,
+ },
+ {
+ titleId: "mici-project-indoor-outdoor-thermometer-title",
+ descriptionId: "mici-project-indoor-outdoor-thermometer-description",
+ level: "intermediate",
+ slug: "indoor-outdoor-thermometer",
+ imgSrc: indoorOutdoorThermometer,
+ },
+ {
+ titleId: "mici-project-teleporting-duck-title",
+ descriptionId: "mici-project-teleporting-duck-description",
+ level: "beginner",
+ slug: "teleporting-duck",
+ imgSrc: teleportingDuck,
+ },
+ {
+ titleId: "mici-project-hot-potato-game-title",
+ descriptionId: "mici-project-hot-potato-game-description",
+ level: "intermediate",
+ slug: "hot-potato-game",
+ imgSrc: hotPotatoGame,
+ },
+];
+
+export const createMiciProjectCards = (intl: IntlShape, languageId: string) =>
+ miciProjects.map((project) => (
+
+ ));
+
+interface TeacherResource {
+ /** Message id prefix for `-title` and `-description`. */
+ id: string;
+ /** Message id of the label saying what kind of resource it is. */
+ typeId: string;
+ url: string;
+ imgSrc: string;
+}
+
+const teacherResources: TeacherResource[] = [
+ {
+ id: "introducing-python-course-resource",
+ typeId: "resource-type-professional-development",
+ url: introducingPythonCourseUrl,
+ imgSrc: introducingPythonCourseImage,
+ },
+ {
+ id: "microbit-classroom-resource",
+ typeId: "resource-type-teaching-tool",
+ url: microbitClassroomUrl,
+ imgSrc: microbitClassroomImage,
+ },
+ {
+ id: "python-editor-poster-creativity-resource",
+ typeId: "resource-type-classroom-resource",
+ url: microbitOrgClassroomResourceUrl("python-editor-poster-creativity"),
+ imgSrc: posterCreativityImage,
+ },
+ {
+ id: "python-editor-poster-debugging-resource",
+ typeId: "resource-type-classroom-resource",
+ url: microbitOrgClassroomResourceUrl("python-editor-poster-debugging"),
+ imgSrc: posterDebuggingImage,
+ },
+ {
+ id: "microbit-labelling-worksheet-resource",
+ typeId: "resource-type-classroom-resource",
+ url: microbitOrgClassroomResourceUrl("microbit-labelling-worksheet"),
+ imgSrc: labellingWorksheetImage,
+ },
+];
+
+export const createLessonCards = (intl: IntlShape) => [
+ ,
+ ...teacherResources.map((resource) => (
+
+ )),
+];
+
+type HelpLinks = Pick<
+ BrandConfig,
+ "userGuideLink" | "supportLink" | "accessibilityLink"
+>;
+
+/**
+ * Help cards for the links the brand supplies; a deployment without one
+ * has no card for it.
+ */
+export const createHelpCards = (
+ intl: IntlShape,
+ { userGuideLink, supportLink, accessibilityLink }: HelpLinks
+) =>
+ [
+ { titleId: "user-guide", url: userGuideLink, imgSrc: userGuideImage },
+ {
+ titleId: "troubleshooting-resource-title",
+ url: supportLink,
+ imgSrc: troubleshootingImage,
+ },
+ {
+ titleId: "accessibility-resource-title",
+ url: accessibilityLink,
+ imgSrc: accessibilityImage,
+ },
+ ]
+ .filter((help): help is typeof help & { url: string } => !!help.url)
+ .map((help) => (
+
+ ));
diff --git a/src/project/AddFilesButton.tsx b/src/project/AddFilesButton.tsx
new file mode 100644
index 000000000..f6da49da4
--- /dev/null
+++ b/src/project/AddFilesButton.tsx
@@ -0,0 +1,43 @@
+/**
+ * (c) 2021, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { RiFileAddLine } from "react-icons/ri";
+import { useIntl } from "react-intl";
+import { CollapsibleButtonComposableProps } from "../common/CollapsibleButton";
+import FileInputButton from "../common/FileInputButton";
+import { useProjectsDatabaseActive } from "../fs/storage-status";
+import { useProjectActions } from "./project-hooks";
+
+interface AddFilesButtonProps extends CollapsibleButtonComposableProps {}
+
+/**
+ * Adds files to the open project from the Files tab. A hex file becomes a
+ * new project instead, or replaces the open one where there is no projects
+ * database to keep both.
+ */
+const AddFilesButton = (props: AddFilesButtonProps) => {
+ const actions = useProjectActions();
+ const intl = useIntl();
+ const projectsDatabaseActive = useProjectsDatabaseActive();
+ return (
+ }
+ tooltip={intl.formatMessage({
+ id: projectsDatabaseActive
+ ? "add-files-hover"
+ : "add-files-hover-replace",
+ })}
+ />
+ );
+};
+
+export default AddFilesButton;
diff --git a/src/project/ChooseMainScriptQuestion.test.tsx b/src/project/ChooseMainScriptQuestion.test.tsx
deleted file mode 100644
index 78278d0e7..000000000
--- a/src/project/ChooseMainScriptQuestion.test.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { render, screen } from "@testing-library/react";
-import { ClassifiedFileInput, FileOperation } from "./changes";
-import ChooseMainScriptQuestion, {
- summarizeChange,
-} from "./ChooseMainScriptQuestion";
-import { stubIntl as intl } from "../messages/testing";
-import FixedTranslationProvider from "../messages/FixedTranslationProvider";
-import { vi } from "vitest";
-
-describe("ChooseMainScriptQuestion", () => {
- const data = () => Promise.resolve(new Uint8Array([0]));
-
- describe("component", () => {
- const setValue = vi.fn();
- const setValidationResult = vi.fn();
- const currentFiles = new Set(["main.py", "magic.py"]);
-
- afterEach(() => {
- setValidationResult.mockClear();
- setValue.mockClear();
- });
-
- const renderComponent = (
- inputs: ClassifiedFileInput[],
- choice: string | undefined
- ) => {
- return render(
-
- ({ ok: true })}
- />
-
- );
- };
-
- it("main.py replacement", async () => {
- const inputs: ClassifiedFileInput[] = [
- {
- data,
- module: false,
- script: true,
- name: "main.py",
- },
- ];
- renderComponent(inputs, "samplefile.py");
- const items = (await screen.findAllByTestId("change")).map(
- (x) => x.textContent
- );
-
- expect(items).toEqual(["Replace main code with main.py"]);
- // We don't use a list for simple cases.
- expect(screen.queryAllByRole("listitem")).toEqual([]);
- });
-
- it("two options for main.py case", async () => {
- const inputs: ClassifiedFileInput[] = [
- {
- data,
- module: false,
- script: true,
- name: "a.py",
- },
- {
- data,
- module: false,
- script: true,
- name: "b.py",
- },
- ];
- const result = renderComponent(inputs, "a.py");
- const findAllListItems = async () =>
- Array.from((await result.findAllByRole("list"))[0].childNodes).map(
- (x) => x.firstChild!.firstChild!.firstChild?.textContent
- );
- expect(await findAllListItems()).toEqual([
- "Replace main code with a.py",
- "Add file b.py",
- ]);
- });
- });
-
- describe("summarizeChange", () => {
- it("most common scenario is special cased to refer to main code", () => {
- expect(
- summarizeChange(intl, {
- operation: FileOperation.REPLACE,
- module: false,
- script: true,
- data,
- source: "somefile.py",
- target: "main.py",
- })
- ).toEqual("choose-main-source-replace-main-code");
- });
-
- it("names modules as such", () => {
- expect(
- summarizeChange(intl, {
- operation: FileOperation.ADD,
- module: true,
- script: false,
- data,
- source: "module.py",
- target: "module.py",
- })
- ).toEqual("choose-main-add-module");
- });
-
- it("non-main non-module replace", () => {
- expect(
- summarizeChange(intl, {
- operation: FileOperation.REPLACE,
- module: false,
- script: false,
- data,
- source: "dave.py",
- target: "dave.py",
- })
- ).toEqual("choose-main-replace-file");
- });
-
- it("non-python add", () => {
- expect(
- summarizeChange(intl, {
- operation: FileOperation.ADD,
- module: false,
- script: false,
- data,
- source: "data.dat",
- target: "data.dat",
- })
- ).toEqual("choose-main-add-file");
- });
- });
-});
diff --git a/src/project/ChooseMainScriptQuestion.tsx b/src/project/ChooseMainScriptQuestion.tsx
deleted file mode 100644
index 2a3ea98c8..000000000
--- a/src/project/ChooseMainScriptQuestion.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import {
- IconButton,
- ListItem,
- MenuItemOption,
- MenuList,
- MenuOptionGroup,
- MenuTrigger,
- Text,
- UnorderedList,
-} from "@microbit/ui";
-import { ReactNode } from "react";
-import { sortBy } from "../common/sort-util";
-import { RiFileSettingsLine } from "react-icons/ri";
-import { IntlShape, useIntl } from "react-intl";
-import { HStack } from "styled-system/jsx";
-import { InputDialogBody } from "../common/InputDialog";
-import { MAIN_FILE } from "../fs/fs";
-import { ClassifiedFileInput, FileOperation } from "./changes";
-import { MainScriptChoice } from "./project-actions";
-
-interface ChooseMainScriptQuestionProps
- extends InputDialogBody {
- currentFiles: Set;
- inputs: ClassifiedFileInput[];
-}
-
-const ChooseMainScriptQuestion = ({
- currentFiles,
- inputs,
- value,
- setValue,
-}: ChooseMainScriptQuestionProps) => {
- const changes = sortBy(
- findProposedChanges(currentFiles, inputs, value.main),
- (c) => c.target !== MAIN_FILE,
- (c) => c.source
- );
- return changes.length > 1 ? (
-
- {changes.map((c) => (
-
-
-
- ))}
-
- ) : (
-
- );
-};
-
-interface ProposedChange {
- source: string;
- target: string;
- script: boolean;
- module: boolean;
- operation: FileOperation;
- data: () => Promise | Promise;
-}
-
-const findProposedChanges = (
- currentFiles: Set,
- inputs: ClassifiedFileInput[],
- main: string | undefined
-): ProposedChange[] => {
- return inputs.map((f) => {
- const target = f.name === main ? "main.py" : f.name;
- return {
- source: f.name,
- data: f.data,
- target,
- module: f.module,
- script: f.script,
- operation: currentFiles.has(target)
- ? FileOperation.REPLACE
- : FileOperation.ADD,
- };
- });
-};
-
-// Exposed for testing.
-export const summarizeChange = (
- intl: IntlShape,
- change: ProposedChange
-): string => {
- const changeType =
- change.operation === FileOperation.REPLACE ? "replace" : "add";
- const moduleNature = change.module ? "module" : "file";
- if (change.source === change.target && change.target !== MAIN_FILE) {
- return intl.formatMessage(
- { id: `choose-main-${changeType}-${moduleNature}` },
- { name: change.target }
- );
- }
- const targetType = change.target === MAIN_FILE ? "main-code" : `file`;
- const id = `choose-main-source-${changeType}-${targetType}`;
- return intl.formatMessage(
- { id },
- {
- source: change.source,
- target: change.target,
- }
- );
-};
-
-interface FileChangeRowProps {
- change: ProposedChange;
- setValue: (value: MainScriptChoice) => void;
- currentFiles: Set;
-}
-
-const FileChangeRow = ({
- change,
- setValue,
- currentFiles,
-}: FileChangeRowProps) => {
- const isMainScript = change.target === MAIN_FILE;
- const intl = useIntl();
- return (
-
-
- {summarizeChange(intl, change)}
-
- {change.script && change.source !== MAIN_FILE && (
-
-
- setValue({ main: value === "main" ? change.source : undefined })
- }
- >
-
- {summarizeChange(intl, {
- ...change,
- target: MAIN_FILE,
- operation: currentFiles.has(MAIN_FILE)
- ? FileOperation.REPLACE
- : FileOperation.ADD,
- })}
-
-
- {summarizeChange(intl, {
- ...change,
- target: change.source,
- operation: currentFiles.has(change.source)
- ? FileOperation.REPLACE
- : FileOperation.ADD,
- })}
-
-
-
- )}
-
- );
-};
-
-const OptionsMenu = ({ children }: { children: ReactNode }) => {
- const intl = useIntl();
- return (
-
-
-
-
- {children}
-
- );
-};
-
-export default ChooseMainScriptQuestion;
diff --git a/src/project/OpenButton.tsx b/src/project/OpenButton.tsx
deleted file mode 100644
index 1287dd93b..000000000
--- a/src/project/OpenButton.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { RiFolderOpenLine } from "react-icons/ri";
-import { useIntl } from "react-intl";
-import { CollapsibleButtonComposableProps } from "../common/CollapsibleButton";
-import FileInputButton from "../common/FileInputButton";
-import { useProjectActions } from "./project-hooks";
-
-interface OpenButtonProps extends CollapsibleButtonComposableProps {}
-
-/**
- * Open HEX button, with an associated input field.
- */
-const OpenButton = (props: OpenButtonProps) => {
- const actions = useProjectActions();
- const intl = useIntl();
- return (
- }
- tooltip={intl.formatMessage({
- id: "open-hover",
- })}
- />
- );
-};
-
-export default OpenButton;
diff --git a/src/project/OpenProjectDeletedRedirect.tsx b/src/project/OpenProjectDeletedRedirect.tsx
new file mode 100644
index 000000000..39539f3d3
--- /dev/null
+++ b/src/project/OpenProjectDeletedRedirect.tsx
@@ -0,0 +1,39 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { useEffect } from "react";
+import { useIntl } from "react-intl";
+import { useNavigate } from "react-router";
+import useActionFeedback from "../common/use-action-feedback";
+import { createHomePageUrl } from "../urls";
+import { useProjects } from "./projects-hooks";
+
+/**
+ * Takes the editor to the home page, saying why, when the project it has
+ * open is deleted in another tab. Staying would show a project that can no
+ * longer be saved.
+ */
+const OpenProjectDeletedRedirect = () => {
+ const projects = useProjects();
+ const navigate = useNavigate();
+ const actionFeedback = useActionFeedback();
+ const intl = useIntl();
+ useEffect(() => {
+ const listener = () => {
+ actionFeedback.warning({
+ title: intl.formatMessage({ id: "project-deleted-elsewhere-title" }),
+ description: intl.formatMessage({
+ id: "project-deleted-elsewhere-description",
+ }),
+ });
+ void navigate(createHomePageUrl());
+ };
+ projects.addEventListener("openprojectdeleted", listener);
+ return () => projects.removeEventListener("openprojectdeleted", listener);
+ }, [actionFeedback, intl, navigate, projects]);
+ return null;
+};
+
+export default OpenProjectDeletedRedirect;
diff --git a/src/project/ProjectActionBar.tsx b/src/project/ProjectActionBar.tsx
index 66efc8e56..81939a97d 100644
--- a/src/project/ProjectActionBar.tsx
+++ b/src/project/ProjectActionBar.tsx
@@ -6,10 +6,9 @@
import { useMediaQuery } from "@microbit/ui";
import SendButton from "./SendButton";
import SaveMenuButton from "./SaveMenuButton";
-import OpenButton from "./OpenButton";
import { widthXl } from "../common/media-queries";
import React from "react";
-import { HStack, styled } from "styled-system/jsx";
+import { styled } from "styled-system/jsx";
import { SystemStyleObject } from "styled-system/types";
interface ProjectActionBarProps {
@@ -38,11 +37,7 @@ const ProjectActionBar = ({
css={cssProp}
>
-
-
- {/* Min-width to avoid collapsing when out of space. Needs some work on responsiveness of the action bar. */}
-
-
+
);
};
diff --git a/src/project/ProjectArea.tsx b/src/project/ProjectArea.tsx
index 7e0ac3b37..828e3ff6e 100644
--- a/src/project/ProjectArea.tsx
+++ b/src/project/ProjectArea.tsx
@@ -3,14 +3,14 @@
*
* SPDX-License-Identifier: MIT
*/
-import { List, ListItem, Text } from "@microbit/ui";
-import { FormattedMessage } from "react-intl";
+import { Divider, List, ListItem } from "@microbit/ui";
+import { useIntl } from "react-intl";
import { Box, VStack } from "styled-system/jsx";
+import AreaHeading from "../common/AreaHeading";
import FileRow from "./FileRow";
import { useProject } from "./project-hooks";
import { isEditableFile } from "./project-utils";
import ProjectAreaNav from "./ProjectAreaNav";
-import ProjectNameEditable from "./ProjectNameEditable";
interface ProjectAreaProps {
selectedFile: string | undefined;
@@ -25,22 +25,15 @@ const ProjectArea = ({
onSelectedFileChanged,
}: ProjectAreaProps) => {
const { files } = useProject();
+ const intl = useIntl();
return (
-
-
-
-
-
-
+
+
+
diff --git a/src/project/ProjectAreaNav.tsx b/src/project/ProjectAreaNav.tsx
index 5a50a3f9e..1e963c4fe 100644
--- a/src/project/ProjectAreaNav.tsx
+++ b/src/project/ProjectAreaNav.tsx
@@ -3,11 +3,10 @@
*
* SPDX-License-Identifier: MIT
*/
-import { Box, Flex, VStack } from "styled-system/jsx";
+import { Flex, VStack } from "styled-system/jsx";
import { SystemStyleObject } from "styled-system/types";
+import AddFilesButton from "./AddFilesButton";
import NewButton from "./NewButton";
-import OpenButton from "./OpenButton";
-import ResetButton from "./ResetButton";
interface ProjectAreaNavProps {
css?: SystemStyleObject;
@@ -18,15 +17,7 @@ const ProjectAreaNav = ({ css: cssProp }: ProjectAreaNavProps) => {
-
-
-
-
+
);
diff --git a/src/project/ProjectDropTarget.tsx b/src/project/ProjectDropTarget.tsx
index 60a7f797c..13b64d2e1 100644
--- a/src/project/ProjectDropTarget.tsx
+++ b/src/project/ProjectDropTarget.tsx
@@ -15,12 +15,16 @@ const ProjectDropTarget = ({ children }: ProjectDropTargetProps) => {
const actions = useProjectActions();
const handleDrop = useCallback(
(files: File[]) => {
- actions.load(files, "drop-load");
+ actions.load(files, "drop");
},
[actions]
);
return (
-
+
{children}
);
diff --git a/src/project/ProjectNameEditable.tsx b/src/project/ProjectNameEditable.tsx
deleted file mode 100644
index 24daf33e5..000000000
--- a/src/project/ProjectNameEditable.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { IconButton, Text, Tooltip } from "@microbit/ui";
-import { ComponentProps, useCallback } from "react";
-import { RiEdit2Line } from "react-icons/ri";
-import { useIntl } from "react-intl";
-import { HStack } from "styled-system/jsx";
-import { useProject, useProjectActions } from "./project-hooks";
-
-type HStackProps = ComponentProps;
-
-interface ProjectNameEditableProps extends ComponentProps {
- button?: "before" | "after";
- clickToEdit?: boolean;
- justifyContent?: HStackProps["justifyContent"];
- alignItems?: HStackProps["alignItems"];
-}
-
-/**
- * A control to enable editing of the project name.
- */
-const ProjectNameEditable = ({
- button = "before",
- justifyContent,
- alignItems = "center",
- clickToEdit = false,
- ...props
-}: ProjectNameEditableProps) => {
- const project = useProject();
- const actions = useProjectActions();
- const intl = useIntl();
- const handleClick = useCallback(() => {
- actions.editProjectName();
- }, [actions]);
- const editButton = (
-
-
-
-
-
- );
- const text = (
-
- {project.name}
-
- );
- return (
-
- {button === "before" ? [editButton, text] : [text, editButton]}
-
- );
-};
-
-export default ProjectNameEditable;
diff --git a/src/project/ResetButton.tsx b/src/project/ResetButton.tsx
deleted file mode 100644
index 0e6224638..000000000
--- a/src/project/ResetButton.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * (c) 2021, Micro:bit Educational Foundation and contributors
- *
- * SPDX-License-Identifier: MIT
- */
-import { Tooltip } from "@microbit/ui";
-import { RiRestartLine } from "react-icons/ri";
-import { useIntl } from "react-intl";
-import CollapsibleButton, {
- CollapsibleButtonComposableProps,
-} from "../common/CollapsibleButton";
-import { useProjectActions } from "./project-hooks";
-
-interface ResetButtonProps extends CollapsibleButtonComposableProps {}
-
-/**
- * Resets the project to the default.
- */
-const ResetButton = (props: ResetButtonProps) => {
- const actions = useProjectActions();
- const intl = useIntl();
- return (
-
- }
- />
-
- );
-};
-
-export default ResetButton;
diff --git a/src/project/project-actions.tsx b/src/project/project-actions.tsx
index b596d4831..fda011993 100644
--- a/src/project/project-actions.tsx
+++ b/src/project/project-actions.tsx
@@ -3,14 +3,13 @@
*
* SPDX-License-Identifier: MIT
*/
-import { Link, List, ListItem, Text, UnorderedList } from "@microbit/ui";
-import { Box, HStack, Stack, VStack } from "styled-system/jsx";
-import { isMakeCodeForV1Hex as isMakeCodeForV1HexNoErrorHandling } from "@microbit/microbit-universal-hex";
+import { ListItem, Text, UnorderedList } from "@microbit/ui";
+import { Box, HStack, VStack } from "styled-system/jsx";
import { saveAs } from "file-saver";
import { ReactNode } from "react";
import { FormattedMessage, IntlShape } from "react-intl";
import { ConfirmDialog } from "../common/ConfirmDialog";
-import { InputDialog, InputDialogBody } from "../common/InputDialog";
+import { InputDialog } from "../common/InputDialog";
import MultipleFilesDialog, {
MultipleFilesChoice,
} from "../common/MultipleFilesDialog";
@@ -26,22 +25,10 @@ import {
} from "@microbit/microbit-connection";
import { MicrobitUSBConnection } from "@microbit/microbit-connection/usb";
import { FileSystem, MAIN_FILE, Statistics, VersionAction } from "../fs/fs";
-import {
- getLowercaseFileExtension,
- isPythonMicrobitModule,
- readFileAsText,
- readFileAsUint8Array,
-} from "../fs/fs-util";
-import {
- defaultInitialProject,
- projectFilesToBase64,
- PythonProject,
-} from "../fs/initial-project";
import { LanguageServerClient } from "../language-server/client";
import {
AnalyticsTask,
deviceFailureCode,
- importFormat,
markUserDisconnect,
transport,
} from "../logging/analytics";
@@ -60,36 +47,17 @@ import TransferHexDialog, {
} from "../workbench/connect-dialogs/TransferHexDialog";
import WebUSBDialog from "../workbench/connect-dialogs/WebUSBDialog";
import { WorkbenchSelection } from "../workbench/use-selection";
-import {
- ClassifiedFileInput,
- FileChange,
- FileInput,
- FileOperation,
-} from "./changes";
-import ChooseMainScriptQuestion from "./ChooseMainScriptQuestion";
import NewFileNameQuestion from "./NewFileNameQuestion";
import { DefaultedProject } from "./project-hooks";
-import {
- ensurePythonExtension,
- isPythonFile,
- validateNewFilename,
-} from "./project-utils";
+import { ImportSource, ProjectImporter } from "./project-import";
+import { ensurePythonExtension, validateNewFilename } from "./project-utils";
import ProjectNameQuestion from "./ProjectNameQuestion";
import WebUSBErrorDialog from "../workbench/connect-dialogs/WebUSBErrorDialog";
import reconnectWebm from "../workbench/connect-dialogs/reconnect.webm";
import reconnectMp4 from "../workbench/connect-dialogs/reconnect.mp4";
-/**
- * Distinguishes the different ways to trigger the load action.
- */
-export type LoadType = "drop-load" | "file-upload";
-
export type FinalFocusRef = React.RefObject | undefined;
-export interface MainScriptChoice {
- main: string | undefined;
-}
-
interface ProjectStatistics extends Statistics {
errorCount: number;
}
@@ -138,7 +106,8 @@ export class ProjectActions {
},
private intl: IntlShape,
private logging: Logging,
- private client: LanguageServerClient | undefined
+ private client: LanguageServerClient | undefined,
+ private importer: ProjectImporter
) {}
private get project(): DefaultedProject {
@@ -269,278 +238,48 @@ export class ProjectActions {
}
};
- private async confirmReplace(customConfirmPrompt?: string): Promise {
- if (!this.fs.dirty) {
- // No need to ask.
- return true;
- }
- return this.dialogs.show((callback) => (
-
-
- {customConfirmPrompt ??
- this.intl.formatMessage({ id: "confirm-replace-body" })}
-
-
-
-
-
- }
- actionLabel={this.intl.formatMessage({
- id: "replace-action-label",
- })}
- />
- ));
- }
-
/**
- * Loads files
- *
- * Replaces the open project if a hex file is opened.
- * No other files may be opened in the same call as a hex file.
+ * Brings files into the editor.
*
- * Uses module marker comments to determine if a Python file
- * is a script or a module. At most one script and any number
- * of modules may be opened together. The existing project is
- * updated.
+ * A hex becomes a new project. Other files are added to the open project,
+ * replacing any with the same names.
*
* @param files the files from drag and drop or an input element.
- * @param the type of user event that triggered the load.
+ * @param source how the user brought them in.
*/
- load = async (
- files: File[],
- type: LoadType = "file-upload"
- ): Promise => {
- if (files.length === 0) {
- throw new Error("Expected to be called with at least one file");
- }
- this.logging.event({
- type: "project_import",
- detail: {
- source: type === "drop-load" ? "drop" : "file_picker",
- format: importFormat(files),
- },
- });
-
- // Avoid lingering messages related to the previous project.
- // Also makes e2e testing easier.
- this.actionFeedback.closeAll();
-
- const errorTitle = this.intl.formatMessage(
- { id: "load-error-title" },
- {
- fileCount: files.length,
- }
- );
- const extensions = new Set(
- files.map((f) => getLowercaseFileExtension(f.name))
- );
- if (extensions.has("mpy")) {
- this.actionFeedback.expectedError({
- title: errorTitle,
- description: this.intl.formatMessage({ id: "load-error-mpy" }),
- });
- } else if (extensions.has("hex")) {
- if (files.length > 1) {
- this.actionFeedback.expectedError({
- title: errorTitle,
- description: this.intl.formatMessage({ id: "load-error-mixed" }),
- });
- } else {
- if (await this.confirmReplace()) {
- const file = files[0];
- const projectName = file.name.replace(/\.hex$/i, "");
- const hex = await readFileAsText(file);
- try {
- await this.fs.replaceWithHexContents(projectName, hex);
- this.actionFeedback.success({
- title: this.intl.formatMessage(
- { id: "loaded-file-feedback" },
- { filename: file.name }
- ),
- });
- } catch (e: any) {
- const isMakeCodeHex = isMakeCodeForV1Hex(hex);
- // Ideally we'd make FormattedMessage work in toasts, but it does not so using intl.
- this.actionFeedback.expectedError({
- title: errorTitle,
- description: isMakeCodeHex ? (
-
-
- {this.intl.formatMessage({
- id: "load-error-makecode-info",
- })}
-
-
- {this.intl.formatMessage(
- { id: "load-error-makecode-link" },
- {
- link: (chunks: ReactNode) => (
-
- {chunks}
-
- ),
- }
- )}
-
-
- ) : (
- e.message
- ),
- });
- }
- }
- }
- } else {
- const classifiedInputs: ClassifiedFileInput[] = [];
- const hasMainPyFile = files.some((x) => x.name === MAIN_FILE);
- for (const f of files) {
- const content = await readFileAsUint8Array(f);
- const python = isPythonFile(f.name);
- const module = python && isPythonMicrobitModule(content);
- const script = hasMainPyFile ? f.name === MAIN_FILE : python && !module;
- classifiedInputs.push({
- name: f.name,
- script,
- module,
- data: () => Promise.resolve(content),
- });
- }
-
- const inputs = await this.chooseScriptForMain(classifiedInputs);
- if (inputs) {
- return this.uploadInternal(inputs);
- }
- }
- };
+ load = (files: File[], source: ImportSource = "file_picker"): Promise =>
+ this.importer.importIntoEditor(files, source);
/**
- * Open a project, asking for confirmation if required.
- *
- * @param project The project.
- * @param confirmPrompt Optional custom confirmation prompt.
- * @returns True if we opened the project, false if the user cancelled.
+ * Opens an idea from the documentation as a new project.
*/
- private openProject = async (
- project: PythonProject,
- confirmPrompt?: string
- ): Promise => {
- const confirmed = await this.confirmReplace(confirmPrompt);
- if (confirmed) {
- await this.fs.replaceWithMultipleFiles(project);
- }
- return confirmed;
- };
-
openIdea = async (slug: string | undefined, code: string, title: string) => {
this.logging.event({
type: "idea_open",
detail: { id: slug },
});
- const pythonProject: PythonProject = {
- files: projectFilesToBase64({
- [MAIN_FILE]: code,
- }),
- projectName: title,
- };
- const confirmPrompt = this.intl.formatMessage(
- { id: "confirm-replace-with-idea" },
- { ideaName: pythonProject.projectName }
- );
- if (await this.openProject(pythonProject, confirmPrompt)) {
+ try {
+ const opened = await this.importer.newProject(
+ title,
+ { [MAIN_FILE]: new TextEncoder().encode(code) },
+ this.intl.formatMessage(
+ { id: "confirm-replace-with-idea" },
+ { ideaName: title }
+ )
+ );
+ if (!opened) {
+ return;
+ }
this.actionFeedback.success({
title: this.intl.formatMessage(
{ id: "loaded-file-feedback" },
{ filename: title }
),
});
- }
- };
-
- reset = async () => {
- this.logging.event({
- type: "project_reset",
- });
- const confirmPrompt = this.intl.formatMessage({
- id: "confirm-replace-reset",
- });
- if (await this.openProject(defaultInitialProject, confirmPrompt)) {
- this.actionFeedback.success({
- title: this.intl.formatMessage({ id: "reset-project-feedback" }),
- });
- }
- };
-
- private async uploadInternal(inputs: ClassifiedFileInput[]) {
- const changes = this.findChanges(inputs);
- try {
- for (const change of changes) {
- const data = await change.data();
- await this.fs.write(change.name, data, VersionAction.INCREMENT);
- }
- this.actionFeedback.success(this.summarizeChanges(changes));
- } catch (e: any) {
+ } catch (e) {
this.actionFeedback.unexpectedError(e);
}
- }
-
- private findChanges(files: FileInput[]): FileChange[] {
- const currentFiles = this.project.files.map((f) => f.name);
- const current = new Set(currentFiles);
- return files.map((f) => ({
- ...f,
- operation: current.has(f.name)
- ? FileOperation.REPLACE
- : FileOperation.ADD,
- }));
- }
-
- private async chooseScriptForMain(
- inputs: ClassifiedFileInput[]
- ): Promise {
- const defaultScript = inputs.find((x) => x.script);
- const chosenScript = await this.dialogs.show(
- (callback) => (
- ) => (
- f.name))}
- inputs={inputs}
- />
- )}
- actionLabel={this.intl.formatMessage({ id: "confirm-action" })}
- size="lg"
- />
- )
- );
- if (!chosenScript) {
- // User cancelled.
- return undefined;
- }
-
- return inputs.map((input) => {
- if (chosenScript && chosenScript.main === input.name) {
- return {
- ...input,
- name: "main.py",
- };
- }
- return input;
- });
- }
+ };
/**
* Flash the device, reporting progress via a dialog.
@@ -1059,48 +798,8 @@ export class ProjectActions {
errorCount: this.client?.errorCount() ?? 0,
};
}
-
- summarizeChanges = (changes: FileChange[]) => {
- if (changes.length === 1) {
- return { title: this.summarizeChange(changes[0]) };
- }
- return {
- title: `${changes.length} changes`,
- description: (
-
- {changes.map((c) => (
- {this.summarizeChange(c)}
- ))}
-
- ),
- };
- };
-
- idForChangeType = (changeType: FileOperation): string => {
- return changeType === FileOperation.REPLACE
- ? "updated-change"
- : "added-change";
- };
-
- summarizeChange = (change: FileChange): string => {
- const translationID = this.idForChangeType(change.operation);
- return this.intl.formatMessage(
- { id: translationID },
- { changeName: change.name }
- );
- };
}
-const isMakeCodeForV1Hex = (hexStr: string) => {
- try {
- return isMakeCodeForV1HexNoErrorHandling(hexStr);
- } catch {
- // We just use this to give a better message in error scenarios so we don't
- // care if we failed to parse it etc.
- return false;
- }
-};
-
export const defaultedProject = (
fs: FileSystem,
intl: IntlShape
diff --git a/src/project/project-hooks.tsx b/src/project/project-hooks.tsx
index a528cf352..4520fbfc6 100644
--- a/src/project/project-hooks.tsx
+++ b/src/project/project-hooks.tsx
@@ -22,6 +22,26 @@ import { useSessionSettings } from "../settings/session-settings";
import { useSettings } from "../settings/settings";
import { useSelection } from "../workbench/use-selection";
import { defaultedProject, ProjectActions } from "./project-actions";
+import { ProjectImporter } from "./project-import";
+import { useProjectsIfAvailable } from "./projects-hooks";
+
+/**
+ * Imports files as new projects or into the open one. Usable from the pages
+ * as well as the editor.
+ */
+export const useProjectImporter = (): ProjectImporter => {
+ const fs = useFileSystem();
+ const projects = useProjectsIfAvailable();
+ const actionFeedback = useActionFeedback();
+ const dialogs = useDialogs();
+ const intl = useIntl();
+ const logging = useLogging();
+ return useMemo(
+ () =>
+ new ProjectImporter(fs, projects, actionFeedback, dialogs, intl, logging),
+ [fs, projects, actionFeedback, dialogs, intl, logging]
+ );
+};
/**
* Hook exposing the main UI actions.
@@ -37,6 +57,7 @@ export const useProjectActions = (): ProjectActions => {
const client = useLanguageServerClient();
const [settings, setSettings] = useSettings();
const [sessionSettings, setSessionSettings] = useSessionSettings();
+ const importer = useProjectImporter();
const actions = useMemo(
() =>
new ProjectActions(
@@ -49,7 +70,8 @@ export const useProjectActions = (): ProjectActions => {
{ values: sessionSettings, setValues: setSessionSettings },
intl,
logging,
- client
+ client,
+ importer
),
[
fs,
@@ -64,6 +86,7 @@ export const useProjectActions = (): ProjectActions => {
setSettings,
sessionSettings,
setSessionSettings,
+ importer,
]
);
return actions;
diff --git a/src/project/project-import.test.ts b/src/project/project-import.test.ts
new file mode 100644
index 000000000..930e2b501
--- /dev/null
+++ b/src/project/project-import.test.ts
@@ -0,0 +1,56 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { MAIN_FILE } from "../fs/fs";
+import { filesForNewProject } from "./project-import";
+
+const text = (s: string) => new TextEncoder().encode(s);
+const decode = (b: Uint8Array) => new TextDecoder().decode(b);
+
+describe("filesForNewProject", () => {
+ it("makes a single script main.py and names the project after it", () => {
+ const { name, files } = filesForNewProject([
+ { name: "dice.py", data: text("print('dice')") },
+ ]);
+ expect(name).toEqual("dice");
+ expect(Object.keys(files)).toEqual([MAIN_FILE]);
+ expect(decode(files[MAIN_FILE])).toEqual("print('dice')");
+ });
+
+ it("keeps a module under its own name and adds the starter main.py", () => {
+ const { name, files } = filesForNewProject([
+ { name: "module.py", data: text("# microbit-module: a@1.0.0\n") },
+ ]);
+ expect(name).toBeUndefined();
+ expect(Object.keys(files).sort()).toEqual([MAIN_FILE, "module.py"]);
+ expect(decode(files[MAIN_FILE])).toMatch(/from microbit import/);
+ });
+
+ it("keeps main.py when given one, with the other files alongside", () => {
+ const { name, files } = filesForNewProject([
+ { name: "helper.py", data: text("x = 1") },
+ { name: MAIN_FILE, data: text("import helper") },
+ ]);
+ expect(name).toBeUndefined();
+ expect(Object.keys(files).sort()).toEqual(["helper.py", MAIN_FILE]);
+ expect(decode(files[MAIN_FILE])).toEqual("import helper");
+ });
+
+ it("does not guess between several scripts", () => {
+ const { name, files } = filesForNewProject([
+ { name: "a.py", data: text("a") },
+ { name: "b.py", data: text("b") },
+ ]);
+ expect(name).toBeUndefined();
+ expect(Object.keys(files).sort()).toEqual(["a.py", "b.py", MAIN_FILE]);
+ });
+
+ it("adds the starter main.py to a lone data file", () => {
+ const { files } = filesForNewProject([
+ { name: "data.txt", data: text("1,2,3") },
+ ]);
+ expect(Object.keys(files).sort()).toEqual(["data.txt", MAIN_FILE]);
+ });
+});
diff --git a/src/project/project-import.tsx b/src/project/project-import.tsx
new file mode 100644
index 000000000..96dfc7c9f
--- /dev/null
+++ b/src/project/project-import.tsx
@@ -0,0 +1,417 @@
+/**
+ * Bringing files into the editor.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { isMakeCodeForV1Hex as isMakeCodeForV1HexNoErrorHandling } from "@microbit/microbit-universal-hex";
+import { Link, List, ListItem, Text } from "@microbit/ui";
+import { ReactNode } from "react";
+import { IntlShape } from "react-intl";
+import { Stack } from "styled-system/jsx";
+import { ConfirmDialog } from "../common/ConfirmDialog";
+import { ActionFeedback } from "../common/use-action-feedback";
+import { Dialogs } from "../common/use-dialogs";
+import { defaultProjectFiles } from "../fs/current-project";
+import { FileSystem, MAIN_FILE, VersionAction } from "../fs/fs";
+import {
+ getLowercaseFileExtension,
+ isPythonMicrobitModule,
+ readFileAsText,
+ readFileAsUint8Array,
+} from "../fs/fs-util";
+import { importFormat } from "../logging/analytics";
+import { Logging } from "../logging/logging";
+import { FileChange, FileOperation } from "./changes";
+import { isPythonFile } from "./project-utils";
+import { Projects } from "./projects";
+
+export type ImportSource = "drop" | "file_picker";
+export type ImportSurface = "editor" | "home" | "projects";
+
+export interface ImportedFile {
+ name: string;
+ data: Uint8Array;
+}
+
+export interface NewProjectFiles {
+ /** A name taken from the file, or undefined for the untitled default. */
+ name: string | undefined;
+ files: Record;
+}
+
+type ImportKind =
+ | { kind: "hex"; file: File }
+ | { kind: "files" }
+ | { kind: "error"; messageId: "load-error-mpy" | "load-error-mixed" };
+
+const classify = (files: File[]): ImportKind => {
+ const extensions = new Set(
+ files.map((f) => getLowercaseFileExtension(f.name))
+ );
+ if (extensions.has("mpy")) {
+ return { kind: "error", messageId: "load-error-mpy" };
+ }
+ if (extensions.has("hex")) {
+ return files.length > 1
+ ? { kind: "error", messageId: "load-error-mixed" }
+ : { kind: "hex", file: files[0] };
+ }
+ return { kind: "files" };
+};
+
+/**
+ * Arranges files into a new project.
+ *
+ * A single Python script (not a marked module) becomes main.py and names the
+ * project, which is what opening a saved program wants. Otherwise files keep
+ * their names and the starter main.py is added if there is none.
+ */
+export const filesForNewProject = (inputs: ImportedFile[]): NewProjectFiles => {
+ const files: Record = Object.fromEntries(
+ inputs.map((f) => [f.name, f.data])
+ );
+ let name: string | undefined;
+ if (!(MAIN_FILE in files)) {
+ const scripts = inputs.filter(
+ (f) =>
+ isPythonFile(f.name) &&
+ !isPythonMicrobitModule(new TextDecoder().decode(f.data))
+ );
+ if (scripts.length === 1) {
+ const [script] = scripts;
+ delete files[script.name];
+ files[MAIN_FILE] = script.data;
+ name = script.name.replace(/\.py$/i, "");
+ } else {
+ Object.assign(files, defaultProjectFiles());
+ }
+ }
+ return { name, files };
+};
+
+/**
+ * Imports files from the editor or the home page.
+ *
+ * A hex is always a whole program, so it becomes a new project; with the
+ * projects database unavailable it replaces the single implicit project
+ * instead. Other files join the open project when imported from the editor,
+ * and make a new project from the home page.
+ */
+export class ProjectImporter {
+ constructor(
+ private fs: FileSystem,
+ private projects: Projects | undefined,
+ private actionFeedback: ActionFeedback,
+ private dialogs: Dialogs,
+ private intl: IntlShape,
+ private logging: Logging
+ ) {}
+
+ /**
+ * A hex becomes a new project; other files are added to the open project,
+ * replacing any with the same names.
+ */
+ importIntoEditor = async (
+ files: File[],
+ source: ImportSource
+ ): Promise => {
+ const kind = this.begin(files, source, "editor");
+ switch (kind.kind) {
+ case "error":
+ return this.loadError(files, kind.messageId);
+ case "hex":
+ await this.newProjectFromHex(kind.file);
+ return;
+ case "files":
+ return this.addToProject(await this.readAll(files));
+ }
+ };
+
+ /**
+ * The files become a new project, open in the editor.
+ *
+ * @returns True if a project was created.
+ */
+ importAsNewProject = async (
+ files: File[],
+ source: ImportSource,
+ surface: Exclude
+ ): Promise => {
+ const kind = this.begin(files, source, surface);
+ switch (kind.kind) {
+ case "error":
+ this.loadError(files, kind.messageId);
+ return false;
+ case "hex":
+ return this.newProjectFromHex(kind.file);
+ case "files": {
+ const inputs = await this.readAll(files);
+ const project = filesForNewProject(inputs);
+ try {
+ if (!(await this.newProject(project.name, project.files))) {
+ return false;
+ }
+ } catch (e) {
+ this.actionFeedback.unexpectedError(e);
+ return false;
+ }
+ this.actionFeedback.success(
+ inputs.length === 1
+ ? this.loadedFeedback(inputs[0].name)
+ : this.summarizeChanges(
+ inputs.map((f) => ({
+ name: f.name,
+ data: () => Promise.resolve(f.data),
+ operation: FileOperation.ADD,
+ }))
+ )
+ );
+ return true;
+ }
+ }
+ };
+
+ /**
+ * Opens a new project with these files, or replaces the implicit project
+ * where there is no projects database, asking first if it has unsaved
+ * edits.
+ *
+ * @param confirmPrompt What replacing means, for the confirmation.
+ * @returns False if the user kept their project.
+ */
+ newProject = async (
+ name: string | undefined,
+ files: Record,
+ confirmPrompt?: string
+ ): Promise => {
+ if (this.projects && (await this.projects.isAvailable())) {
+ await this.projects.createFromFiles(name, files);
+ return true;
+ }
+ if (!(await this.confirmReplace(confirmPrompt))) {
+ return false;
+ }
+ await this.fs.replaceWithFiles(name, files);
+ return true;
+ };
+
+ /**
+ * Without the projects database a replaced project is gone, so ask when
+ * there are edits since the last save. Nothing to ask about otherwise.
+ */
+ private async confirmReplace(customPrompt?: string): Promise {
+ if (!this.fs.dirty) {
+ return true;
+ }
+ return this.dialogs.show((callback) => (
+
+
+ {customPrompt ??
+ this.intl.formatMessage({ id: "confirm-replace-body" })}
+
+ {this.intl.formatMessage({ id: "confirm-save-hint" })}
+
+ }
+ actionLabel={this.intl.formatMessage({ id: "replace-action-label" })}
+ />
+ ));
+ }
+
+ /** Files that would overwrite existing ones need a yes first. */
+ private async confirmReplaceFiles(names: string[]): Promise {
+ if (names.length === 0) {
+ return true;
+ }
+ return this.dialogs.show((callback) => (
+
+ ));
+ }
+
+ private begin(
+ files: File[],
+ source: ImportSource,
+ surface: ImportSurface
+ ): ImportKind {
+ if (files.length === 0) {
+ throw new Error("Expected to be called with at least one file");
+ }
+ this.logging.event({
+ type: "project_import",
+ detail: { source, format: importFormat(files), surface },
+ });
+ // Avoid lingering messages related to the previous project.
+ // Also makes e2e testing easier.
+ this.actionFeedback.closeAll();
+ return classify(files);
+ }
+
+ private async newProjectFromHex(file: File): Promise {
+ const name = file.name.replace(/\.hex$/i, "");
+ const hex = await readFileAsText(file);
+ let files: Record;
+ try {
+ files = await this.fs.filesFromHex(hex);
+ } catch (e: any) {
+ this.hexError(file, hex, e);
+ return false;
+ }
+ try {
+ if (!(await this.newProject(name, files))) {
+ return false;
+ }
+ } catch (e) {
+ this.actionFeedback.unexpectedError(e);
+ return false;
+ }
+ this.actionFeedback.success(this.loadedFeedback(file.name));
+ return true;
+ }
+
+ private async addToProject(inputs: ImportedFile[]): Promise {
+ const current = new Set(this.fs.project.files.map((f) => f.name));
+ const changes: FileChange[] = inputs.map((f) => ({
+ name: f.name,
+ data: () => Promise.resolve(f.data),
+ operation: current.has(f.name)
+ ? FileOperation.REPLACE
+ : FileOperation.ADD,
+ }));
+ const replaced = changes
+ .filter((c) => c.operation === FileOperation.REPLACE)
+ .map((c) => c.name);
+ if (!(await this.confirmReplaceFiles(replaced))) {
+ return;
+ }
+ try {
+ for (const change of changes) {
+ await this.fs.write(
+ change.name,
+ await change.data(),
+ VersionAction.INCREMENT
+ );
+ }
+ this.actionFeedback.success(this.summarizeChanges(changes));
+ } catch (e: any) {
+ this.actionFeedback.unexpectedError(e);
+ }
+ }
+
+ private async readAll(files: File[]): Promise {
+ return Promise.all(
+ files.map(async (f) => ({
+ name: f.name,
+ data: await readFileAsUint8Array(f),
+ }))
+ );
+ }
+
+ private loadErrorTitle(files: File[]): string {
+ return this.intl.formatMessage(
+ { id: "load-error-title" },
+ { fileCount: files.length }
+ );
+ }
+
+ private loadError(files: File[], messageId: string): void {
+ this.actionFeedback.expectedError({
+ title: this.loadErrorTitle(files),
+ description: this.intl.formatMessage({ id: messageId }),
+ });
+ }
+
+ private hexError(file: File, hex: string, e: any): void {
+ const isMakeCodeHex = isMakeCodeForV1Hex(hex);
+ // Ideally we'd make FormattedMessage work in toasts, but it does not so using intl.
+ this.actionFeedback.expectedError({
+ title: this.loadErrorTitle([file]),
+ description: isMakeCodeHex ? (
+
+
+ {this.intl.formatMessage({
+ id: "load-error-makecode-info",
+ })}
+
+
+ {this.intl.formatMessage(
+ { id: "load-error-makecode-link" },
+ {
+ link: (chunks: ReactNode) => (
+
+ {chunks}
+
+ ),
+ }
+ )}
+
+
+ ) : (
+ e.message
+ ),
+ });
+ }
+
+ private loadedFeedback(filename: string) {
+ return {
+ title: this.intl.formatMessage(
+ { id: "loaded-file-feedback" },
+ { filename }
+ ),
+ };
+ }
+
+ private summarizeChanges(changes: FileChange[]) {
+ if (changes.length === 1) {
+ return { title: this.summarizeChange(changes[0]) };
+ }
+ return {
+ title: `${changes.length} changes`,
+ description: (
+
+ {changes.map((c) => (
+ {this.summarizeChange(c)}
+ ))}
+
+ ),
+ };
+ }
+
+ private summarizeChange(change: FileChange): string {
+ return this.intl.formatMessage(
+ {
+ id:
+ change.operation === FileOperation.REPLACE
+ ? "updated-change"
+ : "added-change",
+ },
+ { changeName: change.name }
+ );
+ }
+}
+
+const isMakeCodeForV1Hex = (hexStr: string) => {
+ try {
+ return isMakeCodeForV1HexNoErrorHandling(hexStr);
+ } catch {
+ // We just use this to give a better message in error scenarios so we don't
+ // care if we failed to parse it etc.
+ return false;
+ }
+};
diff --git a/src/project/projects-hooks.tsx b/src/project/projects-hooks.tsx
new file mode 100644
index 000000000..f27c7dcaf
--- /dev/null
+++ b/src/project/projects-hooks.tsx
@@ -0,0 +1,46 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { createContext, use, useCallback, useSyncExternalStore } from "react";
+import { ProjectListEntry } from "../fs/projects-db";
+import { Projects } from "./projects";
+
+const ProjectsContext = createContext(undefined);
+
+export const ProjectsProvider = ProjectsContext.Provider;
+
+/**
+ * The projects in this browser. Throws in iframe controller mode, where the
+ * embedding page owns the project; use useProjectsIfAvailable there.
+ */
+export const useProjects = (): Projects => {
+ const projects = use(ProjectsContext);
+ if (!projects) {
+ throw new Error("Missing ProjectsProvider");
+ }
+ return projects;
+};
+
+/**
+ * The projects in this browser, or undefined in iframe controller mode.
+ */
+export const useProjectsIfAvailable = (): Projects | undefined =>
+ use(ProjectsContext);
+
+/**
+ * The project list, kept up to date as projects change in this tab or
+ * another. The route loader refreshes it before the page renders.
+ */
+export const useProjectList = (): ProjectListEntry[] => {
+ const projects = useProjects();
+ const subscribe = useCallback(
+ (listener: () => void) => {
+ projects.addEventListener("change", listener);
+ return () => projects.removeEventListener("change", listener);
+ },
+ [projects]
+ );
+ return useSyncExternalStore(subscribe, () => projects.projects);
+};
diff --git a/src/project/projects-session-migration.test.ts b/src/project/projects-session-migration.test.ts
new file mode 100644
index 000000000..778547c40
--- /dev/null
+++ b/src/project/projects-session-migration.test.ts
@@ -0,0 +1,69 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import "fake-indexeddb/auto";
+import { vi } from "vitest";
+import { deferred } from "../common/deferred";
+import { getCurrentProjectId } from "../fs/current-project";
+import { FileSystem } from "../fs/fs";
+import { DefaultHost } from "../fs/host";
+import { ProjectsDatabase } from "../fs/projects-db";
+import { FSStorage, SessionStorageFSStorage } from "../fs/storage";
+import { MockLogging } from "../logging/mock";
+import { Projects } from "./projects";
+
+// Separate from projects.test.ts, which runs without a window and so
+// without the session storage this is about.
+describe("Projects with a project left in session storage", () => {
+ let counter = 0;
+ let db: ProjectsDatabase;
+ let logging: MockLogging;
+ let legacy: SessionStorageFSStorage;
+
+ beforeEach(async () => {
+ sessionStorage.clear();
+ db = await ProjectsDatabase.open(`session-${Date.now()}-${counter++}`);
+ logging = new MockLogging();
+ legacy = new SessionStorageFSStorage(sessionStorage);
+ await legacy.write("main.py", new TextEncoder().encode("# mine"));
+ await legacy.setProjectName("My project");
+ });
+ afterEach(() => {
+ db.close();
+ });
+
+ const start = () => {
+ const storage = deferred();
+ const fs = new FileSystem(
+ logging,
+ new DefaultHost(undefined, storage.promise),
+ () => Promise.reject(new Error("MicroPython is not needed here"))
+ );
+ return new Projects(fs, logging, Promise.resolve(db), storage);
+ };
+
+ it("has it in the list, as the tab's project, before a page can ask", async () => {
+ const projects = start();
+
+ const list = await projects.refresh();
+
+ expect(list.map((p) => p.name)).toEqual(["My project"]);
+ expect(list[0].fileNames).toEqual(["main.py"]);
+ expect(getCurrentProjectId(sessionStorage)).toEqual(list[0].id);
+ expect(await legacy.ls()).toEqual([]);
+ });
+
+ it("still starts if it cannot be moved, and keeps the session copy", async () => {
+ vi.spyOn(db, "create").mockRejectedValueOnce(new Error("Simulated"));
+ const projects = start();
+
+ expect(await projects.isAvailable()).toEqual(true);
+ expect(await projects.refresh()).toEqual([]);
+ expect(await legacy.ls()).toEqual(["main.py"]);
+ expect(logging.errors.map((e) => e.message)).toEqual([
+ "Failed to migrate the session storage project",
+ ]);
+ });
+});
diff --git a/src/project/projects.test.ts b/src/project/projects.test.ts
new file mode 100644
index 000000000..f0d0a6487
--- /dev/null
+++ b/src/project/projects.test.ts
@@ -0,0 +1,668 @@
+/**
+ * @vitest-environment node
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import "fake-indexeddb/auto";
+import * as nodeFs from "fs";
+import { vi } from "vitest";
+import { deferred } from "../common/deferred";
+import { ConsoleLogging } from "../deployment/default/logging";
+import { FileSystem, MAIN_FILE, VersionAction } from "../fs/fs";
+import { DefaultHost } from "../fs/host";
+import { PendingProjectLink } from "../fs/project-link";
+import { testProjectLink } from "../fs/project-link-test-data";
+import { ProjectsDatabase } from "../fs/projects-db";
+import { FSStorage } from "../fs/storage";
+import { MicroPythonSource } from "../micropython/micropython";
+import { Projects, ProjectSaveErrorEvent } from "./projects";
+
+const hexes = [
+ nodeFs.readFileSync("src/micropython/microbit-micropython-v1.hex", {
+ encoding: "ascii",
+ }),
+ nodeFs.readFileSync("src/micropython/main/microbit-micropython-v2.hex", {
+ encoding: "ascii",
+ }),
+];
+const microPythonSource: MicroPythonSource = async () => [
+ { boardId: 0x9900, hex: hexes[0] },
+ { boardId: 0x9903, hex: hexes[1] },
+];
+
+let counter = 0;
+const logging = new ConsoleLogging();
+
+// Recency ordering is by timestamp; make each one distinct so the tests do
+// not depend on how much happens within a millisecond.
+beforeEach(() => {
+ let now = 1_000_000;
+ vi.spyOn(Date, "now").mockImplementation(() => now++);
+});
+
+/** A tab: its own file system and projects session over a database. */
+const openTab = (db: ProjectsDatabase | undefined) => {
+ const storage = deferred();
+ const host = new DefaultHost(undefined, storage.promise);
+ const fs = new FileSystem(logging, host, microPythonSource);
+ const projects = new Projects(fs, logging, Promise.resolve(db), storage);
+ return { db, fs, projects };
+};
+
+const setup = async (dbAvailable = true) =>
+ openTab(
+ dbAvailable
+ ? await ProjectsDatabase.open(`projects-${Date.now()}-${counter++}`)
+ : undefined
+ );
+
+const decode = (data: Uint8Array) => new TextDecoder().decode(data);
+
+const fileNames = (fs: FileSystem) => fs.project.files.map((f) => f.name);
+
+describe("Projects", () => {
+ it("openCurrent creates a project and gives the file system its storage", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+
+ expect(projects.currentId).toBeDefined();
+ expect(fileNames(fs)).toEqual([MAIN_FILE]);
+ expect((await projects.refresh()).map((p) => p.id)).toEqual([
+ projects.currentId,
+ ]);
+ // Written through to the database, not just the in-memory copy.
+ await fs.write(MAIN_FILE, "# edited", VersionAction.MAINTAIN);
+ await projects.rename(projects.currentId!, "Named");
+ expect(
+ new TextDecoder().decode(await db!.file(projects.currentId!, MAIN_FILE))
+ ).toEqual("# edited");
+ });
+
+ it("reports whether main.py is still the starter program", async () => {
+ const { fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ expect((await fs.statistics()).defaultMain).toEqual(true);
+
+ await fs.write(MAIN_FILE, "# edited", VersionAction.MAINTAIN);
+ expect((await fs.statistics()).defaultMain).toEqual(false);
+ });
+
+ it("has a pending #project: link until the editor opens it", async () => {
+ const storage = deferred();
+ const link = new PendingProjectLink(testProjectLink);
+ const fs = new FileSystem(
+ logging,
+ new DefaultHost(link, storage.promise),
+ microPythonSource
+ );
+ const db = await ProjectsDatabase.open(`projects-${counter++}`);
+ const projects = new Projects(
+ fs,
+ logging,
+ Promise.resolve(db),
+ storage,
+ link
+ );
+ expect(projects.hasPendingProjectLink).toEqual(true);
+
+ expect(await projects.openCurrent()).toEqual(true);
+
+ expect(projects.hasPendingProjectLink).toEqual(false);
+ expect((await db.get(projects.currentId!))?.name).toEqual("Hearts");
+ });
+
+ it("concurrent openCurrent calls choose one project", async () => {
+ const { projects } = await setup();
+ await Promise.all([projects.openCurrent(), projects.openCurrent()]);
+ expect((await projects.refresh()).map((p) => p.id)).toEqual([
+ projects.currentId,
+ ]);
+ });
+
+ it("openCurrent keeps the open project", async () => {
+ const { projects } = await setup();
+ await projects.openCurrent();
+ const first = projects.currentId;
+ await projects.openCurrent();
+ expect(projects.currentId).toEqual(first);
+ });
+
+ it("create switches the editor to the new project, and open switches back", async () => {
+ const { fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ const first = projects.currentId!;
+ await fs.write("helper.py", "# helper", VersionAction.INCREMENT);
+
+ const second = await projects.create("Second");
+
+ expect(projects.currentId).toEqual(second);
+ expect(fs.project.name).toEqual("Second");
+ expect(fileNames(fs)).toEqual([MAIN_FILE]);
+ // Left for the pages to refresh, so the new card can't show early.
+ expect(projects.projects.map((p) => p.id)).not.toContain(second);
+ expect((await projects.refresh()).map((p) => p.id)).toEqual([
+ second,
+ first,
+ ]);
+
+ await projects.open(first);
+ expect(fs.project.name).toBeUndefined();
+ expect(fileNames(fs)).toEqual([MAIN_FILE, "helper.py"]);
+ });
+
+ it("renames the open project through the file system and others directly", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ const open = projects.currentId!;
+ await db!.create({ id: "other", name: "Other", timestamp: 1 }, {});
+
+ await projects.rename(open, "Renamed open");
+ await projects.rename("other", "Renamed other");
+
+ expect(fs.project.name).toEqual("Renamed open");
+ expect((await db!.get(open))?.name).toEqual("Renamed open");
+ expect((await db!.get("other"))?.name).toEqual("Renamed other");
+ expect(projects.projects.map((p) => p.name).sort()).toEqual([
+ "Renamed open",
+ "Renamed other",
+ ]);
+ });
+
+ it("duplicates the open project including unsaved edits", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ await fs.write(MAIN_FILE, "# latest", VersionAction.MAINTAIN);
+
+ const copy = await projects.duplicate(projects.currentId!, "Copy");
+
+ expect((await db!.get(copy))?.name).toEqual("Copy");
+ expect(new TextDecoder().decode(await db!.file(copy, MAIN_FILE))).toEqual(
+ "# latest"
+ );
+ expect(projects.currentId).not.toEqual(copy);
+ });
+
+ it("deleting the open project makes openCurrent choose another", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ const deleted = projects.currentId!;
+ await db!.create({ id: "other", name: "Other", timestamp: 1 }, {});
+
+ await projects.delete([deleted]);
+ expect(projects.currentId).toBeUndefined();
+ expect(projects.projects.map((p) => p.id)).toEqual(["other"]);
+
+ await projects.openCurrent();
+ expect(projects.currentId).toEqual("other");
+ expect(fs.project.name).toEqual("Other");
+ });
+
+ it("has unsaved changes while a failed save has not been made good", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ expect(projects.hasUnsavedChanges).toEqual(false);
+ vi.spyOn(logging, "error").mockImplementation(() => undefined);
+ vi.spyOn(db!, "save").mockRejectedValueOnce(new Error("Simulated"));
+
+ await fs.write(MAIN_FILE, "# one", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(projects.hasUnsavedChanges).toEqual(true));
+
+ await fs.write(MAIN_FILE, "# two", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(projects.hasUnsavedChanges).toEqual(false));
+ });
+
+ it("saves an edit that failed to save when the project is switched", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ const first = projects.currentId!;
+ vi.spyOn(logging, "error").mockImplementation(() => undefined);
+ vi.spyOn(db!, "save").mockRejectedValueOnce(new Error("Simulated"));
+ await fs.write(MAIN_FILE, "# not saved yet", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(projects.hasUnsavedChanges).toEqual(true));
+
+ await projects.create("Second");
+
+ expect(decode((await db!.file(first, MAIN_FILE))!)).toEqual(
+ "# not saved yet"
+ );
+ expect(projects.hasUnsavedChanges).toEqual(false);
+ });
+
+ describe("opening the open project again after a failed save", () => {
+ // As after going to the projects page to free some space.
+ const withFailedEdit = async (failures: "once" | "always") => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ vi.spyOn(logging, "error").mockImplementation(() => undefined);
+ const save = vi.spyOn(db!, "save");
+ if (failures === "once") {
+ save.mockRejectedValueOnce(new Error("Simulated"));
+ } else {
+ save.mockRejectedValue(new Error("Simulated"));
+ }
+ await fs.write(MAIN_FILE, "# not saved yet", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(projects.hasUnsavedChanges).toEqual(true));
+ return { db: db!, fs, projects, id: projects.currentId! };
+ };
+
+ it("saves the edit and keeps it on screen", async () => {
+ const { db, fs, projects, id } = await withFailedEdit("once");
+
+ await projects.open(id);
+
+ expect(decode((await fs.read(MAIN_FILE)).data)).toEqual(
+ "# not saved yet"
+ );
+ expect(decode((await db.file(id, MAIN_FILE))!)).toEqual(
+ "# not saved yet"
+ );
+ expect(projects.hasUnsavedChanges).toEqual(false);
+ });
+
+ it("keeps the edit on screen if it still cannot be saved", async () => {
+ const { fs, projects, id } = await withFailedEdit("always");
+
+ await projects.open(id);
+
+ expect(decode((await fs.read(MAIN_FILE)).data)).toEqual(
+ "# not saved yet"
+ );
+ expect(projects.currentId).toEqual(id);
+ expect(projects.hasUnsavedChanges).toEqual(true);
+ });
+ });
+
+ it("a failed save raises saveerror each time but is logged once", async () => {
+ const { db, fs, projects } = await setup();
+ await projects.openCurrent();
+ await fs.initialize();
+ const error = new DOMException("Simulated", "QuotaExceededError");
+ vi.spyOn(db!, "save").mockRejectedValue(error);
+ const logged = vi
+ .spyOn(logging, "error")
+ .mockImplementation(() => undefined);
+ const errors: unknown[] = [];
+ projects.addEventListener("saveerror", (e: ProjectSaveErrorEvent) => {
+ errors.push(e.error);
+ });
+
+ await fs.write(MAIN_FILE, "# one", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(errors).toHaveLength(1));
+ await fs.write(MAIN_FILE, "# two", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(errors).toHaveLength(2));
+
+ expect(errors).toEqual([error, error]);
+ expect(logged).toHaveBeenCalledTimes(1);
+ // The in-memory copy still has the edit.
+ expect((await fs.read(MAIN_FILE)).data).toEqual(
+ new TextEncoder().encode("# two")
+ );
+ });
+
+ describe("with the same project open in another tab", () => {
+ const twoTabs = async () => {
+ const a = await setup();
+ const b = openTab(a.db);
+ // No session storage here, so the second tab opens the most recent
+ // project: the first tab's.
+ for (const tab of [a, b]) {
+ await tab.projects.openCurrent();
+ await tab.fs.initialize();
+ }
+ expect(b.projects.currentId).toEqual(a.projects.currentId);
+ return { a, b, db: a.db!, id: a.projects.currentId! };
+ };
+
+ it("shows the other tab's edits", async () => {
+ const { a, b } = await twoTabs();
+ await a.fs.write(
+ MAIN_FILE,
+ "# from the other tab",
+ VersionAction.MAINTAIN
+ );
+ await vi.waitFor(async () =>
+ expect(decode((await b.fs.read(MAIN_FILE)).data)).toEqual(
+ "# from the other tab"
+ )
+ );
+ });
+
+ it("reloads without changing the project id or unchanged files' versions", async () => {
+ const { a, b } = await twoTabs();
+ await b.fs.write("helper.py", "# helper", VersionAction.INCREMENT);
+ await vi.waitFor(() =>
+ expect(a.fs.project.files.map((f) => f.name)).toContain("helper.py")
+ );
+ const id = b.fs.project.id;
+ const version = (name: string) =>
+ b.fs.project.files.find((f) => f.name === name)!.version;
+ const helperBefore = version("helper.py");
+ const mainBefore = version(MAIN_FILE);
+
+ await a.fs.write(MAIN_FILE, "# from a", VersionAction.MAINTAIN);
+ await vi.waitFor(() =>
+ expect(version(MAIN_FILE)).toBeGreaterThan(mainBefore)
+ );
+
+ expect(b.fs.project.id).toEqual(id);
+ expect(version("helper.py")).toEqual(helperBefore);
+ });
+
+ it("keeps the other tab's rename when this one has edits still to save", async () => {
+ const { a, b, db, id } = await twoTabs();
+ await b.fs.write(MAIN_FILE, "# unsaved in b", VersionAction.MAINTAIN);
+ await a.projects.rename(id, "Renamed in A");
+
+ // Long enough for the reloads and flushes this sets off to finish.
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ expect((await db.get(id))?.name).toEqual("Renamed in A");
+ expect(a.fs.project.name).toEqual("Renamed in A");
+ expect(b.fs.project.name).toEqual("Renamed in A");
+ expect(decode((await db.file(id, MAIN_FILE))!)).toEqual("# unsaved in b");
+ });
+
+ it("lets go of a project the other tab deletes and does not write it back", async () => {
+ const { a, b, db, id } = await twoTabs();
+ const errors: unknown[] = [];
+ b.projects.addEventListener("saveerror", (e: ProjectSaveErrorEvent) => {
+ errors.push(e.error);
+ });
+ const deleted = new Promise((resolve) =>
+ b.projects.addEventListener("openprojectdeleted", resolve)
+ );
+
+ await a.projects.delete([id]);
+ await deleted;
+ expect(b.projects.currentId).toBeUndefined();
+
+ // The editor may still be showing it.
+ await b.fs.write(MAIN_FILE, "# typed after", VersionAction.MAINTAIN);
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(errors).toEqual([]);
+ expect(await db.get(id)).toBeUndefined();
+ expect(await db.files(id)).toEqual({});
+ });
+
+ /**
+ * Runs an action in the middle of the second tab's handling of a change
+ * to the open project: just after it has read the project's record.
+ */
+ const duringReload = async (
+ action: (tabs: Awaited>) => Promise
+ ) => {
+ const tabs = await twoTabs();
+ const load = tabs.db.load.bind(tabs.db);
+ let acted: Promise | undefined;
+ vi.spyOn(tabs.db, "load").mockImplementationOnce(async (id) => {
+ const content = await load(id);
+ acted = action(tabs);
+ await acted;
+ return content;
+ });
+ await tabs.a.fs.write(MAIN_FILE, "# changed", VersionAction.MAINTAIN);
+ await vi.waitFor(() => expect(acted).toBeDefined());
+ await acted;
+ return tabs;
+ };
+
+ it("saves this tab's failed edit before reloading for the other's change", async () => {
+ const { a, b, db, id } = await twoTabs();
+ vi.spyOn(logging, "error").mockImplementation(() => undefined);
+ vi.spyOn(db, "save").mockRejectedValueOnce(new Error("Simulated"));
+ await b.fs.write(MAIN_FILE, "# b, not saved yet", VersionAction.MAINTAIN);
+ await vi.waitFor(() =>
+ expect(b.projects.hasUnsavedChanges).toEqual(true)
+ );
+
+ await a.fs.write("helper.py", "# from a", VersionAction.INCREMENT);
+ await vi.waitFor(() =>
+ expect(b.fs.project.files.map((f) => f.name)).toContain("helper.py")
+ );
+
+ // b still shows its edit, and everything agrees with the database.
+ expect(decode((await b.fs.read(MAIN_FILE)).data)).toEqual(
+ "# b, not saved yet"
+ );
+ expect(decode((await db.file(id, MAIN_FILE))!)).toEqual(
+ "# b, not saved yet"
+ );
+ expect(b.projects.hasUnsavedChanges).toEqual(false);
+ await vi.waitFor(async () =>
+ expect(decode((await a.fs.read(MAIN_FILE)).data)).toEqual(
+ "# b, not saved yet"
+ )
+ );
+ });
+
+ it("keeps this tab's copy if its edit still cannot be saved", async () => {
+ const { a, b, db } = await twoTabs();
+ vi.spyOn(logging, "error").mockImplementation(() => undefined);
+ const save = db.save.bind(db);
+ // Saves of b's edit fail; a's go through.
+ vi.spyOn(db, "save").mockImplementation((project, files, options) =>
+ MAIN_FILE in files.writes
+ ? Promise.reject(new Error("Simulated"))
+ : save(project, files, options)
+ );
+ await b.fs.write(MAIN_FILE, "# b, cannot save", VersionAction.MAINTAIN);
+ await vi.waitFor(() =>
+ expect(b.projects.hasUnsavedChanges).toEqual(true)
+ );
+
+ await a.fs.write("helper.py", "# from a", VersionAction.INCREMENT);
+ await new Promise((resolve) => setTimeout(resolve, 800));
+
+ expect(decode((await b.fs.read(MAIN_FILE)).data)).toEqual(
+ "# b, cannot save"
+ );
+ expect(b.projects.hasUnsavedChanges).toEqual(true);
+ });
+
+ it("still lets go of a deleted project if refreshing the list fails", async () => {
+ const { a, b, id } = await twoTabs();
+ const logged = vi
+ .spyOn(logging, "error")
+ .mockImplementation(() => undefined);
+ vi.spyOn(b.projects, "refresh").mockRejectedValueOnce(
+ new Error("Simulated")
+ );
+ const deleted = new Promise((resolve) =>
+ b.projects.addEventListener("openprojectdeleted", resolve)
+ );
+
+ await a.projects.delete([id]);
+ await deleted;
+
+ expect(b.projects.currentId).toBeUndefined();
+ expect(logged).toHaveBeenCalledWith(
+ "Failed to refresh the project list",
+ expect.any(Error)
+ );
+ });
+
+ it("still lets go of it if it is deleted while reloading", async () => {
+ let deleted: Promise | undefined;
+ const errors: unknown[] = [];
+ const { b, db, id } = await duringReload(async ({ a, b, id }) => {
+ b.projects.addEventListener("saveerror", (e: ProjectSaveErrorEvent) => {
+ errors.push(e.error);
+ });
+ deleted = new Promise((resolve) =>
+ b.projects.addEventListener("openprojectdeleted", resolve)
+ );
+ await a.projects.delete([id]);
+ });
+
+ await deleted;
+ expect(b.projects.currentId).toBeUndefined();
+ await b.fs.write(MAIN_FILE, "# typed after", VersionAction.MAINTAIN);
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(errors).toEqual([]);
+ expect(await db.get(id)).toBeUndefined();
+ });
+
+ it("does not go back to it if the user has opened another meanwhile", async () => {
+ let other: string | undefined;
+ const { b } = await duringReload(async ({ b }) => {
+ other = await b.projects.create("Other");
+ });
+ // Long enough for a mistaken switch back to have happened.
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(b.projects.currentId).toEqual(other);
+ expect(b.fs.project.name).toEqual("Other");
+ });
+ });
+
+ describe("when a project fails to load", () => {
+ const error = new Error("Simulated read failure");
+ const helper = new TextEncoder().encode("# helper");
+
+ const withSavedProject = async () => {
+ const result = await setup();
+ await result.db!.create(
+ { id: "saved", name: "Saved", timestamp: 1 },
+ {
+ [MAIN_FILE]: new TextEncoder().encode("# saved"),
+ "helper.py": helper,
+ }
+ );
+ return result;
+ };
+
+ const expectSavedIntact = async (db: ProjectsDatabase) => {
+ expect((await db.get("saved"))?.name).toEqual("Saved");
+ expect(Object.keys(await db.files("saved")).sort()).toEqual([
+ "helper.py",
+ MAIN_FILE,
+ ]);
+ };
+
+ it("open rejects, writes nothing and keeps the open project", async () => {
+ const { db, fs, projects } = await withSavedProject();
+ const first = await projects.create("First");
+ await fs.initialize();
+ vi.spyOn(db!, "load").mockRejectedValueOnce(error);
+
+ await expect(projects.open("saved")).rejects.toBe(error);
+
+ await expectSavedIntact(db!);
+ expect((await db!.get("saved"))?.timestamp).toEqual(1);
+ expect(projects.currentId).toEqual(first);
+ expect(fs.project.name).toEqual("First");
+ });
+
+ it("openCurrent rejects, keeps the error for the page and can retry", async () => {
+ const { db, fs, projects } = await withSavedProject();
+ vi.spyOn(db!, "load").mockRejectedValueOnce(error);
+
+ await expect(projects.openCurrent()).rejects.toBe(error);
+ expect(projects.takeOpenFailure()).toBe(error);
+ expect(projects.takeOpenFailure()).toBeUndefined();
+ await expectSavedIntact(db!);
+
+ await projects.openCurrent();
+ await fs.initialize();
+ expect(projects.currentId).toEqual("saved");
+ expect(fileNames(fs)).toEqual([MAIN_FILE, "helper.py"]);
+ });
+
+ it("a reload for another tab's change keeps this tab's copy", async () => {
+ const { db, fs, projects } = await withSavedProject();
+ await projects.openCurrent();
+ await fs.initialize();
+ vi.spyOn(db!, "load").mockRejectedValueOnce(error);
+ const logged = vi
+ .spyOn(logging, "error")
+ .mockImplementation(() => undefined);
+
+ const otherTab = new BroadcastChannel("python-editor-projects");
+ otherTab.postMessage({ type: "changed", projectIds: ["saved"] });
+ otherTab.close();
+
+ await vi.waitFor(() =>
+ expect(logged).toHaveBeenCalledWith("Failed to reload project", error)
+ );
+ expect(projects.currentId).toEqual("saved");
+ expect(fileNames(fs)).toEqual([MAIN_FILE, "helper.py"]);
+ await expectSavedIntact(db!);
+ });
+ });
+
+ it("switches project even if MicroPython failed to load", async () => {
+ const storage = deferred();
+ let failLoad!: (e: Error) => void;
+ const loading = new Promise((_, reject) => {
+ failLoad = reject;
+ });
+ let source: MicroPythonSource = () => loading;
+ const fs = new FileSystem(
+ logging,
+ new DefaultHost(undefined, storage.promise),
+ () => source()
+ );
+ const db = await ProjectsDatabase.open(`projects-${counter++}`);
+ const projects = new Projects(fs, logging, Promise.resolve(db), storage);
+ await projects.openCurrent();
+ const first = projects.currentId!;
+ await fs.initializeInBackground();
+ // The load fails while the switch waits for it.
+ const switchStorage = fs.switchStorage.bind(fs);
+ vi.spyOn(fs, "switchStorage").mockImplementationOnce((s) => {
+ const switching = switchStorage(s);
+ failLoad(new Error("Simulated MicroPython load failure"));
+ source = microPythonSource;
+ return switching;
+ });
+
+ const second = await projects.create("Second");
+ await fs.write(MAIN_FILE, "# typed in second", VersionAction.MAINTAIN);
+ await projects.rename(second, "Second");
+
+ expect(projects.currentId).toEqual(second);
+ expect(decode((await db.file(second, MAIN_FILE))!)).toEqual(
+ "# typed in second"
+ );
+ expect(decode((await db.file(first, MAIN_FILE))!)).not.toEqual(
+ "# typed in second"
+ );
+ });
+
+ it("an error from the first project's storage leaves the database copy", async () => {
+ const { db, fs, projects } = await setup();
+ await db!.create(
+ { id: "saved", name: "Saved", timestamp: 1 },
+ { [MAIN_FILE]: new TextEncoder().encode("# saved") }
+ );
+ await projects.openCurrent();
+ await fs.initialize();
+
+ await expect(fs.remove("missing.py")).rejects.toThrow(/No such file/);
+ // A clear would run in the background after the rejection, with nothing
+ // to await, so outlast the storage's flush delay before checking.
+ await new Promise((resolve) => setTimeout(resolve, 600));
+
+ expect((await db!.get("saved"))?.name).toEqual("Saved");
+ expect(Object.keys(await db!.files("saved"))).toEqual([MAIN_FILE]);
+ });
+
+ it("without the database there is nothing to manage and the editor still works", async () => {
+ const { fs, projects } = await setup(false);
+ expect(await projects.isAvailable()).toEqual(false);
+ await projects.openCurrent();
+ await fs.initialize();
+ expect(fileNames(fs)).toEqual([MAIN_FILE]);
+ expect(await projects.refresh()).toEqual([]);
+ await expect(projects.create("x")).rejects.toThrow(/not available/);
+ });
+});
diff --git a/src/project/projects.ts b/src/project/projects.ts
new file mode 100644
index 000000000..c49ab481d
--- /dev/null
+++ b/src/project/projects.ts
@@ -0,0 +1,485 @@
+/**
+ * The projects in this browser and which one the editor has open.
+ *
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { Deferred } from "../common/deferred";
+import { TypedEventTarget } from "../common/events";
+import {
+ chooseProject,
+ defaultProjectFiles,
+ getCurrentProjectId,
+ migrateSessionProject,
+ sessionStorageIfPossible,
+ setCurrentProjectId,
+} from "../fs/current-project";
+import { FileSystem } from "../fs/fs";
+import { generateId } from "../fs/fs-util";
+import { IndexedDBFSStorage } from "../fs/indexeddb-storage";
+import { PendingProjectLink } from "../fs/project-link";
+import {
+ NoSuchProjectError,
+ ProjectContent,
+ ProjectListEntry,
+ ProjectsDatabase,
+} from "../fs/projects-db";
+import {
+ FSStorage,
+ InMemoryFSStorage,
+ SessionStorageFSStorage,
+ SplitStrategyStorage,
+} from "../fs/storage";
+import { hasStorageVersionError } from "../fs/storage-status";
+import { Logging } from "../logging/logging";
+
+export class ProjectsChangedEvent extends Event {
+ constructor() {
+ super("change");
+ }
+}
+
+/**
+ * A write to the open project's storage failed. Its changes go with the next
+ * write that is made.
+ */
+export class ProjectSaveErrorEvent extends Event {
+ constructor(public readonly error: unknown) {
+ super("saveerror");
+ }
+}
+
+/**
+ * The project open in this tab was deleted in another. The editor has
+ * nothing to save to any more, so whatever is showing it should leave.
+ */
+export class OpenProjectDeletedEvent extends Event {
+ constructor() {
+ super("openprojectdeleted");
+ }
+}
+
+interface EventMap {
+ change: ProjectsChangedEvent;
+ saveerror: ProjectSaveErrorEvent;
+ openprojectdeleted: OpenProjectDeletedEvent;
+}
+
+/**
+ * What other tabs are told. Ids name the projects affected; a tab with one of
+ * them open reloads or lets go of it.
+ */
+interface SyncMessage {
+ type: "changed" | "deleted";
+ projectIds: string[];
+}
+
+const syncChannelName = "python-editor-projects";
+
+/**
+ * Lists, creates, opens, renames, duplicates and deletes projects, and keeps
+ * the file system on the open one.
+ *
+ * The host waits on the file system's first storage, which this resolves
+ * when a project is first opened, so the pages can show without choosing a
+ * project. Later opens switch the file system's storage. Without the
+ * projects database the editor falls back to session storage and there is
+ * nothing to list; pages redirect to the editor.
+ */
+export class Projects extends TypedEventTarget {
+ private db: ProjectsDatabase | undefined;
+ private readonly ready: Promise;
+ private firstStorageResolved = false;
+ private openId: string | undefined;
+ private openStorage: IndexedDBFSStorage | undefined;
+ private opening: Promise | undefined;
+ private openFailure: unknown;
+ private cachedList: ProjectListEntry[] = [];
+ private saveErrorReported = false;
+ private readonly channel: BroadcastChannel | undefined;
+ private readonly session = sessionStorageIfPossible();
+
+ /**
+ * @param firstStorage Resolved with the file system's storage when a
+ * project is first opened; the host's DefaultHost waits on it.
+ * @param projectLink The #project: link at boot, made a new project when
+ * the editor first chooses one. Left for the host without the database.
+ */
+ constructor(
+ private fs: FileSystem,
+ private logging: Logging,
+ db: Promise,
+ private firstStorage: Deferred,
+ private projectLink: PendingProjectLink = new PendingProjectLink()
+ ) {
+ super();
+ this.ready = db.then(async (resolved) => {
+ this.db = resolved;
+ if (resolved) {
+ await this.migrateSessionProject(resolved);
+ }
+ });
+ this.channel =
+ typeof BroadcastChannel !== "undefined"
+ ? new BroadcastChannel(syncChannelName)
+ : undefined;
+ this.channel?.addEventListener("message", this.handleSyncMessage);
+ }
+
+ /**
+ * Brings in the project that the editor, before the projects database,
+ * kept in session storage. Part of getting ready, so that the pages list
+ * it and the editor opens it like any other project, whichever the tab
+ * loads first: the editor used to be at what is now the home page's
+ * address.
+ */
+ private async migrateSessionProject(db: ProjectsDatabase): Promise {
+ try {
+ const id = await migrateSessionProject(db, this.session);
+ if (id) {
+ this.channel?.postMessage({ type: "changed", projectIds: [id] });
+ }
+ } catch (e) {
+ // The app can still start. The session copy is kept for the next
+ // page load to try again.
+ this.logging.error("Failed to migrate the session storage project", e);
+ }
+ }
+
+ /**
+ * False without the projects database, in which case there is one
+ * implicit project and no project management.
+ */
+ async isAvailable(): Promise {
+ await this.ready;
+ return this.db !== undefined;
+ }
+
+ /**
+ * The projects as of the last refresh, most recent first. Route loaders
+ * refresh before the pages render; the pages then subscribe to changes.
+ */
+ get projects(): ProjectListEntry[] {
+ return this.cachedList;
+ }
+
+ /**
+ * True while the #project: link the app started with has yet to be opened.
+ */
+ get hasPendingProjectLink(): boolean {
+ return this.projectLink.pending;
+ }
+
+ /**
+ * True while an edit to the open project has failed to save and has not
+ * been saved since, so that closing the tab would lose it.
+ */
+ get hasUnsavedChanges(): boolean {
+ return this.openStorage?.hasUnsavedChanges ?? false;
+ }
+
+ /** The project the editor has open in this tab, if any. */
+ get currentId(): string | undefined {
+ return this.openId;
+ }
+
+ async refresh(): Promise {
+ await this.ready;
+ this.cachedList = this.db ? await this.db.listWithFileNames() : [];
+ this.dispatchTypedEvent("change", new ProjectsChangedEvent());
+ return this.cachedList;
+ }
+
+ /**
+ * Makes sure the editor has a project: one from the #project: link the
+ * app booted with, else the one already open, the tab's, the most recent,
+ * or a new one. For the editor route's loader. Concurrent calls share one
+ * choice so they cannot each create a project.
+ *
+ * @returns True if a #project: link became a project, so the caller can
+ * drop the hash from the URL.
+ * @throws If the project fails to load. The error is also kept for
+ * takeOpenFailure.
+ */
+ openCurrent(): Promise {
+ if (!this.opening) {
+ this.openFailure = undefined;
+ this.opening = this.chooseAndOpen()
+ .catch((error: unknown) => {
+ this.openFailure = error;
+ throw error;
+ })
+ .finally(() => {
+ this.opening = undefined;
+ });
+ }
+ return this.opening;
+ }
+
+ /**
+ * Why the last openCurrent failed, if it did, for the page the editor
+ * redirects to to report. Cleared once taken or by the next openCurrent.
+ */
+ takeOpenFailure(): unknown {
+ const failure = this.openFailure;
+ this.openFailure = undefined;
+ return failure;
+ }
+
+ private async chooseAndOpen(): Promise {
+ await this.ready;
+ if (!this.db) {
+ // Only when needed: constructing a split reads session storage, and
+ // clears it if the read fails.
+ if (!this.firstStorageResolved) {
+ this.resolveFirstStorage(
+ new SplitStrategyStorage(
+ new InMemoryFSStorage(undefined),
+ hasStorageVersionError()
+ ? undefined
+ : SessionStorageFSStorage.create(),
+ this.logging
+ )
+ );
+ }
+ return false;
+ }
+ const link = this.projectLink.take();
+ if (!link && this.openId && (await this.db.get(this.openId))) {
+ return false;
+ }
+ const id = await chooseProject(this.db, this.session, link);
+ await this.switchTo(id);
+ if (link) {
+ await this.changed([id]);
+ }
+ return link !== undefined;
+ }
+
+ async open(id: string): Promise {
+ const db = await this.requireDb();
+ await this.switchTo(id);
+ await db.touch(id);
+ }
+
+ async create(name: string): Promise {
+ return this.createFromFiles(name, defaultProjectFiles());
+ }
+
+ /**
+ * Creates a project with the given files, e.g. from an imported hex or an
+ * idea, and opens it in the editor.
+ *
+ * Leaves this tab's list alone: the caller is heading to the editor, and
+ * a refresh could show the new card on the page first. The pages refresh
+ * when next visited.
+ */
+ async createFromFiles(
+ name: string | undefined,
+ files: Record
+ ): Promise {
+ const db = await this.requireDb();
+ const id = generateId();
+ const meta = { id, name, timestamp: Date.now() };
+ await db.create(meta, files);
+ await this.switchTo(id, { meta, files });
+ this.channel?.postMessage({ type: "changed", projectIds: [id] });
+ return id;
+ }
+
+ async rename(id: string, name: string): Promise {
+ const db = await this.requireDb();
+ if (id === this.openId) {
+ // Through the file system so its copy of the name changes too.
+ await this.fs.setProjectName(name);
+ await this.openStorage?.flush();
+ } else {
+ await db.update(id, { name, timestamp: Date.now() });
+ }
+ await this.changed([id]);
+ }
+
+ async duplicate(id: string, name: string): Promise {
+ const db = await this.requireDb();
+ if (id === this.openId) {
+ await this.openStorage?.flush();
+ }
+ const newId = generateId();
+ await db.duplicate(id, { id: newId, name, timestamp: Date.now() });
+ await this.changed([newId]);
+ return newId;
+ }
+
+ async delete(ids: string[]): Promise {
+ const db = await this.requireDb();
+ for (const id of ids) {
+ if (id === this.openId) {
+ this.letGoOfOpenProject();
+ }
+ await db.delete(id);
+ }
+ await this.refresh();
+ this.channel?.postMessage({ type: "deleted", projectIds: ids });
+ }
+
+ private async requireDb(): Promise {
+ await this.ready;
+ if (!this.db) {
+ throw new Error("The projects database is not available");
+ }
+ return this.db;
+ }
+
+ private resolveFirstStorage(storage: FSStorage): void {
+ if (!this.firstStorageResolved) {
+ this.firstStorageResolved = true;
+ this.firstStorage.resolve(storage);
+ }
+ }
+
+ /**
+ * Points the file system at a project. The first time this supplies the
+ * storage the host is waiting for; afterwards it switches. Loads the
+ * project before changing anything, so a failed read leaves all as it was.
+ *
+ * Asked for the project that is already open, it reloads it: another tab
+ * has changed it, or the user has opened it again. What this tab has still
+ * to save is saved first, and if that fails the tab keeps its copy.
+ *
+ * @param created The project's content when the caller has just created
+ * it, to skip reading it back.
+ * @throws NoSuchProjectError if the project has been deleted.
+ */
+ private async switchTo(id: string, created?: ProjectContent): Promise {
+ const db = await this.requireDb();
+ const previous = this.openStorage;
+ const reloading = this.openId === id && previous !== undefined;
+ if (reloading) {
+ const record = await db.get(id);
+ if (!record) {
+ throw new NoSuchProjectError(id);
+ }
+ // Saved before reloading so that the reload has it too. Otherwise the
+ // database's copy would go on screen in its place, and the save that
+ // followed would leave the two out of step. The name is the other
+ // tab's to change, so take it before saving.
+ previous.adoptName(record.name);
+ await previous.flush();
+ if (previous.hasUnsavedChanges) {
+ // It cannot be saved, and a reload would lose it from here too.
+ return;
+ }
+ }
+ const content = created ?? (await db.load(id));
+ if (!content) {
+ throw new NoSuchProjectError(id);
+ }
+ if (reloading && this.openStorage !== previous) {
+ // What was open changed while this waited: the user opened another
+ // project, a "deleted" message let go of this one, or an overlapping
+ // reload got there first. This reload has been overtaken.
+ return;
+ }
+ const primary = new InMemoryFSStorage(content.meta.name);
+ for (const [name, data] of Object.entries(content.files)) {
+ await primary.write(name, data);
+ }
+ if (reloading) {
+ // For anything edited here since the save above.
+ previous.adoptName(content.meta.name);
+ }
+ const indexed = new IndexedDBFSStorage(
+ db,
+ content.meta,
+ (e) => this.handleSaveError(e),
+ () => this.channel?.postMessage({ type: "changed", projectIds: [id] })
+ );
+ const storage = new SplitStrategyStorage(primary, indexed, this.logging, {
+ preloaded: true,
+ });
+ this.openId = id;
+ this.openStorage = indexed;
+ setCurrentProjectId(this.session, id);
+ if (reloading) {
+ await this.fs.reloadStorage(storage);
+ } else if (this.firstStorageResolved) {
+ await this.fs.switchStorage(storage);
+ } else {
+ this.resolveFirstStorage(storage);
+ }
+ await previous?.dispose();
+ }
+
+ /**
+ * The open project is gone. The file system keeps its copy until the
+ * editor next asks for a project, but nothing more is written from it.
+ */
+ private letGoOfOpenProject(): void {
+ this.openStorage?.abandon();
+ this.openId = undefined;
+ this.openStorage = undefined;
+ if (getCurrentProjectId(this.session)) {
+ setCurrentProjectId(this.session, undefined);
+ }
+ }
+
+ /**
+ * Writes are per keystroke, so once storage is full every flush fails;
+ * report the first so Sentry sees it and leave the toast to say the rest.
+ */
+ private handleSaveError(error: unknown): void {
+ if (!this.saveErrorReported) {
+ this.saveErrorReported = true;
+ this.logging.error("Failed to save project", error);
+ }
+ this.dispatchTypedEvent("saveerror", new ProjectSaveErrorEvent(error));
+ }
+
+ private async changed(ids: string[]): Promise {
+ await this.refresh();
+ this.channel?.postMessage({ type: "changed", projectIds: ids });
+ }
+
+ private handleSyncMessage = (event: MessageEvent) => {
+ void (async () => {
+ const { type, projectIds } = event.data;
+ try {
+ await this.refresh();
+ } catch (e) {
+ // The list is stale, but what the notice means for the open project
+ // still has to be acted on: it may have been deleted.
+ this.logging.error("Failed to refresh the project list", e);
+ }
+ const id = this.openId;
+ if (!id || !projectIds.includes(id)) {
+ return;
+ }
+ if (type === "changed") {
+ // Reload the open project so this tab shows the other's edits. A
+ // "changed" message says nothing about now: the project may have
+ // been deleted since it was sent, with the "deleted" message still
+ // to come, in which case it is not there to reload.
+ try {
+ await this.switchTo(id);
+ return;
+ } catch (e) {
+ if (!(e instanceof NoSuchProjectError)) {
+ // Carry on with this tab's copy.
+ this.logging.error("Failed to reload project", e);
+ return;
+ }
+ }
+ }
+ if (this.openId === id) {
+ // Unless the user opened another project, or a "deleted" message
+ // was handled, while this waited.
+ this.letGoOfOpenProject();
+ this.dispatchTypedEvent(
+ "openprojectdeleted",
+ new OpenProjectDeletedEvent()
+ );
+ }
+ })();
+ };
+}
diff --git a/src/project/storage-error-toast.tsx b/src/project/storage-error-toast.tsx
new file mode 100644
index 000000000..472dbd7f4
--- /dev/null
+++ b/src/project/storage-error-toast.tsx
@@ -0,0 +1,67 @@
+/**
+ * (c) 2026, Micro:bit Educational Foundation and contributors
+ *
+ * SPDX-License-Identifier: MIT
+ */
+import { ToastOptions, useToast } from "@microbit/ui";
+import { useCallback, useEffect } from "react";
+import { useIntl } from "react-intl";
+import { useProjectsIfAvailable } from "./projects-hooks";
+import { ProjectSaveErrorEvent } from "./projects";
+
+const toastId = "storage-error";
+
+export const isQuotaExceededError = (error: unknown): boolean =>
+ error instanceof DOMException && error.name === "QuotaExceededError";
+
+/**
+ * Shows the persistent "storage full" or "failed to save" toast, the same
+ * one as ml-trainer. Repeat failures update the toast rather than stacking.
+ */
+export const useShowStorageError = (): ((error: unknown) => void) => {
+ const toast = useToast();
+ const intl = useIntl();
+ return useCallback(
+ (error: unknown) => {
+ const options: ToastOptions = {
+ id: toastId,
+ status: "error",
+ persistent: true,
+ ...(isQuotaExceededError(error)
+ ? {
+ title: intl.formatMessage({ id: "storage-error-quota-title" }),
+ description: intl.formatMessage({
+ id: "storage-error-quota-description",
+ }),
+ }
+ : { title: intl.formatMessage({ id: "storage-error-other" }) }),
+ };
+ if (toast.isActive(toastId)) {
+ toast.update(toastId, options);
+ } else {
+ toast(options);
+ }
+ },
+ [intl, toast]
+ );
+};
+
+/**
+ * Tells the user when the open project stops saving to the projects
+ * database. Nothing to do in iframe mode, where the host owns the project.
+ */
+const StorageErrorToast = () => {
+ const projects = useProjectsIfAvailable();
+ const showStorageError = useShowStorageError();
+ useEffect(() => {
+ if (!projects) {
+ return;
+ }
+ const listener = (e: ProjectSaveErrorEvent) => showStorageError(e.error);
+ projects.addEventListener("saveerror", listener);
+ return () => projects.removeEventListener("saveerror", listener);
+ }, [projects, showStorageError]);
+ return null;
+};
+
+export default StorageErrorToast;
diff --git a/src/router-hooks.test.tsx b/src/router-hooks.test.tsx
index cff888e3a..1062efd46 100644
--- a/src/router-hooks.test.tsx
+++ b/src/router-hooks.test.tsx
@@ -8,8 +8,9 @@ import { useEffect } from "react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { LoggingProvider } from "./logging/logging-hooks";
import { MockLogging } from "./logging/mock";
+import { IframeModeProvider } from "./iframe-mode-hooks";
import { NavigationSource, RouterState, useRouterState } from "./router-hooks";
-import { editorRoutePath } from "./urls";
+import { editorRoutePath, iframeEditorRoutePath } from "./urls";
const result: { current?: ReturnType } = {};
const state = (): RouterState => result.current![0];
@@ -24,14 +25,17 @@ const Probe = () => {
return null;
};
-const renderAt = (path: string) => {
+const renderAt = (path: string, iframe = false) => {
const logging = new MockLogging();
const router = createMemoryRouter(
[
{
path: "",
children: [
- { path: editorRoutePath, element: },
+ {
+ path: iframe ? iframeEditorRoutePath : editorRoutePath,
+ element: ,
+ },
{ path: "*", element: },
],
},
@@ -40,20 +44,22 @@ const renderAt = (path: string) => {
);
render(
-
+
+