Repository navigation
feat: add a built-in editor for the games XBlock - #3259
bradenmacdonald merged 16 commits into
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #3259 +/- ##
==========================================
+ Coverage 96.05% 96.20% +0.14%
==========================================
Files 1413 1446 +33
Lines 34384 35374 +990
Branches 8196 8174 -22
==========================================
+ Hits 33028 34031 +1003
- Misses 1299 1301 +2
+ Partials 57 42 -15 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
df58bcb to
2de3130
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Critical build and routing findings, along with unresolved editor behavior issues, remain.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 2
Open (5)
What changed in this PR
Adds a per-XBlock editor plugin slot and a Games XBlock editor backed by custom handlers and React Query.
Changes:
- Adds and documents
XBlockEditorSlotwith default-editor fallback and plugin routing. - Adds asynchronous save overrides and title locking.
- Adds the Games editor UI, validation, image handling, API hooks, styles, and tests.
| File | Summary |
|---|---|
src/plugin-slots/XBlockEditorSlot/README.md |
Documents the editor slot. |
src/plugin-slots/XBlockEditorSlot/index.tsx |
Implements the slot and ID helpers. |
src/plugin-slots/XBlockEditorSlot/index.test.tsx |
Tests slot rendering and IDs. |
src/plugin-slots/XBlockEditorSlot/defaultContent.test.tsx |
Tests default-content isolation. |
src/plugin-slots/README.md |
Documents available plugin slots. |
src/editors/Editor.tsx |
Integrates editors with the new slot. |
src/editors/containers/EditorContainer/onSave.test.tsx |
Tests custom save behavior. |
src/editors/containers/EditorContainer/index.tsx |
Adds save overrides and title locking. |
src/editors/containers/EditorContainer/components/TitleHeader/index.tsx |
Adds title-edit disabling. |
src/editors/containers/EditorContainer/components/TitleHeader/index.test.tsx |
Tests title locking. |
src/course-unit/xblock-container-iframe/hooks/useMessageHandlers.tsx |
Routes claimed XBlocks to plugins. |
src/course-unit/xblock-container-iframe/hooks/tests/hooks.test.tsx |
Tests plugin routing. |
plugins/xblock-games-editor/types.ts |
Defines Games editor types. |
plugins/xblock-games-editor/PictureIcon.tsx |
Provides the image icon. |
plugins/xblock-games-editor/package.json |
Defines plugin metadata. |
plugins/xblock-games-editor/messages.ts |
Adds localized messages. |
plugins/xblock-games-editor/index.tsx |
Exports the plugin. |
plugins/xblock-games-editor/hostComponents.ts |
Supplies typed host components. |
plugins/xblock-games-editor/GamesEditor.tsx |
Implements the Games editor UI and save flow. |
plugins/xblock-games-editor/GamesEditor.test.tsx |
Tests editor behavior. |
plugins/xblock-games-editor/GamesEditor.scss |
Styles the editor. |
plugins/xblock-games-editor/GameImageSettingsModal.tsx |
Implements image settings. |
plugins/xblock-games-editor/GameImageSettingsModal.scss |
Styles the image settings modal. |
plugins/xblock-games-editor/data/useGameState.ts |
Manages local editor state and uploads. |
plugins/xblock-games-editor/data/apiHooks.ts |
Defines React Query hooks. |
plugins/xblock-games-editor/data/api.ts |
Implements Games handler requests. |
plugins/xblock-games-editor/data/api.test.ts |
Tests handler URLs and requests. |
package.json |
Registers the plugin package. |
package-lock.json |
Locks the plugin dependency. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
2de3130 to
b035e61
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved critical and moderate issues remain in the Games editor and plugin routing and persistence flows.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 6
Open (8)
Convert validation errors to boolean isInvalid values · New Narrow the card ID before uploading an image · New Narrow the unknown save error before reading validation errors · New Pass the reordered list to updateOrder · New Preserve card keys in the save payload · New Send hasTimer when saving flashcards · New Disable image-settings editing while saving · New Use sessionStorage for game save triggers · New
b035e61 to
aa69711
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Five moderate findings and one nit remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
Resolved since last review (8)
Send hasTimer when saving flashcards Preserve card keys in the save payload Pass the reordered list to updateOrder Narrow the unknown save error before reading validation errors Narrow the card ID before uploading an image Convert validation errors to boolean isInvalid values Use sessionStorage for game save triggers Disable image-settings editing while saving
aa69711 to
a0f9e96
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved Games editor issues remain in save flow, validation, accessibility, and new-block handling.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
Resolved since last review (1)
a0f9e96 to
df5d162
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved moderate issues affect routing, accessibility, retry behavior, state tracking, and error handling.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 2
Open (2)
Resolved since last review (1)
df5d162 to
363bed8
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved moderate findings affect endpoint resolution, retry behavior, accessibility, and dirty-state handling.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
Resolved since last review (2)
363bed8 to
0af8aa0
Compare
…igger A native button provides the role and keyboard activation that the div re-implemented by hand. aria-disabled keeps it in the tab order while a save is out.
Replaces a test that walked the DOM ancestors of the menu and chevron asserting none was a button. The user-visible symptom of nesting the menu inside the collapsible trigger is that opening the menu toggles the card, so the test now checks that instead.
"Heads a failed save" read as a typo for "heeds". The tests check that the alert shows a translated heading rather than the English fallback; the names now say so.
|
@djoseph-apphelix Thanks for the changes. I had one question about a class for the background color on one element. One more thing-- do you already have plans to move the games block's backend to a submodule either in XBlocks-core or XBlock-extra? Since this block was proposed as a block to contribute as a product proposal, and we're planning to add it directly into the authoring MFE, I'd suggest putting it in XBlocks-core. |
bradenmacdonald
left a comment
There was a problem hiding this comment.
Thanks for the great review @Kelketek, and thanks @djoseph-apphelix for working through all the review comments here from @Kelketek and Copilot. This is a nice looking XBlock, and there are some nice cleanups in this PR.
-
Comment: When adding a new instance of the block, the default title is "Games" but that doesn't make sense - "Games" is a good name for the XBlock in general but when you add one instance of it, you're adding a single game (either a flashcard game or a matching game), so the default title should be "Game". (Non-blocking, probably not part of this PR anyways).
-
Comment: it would be better if the editor worked like the Problem editor to prompt you for which type of game you want to add before you start filling out the fields. It's not obvious that you can completely change the type of game using a small control on the right-hand side of the editor. (Non-blocking, address in optional follow-up PR)
Please let me know which of these nits you want to address if any, and then I'll merge this for you.
| // Studio sends `newXBlockEditor` only for the block types it knows this app | ||
| // edits; every other Edit click arrives here as a legacy-modal request. | ||
| // This app knows its own editors, so a block it can edit opens here without | ||
| // Studio having to be told about each new block type. |
There was a problem hiding this comment.
This seems like something we should change in the future. Studio should just send an "edit" message in any case, and this MFE can decide if it opens a new editor or frames in the legacy editor.
No action needed for now.
|
@Kelketek @navinkarkera @arbrandes This PR is still showing as "requested changes" from you three. Do you want to take another look, or can I dismiss that and merge it soon? I believe all the major comments have been addressed. |
Kelketek
left a comment
There was a problem hiding this comment.
Whoops, forgot to submit the actual most recent review pass. I just had one little thing that's not a huge blocker-- a question about a class. Other than that this looks good to me, and if it needs to be addressed in a follow-up, or if it's fine as-is, I'm OK.
| > | ||
| <Collapsible.Advanced | ||
| className="card" | ||
| className="card d-flex flex-column align-items-start align-self-stretch w-100 position-relative bg-white" |
There was a problem hiding this comment.
Is bg-white the right class or is there a class that sets the paragon background color to ensure it's not transparent? Presumably a dark mode might exist and this would be unpleasant.
There was a problem hiding this comment.
Good catch. Paragon's .card already sets the themed card background, so bg-white was overriding it. Removed in 0fe408b, along with an inline white background on the sortable wrapper.
| const onSave = jest.fn(() => Promise.reject(new Error('handler said no'))); | ||
| renderContainer({ onSave, isDirty: () => true }); | ||
| fireEvent.click(screen.getByRole('button', { name: /save changes/i })); | ||
| // The toast sits outside the modal, which hides everything but itself from |
There was a problem hiding this comment.
@djoseph-apphelix Let's address it in a follow-up, since the problem is pre-existing. Could you please create an issue for it so we can track the problem?
|
@bradenmacdonald I had @navinkarkera give this a first-pass review (internal ticket) and then I followed up on that first pass afterward since he's on leave now. You should be able to safely dismiss his. I've left my approval. |
The card forced a white background with bg-white and an inline style. Paragon's .card already supplies the themed card background, so a non-white theme would have been overridden.
The inner editor took learningContextId as a prop copied out of the editors' store. It now reads it from EditorContext, which the host page provides, and decides isLibrary with isLibraryKey on that context alone. The separate check for an lb: block id is dropped: a library block always opens in a library context.
arbrandes
left a comment
There was a problem hiding this comment.
Claude found two things I'd fix before merging, since both end up in saved block content: the "decorative" alt-text option doesn't do what it says, and image URLs are saved with the Studio host baked in. The rest is small.
| */ | ||
| const useAltText = (savedText: string) => { | ||
| const [value, setValue] = React.useState(savedText); | ||
| const [isDecorative, setIsDecorative] = React.useState(savedText === ''); |
There was a problem hiding this comment.
"Decorative" never reaches learners. Either drop the decorative checkbox, or have the block store an explicit flag for it. The flashcards handler replaces an empty *_image_alt with the card's term or definition, so an image marked decorative is rendered with the card text as its alt, never alt="". It also means a freshly uploaded image (alt '') opens this dialog with "decorative" already checked, so the default path for a new image skips alt text altogether.
Related, in useGameState.ts:291-307: clear ${imageType}_image_alt when a new image lands. Replacing an image keeps the previous image's alt text, which now describes the wrong picture.
There was a problem hiding this comment.
Right: the block substitutes the card text for an empty alt, so "decorative" was never real. Dropped the checkbox in 5179daf. Alt text is now required to save, the editor's preview falls back to the card text the way the block does, and a new upload clears the previous image's alt.
| const absolute = <T extends string | undefined>(url: T, studioEndpointUrl: string): T | string => { | ||
| if (!url || url.startsWith('http')) { return url; } | ||
| return `${studioEndpointUrl}${url}`; | ||
| }; | ||
|
|
There was a problem hiding this comment.
Don't persist the Studio-prefixed image URL. Keep the URL as the handler returned it in state and in the save payload, and add studioEndpointUrl only when rendering the preview. With the block's default storage, upload_image returns asset_storage.url(...), which is a relative /media/... URL; absolute() turns it into https://<studio-host>/media/... (here and at :303), and api.ts:66-74 saves that back into the block's cards. Learner-facing content then points at the Studio host, which breaks on export/import or a domain change, and is painful to fix after the fact.
There was a problem hiding this comment.
Fixed in 5179daf. URLs are stored and saved exactly as the handler returns them; imageDisplayUrl adds the Studio host only when rendering the card image, the collapsed preview and the settings dialog.
| SaveArgs, | ||
| } from '../types'; |
There was a problem hiding this comment.
Use @src instead of ../. data/api.ts, data/apiHooks.ts, data/useGameState.ts and every file under components/ import messages, types or gameContent that way. Please switch them to @src/editors/containers/GamesEditor/....
|
|
||
| .timer-toggle-button:focus::before, | ||
| .shuffle-toggle-button:focus::before { | ||
| display: none; | ||
| } |
There was a problem hiding this comment.
Don't hide the focus ring. Delete this rule. It hides Paragon's .btn:focus::before indicator, so the Shuffle and Timer toggles have no visible keyboard focus.
| if (card.card_key) { | ||
| baseCard.card_key = card.card_key; | ||
| } |
There was a problem hiding this comment.
Switching to Matching silently drops images. Is this intended? Saving as Matching strips every image field, so an author who tries Matching and switches back to Flashcards finds all images gone (and the files orphaned in storage). save_settings accepts the image fields regardless of type, so the simplest fix is to always send them; otherwise, warn when switching type with images present.
There was a problem hiding this comment.
Not intended. Fixed in 0bdb7ec: the image fields go with every game type, with a test.
| | { type: 'setError' | 'setLoadError'; value: Error; } | ||
| | { type: 'clearError' | 'setDirty'; }; | ||
|
|
||
| export const reducer = (state: GameState, action: Action): GameState => { |
There was a problem hiding this comment.
Yeah, not great. Only reason I'm not objecting is that this is going to eventually become a plugin.
Navin is on PTO and @Kelketek handled the review after this initial review.
Image URLs were made absolute against the Studio host on load and after upload, and saved that way, so learner content pointed at Studio and broke on export, import or a domain change. The URL is now stored and saved as the block returns it; imageDisplayUrl adds the host only when rendering. The image settings dialog offered a "decorative" option that saved an empty alt. The block replaces an empty alt with the card's text before learners see it, so the option never did what it said, and a new upload opened the dialog with it already ticked. The option is removed, alt text is required to save, the preview falls back to the card's text as the block does, and a new upload clears the previous image's alt.
Replaces the remaining ../ imports of messages, types and gameContent under the editor with @src/editors/containers/GamesEditor/..., as the repo convention asks.
A rule hid Paragon's .btn:focus::before indicator on the two toggles, leaving them with no visible keyboard focus.
The save payload dropped every image field for a matching game, so an author who tried Matching and switched back found the images gone and the files orphaned. The block accepts the fields for every type, so they are always sent.
…educer The editor kept its state in a Redux-style reducer with action objects, plus a second synchronous copy so the save could read the latest state after awaiting an upload. The state now lives in one small store read through useSyncExternalStore, and each change is a named pure function. Behaviour and the editor's action API are unchanged.
|
Thanks @djoseph-apphelix. @arbrandes is this good to merge now that those last issues are addressed? |
|
@arbrandes Any remaining issues here or are we good to go? |
arbrandes
left a comment
There was a problem hiding this comment.
Thanks for addressing my previous review. Looks good! 👍🏼
|
Thanks for all your work here @djoseph-apphelix ! If you have time to look into the follow ups like #3292 and #3293 , please do so :) |




Description
Adds a built-in editor for the Games XBlock (flashcards and matching games, with images and alt text), wired the way the PDF editor is (#2916). Following review, this replaces the XBlockEditorSlot/plugin approach this PR started with; built-in editors can move to plugins once frontend-base is available.
src/editors/containers/GamesEditor/, registered asgamesinblockTypesandsupportedEditors. TypeScript throughout. It loads and saves through the block's own handlers (get_settings,save_settings,upload_image) using React Query hooks indata/apiHooks.ts, and keeps its form state in a local reducer (data/useGameState.ts). Nothing is added to the Redux store. The generatedgamescaffold editor and its stub Redux slice are removed.newXBlockEditoronly for the block types it routes itself; every other Edit click arrives as the legacyeditXBlockmessage. The unit page now checks this app's own registry (src/editors/hasBuiltInEditor.ts: an entry insupportedEditors, subject to that type's opt-out flag, currently onlyuseNewPdfEditor) and opens the built-in editor when there is one. The Games block has nostudio_view, so the legacy modal has nothing to show for it.editorsNeedingExistingBlock).EditorContaineronSave. An optional override for editors that persist through their own handler; the shared save thunk only builds payloads forhtml,problem,videoandpdf, and would drop the image storage keys this block needs.validateEntrystill gates the save. While it is pending, Save, Cancel, close and title editing are disabled, and a rejection shows the existing save-failed toast.TitleHeaderis converted to TypeScript.sharedComponents/Buttonandgeneric/DraggableListare converted to TypeScript.DraggableListnow computes the new order outside thesetStateupdater, soupdateOrderalways receives it.Who is affected
hasBuiltInEditor, so a future built-in editor does not need an edx-platform change.gamesto the course's Advanced Module List.Screenshots
Shown in the editor's fullscreen mode.
Flashcards. Cards collapse to a preview (card 1 shows its image thumbnail); the sidebar holds the game type and the shuffle setting.
Image alt text. Each flashcard image has its own settings dialog for alt text, which is required. The block shows the card's text to learners when an image has none.
Matching. Switching the type removes the image controls and adds the timer setting.
Validation. A card with a term but no definition blocks the save; the alert and the flagged field are shown, and nothing is sent.
Supporting information
Testing instructions
"games"to Advanced Module List./course/<course_id>/editor/games/<usage_key>directly. The editor opens, and Save returns to the unit.legacy_studio.pdf_editorwaffle flag enabled it opens the legacy modal.Other information
container.jsis unchanged; the unit page routes Games (and any future built-in editor) from this app'ssupportedEditors.handler_url, as the PDF editor does; legacy (v1) library blocks use the fixed handler route.upload_imagehandler, and the stored file keys (*_image_path) are sent back on save so a card keeps its link to its file.Best Practices Checklist
We're trying to move away from some deprecated patterns in this codebase. Please
check if your PR meets these recommendations before asking for a review:
.ts,.tsx).propTypesanddefaultPropsin any new or modified code.src/testUtils.tsx(specificallyinitializeMocks)apiHooks.tsin this repo for examples.messages.tsfiles have adescriptionfor translators to use.../in import paths. To import from parent folders, use@src, e.g.import { initializeMocks } from '@src/testUtils';instead offrom '../../../../testUtils'