diff --git a/static/js/gallery.js b/static/js/gallery.js index 42f05dff2b..f981ebf65d 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(); } }; @@ -2269,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; @@ -2397,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 @@ -3169,7 +3176,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 @@ -3298,8 +3305,43 @@ 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 = !!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; @@ -3339,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(); @@ -3348,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; } diff --git a/static/js/galleryEditor.js b/static/js/galleryEditor.js index 43f79e87fc..c6966b7082 100644 --- a/static/js/galleryEditor.js +++ b/static/js/galleryEditor.js @@ -275,8 +275,11 @@ function _onEditorSessionEnd(fn) { _editorSession?.signal.addEventListener('abort', fn, { once: 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) { @@ -3149,6 +3152,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; @@ -3257,9 +3265,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; @@ -3281,11 +3290,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(); }); } @@ -3413,15 +3422,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. @@ -3472,13 +3492,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/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/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); +}); 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); +}); 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([]); +}); 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