diff --git a/photomap/frontend/static/css/control-and-search-panels.css b/photomap/frontend/static/css/control-and-search-panels.css index ead22a3e..413e0a5b 100644 --- a/photomap/frontend/static/css/control-and-search-panels.css +++ b/photomap/frontend/static/css/control-and-search-panels.css @@ -245,75 +245,12 @@ display: none !important; } -@media (max-width: 600px) { - #panelStackContainer { - position: fixed; - left: 0; - right: 0; - bottom: 0; - width: 100vw; - display: flex; - flex-direction: column; - align-items: stretch; - z-index: 4000; - pointer-events: none; - } - - #searchPanel, - #controlPanel { - position: static !important; - width: 100vw; - /* Without this the side padding is added to 100vw, pushing the centred - icon row off the right-hand edge. */ - box-sizing: border-box; - margin: 0; - border-radius: 0; - box-shadow: none; - pointer-events: auto; - /* Remove any max-width if present */ - } - - #searchPanel { - order: 0; - border-bottom: 1px solid #222; - } - - #controlPanel { - order: 1; - border-top: 1px solid #222; - } - - /* Keep icons in a horizontal row */ - .control-icons-row, - .search-icons-row { - flex-direction: row !important; - align-items: center; - justify-content: center; - gap: 0.5em; - width: 100%; - } - - #controlPanel button, - #searchPanel button { - width: 48px; - height: 48px; - min-width: 48px; - min-height: 48px; - font-size: 2em; - } - - /* The rule above is less specific than #controlPanel button.menu-chevron, so - the chevron keeps its 16px width here; only the height needs restating to - stay flush with the 48px button it is attached to. */ - #controlPanel button.menu-chevron { - height: 48px; - min-height: 48px; - } -} +/* On phones the two panels stack inside the bottom sheet, which slides up and + down; that layout lives in mobile-sheets.css. */ -/* The two panels share the bottom edge until they stack at 600px, and with - seven icons in the Search panel they would run into each other on a tablet - in portrait (768-820px). The room comes out of the gaps between icons. Below +/* The two panels share the bottom edge until they move into the phone layout's + bottom sheet at 600px, and with seven icons in the Search panel they would + run into each other on a tablet in portrait (768-820px). The room comes out of the gaps between icons. Below about 745px they still overlap, by less than they would otherwise. */ @media (min-width: 601px) and (max-width: 860px) { .control-icons-row, diff --git a/photomap/frontend/static/css/grid-view.css b/photomap/frontend/static/css/grid-view.css index 7a967d7b..db11a130 100644 --- a/photomap/frontend/static/css/grid-view.css +++ b/photomap/frontend/static/css/grid-view.css @@ -8,6 +8,25 @@ height: calc(var(--visible-viewport-height, 100dvh) - var(--grid-top-reserve)); } +/* In the phone layout the badge is in the top sheet, which covers the grid + only by its handle unless the user pulls it open to seek. The bottom sheet + is another matter: open, it is two rows of buttons tall, and Swiper divides + the container's height between the grid rows, so the container has to stop + above it. --bottom-sheet-height follows the sheet as it opens and closes + (mobile-sheets.js), and grid-view.js re-counts the rows when it does. */ +.mobile-sheets #gridViewSwiper { + --grid-top-reserve: calc(var(--top-sheet-peek) + 6px); + height: calc( + var(--visible-viewport-height, 100dvh) - var(--grid-top-reserve) - var(--bottom-sheet-height, 0px) - 6px + ); +} + +/* The sheets are hidden in fullscreen, so the grid gets the whole height. */ +html.mobile-sheets:fullscreen #gridViewSwiper, +html.mobile-sheets:-webkit-full-screen #gridViewSwiper { + height: var(--visible-viewport-height, 100dvh); +} + /* The badge is hidden in fullscreen (seek-slider.css), so give the row back. */ :fullscreen #gridViewSwiper, :-webkit-full-screen #gridViewSwiper { diff --git a/photomap/frontend/static/css/mobile-sheets.css b/photomap/frontend/static/css/mobile-sheets.css new file mode 100644 index 00000000..6c0d2124 --- /dev/null +++ b/photomap/frontend/static/css/mobile-sheets.css @@ -0,0 +1,566 @@ +/* ===== Phone layout: top and bottom sheets ===== + + On small screens the Control and Search panels share one sheet at the + bottom of the window and the album badge and seek slider share one at the + top. Each slides between expanded and collapsed (only its grab handle left + showing), dragged or tapped — see mobile-sheets.js. The bottom sheet also + holds the metadata drawer's contents below the panels: at the expanded stop + only their title row shows, and its third, "details" stop opens them. + + Everything here is keyed off html.mobile-sheets, set from the media query in + main.html's , and the sheet states off + html[data-top-sheet] / html[data-bottom-sheet]. This file loads after the + panel and slider stylesheets, so at equal specificity its rules win. */ + +:root { + --bottom-sheet-peek: 24px; + /* The progress strip (4px) above the handle (22px). */ + --top-sheet-peek: 26px; + --sheet-background: rgba(20, 20, 20, 0.82); + --sheet-handle-color: rgba(255, 255, 255, 0.6); + /* The details' title row (file name over path): what of them shows at the + expanded stop. */ + --sheet-details-peek: 52px; +} + +/* Outside the phone layout the wrapper is not there as far as layout goes, and + the handles are not shown. */ +#topSheetContainer { + display: contents; +} + +.sheet-handle, +#sheetDetails { + display: none; +} + +/* ----- Common to both sheets ----- */ + +.mobile-sheets .mobile-sheet { + position: fixed; + left: 0; + right: 0; + box-sizing: border-box; + background: var(--sheet-background); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + /* The sheet owns vertical drags; nothing on it should scroll or zoom the + page. Range inputs still drag their thumb. */ + touch-action: none; + -webkit-tap-highlight-color: transparent; + pointer-events: auto; +} + +.mobile-sheets.sheets-ready .mobile-sheet { + transition: transform 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); +} + +.mobile-sheets.sheets-ready .mobile-sheet.sheet-dragging { + transition: none; +} + +.mobile-sheets .sheet-handle { + display: flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 100%; + margin: 0; + padding: 0; + background: none; + border: none; + cursor: grab; + -webkit-tap-highlight-color: transparent; +} + +/* The pill. */ +.mobile-sheets .sheet-handle::before { + content: ""; + width: 40px; + height: 5px; + border-radius: 3px; + background: var(--sheet-handle-color); +} + +.mobile-sheets .sheet-handle:focus-visible { + outline: 2px solid #fff; + outline-offset: -2px; +} + +/* Hidden with the rest of the controls in fullscreen. */ +html.mobile-sheets:fullscreen .mobile-sheet, +html.mobile-sheets:-webkit-full-screen .mobile-sheet { + display: none !important; +} + +/* ----- Bottom sheet: Search and Control panels ----- */ + +.mobile-sheets #panelStackContainer { + /* panel-anchor.js publishes how far an iPadOS-stranded layout viewport + hangs below the visible one; the sheet has to clear it just as the + free-floating panels did. */ + bottom: var(--visible-viewport-overshoot, 0px); + width: auto; + z-index: 4000; + display: flex; + flex-direction: row; + /* Upright, the second panel wraps under the first. Sideways the two share + one row, with the smaller buttons set below for short screens. */ + flex-wrap: wrap; + justify-content: center; + align-items: stretch; + padding: 0 4px; + border-radius: 14px 14px 0 0; + box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.35); +} + +.mobile-sheets #bottomSheetHandle { + flex-basis: 100%; + height: var(--bottom-sheet-peek); +} + +html.mobile-sheets[data-bottom-sheet="collapsed"] #panelStackContainer { + transform: translateY(calc(100% - var(--bottom-sheet-peek))); +} + +/* A phone held sideways has no toolbar under the page: the bottom edge is + where iOS takes a swipe up to go home (the home indicator's strip is about + 21px), and a handle that low loses its drags to it. Collapsed, the handle + grows to 40px and its pill moves to the top, about 30px clear of the edge, + so it is grabbed above that strip (34px proved too short on an iPhone 15). + Without viewport-fit=cover, env(safe-area-inset-bottom) reports nothing to + go by. */ +@media (max-height: 500px) and (pointer: coarse) { + html.mobile-sheets[data-bottom-sheet="collapsed"] { + --bottom-sheet-peek: 40px; + } + + html.mobile-sheets[data-bottom-sheet="collapsed"] #bottomSheetHandle { + align-items: flex-start; + padding-top: 8px; + } +} + +/* Once collapsed, nothing below the handle shows: the Grid View checkmark + overhangs its button upwards, into the strip left on screen. Hidden only + after the sheet has slid down (the delay), never while it is dragged, and + shown again at once when it opens. */ +html.mobile-sheets[data-bottom-sheet="collapsed"] #panelStackContainer:not(.sheet-dragging) > :not(.sheet-handle) { + visibility: hidden; + transition: visibility 0s linear 0.28s; +} + +/* Expanded: the details hang below the window, all but their title row. */ +html.mobile-sheets[data-bottom-sheet="expanded"] #panelStackContainer { + transform: translateY(calc(var(--sheet-details-height) - var(--sheet-details-peek))); +} + +/* The panels are now rows of the sheet rather than floating boxes. The sheet + supplies the background; panel-anchor.js's translate is applied to the + sheet through its bottom offset instead, so it must not move them within it. */ +.mobile-sheets #searchPanel, +.mobile-sheets #controlPanel { + position: static !important; + transform: none !important; + flex: 1 1 auto; + box-sizing: border-box; + margin: 0; + padding: 0.3em 0.3em; + background: none; + border-radius: 0; + box-shadow: none; + pointer-events: auto; +} + +.mobile-sheets #searchPanel { + border-bottom: 1px solid rgba(255, 255, 255, 0.08); +} + +/* Keep icons in a horizontal row. */ +.mobile-sheets .control-icons-row, +.mobile-sheets .search-icons-row { + flex-direction: row; + align-items: center; + justify-content: center; +} + +/* Thumb-sized targets, as the stacked phone panels always had. The narrow + screen rules in control-and-search-panels.css step them back down. */ +.mobile-sheets #controlPanel button, +.mobile-sheets #searchPanel button { + width: 48px; + height: 48px; + min-width: 48px; + min-height: 48px; +} + +/* Higher specificity than the rule above, so the chevron keeps its own width; + only its height follows the 48px button it is attached to. */ +.mobile-sheets #controlPanel button.menu-chevron { + width: 24px; + min-width: 24px; + height: 48px; + min-height: 48px; +} + +/* Phones held sideways: the window is too short to give two rows of panels, + so both share one. At 38px, with the gaps taken out, the two rows of icons + need about 610px, which every phone in landscape has. */ +@media (max-height: 500px) { + .mobile-sheets #panelStackContainer { + justify-content: space-evenly; + } + + .mobile-sheets #searchPanel, + .mobile-sheets #controlPanel { + flex: 0 1 auto; + padding: 0.15em 0.2em; + } + + .mobile-sheets #searchPanel { + border-bottom: none; + } + + .mobile-sheets .control-icons-row, + .mobile-sheets .search-icons-row { + gap: 1px; + } + + .mobile-sheets #controlPanel button, + .mobile-sheets #searchPanel button { + width: 38px; + height: 38px; + min-width: 38px; + min-height: 38px; + } + + .mobile-sheets #controlPanel button.menu-chevron { + width: 20px; + min-width: 20px; + height: 38px; + min-height: 38px; + } +} + +@media (max-width: 429px) { + .mobile-sheets #controlPanel button, + .mobile-sheets #searchPanel button { + width: 40px; + height: 40px; + min-width: 40px; + min-height: 40px; + } + + .mobile-sheets #controlPanel button.menu-chevron { + height: 40px; + min-height: 40px; + } +} + +/* The text search box opens from the Search panel; sit it above the sheet + instead of behind it, across the width of the phone. */ +.mobile-sheets #textSearchPanel { + left: 8px; + right: 8px; + min-width: 0; + /* panel-anchor.js lifts this box by the stranded-viewport overshoot with + its own translate, as it does the sheet with its bottom offset; so the + overshoot is not added here as well. */ + bottom: calc(var(--bottom-sheet-height, 160px) + 8px); + z-index: 4001; + box-sizing: border-box; + padding: 0.9em 0.9em; + /* Whatever room is left between the two sheets; scroll beyond that. */ + max-height: calc( + var(--visible-viewport-height, 100dvh) - var(--bottom-sheet-height, 160px) - var(--top-sheet-height, 26px) - 16px + ); + overflow-y: auto; +} + +/* Its two columns (image query beside the text fields) need well over a + phone's width; stack them, with each text field's label above it. */ +.mobile-sheets #textSearchPanel .search-input-container.vertical-search-inputs { + flex-direction: column; + gap: 0.8em; +} + +.mobile-sheets #textSearchPanel .search-image-column { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + justify-content: flex-start; + gap: 0.4em 1em; + min-width: 0; + max-width: none; + margin-right: 0; +} + +.mobile-sheets #textSearchPanel .search-image-label { + flex-basis: 100%; +} + +.mobile-sheets #textSearchPanel .search-image-column .search-row { + flex: 1 1 120px; + width: auto; +} + +.mobile-sheets #textSearchPanel .search-fields-column { + grid-template-columns: 1fr; + padding-right: 0; +} + +.mobile-sheets #textSearchPanel .search-fields-column .search-label, +.mobile-sheets #textSearchPanel .search-fields-column .search-field-wrapper { + grid-column: 1; +} + +.mobile-sheets #textSearchPanel .search-fields-column .search-label { + width: auto; + text-align: left; +} + +/* ----- Top sheet: album badge and seek slider ----- */ + +.mobile-sheets #topSheetContainer { + top: 0; + /* Under the semantic map (1000), as the badge always was, so the map's + titlebar is not covered; above the photo and grid. */ + z-index: 999; + display: flex; + flex-direction: column; + align-items: stretch; + padding: 6px 0 0; + border-radius: 0 0 14px 14px; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35); +} + +html.mobile-sheets[data-top-sheet="collapsed"] #topSheetContainer { + transform: translateY(calc(-100% + var(--top-sheet-peek))); +} + +/* The badge keeps its own pill (it carries the cluster colour) but sits in the + sheet instead of floating over the corner of the photo. */ +.mobile-sheets .fixed-score-display { + position: static; + align-self: flex-start; + max-width: calc(100% - 16px); + margin: 0 8px; + box-shadow: none; + order: 1; +} + +/* The slider gets the full width of the sheet, under the badge. seek-slider.js + leaves its left edge alone in this layout. Room is left at the sides for the + end tick labels, which centre on the slider's ends, and below for the tick + row, which hangs under the slider. */ +.mobile-sheets .score-slider-row { + position: static; + left: auto; + right: auto; + order: 2; + margin: 10px 0 0; + padding: 0 32px 34px; + transition: none; +} + +.mobile-sheets .slider-with-ticks-container { + min-width: 0; +} + +/* Drag the thumb, not the sheet: make the slider a comfortable target. */ +.mobile-sheets .slide-seek-slider { + height: 28px; +} + +/* No caption beside the slider, and no hover zone: the sheet opens and closes + the slider here, and the zone, which hangs 20px below the slider row, would + sit over the handle and swallow taps meant for it. */ +.mobile-sheets .context-label, +.mobile-sheets .slider-hover-zone { + display: none; +} + +/* Ten date labels do not fit across a phone held upright; show every other. */ +@media (max-width: 600px) { + .mobile-sheets .slider-tick:nth-child(even) .slider-tick-label { + visibility: hidden; + } +} + +/* The progress strip is what remains of the slider when the sheet is + collapsed: it sits on the sheet's bottom edge, above the handle, and is part + of the target that opens the sheet rather than a hover target of its own. */ +.mobile-sheets .slider-hover-strip { + position: static; + order: 3; + flex: 0 0 4px; + margin: 0 12px; + border-radius: 2px; + pointer-events: none; +} + +.mobile-sheets #topSheetHandle { + order: 4; + height: calc(var(--top-sheet-peek) - 4px); +} + +/* ----- Bottom sheet: the metadata details ----- */ + +/* The drawer they came from is empty in this layout. */ +.mobile-sheets #bannerDrawerContainer { + display: none; +} + +/* The details reach from under the panels to just below the top sheet's + handle, whatever they hold, and never further (so the sheet's own handle + stays on screen), so the expanded stop (and with it everything + that clears the sheet) does not move from one photo to the next; longer + details scroll. mobile-sheets.js publishes the panels' height. */ +html.mobile-sheets { + --sheet-details-height: max( + var(--sheet-details-peek), + calc( + var(--visible-viewport-height, 100dvh) - var(--top-sheet-peek) - 8px - var(--bottom-sheet-panels-height, 140px) + ) + ); +} + +.mobile-sheets #sheetDetails { + display: block; + flex: 0 0 auto; + box-sizing: border-box; + /* Edge to edge, past the sheet's side padding. */ + width: calc(100% + 8px); + margin: 0 -4px; + height: var(--sheet-details-height); +} + +.mobile-sheets #sheetDetails .filename-banner { + box-sizing: border-box; + width: 100%; + min-width: 0; + max-width: none; + height: 100%; + padding: 0; + margin: 0; + background: none; + border-radius: 0; + font-size: 0.95em; + overflow-x: hidden; + overflow-y: auto; + /* Scrolling the details never scrolls the page, and a downward drag with + them at the top is the sheet's (mobile-sheets.js). */ + overscroll-behavior: contain; + touch-action: pan-y; + -webkit-overflow-scrolling: touch; +} + +/* The title row stays in place as the details scroll, and is a sheet target: + dragged, it moves the sheet; tapped, it opens or closes the details. At the + expanded stop exactly --sheet-details-peek of it shows, so there the file + name and path take one line each; opened, the path wraps to show in full + and the row grows into the details. */ +.mobile-sheets #sheetDetails .filename-titlebar { + position: sticky; + top: 0; + z-index: 1; + box-sizing: border-box; + min-height: var(--sheet-details-peek); + padding: 6px 12px; + /* Opaque: the details scroll under it. */ + background: #282828; + /* Inside the row's height, so the row is exactly what the expanded stop + leaves showing. */ + border-top: 1px solid rgba(255, 255, 255, 0.08); + border-bottom: none; + cursor: pointer; + touch-action: none; +} + +.mobile-sheets #sheetDetails .filename-titles { + cursor: pointer; +} + +.mobile-sheets #sheetDetails #filenameText, +.mobile-sheets #sheetDetails #filepathText { + display: block; + flex: none; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + word-break: normal; +} + +html.mobile-sheets[data-bottom-sheet="details"] #sheetDetails #filepathText { + white-space: normal; + overflow-wrap: anywhere; +} + +/* Which way the row takes the details. */ +.mobile-sheets #sheetDetails .filename-titlebar::after { + content: ""; + flex: 0 0 auto; + width: 8px; + height: 8px; + margin: 5px 4px 0; + border-left: 2px solid var(--sheet-handle-color); + border-top: 2px solid var(--sheet-handle-color); + transform: rotate(45deg); + transition: transform 0.2s; +} + +html.mobile-sheets[data-bottom-sheet="details"] #sheetDetails .filename-titlebar::after { + margin-top: -5px; + transform: rotate(225deg); +} + +.mobile-sheets #sheetDetails .filenameDescContainer { + padding: 0.8em 12px 0; +} + +.mobile-sheets #sheetDetails #recallButtonsContainer { + padding: 0 12px 1em; +} + +/* The drawer caps its description at 40vh and scrolls it on its own. Here + the whole of the details scrolls instead: a second scroller inside it + would also take the downward drags that close the sheet. */ +.mobile-sheets #sheetDetails #descriptionText { + max-height: none; + overflow: visible; +} + +/* metadata-drawer.css breaks words anywhere in the drawer on narrow screens, + which lets the table squeeze its label column down to a few letters + ("Positi / ve Pro / mpt"). Break labels only between words and give them a + fixed share of the width; values still break anywhere (long paths, URLs). */ +.mobile-sheets #sheetDetails .filename-banner { + word-break: normal; +} + +.mobile-sheets #sheetDetails .invoke-metadata > tbody > tr > th, +.mobile-sheets #sheetDetails .invoke-metadata > tr > th, +.mobile-sheets #sheetDetails .exif-metadata table > tbody > tr > th, +.mobile-sheets #sheetDetails .exif-metadata table > tr > th { + overflow-wrap: break-word; + hyphens: auto; +} + +/* Held upright there is little width to share; sideways the labels already + get enough. */ +@media (max-width: 600px) { + .mobile-sheets #sheetDetails .invoke-metadata > tbody > tr > th, + .mobile-sheets #sheetDetails .invoke-metadata > tr > th, + .mobile-sheets #sheetDetails .exif-metadata table > tbody > tr > th, + .mobile-sheets #sheetDetails .exif-metadata table > tr > th { + width: 30%; + } +} + +.mobile-sheets #sheetDetails .invoke-metadata th, +.mobile-sheets #sheetDetails .invoke-metadata td, +.mobile-sheets #sheetDetails .exif-metadata th, +.mobile-sheets #sheetDetails .exif-metadata td { + padding: 6px 8px; +} diff --git a/photomap/frontend/static/javascript/control-panel.js b/photomap/frontend/static/javascript/control-panel.js index 88e194c8..db312c49 100644 --- a/photomap/frontend/static/javascript/control-panel.js +++ b/photomap/frontend/static/javascript/control-panel.js @@ -39,6 +39,14 @@ function isDocumentFullscreen() { ); } +/** + * Can this browser put the page into fullscreen? iPhone Safari cannot (only a + * video can go fullscreen there), and its Fullscreen button did nothing. + */ +export function pageFullscreenSupported() { + return Boolean(document.fullscreenEnabled || document.webkitFullscreenEnabled); +} + // Toggle fullscreen mode. // // The exit chain has to cover every spelling the state check above accepts, or @@ -291,7 +299,11 @@ async function handleSuccessfulDelete(globalIndex) { // Setup button event listeners function setupControlPanelEventListeners() { - // Fullscreen button + // Fullscreen button, where there is a fullscreen to go to + if (elements.fullscreenBtn && !pageFullscreenSupported()) { + const container = elements.fullscreenBtn.closest(".control-icon-container") || elements.fullscreenBtn; + container.style.display = "none"; + } if (elements.fullscreenBtn) { elements.fullscreenBtn.addEventListener("click", (e) => { e.stopPropagation(); diff --git a/photomap/frontend/static/javascript/grid-view.js b/photomap/frontend/static/javascript/grid-view.js index be239aaf..9948341f 100644 --- a/photomap/frontend/static/javascript/grid-view.js +++ b/photomap/frontend/static/javascript/grid-view.js @@ -8,6 +8,7 @@ import { updateImageLabel, } from "./metadata-drawer.js"; import { applyRefTarget } from "./invoke-ref-target.js"; +import { isMobileSheetsMode, sheetVisibleHeight } from "./mobile-sheets.js"; import { fetchImageByIndex } from "./search.js"; import { slideState } from "./slide-state.js"; import { state } from "./state.js"; @@ -55,7 +56,12 @@ class GridViewManager { // The grid is pushed down (grid-view.css) to clear the album badge; take // that off the height so the bottom row still clears the panels. const topReserve = parseFloat(getComputedStyle(gridContainer).marginTop) || 0; - const availableHeight = window.innerHeight - 120 - topReserve; + // The bottom panels' share. In the phone layout they are a sheet that + // covers the grid, by its full height when open and by its handle when + // closed; grid-view.css stops the container above it, and the grid is + // re-measured whenever it opens or closes. + const bottomReserve = isMobileSheetsMode() ? sheetVisibleHeight("bottom") + 6 : 120; + const availableHeight = window.innerHeight - bottomReserve - topReserve; const factor = state.gridThumbSizeFactor || 1.0; const targetTileSize = 200 * factor; @@ -604,6 +610,7 @@ class GridViewManager { }; this.addEventListener(window, "resize", handleResize); + this.addEventListener(window, "mobileSheetChanged", handleResize); // Flips when layout actually adopts the new orientation — on Chrome for // iOS that can come after the resize event carried stale dimensions. const orientationQuery = window.matchMedia?.("(orientation: portrait)"); diff --git a/photomap/frontend/static/javascript/metadata-drawer.js b/photomap/frontend/static/javascript/metadata-drawer.js index e4819867..de26202d 100644 --- a/photomap/frontend/static/javascript/metadata-drawer.js +++ b/photomap/frontend/static/javascript/metadata-drawer.js @@ -14,6 +14,14 @@ import { SHOW_CLUSTER_LABELS_IN_BADGES, } from "./cluster-utils.js"; import { applyRefTarget } from "./invoke-ref-target.js"; +import { + closeSheetDetails, + isMobileSheetsMode, + setSheetState, + SHEET_DETAILS, + sheetState, + sheetVisibleHeight, +} from "./mobile-sheets.js"; import { enhanceReferenceImageThumbnails, registerReferenceThumbnailClickHandler } from "./reference-thumbnails.js"; export { enhanceReferenceImageThumbnails }; @@ -27,14 +35,26 @@ scoreDisplay.setToggleBookmarkCallback((globalIndex) => { scoreDisplay.refreshDisplay(); }); -// Show the banner by moving container up +// In the phone layout the drawer's contents are the bottom sheet's details +// stop (mobile-sheets.js), so opening and closing the drawer means moving the +// sheet to that stop or back down to the panels. + +// Show the banner by sliding the drawer out export function showMetadataOverlay() { + if (isMobileSheetsMode()) { + setSheetState("bottom", SHEET_DETAILS); + return; + } const container = document.getElementById("bannerDrawerContainer"); container.classList.add("visible"); } -// Hide the banner by moving container down +// Hide the banner by sliding the drawer back in export function hideMetadataOverlay() { + if (isMobileSheetsMode()) { + closeSheetDetails(); + return; + } const container = document.getElementById("bannerDrawerContainer"); container.classList.remove("visible"); } @@ -42,7 +62,9 @@ export function hideMetadataOverlay() { // Toggle the banner container export function toggleMetadataOverlay() { const container = document.getElementById("bannerDrawerContainer"); - const isVisible = container.classList.contains("visible"); + const isVisible = isMobileSheetsMode() + ? sheetState("bottom") === SHEET_DETAILS + : container.classList.contains("visible"); if (isVisible) { hideMetadataOverlay(); @@ -564,6 +586,8 @@ export function initializeMetadataDrawer() { // label, score row), so re-measure when it does; otherwise the drawer's tab // ends up overlapping a badge that grew after the drawer was placed. window.addEventListener("scoreDisplayContentChanged", positionMetadataDrawer); + // The phone layout's top sheet opening or closing moves the edge to clear. + window.addEventListener("mobileSheetChanged", positionMetadataDrawer); // Metadata-fields accordion: mirrors the open/closed pattern used by the // Settings dialog accordions, with the open state persisted in @@ -615,6 +639,12 @@ const DRAWER_TOP_FALLBACK = 78; const DRAWER_TOP_GAP = 12; function drawerRestingTop() { + // In the phone layout the badge rides in the top sheet, and measuring it + // mid-slide would catch the sheet part-way. Clear the sheet in the state it + // is settling to instead; it reports a change whenever that moves. + if (isMobileSheetsMode()) { + return Math.round(sheetVisibleHeight("top") + DRAWER_TOP_GAP); + } const badge = document.getElementById("fixedScoreDisplay"); const rect = badge ? badge.getBoundingClientRect() : null; if (!rect || rect.height === 0) { diff --git a/photomap/frontend/static/javascript/mobile-sheets.js b/photomap/frontend/static/javascript/mobile-sheets.js new file mode 100644 index 00000000..cd853f29 --- /dev/null +++ b/photomap/frontend/static/javascript/mobile-sheets.js @@ -0,0 +1,783 @@ +// mobile-sheets.js +// +// Phone layout: the Control and Search panels share one bottom sheet, and the +// album badge and seek slider share one top sheet. Each sheet slides between +// expanded and collapsed — collapsed leaves only a grab handle on screen — by +// dragging it or tapping its handle, the bottom-sheet pattern of Google Maps. +// +// The bottom sheet has a third stop above "expanded": "details". The metadata +// drawer's contents (#filenameBanner) are moved into the sheet, under the +// panels, and at the expanded stop only their title row (the file name) shows +// along the sheet's bottom edge. Pulling the sheet further up, or tapping that +// row, opens the rest over the photo. Outside the phone layout the banner goes +// back into its drawer, which works as it always has. +// +// Whether the phone layout applies is decided once, by the media query in +// main.html's , and published as the +// `mobile-sheets` class on . Every stylesheet keys off that class rather +// than repeating the query, so CSS and JS cannot disagree about the mode. The +// sheets' states live on too, as data-top-sheet / data-bottom-sheet. +// An inline script in main.html's sets all three before first paint; +// this module keeps them current afterwards. +// +// Listeners learn about changes from a `mobileSheetChanged` window event, +// detail { sheet: "top" | "bottom", state, expanded, mobile }, where state is +// "collapsed", "expanded" or (bottom only) "details", and expanded is true for +// either of the last two. It is dispatched for a sheet whenever its state +// changes and for both sheets when the mode changes. + +const FALLBACK_QUERY = "(max-width: 600px), (max-height: 500px) and (pointer: coarse)"; +const MODE_CLASS = "mobile-sheets"; +const DRAGGING_CLASS = "sheet-dragging"; +const BOTTOM_STATE_KEY = "bottomSheetState"; + +export const SHEET_COLLAPSED = "collapsed"; +export const SHEET_EXPANDED = "expanded"; +export const SHEET_DETAILS = "details"; + +// Movement before a press on the sheet becomes a drag rather than a tap. Above +// attachLongPress's 10px cancel threshold would let a drag that started on the +// Slideshow button also open its menu, so stay at or under it. +const DRAG_START_PX = 8; +// Release speed, in px/ms toward the collapsed end or away from it, that +// carries the sheet on to the next stop that way however little it has moved +// — a flick. +const FLICK_SPEED = 0.35; +// Only the last stretch of a drag says which way the finger was going at the +// end; an older sample would let a drag that reversed settle the wrong way. +const VELOCITY_WINDOW_MS = 100; +// How long a click is swallowed after a drag ends. The click a drag produces +// arrives straight after pointerup; this only bounds a listener for a click +// that never comes. +const CLICK_SUPPRESS_MS = 400; +// Movement, in the details content, before a touch is judged a scroll or a +// pull on the sheet. Under the browsers' own scroll slop, so the judgement +// comes before any native scroll can start; over a finger's jitter. +const SCROLLER_DECIDE_PX = 4; + +// Controls that keep their own pointer gestures. The seek slider is the one +// that matters: dragging its thumb must seek, not move the sheet. +const OWN_GESTURE_SELECTOR = "input, select, textarea"; + +/** The media query that selects the phone layout. */ +export function mobileSheetsQuery() { + const meta = document.querySelector('meta[name="mobile-sheets-query"]'); + return meta?.content || FALLBACK_QUERY; +} + +/** Is the phone layout in effect? */ +export function isMobileSheetsMode() { + return document.documentElement.classList.contains(MODE_CLASS); +} + +// mobile-sheets.css hides both sheets while the page is fullscreen. +function sheetsHiddenByFullscreen() { + return Boolean(document.fullscreenElement || document.webkitFullscreenElement); +} + +function readStoredBottomState() { + try { + return localStorage.getItem(BOTTOM_STATE_KEY); + } catch { + return null; + } +} + +function storeBottomState(value) { + try { + localStorage.setItem(BOTTOM_STATE_KEY, value); + } catch { + // Private mode or blocked storage: the sheet still works, it just starts + // expanded again next time. + } +} + +/** + * The metadata drawer's contents, which the bottom sheet borrows in the phone + * layout. `slot` is the sheet's empty container for them, `home` the drawer + * they come from, and `peekRow` the title row left showing at the expanded + * stop. The banner is also the details' scroll container. + */ +function findDetails() { + const slot = document.getElementById("sheetDetails"); + const banner = document.getElementById("filenameBanner"); + const home = document.getElementById("bannerDrawerContainer"); + const peekRow = document.getElementById("filenameTitlebar"); + if (!slot || !banner || !home || !peekRow) { + return null; + } + return { slot, banner, home, peekRow }; +} + +class Sheet { + /** + * @param {object} options + * @param {"top"|"bottom"} options.name which edge of the window it hangs from + * @param {HTMLElement} options.element the sheet itself + * @param {HTMLElement} options.handle the grab handle inside it + * @param {string} options.peekVar CSS custom property holding the collapsed height + * @param {number} options.peekFallback px to use when the property is unreadable + * @param {object|null} [options.details] see findDetails(); bottom sheet only + */ + constructor({ name, element, handle, peekVar, peekFallback, details = null }) { + this.name = name; + this.element = element; + this.handle = handle; + this.peekVar = peekVar; + this.peekFallback = peekFallback; + this.details = details; + this.attribute = name === "top" ? "topSheet" : "bottomSheet"; + // Distance travelled toward the collapsed end, for each px the pointer + // moves down the screen. + this.direction = name === "top" ? -1 : 1; + this.drag = null; + // Per-touch decision, inside the scrolling details, whether a downward + // drag belongs to the sheet; see onScrollerTouchMove. + this.touchGate = null; + // The stop the details were opened from, to go back to on closing them. + this.stateBeforeDetails = SHEET_EXPANDED; + // Last on-screen height listeners were told about; see notifyIfResized. + this.notifiedHeight = null; + + this.onPointerDown = this.onPointerDown.bind(this); + this.onPointerMove = this.onPointerMove.bind(this); + this.onPointerUp = this.onPointerUp.bind(this); + this.onPointerCancel = this.onPointerCancel.bind(this); + this.onClick = this.onClick.bind(this); + this.onScrollerTouchStart = this.onScrollerTouchStart.bind(this); + this.onScrollerTouchMove = this.onScrollerTouchMove.bind(this); + } + + /** "collapsed", "expanded" or, for a sheet with details, "details". */ + get state() { + const value = document.documentElement.dataset[this.attribute]; + if (value === SHEET_DETAILS) { + return this.details ? SHEET_DETAILS : SHEET_EXPANDED; + } + return value === SHEET_EXPANDED ? SHEET_EXPANDED : SHEET_COLLAPSED; + } + + get expanded() { + return this.state !== SHEET_COLLAPSED; + } + + /** Collapsed height: what stays on screen, in px. */ + peekHeight() { + // The bottom sheet's handle is exactly its peek, and its height is the + // one to trust: a phone held sideways sets the peek with calc() and env() + // (mobile-sheets.css), which a custom property hands back unevaluated. + if (this.name === "bottom" && this.handle.offsetHeight > 0) { + return this.handle.offsetHeight; + } + const raw = getComputedStyle(this.element).getPropertyValue(this.peekVar); + const value = parseFloat(raw); + return Number.isFinite(value) ? value : this.peekFallback; + } + + /** How far the sheet travels between its two ends, in px. */ + travel() { + return Math.max(0, this.element.offsetHeight - this.peekHeight()); + } + + /** + * How far below the fully open position the expanded stop is: the height of + * the details under their title row, which hang below the window there. + */ + detailsOffset() { + if (!this.details || !isMobileSheetsMode() || !this.details.slot.contains(this.details.banner)) { + return 0; + } + const { slot } = this.details; + return Math.min(this.travel(), Math.max(0, slot.offsetHeight - this.detailsPeekHeight())); + } + + /** + * How much of the details' title row the expanded stop shows: the CSS's + * fixed --sheet-details-peek, not the row's height, which grows when the + * open details let the path wrap. + */ + detailsPeekHeight() { + const value = parseFloat(getComputedStyle(this.element).getPropertyValue("--sheet-details-peek")); + return Number.isFinite(value) ? value : this.details.peekRow.offsetHeight; + } + + /** Distance toward the collapsed end, from fully open, of a stop. */ + offsetOf(state) { + if (state === SHEET_COLLAPSED) { + return this.travel(); + } + return state === SHEET_DETAILS ? 0 : this.detailsOffset(); + } + + /** The sheet's stops, nearest fully open first. */ + stops() { + const states = this.details ? [SHEET_DETAILS, SHEET_EXPANDED, SHEET_COLLAPSED] : [SHEET_EXPANDED, SHEET_COLLAPSED]; + return states.map((state) => ({ state, offset: this.offsetOf(state) })); + } + + /** + * On-screen height in its settled state, in px. The details stop floats + * over the photo rather than taking room from it, so it reports the + * expanded height: what is under the sheet does not reflow as it opens. + */ + visibleHeight() { + if (!isMobileSheetsMode() || sheetsHiddenByFullscreen()) { + return 0; + } + if (!this.expanded) { + return this.peekHeight(); + } + return this.element.offsetHeight - this.detailsOffset(); + } + + attach() { + this.element.addEventListener("pointerdown", this.onPointerDown); + this.element.addEventListener("pointermove", this.onPointerMove); + this.element.addEventListener("pointerup", this.onPointerUp); + this.element.addEventListener("pointercancel", this.onPointerCancel); + this.element.addEventListener("click", this.onClick); + if (this.details) { + const scroller = this.details.banner; + scroller.addEventListener("touchstart", this.onScrollerTouchStart, { passive: true }); + scroller.addEventListener("touchmove", this.onScrollerTouchMove, { passive: false }); + } + this.syncAccessibility(); + } + + /** + * Settle the sheet at a stop. + * + * @param {"collapsed"|"expanded"|"details"} state + * @param {object} [options] + * @param {boolean} [options.force] notify listeners even if nothing changed + */ + setState(state, { force = false } = {}) { + if (state === SHEET_DETAILS && !this.details) { + state = SHEET_EXPANDED; + } + const previous = this.state; + const changed = state !== previous; + if (changed && state === SHEET_DETAILS) { + this.stateBeforeDetails = previous; + } + document.documentElement.dataset[this.attribute] = state; + // The details are a visit, not a preference: only the panels' own stops + // are remembered, so opening the details from a closed sheet and closing + // them again leaves it closed next time too. + if (this.name === "bottom" && changed && state !== SHEET_DETAILS) { + storeBottomState(state); + } + if (changed && state !== SHEET_DETAILS && this.details) { + // Reopened, the details start from the top again. + this.details.banner.scrollTop = 0; + } + this.syncAccessibility(); + if (changed || force) { + publishSheetHeights(); + this.notify(); + } + } + + /** Tell listeners the sheet's stop (and so its height) may have changed. */ + notify() { + const state = this.state; + this.notifiedHeight = Math.round(this.visibleHeight()); + window.dispatchEvent( + new CustomEvent("mobileSheetChanged", { + detail: { + sheet: this.name, + state, + expanded: state !== SHEET_COLLAPSED, + mobile: isMobileSheetsMode(), + }, + }) + ); + } + + /** + * The sheet grew or shrank without moving stop — panel labels switched on, + * a rotation, the badge taking a second line. Whatever was laid out around + * it has to be told, just as for a change of stop. + */ + notifyIfResized() { + if (this.notifiedHeight !== null && Math.round(this.visibleHeight()) !== this.notifiedHeight) { + this.notify(); + } + } + + setExpanded(expanded, options) { + this.setState(expanded ? SHEET_EXPANDED : SHEET_COLLAPSED, options); + } + + /** + * Keep keyboard focus and assistive technology off whatever the sheet has + * slid out of view, and say on the handle which way it goes. + */ + syncAccessibility() { + const mobile = isMobileSheetsMode(); + const state = this.state; + const hidden = mobile && state === SHEET_COLLAPSED; + for (const child of this.element.children) { + if (child === this.handle || child.dataset.sheetPeek !== undefined) { + continue; + } + child.inert = hidden; + } + if (this.details) { + // Below the title row, the details are off screen until they open. In + // the drawer (outside the phone layout) none of this applies. + const belowFold = mobile && state !== SHEET_DETAILS; + for (const child of this.details.banner.children) { + if (child !== this.details.peekRow) { + child.inert = belowFold; + } + } + if (mobile) { + this.details.peekRow.setAttribute("aria-expanded", String(state === SHEET_DETAILS)); + } else { + this.details.peekRow.removeAttribute("aria-expanded"); + } + } + this.handle.setAttribute("aria-expanded", String(!hidden)); + } + + /** Is this press in the scrolling part of the details (not their title row)? */ + inDetailsScroller(target) { + if (!this.details || !target) { + return false; + } + const { banner, peekRow } = this.details; + return banner.contains(target) && !peekRow.contains(target); + } + + onPointerDown(event) { + if (!isMobileSheetsMode() || !event.isPrimary) { + return; + } + if (event.pointerType === "mouse" && event.button !== 0) { + return; + } + if (event.target.closest?.(OWN_GESTURE_SELECTOR)) { + return; + } + // In the open details, a press in the content scrolls it; only one made + // with the content already at its top can pull the sheet down instead. + const fromScroller = this.inDetailsScroller(event.target); + if (fromScroller && this.details.banner.scrollTop > 0) { + return; + } + this.drag = { + id: event.pointerId, + startX: event.clientX, + startY: event.clientY, + startOffset: this.offsetOf(this.state), + offset: null, + active: false, + fromScroller, + pointerType: event.pointerType, + samples: [], + }; + } + + onPointerMove(event) { + const drag = this.drag; + if (!drag || event.pointerId !== drag.id) { + return; + } + // A mouse released off the sheet before the drag began (and so before + // the pointer was captured) sends its pointerup elsewhere; drop the press + // rather than let a later hover move the sheet. + if (drag.pointerType === "mouse" && event.buttons === 0) { + this.drag = null; + return; + } + const dx = event.clientX - drag.startX; + const dy = event.clientY - drag.startY; + + if (!drag.active) { + if (Math.abs(dy) < DRAG_START_PX || Math.abs(dy) < Math.abs(dx)) { + // A sideways press is not a sheet gesture at all; let it go so a + // later vertical wobble cannot turn it into one. + if (Math.abs(dx) >= DRAG_START_PX) { + this.drag = null; + } + return; + } + // Upward in the details content is a scroll, not a sheet gesture. + if (drag.fromScroller && dy < 0) { + this.drag = null; + return; + } + drag.active = true; + // Keep receiving the moves when the finger leaves the sheet, which it + // does at once when dragging a collapsed sheet open. + try { + this.element.setPointerCapture?.(drag.id); + } catch { + // The pointer has already gone; pointerup/cancel will clean up. + } + this.element.classList.add(DRAGGING_CLASS); + } + + const offset = Math.min(this.travel(), Math.max(0, drag.startOffset + dy * this.direction)); + drag.offset = offset; + drag.samples.push({ t: event.timeStamp, offset }); + while (drag.samples.length > 2 && event.timeStamp - drag.samples[0].t > VELOCITY_WINDOW_MS) { + drag.samples.shift(); + } + this.element.style.transform = `translateY(${offset * this.direction}px)`; + event.preventDefault(); + } + + onPointerUp(event) { + const drag = this.drag; + if (!drag || event.pointerId !== drag.id) { + return; + } + this.drag = null; + if (!drag.active) { + return; + } + // A mouse (or pen) press dragged and released still clicks whatever it + // began on — the Delete button, say. A touch that moved past the slop + // never clicks, so for touch there is nothing to swallow, and swallowing + // anyway would eat the user's next real tap. + if (drag.pointerType !== "touch") { + this.suppressNextClick(); + } + this.finishDrag(drag, this.releaseSpeed(drag)); + } + + onPointerCancel(event) { + const drag = this.drag; + if (!drag || event.pointerId !== drag.id) { + return; + } + this.drag = null; + if (drag.active) { + // No release to read a flick from: settle at the nearest stop. + this.finishDrag(drag, 0); + } + } + + /** + * A touch in the details content scrolls it natively (touch-action: pan-y + * there), and once the browser starts that pan the pointer is cancelled. A + * downward drag with the content at its top has nothing to scroll and + * belongs to the sheet, so stop the browser from claiming it; any other + * first move is left to scroll. + */ + onScrollerTouchStart(event) { + const touch = event.touches[0]; + const atTop = this.details.banner.scrollTop <= 0; + this.touchGate = + event.touches.length === 1 && + atTop && + this.state === SHEET_DETAILS && + this.inDetailsScroller(event.target) && + !event.target.closest?.(OWN_GESTURE_SELECTOR) + ? { y: touch.clientY, owner: null } + : null; + } + + onScrollerTouchMove(event) { + const gate = this.touchGate; + if (!gate) { + return; + } + if (event.touches.length !== 1) { + this.touchGate = null; + return; + } + if (gate.owner === null) { + const dy = event.touches[0].clientY - gate.y; + if (Math.abs(dy) < SCROLLER_DECIDE_PX) { + return; + } + gate.owner = dy > 0 ? "sheet" : "scroll"; + } + if (gate.owner === "sheet" && event.cancelable) { + event.preventDefault(); + } + } + + /** Speed toward the collapsed end at release, in px/ms (negative = opening). */ + releaseSpeed(drag) { + const first = drag.samples[0]; + const last = drag.samples[drag.samples.length - 1]; + if (!first || !last || last.t <= first.t) { + return 0; + } + return (last.offset - first.offset) / (last.t - first.t); + } + + finishDrag(drag, speed) { + this.element.classList.remove(DRAGGING_CLASS); + this.element.style.transform = ""; + + const position = drag.offset ?? drag.startOffset; + const stops = this.stops(); + let target; + if (speed > FLICK_SPEED) { + // On to the next stop toward collapsed, or the last one. + target = stops.find((stop) => stop.offset > position + 1) ?? stops[stops.length - 1]; + } else if (speed < -FLICK_SPEED) { + target = [...stops].reverse().find((stop) => stop.offset < position - 1) ?? stops[0]; + } else { + target = stops.reduce((best, stop) => + Math.abs(stop.offset - position) < Math.abs(best.offset - position) ? stop : best + ); + } + this.setState(target.state); + } + + /** Swallow the one click a mouse drag ends in (see onPointerUp). */ + suppressNextClick() { + const swallow = (event) => { + event.stopPropagation(); + event.preventDefault(); + cleanup(); + }; + const cleanup = () => { + window.removeEventListener("click", swallow, true); + clearTimeout(timer); + }; + window.addEventListener("click", swallow, true); + const timer = setTimeout(cleanup, CLICK_SUPPRESS_MS); + } + + onClick(event) { + if (!isMobileSheetsMode()) { + return; + } + const state = this.state; + // The handle steps between collapsed and expanded, and down out of the + // details. Anywhere else on a collapsed sheet is part of the strip left + // showing, and opens it — the target there is small enough. The details' + // title row opens and closes them (its copy button just copies). + if (this.handle.contains(event.target)) { + this.setState(state === SHEET_EXPANDED ? SHEET_COLLAPSED : SHEET_EXPANDED); + } else if (state === SHEET_COLLAPSED) { + this.setState(SHEET_EXPANDED); + } else if (this.details?.peekRow.contains(event.target) && !event.target.closest?.("button, a")) { + this.setState(state === SHEET_DETAILS ? SHEET_EXPANDED : SHEET_DETAILS); + } + } +} + +const sheets = {}; + +/** + * Publish each sheet's settled on-screen height as --top-sheet-height and + * --bottom-sheet-height on , for rules that have to clear them (the + * text search box sits above the bottom sheet), and the height of the bottom + * sheet above its details as --bottom-sheet-panels-height, which sizes them. + */ +function publishSheetHeights() { + const root = document.documentElement; + const mobile = isMobileSheetsMode(); + for (const sheet of Object.values(sheets)) { + const property = `--${sheet.name}-sheet-height`; + if (mobile) { + root.style.setProperty(property, `${Math.round(sheet.visibleHeight())}px`); + } else { + root.style.removeProperty(property); + } + } + const details = sheets.bottom?.details; + if (mobile && details) { + // The sheet is position: fixed, so it is the slot's offsetParent. + root.style.setProperty("--bottom-sheet-panels-height", `${Math.round(details.slot.offsetTop)}px`); + } else { + root.style.removeProperty("--bottom-sheet-panels-height"); + } +} + +/** Put the metadata drawer's contents in the bottom sheet, or back. */ +function placeDetails(mobile) { + const details = sheets.bottom?.details; + if (!details) { + return; + } + const parent = mobile ? details.slot : details.home; + if (details.banner.parentElement !== parent) { + parent.appendChild(details.banner); + } +} + +/** + * On-screen height of a sheet in its settled state, in px; 0 outside the + * phone layout or before initialization. The bottom sheet's details stop + * counts as expanded: it floats over the page. + * + * @param {"top"|"bottom"} name + */ +export function sheetVisibleHeight(name) { + return sheets[name]?.visibleHeight() ?? 0; +} + +/** + * Height of a sheet's handle strip, in px; 0 outside the phone layout. For the + * bottom sheet held sideways on a touch screen that is its collapsed height + * only while it is collapsed: the handle grows when it collapses. + * + * @param {"top"|"bottom"} name + */ +export function sheetPeekHeight(name) { + if (!isMobileSheetsMode()) { + return 0; + } + return sheets[name]?.peekHeight() ?? 0; +} + +/** A sheet's stop: "collapsed", "expanded" or "details"; null if there is none. */ +export function sheetState(name) { + return sheets[name]?.state ?? null; +} + +/** + * Move a sheet to a stop from code. No-op outside the phone layout, and while + * fullscreen hides the sheets: a change made then would only show, unasked + * for, when fullscreen ends. + */ +export function setSheetState(name, state) { + if (isMobileSheetsMode() && !sheetsHiddenByFullscreen()) { + sheets[name]?.setState(state); + } +} + +/** Close the bottom sheet's details, back to the stop they were opened from. */ +export function closeSheetDetails() { + const sheet = sheets.bottom; + if (sheet && sheet.state === SHEET_DETAILS && !sheetsHiddenByFullscreen()) { + sheet.setState(sheet.stateBeforeDetails === SHEET_COLLAPSED ? SHEET_COLLAPSED : SHEET_EXPANDED); + } +} + +/** Open or close a sheet from code. No-op outside the phone layout. */ +export function setSheetExpanded(name, expanded) { + setSheetState(name, expanded ? SHEET_EXPANDED : SHEET_COLLAPSED); +} + +function applyMode(mobile) { + const root = document.documentElement; + const wasMobile = root.classList.contains(MODE_CLASS); + root.classList.toggle(MODE_CLASS, mobile); + if (mobile === wasMobile) { + return; + } + // A drag cannot survive the layout changing under it. + for (const sheet of Object.values(sheets)) { + sheet.drag = null; + sheet.touchGate = null; + sheet.element.classList.remove(DRAGGING_CLASS); + sheet.element.style.transform = ""; + } + placeDetails(mobile); + // The slider row is only ever opened by the user; coming back into the + // phone layout it starts closed, as it does on load. Nor do the details + // carry over: the drawer they came from was closed or open on its own. + if (sheets.top) { + root.dataset.topSheet = SHEET_COLLAPSED; + } + for (const sheet of Object.values(sheets)) { + const state = sheet.state === SHEET_DETAILS ? SHEET_EXPANDED : sheet.state; + sheet.setState(state, { force: true }); + } +} + +/** Find the sheets in the page and start following the media query. */ +export function initializeMobileSheets() { + const root = document.documentElement; + if (!root.dataset.bottomSheet) { + root.dataset.bottomSheet = readStoredBottomState() === SHEET_COLLAPSED ? SHEET_COLLAPSED : SHEET_EXPANDED; + } + if (!root.dataset.topSheet) { + root.dataset.topSheet = SHEET_COLLAPSED; + } + + const definitions = [ + { + name: "bottom", + element: document.getElementById("panelStackContainer"), + handle: document.getElementById("bottomSheetHandle"), + peekVar: "--bottom-sheet-peek", + peekFallback: 24, + details: findDetails(), + }, + { + name: "top", + element: document.getElementById("topSheetContainer"), + handle: document.getElementById("topSheetHandle"), + peekVar: "--top-sheet-peek", + peekFallback: 26, + }, + ]; + for (const definition of definitions) { + if (definition.element && definition.handle) { + const sheet = new Sheet(definition); + sheet.attach(); + sheets[definition.name] = sheet; + } + } + + const query = window.matchMedia?.(mobileSheetsQuery()); + const mobile = Boolean(query?.matches); + root.classList.toggle(MODE_CLASS, mobile); + placeDetails(mobile); + for (const sheet of Object.values(sheets)) { + sheet.syncAccessibility(); + } + publishSheetHeights(); + query?.addEventListener?.("change", (event) => applyMode(event.matches)); + + // Heights change with rotation and with what the sheets hold (the panel + // labels can be switched off; a search changes the badge). + window.addEventListener("resize", publishSheetHeights); + document.addEventListener("fullscreenchange", publishSheetHeights); + document.addEventListener("webkitfullscreenchange", publishSheetHeights); + if (typeof ResizeObserver !== "undefined") { + const observer = new ResizeObserver(() => { + publishSheetHeights(); + for (const sheet of Object.values(sheets)) { + sheet.notifyIfResized(); + } + }); + for (const sheet of Object.values(sheets)) { + observer.observe(sheet.element); + } + } + + // Transitions are switched on only now, so the state the script + // restored does not animate in on load. + requestAnimationFrame(() => root.classList.add("sheets-ready")); + + // Announce the starting state. This module initializes as soon as it is + // imported, before most listeners are attached, so they cannot rely on + // hearing it: each reads the current state (isMobileSheetsMode, + // sheetVisibleHeight) when it sets itself up, and listens for changes. + for (const sheet of Object.values(sheets)) { + sheet.setState(sheet.state, { force: true }); + } +} + +/** Test hook: what the ResizeObserver does, which jsdom lacks. */ +export function notifySheetsResizedForTests() { + publishSheetHeights(); + for (const sheet of Object.values(sheets)) { + sheet.notifyIfResized(); + } +} + +/** Test hook: forget the sheets found by the last initialization. */ +export function resetMobileSheetsForTests() { + for (const key of Object.keys(sheets)) { + delete sheets[key]; + } +} + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", initializeMobileSheets); +} else { + initializeMobileSheets(); +} diff --git a/photomap/frontend/static/javascript/panel-anchor.js b/photomap/frontend/static/javascript/panel-anchor.js index f6c4e07a..4675a2e2 100644 --- a/photomap/frontend/static/javascript/panel-anchor.js +++ b/photomap/frontend/static/javascript/panel-anchor.js @@ -224,11 +224,17 @@ export function syncPanelAnchor() { // to — so after a stranded fullscreen exit the bottom of the photo hangs off // the screen too. Publish the visible height for those rules to consume // (they fall back to 100dvh when it is unset). + // + // The phone layout's bottom sheet (mobile-sheets.css) cannot take the + // translate the panels get above — it uses its own transform to slide — so + // it lifts itself by the overshoot through its bottom offset instead. const root = document.documentElement; if (overshoot) { root.style.setProperty("--visible-viewport-height", `${root.clientHeight - overshoot}px`); + root.style.setProperty("--visible-viewport-overshoot", `${overshoot}px`); } else { root.style.removeProperty("--visible-viewport-height"); + root.style.removeProperty("--visible-viewport-overshoot"); } } diff --git a/photomap/frontend/static/javascript/search-ui.js b/photomap/frontend/static/javascript/search-ui.js index b24ccc07..b89577db 100644 --- a/photomap/frontend/static/javascript/search-ui.js +++ b/photomap/frontend/static/javascript/search-ui.js @@ -155,6 +155,16 @@ document.addEventListener("DOMContentLoaded", async () => { e.stopPropagation(); }); + // In the phone layout the box sits above the bottom sheet, and the sheet's + // details stop rises over the space it would need: close it. + window.addEventListener("mobileSheetChanged", (e) => { + if (e.detail?.state === "details" && textSearchPanel.style.display === "block") { + releaseSearchFocus(); + textSearchPanel.style.display = "none"; + textSearchPanel.style.opacity = 0; + } + }); + const doSearchBtn = document.getElementById("doSearchBtn"); const searchInput = document.getElementById("searchInput"); const negativeSearchInput = document.getElementById("negativeSearchInput"); diff --git a/photomap/frontend/static/javascript/seek-slider.js b/photomap/frontend/static/javascript/seek-slider.js index 0970b909..e17523cc 100644 --- a/photomap/frontend/static/javascript/seek-slider.js +++ b/photomap/frontend/static/javascript/seek-slider.js @@ -1,6 +1,7 @@ import { backStack } from "./back-stack.js"; import { bookmarkManager } from "./bookmarks.js"; import { scoreDisplay } from "./score-display.js"; +import { isMobileSheetsMode } from "./mobile-sheets.js"; import { getCurrentSlideIndex, slideState } from "./slide-state.js"; import { state } from "./state.js"; import { debounce } from "./utils.js"; @@ -45,6 +46,12 @@ class SeekSlider { this.lastFetchTime = 0; this.FETCH_THROTTLE_MS = 200; this.slideChangedTimer = null; + // In the phone layout the slider lives in the top sheet and is open for + // exactly as long as the sheet is (mobile-sheets.js). While pinned, none + // of the hover / fade-out / badge-tap paths may close it. + this.sheetPinned = false; + // When a pinned slider was last released; see onSliderInput. + this.lastSliderChangeAt = 0; } initialize() { @@ -74,6 +81,54 @@ class SeekSlider { // Update slider position when score display content changes window.addEventListener("scoreDisplayContentChanged", () => this.updateSliderPosition()); + + window.addEventListener("mobileSheetChanged", (event) => this.onMobileSheetChanged(event.detail)); + } + + /** Open the slider with the top sheet, and close it with the sheet. */ + async onMobileSheetChanged(detail) { + if (!detail) { + return; + } + if (detail.sheet === "top") { + if (detail.mobile && detail.expanded) { + await this.pinForSheet(); + } else if (this.sheetPinned) { + this.unpinForSheet(); + } + } + // The layout switched one way or the other: the row's left edge is either + // measured from the badge again or must stop being. + this.updateSliderPosition(); + } + + async pinForSheet() { + this.sheetPinned = true; + this.clearHideTimer(); + this.clearFadeOutTimer(); + this.sliderVisible = true; + this.hoverStrip?.classList.add("hidden"); + this.scoreSliderRow?.classList.add("visible"); + this.sliderContainer?.classList.add("visible"); + await this.refreshPinnedSlider(); + } + + /** Bring a pinned slider's range, value and ticks up to date. */ + async refreshPinnedSlider() { + if (!this.sheetPinned || !this.slider) { + return; + } + await this.updateSliderRange(); + this.slider.value = slideState.getCurrentIndex() + 1; + this.updateHoverStripProgress(); + await this.renderSliderTicks(); + this.searchResultsChanged = false; + } + + unpinForSheet() { + this.sheetPinned = false; + this.hideSlider(); + this.clearFadeOutTimer(); } /** @@ -86,6 +141,13 @@ class SeekSlider { if (!this.scoreDisplayElement || !this.scoreSliderRow || !this.hoverStrip) { return; } + // In the phone layout the slider has its own full-width row under the + // badge (mobile-sheets.css); an inline left would squeeze it back beside it. + if (isMobileSheetsMode()) { + this.scoreSliderRow.style.left = ""; + this.hoverStrip.style.left = ""; + return; + } const rect = this.scoreDisplayElement.getBoundingClientRect(); const basePosition = rect.right + 8; // 8px gap after the badge @@ -168,7 +230,8 @@ class SeekSlider { this.scoreDisplayElement.addEventListener("click", (e) => { // Don't toggle slider if clicking on the star icon (for bookmark toggle) // or anywhere in the album row (pulldown, reindex button, progress ring). - if (e.target.closest(".score-star") || e.target.closest(".album-badge-row")) { + // In the phone layout the top sheet opens and closes the slider instead. + if (e.target.closest(".score-star") || e.target.closest(".album-badge-row") || this.sheetPinned) { return; } this.toggleSlider(); @@ -206,13 +269,17 @@ class SeekSlider { } window.addEventListener("slideChanged", async (event) => await this.onSlideChanged(event)); + // A closed slider picks these up the next time it opens; a pinned one is + // open now, so it has to be brought up to date straight away. window.addEventListener("searchResultsChanged", () => { this.searchResultsChanged = true; this.updateHoverStripProgress(); + this.refreshPinnedSlider(); }); window.addEventListener("albumChanged", () => { this.searchResultsChanged = true; this.updateHoverStripProgress(); + this.refreshPinnedSlider(); }); } @@ -221,6 +288,9 @@ class SeekSlider { */ scheduleHide() { this.clearHideTimer(); + if (this.sheetPinned) { + return; + } this.hideTimerId = setTimeout(() => { this.hideSlider(); this.hideTimerId = null; @@ -294,7 +364,10 @@ class SeekSlider { panelText = ""; } - if (panelText) { + // A pinned slider's bubble is put away on release (onSliderChange); a date + // lookup for a drag that has since been released must not bring it back. + const released = this.sheetPinned && this.lastSliderChangeAt >= now; + if (panelText && !released) { this.infoPanel.textContent = panelText; this.infoPanel.style.display = "block"; let left = 0; @@ -353,6 +426,16 @@ class SeekSlider { async onSliderChange() { this.infoPanel.textContent = ""; + // A closed slider takes the date bubble with it; a pinned one stays open, + // so put the bubble away once any date lookup still in flight has landed. + if (this.sheetPinned) { + this.lastSliderChangeAt = Date.now(); + setTimeout(() => { + if (this.infoPanel) { + this.infoPanel.style.display = "none"; + } + }, 800); + } const targetIndex = parseInt(this.slider.value, 10) - 1; // Update hover strip with final slider position this.updateHoverStripProgress(targetIndex + 1); @@ -408,6 +491,9 @@ class SeekSlider { } hideSlider() { + if (this.sheetPinned) { + return; + } if (this.sliderVisible && this.sliderContainer) { this.sliderVisible = false; this.sliderContainer.classList.remove("visible"); @@ -426,6 +512,9 @@ class SeekSlider { } hideSliderWithDelay(event) { + if (this.sheetPinned) { + return; + } if (!this.sliderContainer.contains(event.relatedTarget)) { this.clearFadeOutTimer(); this.fadeOutTimeoutId = setTimeout(() => { @@ -449,6 +538,9 @@ class SeekSlider { resetFadeOutTimer() { this.clearFadeOutTimer(); + if (this.sheetPinned) { + return; + } this.fadeOutTimeoutId = setTimeout(() => { if (!this.sliderContainer.querySelector(":hover")) { this.sliderContainer.classList.remove("visible"); @@ -563,6 +655,9 @@ class SeekSlider { } async toggleSlider() { + if (this.sheetPinned) { + return; + } this.sliderVisible = !this.sliderVisible; if (this.sliderVisible) { // Hide the yellow strip and show the slider row with animation diff --git a/photomap/frontend/static/javascript/touch.js b/photomap/frontend/static/javascript/touch.js index e819d84d..f164b0c7 100644 --- a/photomap/frontend/static/javascript/touch.js +++ b/photomap/frontend/static/javascript/touch.js @@ -3,6 +3,7 @@ import { showBackFlyout } from "./back-button.js"; import { backStack } from "./back-stack.js"; +import { isMobileSheetsMode, SHEET_DETAILS, setSheetState } from "./mobile-sheets.js"; import { showSlideshowModeMenu, toggleSlideshowWithIndicator } from "./slideshow.js"; import { state } from "./state.js"; import { attachLongPress } from "./utils.js"; @@ -15,6 +16,11 @@ const swipeThreshold = 50; // Minimum distance in px for a swipe const tapThreshold = 10; // Maximum movement in px for a tap const tapTimeThreshold = 500; // Maximum time in ms for a tap +// A zoomed photo pans under a one-finger drag; that is not a swipe. +function photoIsZoomed() { + return Boolean(document.querySelector("#singleSwiper .swiper-slide-zoomed")) || window.visualViewport?.scale > 1.01; +} + function handleTouchStart(e) { // Only track single-finger touches if (e.touches.length === 1) { @@ -127,11 +133,13 @@ function handleTouchEnd(e) { if (isTap && isFullscreen && !tappedAControl) { toggleSlideshowWithIndicator(); - } else { - // Only detect horizontal swipe (left/right) for pausing slideshow - if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > swipeThreshold) { - state.single_swiper.pauseSlideshow(); - } + } else if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > swipeThreshold) { + // A horizontal swipe changes slide; pause the slideshow for it. + state.single_swiper.pauseSlideshow(); + } else if (deltaY < -swipeThreshold && isMobileSheetsMode() && !isFullscreen && !tappedAControl && !photoIsZoomed()) { + // Phone layout: swiping up on the photo opens its details, as in Photos. + // Not in fullscreen, where the sheets are hidden. + setSheetState("bottom", SHEET_DETAILS); } // Reset touch tracking diff --git a/photomap/frontend/static/javascript/umap.js b/photomap/frontend/static/javascript/umap.js index 8f34e614..709fadf4 100644 --- a/photomap/frontend/static/javascript/umap.js +++ b/photomap/frontend/static/javascript/umap.js @@ -8,6 +8,7 @@ import { setClusterLabels, trackVocabBuildRequest, } from "./cluster-utils.js"; +import { isMobileSheetsMode, sheetVisibleHeight } from "./mobile-sheets.js"; import { exitSearchMode } from "./search-ui.js"; import { getImagePath, setSearchResults } from "./search.js"; import { getCurrentSlideIndex, slideState } from "./slide-state.js"; @@ -2647,10 +2648,18 @@ function setUmapWindowSize(sizeKey) { const controlsHeight = reservedControlsHeight(50, 40); // Measure how much vertical space the bottom Control/Search panels occupy. // The window covers the full viewport; its dark background fills the dead zone behind the panels. + // In the phone layout both panels are in the bottom sheet, so clear that + // as it settles (open, or down to its handle; its details stop, which + // floats over everything, counts as open). const bottomPanel = document.getElementById("controlPanel"); - const panelReservedHeight = bottomPanel - ? Math.round(window.innerHeight - bottomPanel.getBoundingClientRect().top) + 16 - : 96; // +16 ≈ 1em gap above the panels + let panelReservedHeight; + if (isMobileSheetsMode()) { + panelReservedHeight = Math.round(sheetVisibleHeight("bottom")) + 16; + } else { + panelReservedHeight = bottomPanel + ? Math.round(window.innerHeight - bottomPanel.getBoundingClientRect().top) + 16 + : 96; // +16 ≈ 1em gap above the panels + } const windowHeight = window.innerHeight; win.style.left = "0px"; win.style.top = "0px"; @@ -2886,7 +2895,7 @@ document.getElementById("umapClusterInfoModal").addEventListener("click", (e) => } }); -window.addEventListener("resize", () => { +function refitFullscreenUmapWindow() { // Only resize if UMAP window is in fullscreen mode const win = document.getElementById("umapFloatingWindow"); if (!win || win.style.display !== "block") { @@ -2898,6 +2907,15 @@ window.addEventListener("resize", () => { updateLandmarkTrace(); updateCurrentImageMarker(); } +} + +window.addEventListener("resize", refitFullscreenUmapWindow); +// The fullscreen map stops above the phone layout's bottom sheet, which is +// open or down to its handle; follow it when it moves or changes height. +window.addEventListener("mobileSheetChanged", (e) => { + if (e.detail?.sheet === "bottom") { + refitFullscreenUmapWindow(); + } }); window.addEventListener("slideshowStartRequested", () => { diff --git a/photomap/frontend/static/main.js b/photomap/frontend/static/main.js index cbe03bab..44a6a78f 100644 --- a/photomap/frontend/static/main.js +++ b/photomap/frontend/static/main.js @@ -12,6 +12,7 @@ import "./javascript/bookmarks.js"; import "./javascript/cluster-utils.js"; import "./javascript/events.js"; import "./javascript/metadata-drawer.js"; +import "./javascript/mobile-sheets.js"; import "./javascript/invoke-recall.js"; import "./javascript/page-visibility.js"; import "./javascript/search-ui.js"; diff --git a/photomap/frontend/templates/main.html b/photomap/frontend/templates/main.html index 265b2248..a72e15d3 100644 --- a/photomap/frontend/templates/main.html +++ b/photomap/frontend/templates/main.html @@ -8,6 +8,31 @@ + + + + + + {% include "modules/search-panel.html" %} {% include "modules/control-panel.html" %} + +
{% include "modules/search.html" %} {% include "modules/umap-floating-window.html" %} diff --git a/photomap/frontend/templates/modules/seek_slider.html b/photomap/frontend/templates/modules/seek_slider.html index a83a0c5b..6b3d2d70 100644 --- a/photomap/frontend/templates/modules/seek_slider.html +++ b/photomap/frontend/templates/modules/seek_slider.html @@ -2,6 +2,10 @@ Line 1 mirrors the semantic-map titlebar: reindex button (swapped for a progress ring while an index update runs) and the album pulldown. Line 2 is the slide position / search score written by score-display.js. --> + +
-
+
@@ -64,3 +68,8 @@
+ + + + diff --git a/tests/frontend/metadata-drawer-sheet.test.js b/tests/frontend/metadata-drawer-sheet.test.js new file mode 100644 index 00000000..d78ecdaa --- /dev/null +++ b/tests/frontend/metadata-drawer-sheet.test.js @@ -0,0 +1,116 @@ +// In the phone layout the metadata drawer's contents are the bottom sheet's +// details stop, so the drawer's open/close entry points (the i, arrow and +// Escape shortcuts, and the swipe up on the photo) move the sheet instead. +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; + +let mobile = true; +let bottomState = "expanded"; +const setSheetState = jest.fn((name, value) => { + bottomState = value; +}); +const closeSheetDetails = jest.fn(() => { + if (bottomState === "details") { + bottomState = "expanded"; + } +}); + +jest.unstable_mockModule("../../photomap/frontend/static/javascript/mobile-sheets.js", () => ({ + isMobileSheetsMode: () => mobile, + setSheetState, + closeSheetDetails, + sheetState: () => bottomState, + sheetVisibleHeight: () => 0, + SHEET_DETAILS: "details", + SHEET_EXPANDED: "expanded", +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/score-display.js", () => ({ + scoreDisplay: { setToggleBookmarkCallback: jest.fn(), setBookmarkStatus: jest.fn(), refreshDisplay: jest.fn() }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/bookmarks.js", () => ({ + bookmarkManager: { isBookmarked: jest.fn(() => false) }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/slide-state.js", () => ({ + slideState: { getCurrentSlide: jest.fn(() => null) }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/state.js", () => ({ + state: { showMetadataFields: false }, + setShowMetadataFields: jest.fn(), +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/search.js", () => ({ + setSearchResults: jest.fn(), +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/utils.js", () => ({ + isColorLight: jest.fn(() => false), + makeDraggable: jest.fn(), +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/cluster-utils.js", () => ({ + getClusterColorFromPoints: jest.fn(), + getClusterInfoForImage: jest.fn(), + getClusterLabelInfo: jest.fn(), + getImageLabelInfo: jest.fn(), + SHOW_CLUSTER_LABELS_IN_BADGES: false, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/invoke-ref-target.js", () => ({ + applyRefTarget: jest.fn(), +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/reference-thumbnails.js", () => ({ + enhanceReferenceImageThumbnails: jest.fn(), + registerReferenceThumbnailClickHandler: jest.fn(), +})); + +document.body.innerHTML = ` +
+
+`; + +const { showMetadataOverlay, hideMetadataOverlay, toggleMetadataOverlay } = + await import("../../photomap/frontend/static/javascript/metadata-drawer.js"); + +const drawer = () => document.getElementById("bannerDrawerContainer"); + +describe("metadata drawer in the phone layout", () => { + beforeEach(() => { + mobile = true; + bottomState = "expanded"; + setSheetState.mockClear(); + closeSheetDetails.mockClear(); + drawer().classList.remove("visible"); + }); + + it("opens the sheet's details instead of the drawer", () => { + showMetadataOverlay(); + expect(setSheetState).toHaveBeenCalledWith("bottom", "details"); + expect(drawer().classList.contains("visible")).toBe(false); + }); + + it("closes them back to the stop they came from", () => { + bottomState = "details"; + hideMetadataOverlay(); + expect(closeSheetDetails).toHaveBeenCalled(); + expect(bottomState).toBe("expanded"); + }); + + it("leaves a collapsed sheet collapsed when asked to close", () => { + bottomState = "collapsed"; + hideMetadataOverlay(); + expect(bottomState).toBe("collapsed"); + expect(setSheetState).not.toHaveBeenCalled(); + }); + + it("toggles on the sheet's stop", () => { + toggleMetadataOverlay(); + expect(bottomState).toBe("details"); + toggleMetadataOverlay(); + expect(bottomState).toBe("expanded"); + }); + + it("still slides the drawer outside the phone layout", () => { + mobile = false; + toggleMetadataOverlay(); + expect(drawer().classList.contains("visible")).toBe(true); + toggleMetadataOverlay(); + expect(drawer().classList.contains("visible")).toBe(false); + expect(setSheetState).not.toHaveBeenCalled(); + expect(closeSheetDetails).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/frontend/mobile-sheets-details.test.js b/tests/frontend/mobile-sheets-details.test.js new file mode 100644 index 00000000..6566b97f --- /dev/null +++ b/tests/frontend/mobile-sheets-details.test.js @@ -0,0 +1,357 @@ +// Tests for the bottom sheet's third stop: the metadata drawer's contents, +// borrowed into the sheet in the phone layout (mobile-sheets.js). +import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals"; + +const MODULE = "../../photomap/frontend/static/javascript/mobile-sheets.js"; + +// jsdom 20 has no PointerEvent; a MouseEvent carrying the pointer fields is +// all the module reads. +function pointer(type, target, { x = 100, y = 100, id = 1, time = 0 } = {}) { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }); + Object.defineProperty(event, "pointerId", { value: id }); + Object.defineProperty(event, "isPrimary", { value: true }); + Object.defineProperty(event, "pointerType", { value: "touch" }); + Object.defineProperty(event, "timeStamp", { value: time }); + target.dispatchEvent(event); + return event; +} + +/** Press on `target`, move vertically in `steps` to `y1`, release. */ +function drag(target, y0, y1, { steps = 10, duration = 400 } = {}) { + pointer("pointerdown", target, { y: y0, time: 0 }); + for (let i = 1; i <= steps; i++) { + pointer("pointermove", target, { y: y0 + ((y1 - y0) * i) / steps, time: (duration * i) / steps }); + } + pointer("pointerup", target, { y: y1, time: duration }); +} + +// jsdom has no Touch constructor; the module reads touches[i].clientY. +function touch(type, target, ys) { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, "touches", { value: ys.map((clientY) => ({ clientY })) }); + target.dispatchEvent(event); + return event; +} + +let queryListeners; +let queryMatches; + +function installMatchMedia(matches) { + queryMatches = matches; + queryListeners = []; + window.matchMedia = jest.fn((query) => ({ + media: query, + get matches() { + return queryMatches; + }, + addEventListener: (type, listener) => queryListeners.push(listener), + removeEventListener: jest.fn(), + })); +} + +function flipQuery(matches) { + queryMatches = matches; + queryListeners.forEach((listener) => listener({ matches })); +} + +// Geometry, in px: the sheet is 700 tall, its details 500 starting 180 down, +// their title row 44. So the expanded stop is 456 below fully open, and the +// collapsed one 676 (700 less the 24px handle). +function buildDom() { + document.body.innerHTML = ` +
+ +
+
+
+
+
+
+
+
photo.png
+

details

+
+
+
+ `; + const set = (id, property, value) => + Object.defineProperty(document.getElementById(id), property, { configurable: true, value }); + set("panelStackContainer", "offsetHeight", 700); + set("sheetDetails", "offsetHeight", 500); + set("sheetDetails", "offsetTop", 180); + set("filenameTitlebar", "offsetHeight", 44); +} + +const root = document.documentElement; +const $ = (id) => document.getElementById(id); + +describe("mobile-sheets.js details stop", () => { + let mod; + let events; + const record = (event) => events.push(event.detail); + + beforeEach(async () => { + jest.useFakeTimers(); + localStorage.clear(); + root.className = ""; + delete root.dataset.topSheet; + delete root.dataset.bottomSheet; + root.removeAttribute("style"); + installMatchMedia(true); + buildDom(); + mod = await import(MODULE); + mod.resetMobileSheetsForTests(); + events = []; + window.addEventListener("mobileSheetChanged", record); + mod.initializeMobileSheets(); + }); + + afterEach(() => { + window.removeEventListener("mobileSheetChanged", record); + jest.useRealTimers(); + }); + + describe("placement", () => { + it("borrows the drawer's contents into the sheet", () => { + expect($("filenameBanner").parentElement).toBe($("sheetDetails")); + expect(root.style.getPropertyValue("--bottom-sheet-panels-height")).toBe("180px"); + }); + + it("hands them back when the phone layout ends, and borrows them again", () => { + flipQuery(false); + expect($("filenameBanner").parentElement).toBe($("bannerDrawerContainer")); + expect(root.style.getPropertyValue("--bottom-sheet-panels-height")).toBe(""); + expect($("descriptionText").parentElement.inert).toBeFalsy(); + expect($("filenameTitlebar").hasAttribute("aria-expanded")).toBe(false); + flipQuery(true); + expect($("filenameBanner").parentElement).toBe($("sheetDetails")); + }); + + it("leaves them in the drawer outside the phone layout", () => { + mod.resetMobileSheetsForTests(); + root.className = ""; + installMatchMedia(false); + buildDom(); + mod.initializeMobileSheets(); + expect($("filenameBanner").parentElement).toBe($("bannerDrawerContainer")); + expect(mod.sheetVisibleHeight("bottom")).toBe(0); + }); + }); + + describe("fullscreen", () => { + afterEach(() => { + delete document.fullscreenElement; + }); + + it("does not move the hidden sheets from code", () => { + Object.defineProperty(document, "fullscreenElement", { configurable: true, value: document.body }); + mod.setSheetState("bottom", "details"); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + }); + + describe("re-announcing", () => { + it("tells listeners when the sheet changes height without changing stop", () => { + // What the ResizeObserver does when, say, the panel labels come on. + Object.defineProperty($("sheetDetails"), "offsetTop", { configurable: true, value: 230 }); + Object.defineProperty($("panelStackContainer"), "offsetHeight", { configurable: true, value: 750 }); + const before = events.length; + mod.notifySheetsResizedForTests(); + expect(events.length).toBe(before + 1); + expect(events.at(-1)).toEqual({ sheet: "bottom", state: "expanded", expanded: true, mobile: true }); + mod.notifySheetsResizedForTests(); + expect(events.length).toBe(before + 1); + }); + }); + + describe("heights", () => { + it("measures the collapsed peek from the handle, whatever the CSS says", () => { + // Sideways, the peek is a calc() with env(), which reads back unevaluated. + Object.defineProperty($("bottomSheetHandle"), "offsetHeight", { configurable: true, value: 46 }); + mod.setSheetState("bottom", "collapsed"); + expect(mod.sheetVisibleHeight("bottom")).toBe(46); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe("46px"); + }); + + it("counts the title row, not the details below it, as the open sheet", () => { + expect(mod.sheetVisibleHeight("bottom")).toBe(244); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe("244px"); + }); + + it("reports the same height at the details stop, which floats over the page", () => { + mod.setSheetState("bottom", "details"); + expect(mod.sheetVisibleHeight("bottom")).toBe(244); + }); + }); + + describe("tapping", () => { + it("opens and closes the details from their title row", () => { + $("filenameText").click(); + expect(root.dataset.bottomSheet).toBe("details"); + expect(events.at(-1)).toEqual({ sheet: "bottom", state: "details", expanded: true, mobile: true }); + $("filenameTitlebar").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("leaves the title row's copy button to copy", () => { + $("copyTextBtn").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("steps down from the details to the panels from the handle", () => { + mod.setSheetState("bottom", "details"); + $("bottomSheetHandle").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("does not open the details from the title row of a collapsed sheet", () => { + mod.setSheetState("bottom", "collapsed"); + $("filenameTitlebar").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + }); + + describe("accessibility", () => { + it("keeps everything under the title row out of reach until the details open", () => { + expect($("filenameTitlebar").inert).toBeFalsy(); + expect($("recallButtonsContainer").inert).toBe(true); + expect($("filenameTitlebar").getAttribute("aria-expanded")).toBe("false"); + mod.setSheetState("bottom", "details"); + expect($("recallButtonsContainer").inert).toBe(false); + expect($("filenameTitlebar").getAttribute("aria-expanded")).toBe("true"); + }); + + it("hides the whole slot with the collapsed sheet", () => { + mod.setSheetState("bottom", "collapsed"); + expect($("sheetDetails").inert).toBe(true); + }); + }); + + describe("persistence", () => { + it("does not remember the details stop", () => { + mod.setSheetState("bottom", "collapsed"); + mod.setSheetState("bottom", "details"); + expect(localStorage.getItem("bottomSheetState")).toBe("collapsed"); + }); + + it("closes the details back to the stop they were opened from", () => { + mod.setSheetState("bottom", "collapsed"); + mod.setSheetState("bottom", "details"); + mod.closeSheetDetails(); + expect(root.dataset.bottomSheet).toBe("collapsed"); + mod.setSheetState("bottom", "expanded"); + mod.setSheetState("bottom", "details"); + mod.closeSheetDetails(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("leaves the sheet alone if the details are not open", () => { + mod.setSheetState("bottom", "collapsed"); + mod.closeSheetDetails(); + expect(root.dataset.bottomSheet).toBe("collapsed"); + }); + + it("does not carry the details stop across a change of layout", () => { + mod.setSheetState("bottom", "details"); + flipQuery(false); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("starts the details from the top each time they open", () => { + mod.setSheetState("bottom", "details"); + $("filenameBanner").scrollTop = 120; + mod.setSheetState("bottom", "expanded"); + expect($("filenameBanner").scrollTop).toBe(0); + }); + }); + + describe("dragging", () => { + it("settles at the nearest stop after a slow drag", () => { + // From expanded (456) up 300 to 156: nearer details (0) than expanded. + drag($("controlPanel"), 400, 100, { duration: 2000 }); + expect(root.dataset.bottomSheet).toBe("details"); + // From details down 150: still nearer details. + drag($("controlPanel"), 100, 250, { duration: 2000 }); + expect(root.dataset.bottomSheet).toBe("details"); + }); + + it("flicks one stop at a time", () => { + mod.setSheetState("bottom", "details"); + drag($("controlPanel"), 100, 140, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + drag($("controlPanel"), 300, 340, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("collapsed"); + drag($("bottomSheetHandle"), 700, 660, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("pulls the sheet down from the details content when it is at the top", () => { + mod.setSheetState("bottom", "details"); + drag($("descriptionText"), 200, 260, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("leaves the details content to scroll once it has scrolled", () => { + mod.setSheetState("bottom", "details"); + $("filenameBanner").scrollTop = 40; + drag($("descriptionText"), 200, 400, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("details"); + expect($("panelStackContainer").style.transform).toBe(""); + }); + + it("leaves an upward drag in the details content to scroll", () => { + mod.setSheetState("bottom", "details"); + drag($("descriptionText"), 400, 300, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("details"); + expect($("panelStackContainer").classList.contains("sheet-dragging")).toBe(false); + }); + + it("always drags from the title row, however far the content has scrolled", () => { + mod.setSheetState("bottom", "details"); + $("filenameBanner").scrollTop = 40; + drag($("filenameText"), 100, 140, { duration: 60 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + }); + + describe("native scrolling of the details", () => { + beforeEach(() => mod.setSheetState("bottom", "details")); + + it("keeps the browser from claiming a downward drag at the top", () => { + touch("touchstart", $("descriptionText"), [200]); + expect(touch("touchmove", $("descriptionText"), [206]).defaultPrevented).toBe(true); + expect(touch("touchmove", $("descriptionText"), [190]).defaultPrevented).toBe(true); + }); + + it("waits out a finger's jitter before deciding", () => { + touch("touchstart", $("descriptionText"), [200]); + expect(touch("touchmove", $("descriptionText"), [198]).defaultPrevented).toBe(false); + expect(touch("touchmove", $("descriptionText"), [230]).defaultPrevented).toBe(true); + }); + + it("lets an upward first move scroll for the rest of the touch", () => { + touch("touchstart", $("descriptionText"), [200]); + expect(touch("touchmove", $("descriptionText"), [195]).defaultPrevented).toBe(false); + expect(touch("touchmove", $("descriptionText"), [230]).defaultPrevented).toBe(false); + }); + + it("lets scrolled content scroll back up", () => { + $("filenameBanner").scrollTop = 40; + touch("touchstart", $("descriptionText"), [200]); + expect(touch("touchmove", $("descriptionText"), [230]).defaultPrevented).toBe(false); + }); + + it("leaves pulldowns and pinches alone", () => { + touch("touchstart", $("refTarget"), [200]); + expect(touch("touchmove", $("refTarget"), [230]).defaultPrevented).toBe(false); + touch("touchstart", $("descriptionText"), [200, 300]); + expect(touch("touchmove", $("descriptionText"), [230, 330]).defaultPrevented).toBe(false); + }); + + it("does nothing at the other stops", () => { + mod.setSheetState("bottom", "expanded"); + touch("touchstart", $("descriptionText"), [200]); + expect(touch("touchmove", $("descriptionText"), [230]).defaultPrevented).toBe(false); + }); + }); +}); diff --git a/tests/frontend/mobile-sheets.test.js b/tests/frontend/mobile-sheets.test.js new file mode 100644 index 00000000..029ebcd5 --- /dev/null +++ b/tests/frontend/mobile-sheets.test.js @@ -0,0 +1,383 @@ +// Tests for mobile-sheets.js: the phone layout's top and bottom sheets. +import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals"; + +const MODULE = "../../photomap/frontend/static/javascript/mobile-sheets.js"; + +// jsdom 20 has no PointerEvent; a MouseEvent carrying the pointer fields is +// all the module reads. +function pointer( + type, + target, + { x = 100, y = 100, id = 1, time = 0, primary = true, button = 0, kind = "touch", buttons } = {} +) { + // A held button reads as buttons = 1 until it is released. + const held = buttons ?? (type === "pointerup" ? 0 : 1); + const event = new MouseEvent(type, { + bubbles: true, + cancelable: true, + clientX: x, + clientY: y, + button, + buttons: held, + }); + Object.defineProperty(event, "pointerId", { value: id }); + Object.defineProperty(event, "isPrimary", { value: primary }); + Object.defineProperty(event, "pointerType", { value: kind }); + Object.defineProperty(event, "timeStamp", { value: time }); + target.dispatchEvent(event); + return event; +} + +/** Press on `target`, move vertically in `steps` to `y1`, release. */ +function drag(target, y0, y1, { steps = 10, duration = 400, release = true, kind = "touch" } = {}) { + pointer("pointerdown", target, { y: y0, time: 0, kind }); + for (let i = 1; i <= steps; i++) { + pointer("pointermove", target, { y: y0 + ((y1 - y0) * i) / steps, time: (duration * i) / steps, kind }); + } + if (release) { + pointer("pointerup", target, { y: y1, time: duration, kind }); + } +} + +let queryListeners; +let queryMatches; + +function installMatchMedia(matches) { + queryMatches = matches; + queryListeners = []; + window.matchMedia = jest.fn((query) => ({ + media: query, + get matches() { + return queryMatches; + }, + addEventListener: (type, listener) => queryListeners.push(listener), + removeEventListener: jest.fn(), + })); +} + +function flipQuery(matches) { + queryMatches = matches; + queryListeners.forEach((listener) => listener({ matches })); +} + +function buildDom() { + document.body.innerHTML = ` +
+
+
+
+ +
+
+ +
+
+
+ `; + for (const [id, height] of [ + ["topSheetContainer", 160], + ["panelStackContainer", 130], + ]) { + Object.defineProperty(document.getElementById(id), "offsetHeight", { configurable: true, value: height }); + } +} + +const root = document.documentElement; + +describe("mobile-sheets.js", () => { + let mod; + let events; + const record = (event) => events.push(event.detail); + + beforeEach(async () => { + jest.useFakeTimers(); + localStorage.clear(); + root.className = ""; + delete root.dataset.topSheet; + delete root.dataset.bottomSheet; + root.removeAttribute("style"); + installMatchMedia(true); + buildDom(); + mod = await import(MODULE); + mod.resetMobileSheetsForTests(); + events = []; + window.addEventListener("mobileSheetChanged", record); + }); + + afterEach(() => { + window.removeEventListener("mobileSheetChanged", record); + jest.useRealTimers(); + }); + + describe("initialization", () => { + it("turns on the phone layout when the query matches", () => { + mod.initializeMobileSheets(); + expect(mod.isMobileSheetsMode()).toBe(true); + expect(root.dataset.bottomSheet).toBe("expanded"); + expect(root.dataset.topSheet).toBe("collapsed"); + }); + + it("leaves the desktop layout alone when it does not", () => { + installMatchMedia(false); + mod.initializeMobileSheets(); + expect(mod.isMobileSheetsMode()).toBe(false); + expect(mod.sheetVisibleHeight("bottom")).toBe(0); + expect(document.getElementById("controlPanel").inert).toBe(false); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe(""); + }); + + it("restores a bottom sheet the user had closed", () => { + localStorage.setItem("bottomSheetState", "collapsed"); + mod.initializeMobileSheets(); + expect(root.dataset.bottomSheet).toBe("collapsed"); + }); + + it("keeps the state the script already set", () => { + root.dataset.bottomSheet = "collapsed"; + mod.initializeMobileSheets(); + expect(root.dataset.bottomSheet).toBe("collapsed"); + }); + + it("announces the starting state of both sheets", () => { + mod.initializeMobileSheets(); + expect(events).toEqual( + expect.arrayContaining([ + { sheet: "bottom", state: "expanded", expanded: true, mobile: true }, + { sheet: "top", state: "collapsed", expanded: false, mobile: true }, + ]) + ); + }); + + it("publishes each sheet's on-screen height", () => { + mod.initializeMobileSheets(); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe("130px"); + // Collapsed: only the peek (the stylesheet is not loaded, so the fallback). + expect(root.style.getPropertyValue("--top-sheet-height")).toBe("26px"); + }); + }); + + describe("accessibility of a collapsed sheet", () => { + it("makes everything but the handle and the progress strip inert", () => { + mod.initializeMobileSheets(); + expect(document.getElementById("fixedScoreDisplay").inert).toBe(true); + expect(document.getElementById("scoreSliderRow").inert).toBe(true); + expect(document.getElementById("sliderHoverStrip").inert).toBeFalsy(); + expect(document.getElementById("topSheetHandle").inert).toBeFalsy(); + expect(document.getElementById("topSheetHandle").getAttribute("aria-expanded")).toBe("false"); + + expect(document.getElementById("controlPanel").inert).toBe(false); + expect(document.getElementById("bottomSheetHandle").getAttribute("aria-expanded")).toBe("true"); + }); + }); + + describe("tapping", () => { + beforeEach(() => mod.initializeMobileSheets()); + + it("toggles a sheet from its handle and remembers the bottom one", () => { + document.getElementById("bottomSheetHandle").click(); + expect(root.dataset.bottomSheet).toBe("collapsed"); + expect(localStorage.getItem("bottomSheetState")).toBe("collapsed"); + expect(document.getElementById("controlPanel").inert).toBe(true); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe("24px"); + expect(events.at(-1)).toEqual({ sheet: "bottom", state: "collapsed", expanded: false, mobile: true }); + + document.getElementById("bottomSheetHandle").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + expect(localStorage.getItem("bottomSheetState")).toBe("expanded"); + }); + + it("does not remember the top sheet", () => { + document.getElementById("topSheetHandle").click(); + expect(root.dataset.topSheet).toBe("expanded"); + expect(localStorage.getItem("bottomSheetState")).toBeNull(); + }); + + it("opens a collapsed sheet from the strip left showing", () => { + document.getElementById("sliderHoverStrip").click(); + expect(root.dataset.topSheet).toBe("expanded"); + }); + + it("leaves an open sheet alone when one of its controls is used", () => { + document.getElementById("deleteBtn").click(); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + }); + + describe("dragging", () => { + beforeEach(() => mod.initializeMobileSheets()); + + it("closes the bottom sheet when dragged down past half way", () => { + const sheet = document.getElementById("panelStackContainer"); + // Slow, so it is the distance and not a flick that decides. + drag(sheet, 500, 580, { duration: 4000 }); + expect(root.dataset.bottomSheet).toBe("collapsed"); + expect(sheet.style.transform).toBe(""); + expect(sheet.classList.contains("sheet-dragging")).toBe(false); + }); + + it("springs back when let go short of half way", () => { + drag(document.getElementById("panelStackContainer"), 500, 530, { duration: 4000 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("follows the finger while dragging, within its travel", () => { + const sheet = document.getElementById("panelStackContainer"); + drag(sheet, 500, 540, { release: false }); + expect(sheet.style.transform).toBe("translateY(40px)"); + expect(sheet.classList.contains("sheet-dragging")).toBe(true); + pointer("pointermove", sheet, { y: 900, time: 500 }); + // 130px tall, 24px peek: 106px of travel. + expect(sheet.style.transform).toBe("translateY(106px)"); + pointer("pointerup", sheet, { y: 900, time: 500 }); + }); + + it("closes on a short fast flick", () => { + drag(document.getElementById("panelStackContainer"), 500, 530, { duration: 50 }); + expect(root.dataset.bottomSheet).toBe("collapsed"); + }); + + it("opens the top sheet when pulled down", () => { + const sheet = document.getElementById("topSheetContainer"); + drag(sheet, 10, 140, { duration: 4000 }); + expect(root.dataset.topSheet).toBe("expanded"); + }); + + it("moves the top sheet the other way", () => { + const sheet = document.getElementById("topSheetContainer"); + drag(sheet, 10, 50, { release: false }); + // Collapsed starts at the far end (160 - 26 = 134) and pulling down opens. + expect(sheet.style.transform).toBe("translateY(-94px)"); + pointer("pointerup", sheet, { y: 50, time: 400 }); + }); + + it("swallows the click that ends a mouse drag started on a button", () => { + const button = document.getElementById("deleteBtn"); + const onClick = jest.fn(); + button.addEventListener("click", onClick); + drag(button, 500, 600, { duration: 4000, kind: "mouse" }); + button.click(); + expect(onClick).not.toHaveBeenCalled(); + // Only that one click. + button.click(); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it("swallows nothing after a touch drag, which never clicks", () => { + const button = document.getElementById("deleteBtn"); + const onClick = jest.fn(); + button.addEventListener("click", onClick); + drag(button, 500, 600, { duration: 4000 }); + // The user's next tap, straight after. + button.click(); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it("swallows nothing after a cancelled drag", () => { + const button = document.getElementById("deleteBtn"); + const onClick = jest.fn(); + button.addEventListener("click", onClick); + drag(button, 500, 600, { release: false, kind: "mouse" }); + pointer("pointercancel", button, { y: 600, kind: "mouse" }); + button.click(); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it("forgets a mouse press released off the sheet before it became a drag", () => { + const sheet = document.getElementById("panelStackContainer"); + pointer("pointerdown", sheet, { y: 500, kind: "mouse" }); + // The button comes up elsewhere; later the mouse hovers back down. + pointer("pointermove", sheet, { y: 520, kind: "mouse", buttons: 0 }); + pointer("pointermove", sheet, { y: 540, kind: "mouse", buttons: 0 }); + expect(sheet.classList.contains("sheet-dragging")).toBe(false); + expect(sheet.style.transform).toBe(""); + }); + + it("stops swallowing if the click never comes", () => { + const button = document.getElementById("deleteBtn"); + const onClick = jest.fn(); + button.addEventListener("click", onClick); + drag(button, 500, 600, { duration: 4000, kind: "mouse" }); + jest.advanceTimersByTime(1000); + button.click(); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it("lets a tap through to the button it lands on", () => { + const button = document.getElementById("deleteBtn"); + const onClick = jest.fn(); + button.addEventListener("click", onClick); + drag(button, 500, 504); + button.click(); + expect(onClick).toHaveBeenCalledTimes(1); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("ignores a sideways drag", () => { + const sheet = document.getElementById("panelStackContainer"); + pointer("pointerdown", sheet, { x: 100, y: 500 }); + pointer("pointermove", sheet, { x: 160, y: 505 }); + pointer("pointermove", sheet, { x: 160, y: 600 }); + pointer("pointerup", sheet, { x: 160, y: 600 }); + expect(sheet.style.transform).toBe(""); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("never starts on the seek slider, which drags its own thumb", () => { + document.getElementById("topSheetHandle").click(); + const sheet = document.getElementById("topSheetContainer"); + drag(document.getElementById("slideSeekSlider"), 60, 10, { duration: 4000 }); + expect(sheet.style.transform).toBe(""); + expect(root.dataset.topSheet).toBe("expanded"); + }); + + it("settles at the nearer end when the browser cancels the gesture", () => { + const sheet = document.getElementById("panelStackContainer"); + drag(sheet, 500, 590, { release: false }); + pointer("pointercancel", sheet, { y: 590, time: 500 }); + expect(root.dataset.bottomSheet).toBe("collapsed"); + expect(sheet.style.transform).toBe(""); + }); + }); + + describe("switching layouts", () => { + beforeEach(() => mod.initializeMobileSheets()); + + it("tells listeners when the phone layout ends", () => { + flipQuery(false); + expect(mod.isMobileSheetsMode()).toBe(false); + expect(events).toEqual( + expect.arrayContaining([ + { sheet: "top", state: "collapsed", expanded: false, mobile: false }, + { sheet: "bottom", state: "expanded", expanded: true, mobile: false }, + ]) + ); + expect(root.style.getPropertyValue("--bottom-sheet-height")).toBe(""); + expect(document.getElementById("fixedScoreDisplay").inert).toBe(false); + }); + + it("comes back with the slider closed", () => { + document.getElementById("topSheetHandle").click(); + flipQuery(false); + flipQuery(true); + expect(root.dataset.topSheet).toBe("collapsed"); + expect(events.at(-1).mobile).toBe(true); + }); + + it("abandons a drag in progress", () => { + const sheet = document.getElementById("panelStackContainer"); + drag(sheet, 500, 560, { release: false }); + flipQuery(false); + expect(sheet.style.transform).toBe(""); + expect(sheet.classList.contains("sheet-dragging")).toBe(false); + pointer("pointerup", sheet, { y: 560, time: 500 }); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + + it("ignores taps and drags outside the phone layout", () => { + flipQuery(false); + document.getElementById("bottomSheetHandle").click(); + drag(document.getElementById("panelStackContainer"), 500, 600); + expect(root.dataset.bottomSheet).toBe("expanded"); + }); + }); +}); diff --git a/tests/frontend/seek-slider-sheet.test.js b/tests/frontend/seek-slider-sheet.test.js new file mode 100644 index 00000000..5c70b563 --- /dev/null +++ b/tests/frontend/seek-slider-sheet.test.js @@ -0,0 +1,129 @@ +// The seek slider in the phone layout's top sheet: open for exactly as long as +// the sheet is, whatever the hover, fade-out and badge-tap paths would do. +import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals"; + +jest.unstable_mockModule("../../photomap/frontend/static/javascript/score-display.js", () => ({ + scoreDisplay: { showIndex: jest.fn(), setBookmarkStatus: jest.fn() }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/back-stack.js", () => ({ + backStack: { markNextAsJump: jest.fn() }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/bookmarks.js", () => ({ + bookmarkManager: { isBookmarked: jest.fn(() => false) }, +})); +const mockSlideState = { getCurrentIndex: jest.fn(() => 2), navigateToIndex: jest.fn(), isSearchMode: false }; +jest.unstable_mockModule("../../photomap/frontend/static/javascript/slide-state.js", () => ({ + slideState: mockSlideState, + getCurrentSlideIndex: jest.fn(() => [2, 5, 0]), +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/state.js", () => ({ + state: { searchResults: [], searchType: "clear", album: "test" }, +})); +jest.unstable_mockModule("../../photomap/frontend/static/javascript/utils.js", () => ({ + debounce: (fn) => fn, +})); +let mobile = true; +jest.unstable_mockModule("../../photomap/frontend/static/javascript/mobile-sheets.js", () => ({ + isMobileSheetsMode: () => mobile, +})); + +const { seekSlider } = await import("../../photomap/frontend/static/javascript/seek-slider.js"); + +function sheetChanged(expanded, isMobile = true) { + window.dispatchEvent(new CustomEvent("mobileSheetChanged", { detail: { sheet: "top", expanded, mobile: isMobile } })); +} + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +describe("seek slider pinned by the top sheet", () => { + beforeEach(async () => { + mobile = true; + global.fetch = jest.fn(async () => ({ ok: true, json: async () => ({ last_modified: 0 }) })); + document.body.innerHTML = ` +
+
+
+
+
+
+ +
+ +
+
+
+
+ `; + seekSlider.sheetPinned = false; + seekSlider.sliderVisible = false; + seekSlider.initialize(); + await flush(); + }); + + afterEach(() => { + seekSlider.unpinForSheet(); + seekSlider.clearFadeOutTimer(); + }); + + it("drops the inline left edge that squeezes it beside the badge", () => { + expect(document.getElementById("scoreSliderRow").style.left).toBe(""); + }); + + it("opens with the sheet, with its range, position and ticks", async () => { + sheetChanged(true); + await flush(); + await flush(); + expect(seekSlider.sheetPinned).toBe(true); + expect(seekSlider.sliderVisible).toBe(true); + expect(document.getElementById("sliderWithTicksContainer").classList.contains("visible")).toBe(true); + expect(document.getElementById("sliderHoverStrip").classList.contains("hidden")).toBe(true); + const slider = document.getElementById("slideSeekSlider"); + expect(slider.max).toBe("5"); + expect(slider.value).toBe("3"); + expect(document.querySelectorAll(".slider-tick").length).toBe(seekSlider.TICK_COUNT); + }); + + it("stays open through the paths that would otherwise close it", async () => { + sheetChanged(true); + await flush(); + seekSlider.hideSlider(); + seekSlider.scheduleHide(); + seekSlider.resetFadeOutTimer(); + await seekSlider.toggleSlider(); + document.getElementById("fixedScoreDisplay").click(); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(seekSlider.sliderVisible).toBe(true); + expect(seekSlider.fadeOutTimeoutId).toBeNull(); + expect(document.getElementById("sliderWithTicksContainer").classList.contains("visible")).toBe(true); + }); + + it("closes with the sheet", async () => { + sheetChanged(true); + await flush(); + sheetChanged(false); + expect(seekSlider.sheetPinned).toBe(false); + expect(seekSlider.sliderVisible).toBe(false); + expect(document.getElementById("sliderHoverStrip").classList.contains("hidden")).toBe(false); + }); + + it("closes when the phone layout ends, and measures from the badge again", async () => { + sheetChanged(true); + await flush(); + mobile = false; + sheetChanged(false, false); + expect(seekSlider.sheetPinned).toBe(false); + expect(seekSlider.sliderVisible).toBe(false); + // jsdom lays nothing out, so only that it is set again, not to what. + expect(document.getElementById("scoreSliderRow").style.left).not.toBe(""); + }); + + it("re-reads the range at once when the search changes under an open sheet", async () => { + sheetChanged(true); + await flush(); + const slider = document.getElementById("slideSeekSlider"); + slider.max = "1"; + window.dispatchEvent(new CustomEvent("searchResultsChanged")); + await flush(); + expect(slider.max).toBe("5"); + }); +});