Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 57 additions & 11 deletions static/js/gallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,22 @@ 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.
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();
}
};
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -2397,12 +2409,7 @@ export function openGallery() {
</div>
`;
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand All @@ -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;
}

Expand Down
35 changes: 29 additions & 6 deletions static/js/galleryEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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();
});
}

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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: <name>" 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');
Expand Down
9 changes: 8 additions & 1 deletion static/js/ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down
61 changes: 61 additions & 0 deletions tests/e2e/photo-editor/edit-tab-label.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const { test, expect } = require('@playwright/test');
const { openBlankEditor } = require('./helpers.js');

// The Gallery's Edit tab shows "Edit: <name>" 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);
});
Loading
Loading