From f312d42766a0d5166c59163ee5e2b1fdaa4d4c1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o?= Date: Fri, 27 Nov 2026 22:06:59 +0000 Subject: [PATCH 1/5] fix(gallery): detect a mounted image editor by its body, not a .gallery-editor descendant _buildEditor() replaces the container's class with `gallery-editor`, so the `#gallery-editor-container .gallery-editor` descendant checks in gallery.js, galleryEditor.js and ui.js never matched. They only behaved because isEditorOpen() or __galleryEditLive sat next to them; the global Escape guard in ui.js had no such fallback and was always false. closeEditor() also leaves that class on the container, so the landing shown after a close carries it too. Matching the container class instead would treat that landing as a mounted editor. Check for the editor body element, which only exists while the editor is built. --- static/js/gallery.js | 14 +- static/js/galleryEditor.js | 5 +- static/js/ui.js | 9 +- ...t_gallery_editor_mounted_checks_browser.py | 254 ++++++++++++++++++ 4 files changed, 277 insertions(+), 5 deletions(-) create mode 100644 tests/test_gallery_editor_mounted_checks_browser.py diff --git a/static/js/gallery.js b/static/js/gallery.js index 42f05dff2b..36e1bc8404 100644 --- a/static/js/gallery.js +++ b/static/js/gallery.js @@ -30,6 +30,14 @@ let _galleryResizeHandler = null; let _editorMod = null; let _editorLoading = false; +// True while the editor DOM is built in the Edit tab. _buildEditor() puts the +// `gallery-editor` class on the container itself and closeEditor() leaves it +// there, so neither that class nor a `.gallery-editor` descendant can tell the +// editor from the landing. The editor body only exists while it is mounted. +function _editorMounted() { + return !!document.querySelector('#gallery-editor-container > .ge-editor-body'); +} + // The editor shell is mounted before the size prompt resolves. A cancellation // can therefore finish while the Gallery loader's transient flag is stale; // restore the visible landing from the DOM after the editor tears down. @@ -37,7 +45,7 @@ if (!window.__galleryEditorSetupCancelHandler) { window.__galleryEditorSetupCancelHandler = () => { const container = document.getElementById('gallery-editor-container'); const tab = document.querySelector('#gallery-editor-tab.active'); - if (container && tab && !container.querySelector('.gallery-editor')) { + if (container && tab && !_editorMounted()) { _renderEditorLanding(); } }; @@ -3169,7 +3177,7 @@ export function openGallery() { const editorVisible = !!( editorContainer && getComputedStyle(editorContainer).display !== 'none' && - editorContainer.querySelector('.gallery-editor') + _editorMounted() ); if (editorVisible || isEditorOpen()) { // The Gallery owns the earliest capture listener, so delegate to the @@ -3299,7 +3307,7 @@ export async function openGalleryImage(imageId) { } function _doCloseGallery() { - const editorMounted = !!document.querySelector('#gallery-editor-container .gallery-editor'); + const editorMounted = _editorMounted(); if ((window.__galleryEditLive || isEditorOpen() || editorMounted) && !window.__galleryAllowCloseEditor) { if (uiModule) uiModule.showToast('Close the edit tab first'); return; diff --git a/static/js/galleryEditor.js b/static/js/galleryEditor.js index d64d8f4c25..06292f10a8 100644 --- a/static/js/galleryEditor.js +++ b/static/js/galleryEditor.js @@ -388,8 +388,11 @@ function _cancelSamQuery(showToast = true) { return true; } +// _buildEditor() puts the `gallery-editor` class on the container itself and +// closeEditor() leaves it there, so the class says nothing about whether the +// editor is mounted. Its body element only exists while it is. function _galleryEditMounted() { - return !!document.querySelector('#gallery-editor-container .gallery-editor'); + return !!document.querySelector('#gallery-editor-container > .ge-editor-body'); } if (!window.__galleryEditEscHardGuardInstalled) { diff --git a/static/js/ui.js b/static/js/ui.js index bb8c4906fb..b765aef29d 100644 --- a/static/js/ui.js +++ b/static/js/ui.js @@ -1393,6 +1393,13 @@ if ('ontouchstart' in window || window.innerWidth <= 768) { // Priority: expanded library card → open chat thinking block → topmost modal. // Runs capture-phase + stopImmediatePropagation so per-modal ESC listeners // never also fire (which would otherwise close several modals at once). +// True while the Gallery image editor DOM is built. The editor puts the +// `gallery-editor` class on its container and leaves it there after closing, +// so only its body element tells a mounted editor from the Edit tab landing. +function _galleryEditorMounted() { + return !!document.querySelector('#gallery-editor-container > .ge-editor-body'); +} + if (!window._odyEscExpandGuard) { window._odyEscExpandGuard = true; @@ -1538,7 +1545,7 @@ if (!window._odyEscExpandGuard) { galleryModal && !galleryModal.classList.contains('hidden') && getComputedStyle(galleryEditor).display !== 'none' && - galleryEditor.querySelector('.gallery-editor') + _galleryEditorMounted() ); if (galleryEditing) { e.preventDefault(); diff --git a/tests/test_gallery_editor_mounted_checks_browser.py b/tests/test_gallery_editor_mounted_checks_browser.py new file mode 100644 index 0000000000..05fea4eec8 --- /dev/null +++ b/tests/test_gallery_editor_mounted_checks_browser.py @@ -0,0 +1,254 @@ +"""Run the shipped "is the image editor mounted?" guards against a real DOM. + +_buildEditor() replaces the container's class with `gallery-editor` and +closeEditor() leaves it there, so a `.gallery-editor` descendant never exists +and the class alone cannot tell the editor from the Edit tab landing. Each +guard below is extracted from its file with acorn and run in Chromium with +its neighbouring flags (isEditorOpen(), __galleryEditLive) forced false, so +only the DOM check decides the outcome. +""" +import json +import os +import subprocess +from pathlib import Path + +import pytest + +try: + from playwright.sync_api import sync_playwright +except ImportError: + sync_playwright = None + +ROOT = Path(__file__).resolve().parents[1] + +# Top-level helpers the guards may call; extracted when present so the call +# sites run against the real helper rather than a stub. +HELPERS = ("_editorMounted", "_galleryEditMounted", "_galleryEditorMounted") + +EXTRACT = r""" +const fs = require('node:fs'), acorn = require('acorn'); +const out = {}; +function parse(file) { + const source = fs.readFileSync(file, 'utf8'); + return [source, acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'module' })]; +} +function walk(node, visit) { + if (!node || typeof node !== 'object') return; + visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(v => walk(v, visit)); + else if (value && typeof value === 'object') walk(value, visit); + } +} +const helpers = new Set(HELPERS); +for (const [key, file] of [['gallery', 'static/js/gallery.js'], ['editor', 'static/js/galleryEditor.js'], ['ui', 'static/js/ui.js']]) { + const [source, tree] = parse(file); + const text = n => source.slice(n.start, n.end); + const found = { helpers: {} }; + for (const node of tree.body) { + if (node.type === 'FunctionDeclaration' && helpers.has(node.id.name)) found.helpers[node.id.name] = text(node); + } + walk(tree, node => { + if (node.type === 'FunctionDeclaration' && node.id?.name === '_doCloseGallery') found.doClose = text(node); + if (node.type === 'AssignmentExpression' && node.left.type === 'MemberExpression' + && node.left.property?.name === '__galleryEditorSetupCancelHandler') found.cancel = text(node.right); + if (node.type === 'AssignmentExpression' && node.left.name === '_escHandler' + && node.right.type === 'ArrowFunctionExpression') found.esc = text(node.right); + if (node.type === 'CallExpression' && node.callee?.property?.name === 'addEventListener' + && node.callee.object?.name === 'document' && node.arguments[0]?.value === 'keydown' + && /gallery-editor-container/.test(text(node.arguments[1] || node))) found.uiEsc = text(node.arguments[1]); + }); + out[key] = found; +} +process.stdout.write(JSON.stringify(out)); +""" + +# Runs `source` with every free identifier resolved through a scope: names in +# `overrides` win, real browser globals pass through, anything else becomes a +# recording stub (callable, with stub properties) so module-private +# collaborators the guard never reaches stay inert. +HARNESS = r""" +window.__runGuard = (source, overrides) => { + const calls = []; + const stub = (path) => new Proxy(function () {}, { + get: (_t, key) => (key === Symbol.toPrimitive ? undefined : stub(`${path}.${String(key)}`)), + apply: (_t, _this, args) => { calls.push([path, ...args.map(a => (typeof a === 'string' ? a : typeof a))]); }, + }); + const local = { ...overrides }; + const scope = new Proxy(local, { + has: (_t, key) => key !== Symbol.unscopables, + get: (_t, key) => { + if (key === Symbol.unscopables) return undefined; + if (key in local) return local[key]; + if (key in globalThis) { + // `with` calls a resolved function with the scope as `this`; DOM + // functions such as getComputedStyle need the window instead. + // Constructors (Set, Object, ...) are left unbound to keep statics. + const value = globalThis[key]; + return typeof value === 'function' && /^[a-z]/.test(key) ? value.bind(globalThis) : value; + } + return stub(String(key)); + }, + set: (_t, key, value) => { local[key] = value; return true; }, + }); + // Sloppy-mode Function so `with` can supply the guard's free variables. + const fn = new Function('scope', `with (scope) { return (${source}); }`)(scope); + return { fn, calls, scope: local }; +}; +""" + +STATES = { + # The editor as _buildEditor() leaves it: class moved onto the container. + "mounted": '', + # Edit tab landing after one open/close: the stale class is still there. + "landing-after-close": '', + # Edit tab landing before the editor was ever opened. + "landing-fresh": '', +} + + +@pytest.fixture(scope="module") +def sources(): + script = EXTRACT.replace("HELPERS", json.dumps(list(HELPERS))) + result = subprocess.run(["node", "-e", script], cwd=ROOT, capture_output=True, text=True, check=True) + data = json.loads(result.stdout) + assert data["gallery"].get("cancel"), "setup-cancel handler not found in gallery.js" + assert data["gallery"].get("esc"), "_escHandler not found in gallery.js" + assert data["gallery"].get("doClose"), "_doCloseGallery not found in gallery.js" + assert data["editor"]["helpers"].get("_galleryEditMounted"), "_galleryEditMounted not found" + assert data["ui"].get("uiEsc"), "ui.js Escape listener not found" + return data + + +@pytest.fixture(scope="module") +def browser_instance(): + if sync_playwright is None: + pytest.fail("playwright is required for gallery editor browser tests. Install requirements-dev.txt") + with sync_playwright() as playwright: + launch_kwargs = {"headless": True, "args": ["--disable-dev-shm-usage", "--no-sandbox"]} + if os.environ.get("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH"): + launch_kwargs["executable_path"] = os.environ["PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH"] + browser = playwright.chromium.launch(**launch_kwargs) + try: + yield browser + finally: + if browser.is_connected(): + browser.close() + + +@pytest.fixture +def page(browser_instance): + context = browser_instance.new_context() + try: + page = context.new_page() + yield page + finally: + context.close() + + +def _mount(page, state): + page.set_content( + '" + ) + page.evaluate(HARNESS) + + +def _run(page, file_sources, body, state): + _mount(page, state) + return page.evaluate( + """([helpers, source, body]) => { + const overrides = { isEditorOpen: () => false, _editorLoading: false }; + window.__galleryEditLive = false; + window.__galleryAllowCloseEditor = false; + // Helpers resolve through the same scope as the guard that calls them. + const shared = window.__runGuard('null', overrides).scope; + for (const [name, src] of Object.entries(helpers)) { + shared[name] = window.__runGuard(src, shared).fn; + } + const run = window.__runGuard(source, shared); + return new Function('run', body)(run); + }""", + [file_sources["helpers"], file_sources["_src"], body], + ) + + +def _with(file_sources, key): + return {**file_sources, "_src": file_sources[key]} + + +@pytest.mark.parametrize("state,expect_landing", [ + ("mounted", False), + ("landing-after-close", True), + ("landing-fresh", True), +]) +def test_setup_cancel_handler_restores_landing_only_when_editor_is_gone(page, sources, state, expect_landing): + rendered = _run(page, _with(sources["gallery"], "cancel"), """ + run.fn(); + return run.calls.some(c => c[0] === '_renderEditorLanding'); + """, state) + assert rendered is expect_landing + + +@pytest.mark.parametrize("state,expect_editor_owns_escape", [ + ("mounted", True), + ("landing-after-close", False), + ("landing-fresh", False), +]) +def test_gallery_escape_keeps_the_gallery_open_while_editor_is_mounted(page, sources, state, expect_editor_owns_escape): + result = _run(page, _with(sources["gallery"], "esc"), """ + let delegated = 0; + window.__galleryEditorHandleEscape = () => { delegated++; }; + const e = { key: 'Escape', prevented: false, preventDefault() { this.prevented = true; }, stopImmediatePropagation() {} }; + run.fn(e); + return { closed: run.calls.some(c => c[0] === 'closeGallery'), delegated, prevented: e.prevented }; + """, state) + if expect_editor_owns_escape: + assert result == {"closed": False, "delegated": 1, "prevented": True} + else: + assert result == {"closed": True, "delegated": 0, "prevented": False} + + +@pytest.mark.parametrize("state,expect_refused", [ + ("mounted", True), + ("landing-after-close", False), + ("landing-fresh", False), +]) +def test_close_gallery_refuses_while_editor_is_mounted(page, sources, state, expect_refused): + result = _run(page, _with(sources["gallery"], "doClose"), """ + run.fn(); + return { + toast: run.calls.some(c => c[0] === 'uiModule.showToast' && c[1] === 'Close the edit tab first'), + closedEditor: run.calls.some(c => c[0] === 'closeEditor'), + }; + """, state) + assert result == {"toast": expect_refused, "closedEditor": not expect_refused} + + +@pytest.mark.parametrize("state,expected", [ + ("mounted", True), + ("landing-after-close", False), + ("landing-fresh", False), +]) +def test_editor_module_mounted_helper_matches_the_built_editor(page, sources, state, expected): + editor = sources["editor"] + mounted = _run(page, {**editor, "_src": editor["helpers"]["_galleryEditMounted"]}, "return run.fn();", state) + assert mounted is expected + + +@pytest.mark.parametrize("state,expect_swallowed", [ + ("mounted", True), + ("landing-after-close", False), + ("landing-fresh", False), +]) +def test_global_escape_leaves_the_gallery_to_the_mounted_editor(page, sources, state, expect_swallowed): + swallowed = _run(page, _with(sources["ui"], "uiEsc"), """ + const e = { key: 'Escape', defaultPrevented: false, target: document.body, stopped: false, + preventDefault() {}, stopImmediatePropagation() { this.stopped = true; } }; + run.fn(e); + return e.stopped; + """, state) + assert swallowed is expect_swallowed From 28d954c562bd3586f0814eba65c1adb664f702f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o?= Date: Sat, 28 Nov 2026 14:37:02 +0000 Subject: [PATCH 2/5] fix(editor): close the editor and show the landing when a draft or image fails to load openEditor() mounts the editor shell before it fetches the draft or image. When that fails (draft not found, draft data that cannot be restored, image onerror) it called closeEditor() without force. state.editorOpen is true at that point, so the close was refused: the user got "Close the edit tab first" on top of the real error and was left in an empty editor. The three failure paths now close with force and dispatch gallery-editor-setup-cancelled, the same way a cancelled New canvas does, so the Gallery renders the Edit tab landing again. Forcing the close makes a stale failure dangerous: a slow draft fetch from a session the user already closed could tear down the session opened after it. The failure paths therefore check that the session they belong to is still the open one, like the save pipeline already does, and stay silent otherwise. --- static/js/galleryEditor.js | 25 ++++- .../photo-editor/load-failure-close.spec.js | 106 ++++++++++++++++++ 2 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 tests/e2e/photo-editor/load-failure-close.spec.js diff --git a/static/js/galleryEditor.js b/static/js/galleryEditor.js index 06292f10a8..296fc070ab 100644 --- a/static/js/galleryEditor.js +++ b/static/js/galleryEditor.js @@ -13834,6 +13834,11 @@ export function openEditor(imageUrl, imageId, presetSize, displayName, draftId) state.draftName = displayName || (presetSize ? `New ${presetSize.w}×${presetSize.h}` : 'Untitled'); state.editorSessionToken += 1; state.editorOpen = true; + const openSession = state.editorSessionToken; + // A load failure for this call must close the shell it mounted, but only + // while that shell is still the open one: by the time a slow fetch fails + // the user may have closed it and opened something else. + const isCurrentOpen = () => state.editorOpen && state.editorSessionToken === openSession; state.documentRevision = 0; state.persistingRevision = 0; state.savedRevision = 0; @@ -13942,9 +13947,10 @@ export function openEditor(imageUrl, imageId, presetSize, displayName, draftId) .then(d => { if (!state.editorOpen) return; if (!d) { + if (!isCurrentOpen()) return; _unmountEditorLoading(); if (uiModule) uiModule.showToast('Draft not found'); - closeEditor(); + _closeEditorAfterLoadFailure(); return; } state.draftId = d.id; @@ -13966,11 +13972,11 @@ export function openEditor(imageUrl, imageId, presetSize, displayName, draftId) }); }) .catch(err => { - if (!state.editorOpen) return; + if (!isCurrentOpen()) return; _unmountEditorLoading(); console.warn('[ge] draft load failed', err); if (uiModule) uiModule.showToast(`Failed to load draft: ${err?.message || 'invalid project data'}`, 7000); - closeEditor(); + _closeEditorAfterLoadFailure(); }); } @@ -14098,15 +14104,26 @@ export function openEditor(imageUrl, imageId, presetSize, displayName, draftId) _schedulePersist(); }; img.onerror = (e) => { + if (!isCurrentOpen()) return; console.error('[_loadSourceImage] onerror — failed to load', imageUrl, e); _removeLoading(); if (uiModule) uiModule.showToast('Failed to load image'); - closeEditor(); + _closeEditorAfterLoadFailure(); }; img.src = imageUrl; } } +// openEditor() mounts the editor shell before it knows whether the draft or +// image it was given can be loaded. When it cannot, the shell is ours to tear +// down: the user-facing close guard would refuse (the editor counts as open) +// and leave an empty editor behind. The setup-cancelled event puts the +// Gallery's Edit tab landing back, as for a cancelled New canvas. +function _closeEditorAfterLoadFailure() { + closeEditor({ force: true }); + window.dispatchEvent(new CustomEvent('gallery-editor-setup-cancelled')); +} + // Update the gallery's Edit tab label to reflect what's currently open. // Pass null to reset to plain "Edit". Only mutates the inner label span // so the SVG icon next to it survives the update. diff --git a/tests/e2e/photo-editor/load-failure-close.spec.js b/tests/e2e/photo-editor/load-failure-close.spec.js new file mode 100644 index 0000000000..9b02bf8986 --- /dev/null +++ b/tests/e2e/photo-editor/load-failure-close.spec.js @@ -0,0 +1,106 @@ +const { test, expect } = require('@playwright/test'); + +// When openEditor() cannot load what it was asked to open, it has to close +// the shell it already mounted and give the Edit tab its landing back. A +// plain closeEditor() there is refused (the editor counts as open), which +// left an empty editor behind with a misleading "Close the edit tab first". + +let toasts; + +test.beforeEach(async ({ page }) => { + toasts = []; + // showToast() logs every toast through this endpoint, which makes it a + // reliable record of what the user was shown, in order. + await page.route('**/api/tasks/notification-logs*', async route => { + if (route.request().method() === 'POST') { + try { toasts.push(JSON.parse(route.request().postData() || '{}').body); } catch (_) {} + } + await route.fulfill({ json: { logs: [], notifications: [] } }); + }); + await page.goto('/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('ge-preflight-dismissed', '1')); + await page.locator('#tool-gallery-btn').waitFor({ state: 'attached', timeout: 20_000 }); + await page.evaluate(async () => { + window.__photoEditorImport = path => import(path); + const gallery = await window.__photoEditorImport('/static/js/gallery.js?v=20260830editor4'); + gallery.openGallery(); + }); + await page.locator('#gallery-editor-tab').waitFor({ state: 'visible', timeout: 20_000 }); + await page.locator('#gallery-editor-tab').click(); + await expect(page.locator('#gallery-editor-container .gallery-editor-landing')).toBeVisible(); +}); + +async function openEditor(page, args) { + await page.evaluate(async openArgs => { + const editor = await window.__photoEditorImport('/static/js/galleryEditor.js'); + editor.openEditor(...openArgs); + }, args); +} + +async function expectBackOnLanding(page, expectedToast) { + await expect.poll(() => toasts).toContain(expectedToast); + await expect(page.locator('#gallery-editor-container .gallery-editor-landing')).toBeVisible(); + expect(await page.evaluate(async () => { + const editor = await window.__photoEditorImport('/static/js/galleryEditor.js'); + return { + open: editor.isEditorOpen(), + mounted: !!document.querySelector('#gallery-editor-container > .ge-editor-body'), + bodyClass: document.body.classList.contains('ge-editor-open'), + galleryOpen: !document.getElementById('gallery-modal').classList.contains('hidden'), + }; + })).toEqual({ open: false, mounted: false, bodyClass: false, galleryOpen: true }); + // Give a late refusal toast time to show up before asserting it never did. + await page.waitForTimeout(500); + expect(toasts).toEqual([expectedToast]); +} + +test('opening a draft id that does not exist returns to the landing', async ({ page }) => { + await page.route('**/api/editor-drafts/no-such-draft-id', route => route.fulfill({ + status: 404, json: { detail: 'Not found' }, + })); + await openEditor(page, [null, null, null, 'Missing draft', 'no-such-draft-id']); + await expectBackOnLanding(page, 'Draft not found'); +}); + +test('a draft whose project data cannot be restored returns to the landing', async ({ page }) => { + await page.route('**/api/editor-drafts/broken-draft-id', route => route.fulfill({ + json: { id: 'broken-draft-id', name: 'Broken', payload: { version: 1, imgWidth: 0, imgHeight: 0, layers: [] } }, + })); + await openEditor(page, [null, null, null, 'Broken draft', 'broken-draft-id']); + await expect.poll(() => toasts.length).toBeGreaterThan(0); + expect(toasts[0]).toMatch(/^Failed to load draft: /); + await expectBackOnLanding(page, toasts[0]); +}); + +test('an image that fails to load returns to the landing', async ({ page }) => { + await page.route('**/api/editor-drafts', route => route.fulfill({ json: { drafts: [] } })); + await page.route('**/no-such-image.png', route => route.fulfill({ status: 404, body: '' })); + await openEditor(page, ['/static/no-such-image.png', 'no-such-image', null, 'Missing image']); + await expectBackOnLanding(page, 'Failed to load image'); +}); + +test('a load failure from a closed session leaves the next session open', async ({ page }) => { + let releaseDraft; + const draftHeld = new Promise(resolve => { releaseDraft = resolve; }); + await page.route('**/api/editor-drafts/slow-missing-draft', async route => { + await draftHeld; + await route.fulfill({ status: 404, json: { detail: 'Not found' } }); + }); + await openEditor(page, [null, null, null, 'Slow draft', 'slow-missing-draft']); + await page.evaluate(async () => { + const editor = await window.__photoEditorImport('/static/js/galleryEditor.js'); + editor.closeEditor({ force: true }); + editor.openEditor(null, null, { w: 320, h: 240 }, 'Next session'); + }); + await page.locator('.ge-main-canvas').waitFor({ state: 'visible', timeout: 20_000 }); + toasts.length = 0; + releaseDraft(); + // The stale "not found" answer for the first session must not close the + // second one, nor tell the user about a draft they are no longer opening. + await page.waitForTimeout(1000); + expect(await page.evaluate(async () => { + const editor = await window.__photoEditorImport('/static/js/galleryEditor.js'); + return { open: editor.isEditorOpen(), mounted: !!document.querySelector('.ge-main-canvas') }; + })).toEqual({ open: true, mounted: true }); + expect(toasts).toEqual([]); +}); From 657a94df188b52d30ab8ef9fae57de8d970eb6de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o?= Date: Sat, 28 Nov 2026 21:25:29 +0000 Subject: [PATCH 3/5] fix(editor): reset the Edit tab label after the editor closes closeEditor() reset the Gallery's Edit tab label before it set state.editorOpen to false. _setEditTabLabel(null) writes "Edit" and then re-renders the document tabs, and that renderer only checks state.editorOpen, so it wrote "Edit: " straight back. Every close path left the old name on the tab: the tab x, a cancelled New canvas and the load-failure closes. Reset the label once the editor no longer counts as open. The document tab strip is unchanged while the editor is open; the new spec also checks it with two documents. --- static/js/galleryEditor.js | 5 +- tests/e2e/photo-editor/edit-tab-label.spec.js | 61 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 tests/e2e/photo-editor/edit-tab-label.spec.js diff --git a/static/js/galleryEditor.js b/static/js/galleryEditor.js index 296fc070ab..962f8978eb 100644 --- a/static/js/galleryEditor.js +++ b/static/js/galleryEditor.js @@ -14174,13 +14174,16 @@ export function closeEditor(options = {}) { // Invalidate asynchronous encoding/network callbacks before tearing down // the document, so a late save cannot mutate the next editor session. state.editorSessionToken += 1; - _setEditTabLabel(null); _clearActiveEditorSession(); _unmountEditorLoading(); // The maximize control lives in the modal header while the editor is open; // drop it on close so the header keeps only the window's own buttons. document.querySelectorAll('.ge-header-max-btn').forEach((btn) => btn.remove()); state.editorOpen = false; + // Reset the Edit tab only now: _setEditTabLabel() re-renders the document + // tabs, which would write "Edit: " back while the editor still + // counted as open. + _setEditTabLabel(null); // Tear down the gallery multi-document tab strip. try { const _extraTabs = document.getElementById('gallery-editor-tabs-extra'); diff --git a/tests/e2e/photo-editor/edit-tab-label.spec.js b/tests/e2e/photo-editor/edit-tab-label.spec.js new file mode 100644 index 0000000000..48a6ec171b --- /dev/null +++ b/tests/e2e/photo-editor/edit-tab-label.spec.js @@ -0,0 +1,61 @@ +const { test, expect } = require('@playwright/test'); +const { openBlankEditor } = require('./helpers.js'); + +// The Gallery's Edit tab shows "Edit: " while a document is open and +// plain "Edit" once the editor is closed. closeEditor() used to reset the +// label while the editor still counted as open, and the document tab strip +// immediately wrote the old name back. + +test.beforeEach(async ({ page }) => { + await page.route('**/api/tasks/notification-logs*', route => route.fulfill({ + json: { logs: [], notifications: [] }, + })); +}); + +const primaryLabel = page => page.locator('#gallery-editor-tab .gallery-tab-label'); +const extraTabs = page => page.locator('#gallery-editor-tabs-extra .gallery-tab'); + +test('closing the edit from the tab x resets the Edit tab label', async ({ page }) => { + // Open through the landing so the Gallery loads the editor itself, the same + // module instance its tab x and isEditorOpen() check talk to. + await page.goto('/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('ge-preflight-dismissed', '1')); + await page.locator('#tool-gallery-btn').click(); + await page.locator('#gallery-editor-tab').click(); + await page.locator('.gallery-editor-template-option').first().click(); + await page.locator('.ge-main-canvas').waitFor({ state: 'visible', timeout: 20_000 }); + await expect(primaryLabel(page)).toHaveText('Edit: 1024×1024'); + await expect(page.locator('#gallery-editor-tab')).toHaveClass(/has-edit/); + + await page.locator('#gallery-editor-tab').hover(); + await page.locator('#gallery-editor-tab-close').click(); + await page.locator('#styled-confirm-ok').click(); + + await expect(page.locator('.ge-main-canvas')).toHaveCount(0); + await expect(primaryLabel(page)).toHaveText('Edit'); + await expect(page.locator('#gallery-editor-tab')).not.toHaveClass(/has-edit/); + await expect(extraTabs(page)).toHaveCount(0); + + await page.locator('#gallery-editor-tab').click(); + await expect(page.locator('#gallery-editor-container .gallery-editor-landing')).toBeVisible(); + await expect(primaryLabel(page)).toHaveText('Edit'); +}); + +test('the document tab strip still follows the open documents up to the close', async ({ page }) => { + await openBlankEditor(page, { width: 320, height: 240 }, 'First doc'); + await page.evaluate(() => window.geEditorControl.invoke('document.create', { width: 200, height: 100, name: 'Second doc' })); + + await expect(primaryLabel(page)).toHaveText('Edit: Second doc'); + await expect(extraTabs(page)).toHaveText(['Edit: First doc×', '+']); + + // With two documents the tab x closes only the active one. + await page.locator('#gallery-editor-tab').hover(); + await page.locator('#gallery-editor-tab-close').click(); + await expect(primaryLabel(page)).toHaveText('Edit: First doc'); + await expect(extraTabs(page)).toHaveText(['+']); + expect(await page.evaluate(() => window.geGalleryEditor.isEditorOpen())).toBe(true); + + await page.evaluate(() => window.geGalleryEditor.closeEditor({ force: true })); + await expect(primaryLabel(page)).toHaveText('Edit'); + await expect(extraTabs(page)).toHaveCount(0); +}); From 759f10edcd13f5c35435cd4f6f1f540ecfb8ae1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o?= Date: Sun, 29 Nov 2026 10:36:12 +0000 Subject: [PATCH 4/5] fix(gallery): keep a live edit reachable after the sheet is hidden With an edit open, closing the Gallery is refused ("Close the edit tab first"), but two paths still hid the sheet and left it unreachable: - the sidebar Gallery button: closeGallery() goes through Modals.close(), which hides and unregisters the node even when closeFn refuses; - a swipe-down on the sheet header (ui.js), which hides the node and fires modal-dismissed without asking the gallery. In both cases _open stayed true, so every later tap went back to the refused close and the edit was stranded in memory. closeGallery() now refuses before calling Modals.close(), so the button leaves the sheet in place and only shows the toast. When the sheet is hidden while an edit is live, isGalleryOpen() reports false and openGallery() shows the existing sheet again (re-registering it with the modal manager if needed) instead of building a new one. The swipe gesture itself is unchanged. --- static/js/gallery.js | 54 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/static/js/gallery.js b/static/js/gallery.js index 36e1bc8404..f981ebf65d 100644 --- a/static/js/gallery.js +++ b/static/js/gallery.js @@ -2277,7 +2277,11 @@ export function openGallery() { // A cancelled lazy-open or an external modal teardown can leave the // module flag set after the DOM node has gone away. Do not let that stale // flag permanently block opening or refresh restoration. - if (document.getElementById('gallery-modal')) return; + const existing = document.getElementById('gallery-modal'); + if (existing) { + if (_isHiddenWithLiveEdit(existing)) _reshowGallery(existing); + return; + } _open = false; } _open = true; @@ -2405,12 +2409,7 @@ export function openGallery() { `; document.body.appendChild(modal); - Modals.register('gallery-modal', { - railBtnId: 'rail-gallery', - sidebarBtnId: 'tool-gallery-btn', - closeFn: () => _doCloseGallery(), - restoreFn: () => {}, - }); + _registerGalleryModal(); // Allow dragging the modal by its header — same pattern as Email Library, // Sessions, etc. The tileManager (corner/edge snap-tiling) listens on @@ -3306,6 +3305,41 @@ export async function openGalleryImage(imageId) { } } +function _isEditLive() { + return !!(window.__galleryEditLive || isEditorOpen() || _editorMounted()); +} + +function _registerGalleryModal() { + Modals.register('gallery-modal', { + railBtnId: 'rail-gallery', + sidebarBtnId: 'tool-gallery-btn', + closeFn: () => _doCloseGallery(), + restoreFn: () => {}, + }); +} + +// A swipe-dismiss (ui.js) hides the sheet without asking the gallery, and a +// close refused because an edit is live still leaves Modals.close() hiding +// the node. Either way the edit is alive behind a hidden sheet. +function _isHiddenWithLiveEdit(modal) { + return !!modal && modal.classList.contains('hidden') + && !modal.classList.contains('modal-minimized') && _isEditLive(); +} + +function _reshowGallery(modal) { + const content = modal.querySelector('.modal-content'); + if (content) { + content.classList.remove('modal-closing'); + content.style.transform = ''; + content.style.transition = ''; + } + modal.style.display = ''; + modal.classList.remove('hidden'); + if (!Modals.isRegistered('gallery-modal')) _registerGalleryModal(); + const btn = document.getElementById('tool-gallery-btn'); + if (btn) btn.classList.add('active'); +} + function _doCloseGallery() { const editorMounted = _editorMounted(); if ((window.__galleryEditLive || isEditorOpen() || editorMounted) && !window.__galleryAllowCloseEditor) { @@ -3347,7 +3381,10 @@ function _doCloseGallery() { export function closeGallery() { if (!_open && !Modals.isMinimized('gallery-modal')) return; - if (Modals.isRegistered('gallery-modal')) { + // Modals.close() hides and unregisters the node even when closeFn refuses, + // which would strand a live edit. Let _doCloseGallery() refuse on its own. + const refused = _isEditLive() && !window.__galleryAllowCloseEditor; + if (!refused && Modals.isRegistered('gallery-modal')) { Modals.close('gallery-modal'); } else { _doCloseGallery(); @@ -3356,6 +3393,7 @@ export function closeGallery() { export function isGalleryOpen() { if (Modals.isMinimized('gallery-modal')) return false; + if (_open && _isHiddenWithLiveEdit(document.getElementById('gallery-modal'))) return false; return _open; } From a8121de248070541faefea157794139165e73144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o?= Date: Sun, 29 Nov 2026 11:08:36 +0000 Subject: [PATCH 5/5] test(gallery): cover the live-edit lockout from the button, a swipe and the dock Phone viewport, real app. With an edit open, the Gallery button must leave the sheet visible, and one tap must bring back the same edit (same layer count) after a CDP touch swipe on the header or a refused dock close. All three fail on dev. --- .../gallery-live-edit-reopen.spec.js | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 tests/e2e/photo-editor/gallery-live-edit-reopen.spec.js diff --git a/tests/e2e/photo-editor/gallery-live-edit-reopen.spec.js b/tests/e2e/photo-editor/gallery-live-edit-reopen.spec.js new file mode 100644 index 0000000000..90fb7bcb76 --- /dev/null +++ b/tests/e2e/photo-editor/gallery-live-edit-reopen.spec.js @@ -0,0 +1,106 @@ +const { test, expect } = require('@playwright/test'); + +// With an edit open the Gallery refuses to close ("Close the edit tab +// first"). Neither the sidebar button nor a swipe-down on the sheet may leave +// that edit stranded behind a hidden sheet. + +test.use({ viewport: { width: 390, height: 844 }, hasTouch: true }); + +const layerCount = page => page.evaluate(async () => { + const { state } = await import('/static/js/editor/state.js'); + return state.layers.length; +}); + +// The button lives in the sidebar, which is closed on a phone. Click it the +// way app.js wires it, through the app's own gallery module instance. +const tapGalleryButton = page => page.evaluate(() => document.getElementById('tool-gallery-btn').click()); + +async function openGalleryEdit(page) { + await page.goto('/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('ge-preflight-dismissed', '1')); + await page.locator('#tool-gallery-btn').waitFor({ state: 'attached', timeout: 20_000 }); + await tapGalleryButton(page); + await expect(page.locator('#gallery-modal')).toBeVisible(); + await page.locator('#gallery-editor-tab').click(); + await page.locator('.gallery-editor-template-option').first().click(); + await page.locator('.ge-main-canvas').waitFor({ state: 'visible', timeout: 20_000 }); + await page.locator('.ge-tour-close').click({ timeout: 500 }).catch(() => {}); + await page.evaluate(async () => { + const result = await window.geEditorControl.invoke('layers.addRaster', {}); + if (!result?.ok) throw new Error(result?.error || 'layers.addRaster failed'); + }); + const layers = await layerCount(page); + expect(layers).toBeGreaterThan(1); + return layers; +} + +async function swipeSheetDown(page) { + // A touch that starts on the header but outside its buttons and tabs is + // what ui.js treats as swipe-to-dismiss. + const start = await page.evaluate(() => { + const header = document.querySelector('#gallery-modal .modal-header'); + const rect = header.getBoundingClientRect(); + for (let x = rect.left + 4; x < rect.right - 4; x += 6) { + for (const y of [rect.top + 4, rect.top + rect.height / 2, rect.bottom - 4]) { + const el = document.elementFromPoint(x, y); + if (el && header.contains(el) && !el.closest('button, a, input, select')) return { x, y }; + } + } + return null; + }); + expect(start).toBeTruthy(); + const cdp = await page.context().newCDPSession(page); + const point = y => [{ x: start.x, y, id: 1, radiusX: 6, radiusY: 6 }]; + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: point(start.y) }); + for (let step = 1; step <= 15; step += 1) { + await page.waitForTimeout(16); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: point(start.y + step * 30) }); + } + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await expect(page.locator('#gallery-modal')).toBeHidden(); +} + +test('the Gallery button keeps the sheet open while an edit is live', async ({ page }) => { + const layers = await openGalleryEdit(page); + + await tapGalleryButton(page); + await expect(page.locator('#toast')).toContainText('Close the edit tab first'); + await expect(page.locator('#gallery-modal')).toBeVisible(); + + await tapGalleryButton(page); + await expect(page.locator('#gallery-modal')).toBeVisible(); + expect(await layerCount(page)).toBe(layers); +}); + +test('one tap brings back a Gallery swiped away during an edit', async ({ page, browserName }) => { + test.skip(browserName !== 'chromium', 'Uses Chromium CDP touch injection'); + const layers = await openGalleryEdit(page); + + await swipeSheetDown(page); + expect(await layerCount(page)).toBe(layers); + + await tapGalleryButton(page); + await expect(page.locator('#gallery-modal')).toBeVisible(); + await expect(page.locator('#gallery-editor-container .ge-main-canvas')).toBeVisible(); + expect(await layerCount(page)).toBe(layers); +}); + +test('one tap brings back a Gallery hidden by a refused dock close', async ({ page }) => { + const layers = await openGalleryEdit(page); + + // The dock closes a tool through Modals.close(), which hides and + // unregisters the sheet even though the Gallery refuses. + await page.evaluate(async () => { + const modals = await import('/static/js/modalManager.js'); + modals.close('gallery-modal'); + }); + await expect(page.locator('#gallery-modal')).toBeHidden(); + + await tapGalleryButton(page); + await expect(page.locator('#gallery-modal')).toBeVisible(); + expect(await layerCount(page)).toBe(layers); + expect(await page.evaluate(async () => { + const modals = await import('/static/js/modalManager.js'); + return modals.isRegistered('gallery-modal'); + })).toBe(true); +});