Files
raucao 64d26951d4
CI / Lint (pull_request) Successful in 56s
CI / Test (pull_request) Successful in 1m27s
Release Drafter / Update release notes draft (pull_request) Successful in 16s
Extend the expanded mobile sheet up to the search field
The tallest detent now fills the viewport down from the top of the search
field, so a fully expanded sheet covers the search field and avatar while
leaving that little strip visible above.

- DETENT_FRACTIONS.expanded is now the whole sheet; the sheet height is the
  viewport minus a top gap (replacing the 0.92 fraction cap).
- The modifier measures that gap from the search field, relative to the sheet's
  container (the viewport top is not the app's top), falling back to 8px.
- Update the sheet-detents unit test and read the real --sheet-height in the
  stacked-sheets acceptance test.
2026-11-30 18:08:02 +04:00

647 lines
21 KiB
JavaScript

import Modifier from 'ember-modifier';
import { service } from '@ember/service';
import { registerDestructor } from '@ember/destroyable';
import {
clamp,
computeDetentLayout,
computeSheetHeight,
findDetent,
nearestDetentIndex,
resolveSnap,
} from '../utils/sheet-detents';
// The mobile breakpoint must match the CSS `width <= 768px` query and the
// `size[0] <= 768` checks in components/map.gjs. matchMedia needs the
// max-width form.
const MOBILE_QUERY = '(max-width: 768px)';
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
// How far the pointer must travel before a press becomes a drag. Keeps taps on
// the header's back/close buttons working.
const DRAG_THRESHOLD_PX = 6;
// Velocity is sampled over this trailing window.
const VELOCITY_WINDOW_MS = 100;
// Must be >= the CSS transform transition duration.
const TRANSITION_MS = 300;
const HANDLE_SELECTOR = '.sheet-handle, .sidebar-header';
// Form fields keep the gesture for text selection / native controls. Buttons
// and links elsewhere (list rows, header-adjacent controls aside) are drag
// surfaces too — the drag threshold keeps taps working.
const FORM_SELECTOR = 'input, select, textarea';
const HEADER_CONTROL_SELECTOR = 'button, a';
// Fallback strip kept above a fully expanded sheet when the search field can't
// be measured. The mobile header pads the search form down by 0.5rem.
const DEFAULT_SHEET_TOP_GAP = 8;
export default class BottomSheetModifier extends Modifier {
@service mapUi;
@service router;
element = null;
named = {};
mediaQuery = null;
reducedMotionQuery = null;
active = false;
destroyed = false;
handle = null;
previousDetentArg = null;
// Gesture state
pointerId = null;
pending = false;
dragging = false;
startY = 0;
startOffset = 0;
currentOffset = 0;
samples = [];
dismissTimer = null;
// Overscroll-to-shrink: set when a drag starts in the sheet content while the
// sheet is at its largest detent and the content is scrolled to the top. A
// downward pull then resizes the sheet instead of scrolling.
overscroll = false;
gestureStartY = 0;
// Deferred service writes. The Map reads sheetInsetPx during render, so the
// modifier must not write it mid-render; it coalesces writes into a
// requestAnimationFrame flush and releases ownership the same way.
pendingInset = null;
pendingSnap = false;
flushRaf = null;
releaseRaf = null;
// Layout, recomputed on viewport changes
viewportHeight = 0;
sheetHeight = 0;
layout = [];
modify(element, _positional, named) {
const firstRun = this.element === null;
this.element = element;
this.named = named ?? {};
// Mark the sheet so selectors can tell the interactive top sheet from the
// inert background (parent) sheet, even on desktop where the modifier does
// not activate. This runs on every modify, before the active-state check.
const background = !!this.named.background;
element.classList.toggle('sheet-background', background);
element.classList.toggle('sheet-top', !background);
if (firstRun) {
this.mediaQuery = window.matchMedia(MOBILE_QUERY);
this.reducedMotionQuery = window.matchMedia(REDUCED_MOTION_QUERY);
this.onMediaChange = () => this.applyActiveState();
this.mediaQuery.addEventListener('change', this.onMediaChange);
this.onResize = () => this.handleViewportChange();
window.addEventListener('resize', this.onResize);
if (window.visualViewport) {
this.onVisualViewport = () => this.handleViewportChange();
window.visualViewport.addEventListener('resize', this.onVisualViewport);
}
registerDestructor(this, () => this.teardown());
}
this.applyActiveState();
}
// --- activation -----------------------------------------------------------
applyActiveState() {
const shouldBeActive = this.mediaQuery.matches && !this.named.disabled;
if (shouldBeActive && !this.active) {
this.activate();
} else if (!shouldBeActive && this.active) {
this.deactivate();
} else if (shouldBeActive) {
this.handleDetentArgChange();
}
}
activate() {
this.active = true;
// A pending release from an earlier deactivate must not fire after we have
// re-claimed the slot (breakpoint flip / disabled arg flip).
this.cancelRelease();
// A background sheet sits behind the interactive one: it must not steal
// inset ownership, take gestures, or inject a handle. It is pinned to the
// minimum detent (see initialDetentName) so it stays hidden.
if (!this.named.background) {
this.mapUi.claimSheetInset(this);
this.injectHandle();
this.element.addEventListener('pointerdown', this.onPointerDown);
// Non-passive so an overscroll pull can stop the browser from claiming
// the pan and let the pointer drag resize the sheet instead.
this.element.addEventListener('touchmove', this.onTouchMove, {
passive: false,
});
}
this.measure();
this.previousDetentArg = this.named.detent ?? null;
this.enterAt(this.initialDetentName());
}
// The detent this sheet opens at. A background sheet is always minimized so
// it can never peek above the interactive top sheet; a top sheet opens at the
// detent remembered for its route, falling back to its declared default.
initialDetentName() {
if (this.named.background) return this.minimumDetent().name;
return (
this.mapUi.getSheetDetent(this.sheetKey()) ??
this.named.detent ??
this.minimumDetent().name
);
}
// The least-visible reachable detent (largest offset). The top sheet can
// never be shorter than this, so a background sheet parked here is always
// fully covered.
minimumDetent() {
return this.layout[this.layout.length - 1];
}
// The most-visible reachable detent (smallest offset, 0 for the expanded
// stop). The content only scrolls while the sheet rests here.
isAtMax() {
const max = this.layout[0]?.offset ?? 0;
return this.currentOffset <= max + 0.5;
}
// Mirrors the at-max state onto the element so CSS can switch the content
// between "drag the sheet" and "scroll" (touch-action).
syncAtMaxClass() {
this.element.classList.toggle('sheet-at-max', this.isAtMax());
}
// Sheet identity for the remembered-detent map. Background sheets never use
// it (they are pinned to the minimum), so deriving it from the active route
// is safe even though a background is rendered under a different route.
sheetKey() {
return this.router.currentRouteName ?? null;
}
deactivate() {
this.active = false;
this.cancelDrag();
this.element.removeEventListener('pointerdown', this.onPointerDown);
this.element.removeEventListener('touchmove', this.onTouchMove);
this.removeHandle();
this.element.classList.remove('sheet-dragging');
this.element.classList.remove('sheet-at-max');
this.element.style.removeProperty('--sheet-height');
this.element.style.removeProperty('--sheet-offset');
this.cancelFlush();
if (!this.named.background) {
this.scheduleRelease();
}
}
teardown() {
this.destroyed = true;
if (this.dismissTimer) {
clearTimeout(this.dismissTimer);
this.dismissTimer = null;
}
this.cancelDrag();
if (this.mediaQuery && this.onMediaChange) {
this.mediaQuery.removeEventListener('change', this.onMediaChange);
}
window.removeEventListener('resize', this.onResize);
if (window.visualViewport && this.onVisualViewport) {
window.visualViewport.removeEventListener(
'resize',
this.onVisualViewport
);
}
if (this.element) {
this.element.removeEventListener('pointerdown', this.onPointerDown);
this.element.removeEventListener('touchmove', this.onTouchMove);
this.removeHandle();
}
// Only release if we actually owned the slot; a background sheet never
// claims it, and a modifier that never activated (desktop) must not touch
// the service at all.
if (this.active) {
this.cancelFlush();
if (!this.named.background) {
this.scheduleRelease();
}
}
}
// --- deferred service writes ---------------------------------------------
queueInset(px) {
this.pendingInset = Math.max(0, Math.round(px));
this.scheduleFlush();
}
queueSnap() {
this.pendingSnap = true;
this.scheduleFlush();
}
// The modifier must not write tracked service state during render (the Map
// reads sheetInsetPx while rendering), so writes are coalesced into a
// requestAnimationFrame callback, which runs outside the render transaction.
scheduleFlush() {
if (this.flushRaf !== null) return;
this.flushRaf = requestAnimationFrame(() => {
this.flushRaf = null;
this.flush();
});
}
cancelFlush() {
if (this.flushRaf !== null) {
cancelAnimationFrame(this.flushRaf);
this.flushRaf = null;
}
}
flush() {
if (this.pendingInset !== null) {
this.mapUi.setSheetInsetFor(this, this.pendingInset);
this.pendingInset = null;
}
if (this.pendingSnap) {
this.pendingSnap = false;
this.mapUi.snapSheetFor(this);
}
}
// The release is scheduled on its own frame (not tied to the modifier's
// lifetime) so it still runs while the modifier is being torn down.
// Ownership makes a stale release a no-op once a newer sheet has claimed.
scheduleRelease() {
this.cancelRelease();
this.releaseRaf = requestAnimationFrame(() => {
this.releaseRaf = null;
this.mapUi.releaseSheetInset(this);
});
}
cancelRelease() {
if (this.releaseRaf !== null) {
cancelAnimationFrame(this.releaseRaf);
this.releaseRaf = null;
}
}
// --- layout ---------------------------------------------------------------
measure() {
// innerHeight is the numeric source of truth for height; a visualViewport
// listener also fires when the iOS keyboard opens, and reading innerHeight
// there keeps the measurement identical so the sheet does not collapse.
this.viewportHeight = window.innerHeight;
this.sheetHeight = computeSheetHeight(this.viewportHeight, this.topGap());
this.layout = computeDetentLayout({
viewportHeight: this.viewportHeight,
sheetHeight: this.sheetHeight,
});
this.element.style.setProperty('--sheet-height', `${this.sheetHeight}px`);
}
// The strip of viewport kept visible above a fully expanded sheet: the top of
// the search field, so the sheet reaches up to (and covers) the search field
// and avatar while leaving that little space above. Measured relative to the
// sheet's container, since the viewport top is not the app's top (e.g. in
// tests the app sits below the QUnit results).
topGap() {
const searchForm = document.querySelector('.search-form');
const container = this.element?.parentElement;
if (searchForm && container) {
const gap =
searchForm.getBoundingClientRect().top -
container.getBoundingClientRect().top;
if (gap > 0 && gap < 200) return Math.round(gap);
}
return DEFAULT_SHEET_TOP_GAP;
}
handleViewportChange() {
if (!this.active || this.destroyed) return;
this.measure();
// Mid-drag: keep the finger-following offset, only refresh the snap
// targets so the release settles correctly.
if (this.dragging || this.pending) return;
const name = this.named.background
? this.minimumDetent().name
: (this.mapUi.getSheetDetent(this.sheetKey()) ??
this.named.detent ??
this.minimumDetent().name);
const detent = findDetent(this.layout, name) ?? this.minimumDetent();
// Skip the settle (and its map-pan signal) when nothing actually moved,
// e.g. an iOS keyboard opening resizes the visual viewport but not
// innerHeight.
if (detent.offset === this.currentOffset) return;
this.settleAt(detent);
}
handleDetentArgChange() {
// Background sheets are pinned to the minimum; a changing arg must not
// un-minimize them.
if (this.named.background) return;
const requested = this.named.detent ?? null;
if (requested === this.previousDetentArg) return;
this.previousDetentArg = requested;
if (requested === null) return;
if (this.dragging || this.pending) return;
const detent = findDetent(this.layout, requested);
if (detent) this.settleAt(detent);
}
// --- positioning ----------------------------------------------------------
applyOffset(offset) {
const clamped = clamp(offset, 0, this.sheetHeight);
this.currentOffset = clamped;
this.element.style.setProperty('--sheet-offset', `${clamped}px`);
this.queueInset(this.sheetHeight - clamped);
this.syncAtMaxClass();
}
settleAt(detent) {
this.element.classList.remove('sheet-dragging');
this.currentOffset = detent.offset;
this.element.style.setProperty('--sheet-offset', `${detent.offset}px`);
this.queueInset(this.sheetHeight - detent.offset);
this.syncAtMaxClass();
// Background sheets restore from the detent memory but must never write it:
// the top sheet's position is the one worth remembering.
if (!this.named.background) {
this.mapUi.setSheetDetent(this.sheetKey(), detent.name);
}
this.queueSnap();
}
enterAt(name) {
const detent =
findDetent(this.layout, name) ?? this.layout[this.layout.length - 1];
// Background sheets appear in place immediately (no entrance animation):
// the top sheet animates over them, so a second animation would be a
// distracting double-slide.
if (this.named.background || this.reducedMotionQuery.matches) {
this.settleAt(detent);
return;
}
// Start fully hidden, then slide to the detent on the next frame so the
// transform transition animates the entrance.
this.currentOffset = this.sheetHeight;
this.element.style.setProperty('--sheet-offset', `${this.sheetHeight}px`);
this.syncAtMaxClass();
this.queueInset(0);
requestAnimationFrame(() => {
if (!this.active || this.destroyed) return;
this.settleAt(detent);
});
}
// --- handle ---------------------------------------------------------------
injectHandle() {
if (this.handle) return;
const handle = document.createElement('div');
handle.className = 'sheet-handle';
handle.setAttribute('aria-hidden', 'true');
handle.setAttribute('data-test-sheet-handle', '');
this.element.prepend(handle);
this.handle = handle;
}
removeHandle() {
if (this.handle?.parentNode) {
this.handle.parentNode.removeChild(this.handle);
}
this.handle = null;
}
// --- gestures -------------------------------------------------------------
onPointerDown = (event) => {
if (this.destroyed || this.pointerId !== null) return;
if (event.pointerType === 'mouse' && event.button !== 0) return;
// Only the primary pointer may start a drag, so a second finger landing on
// the header during a map pinch does not hijack the gesture.
if (!event.isPrimary) return;
const target = event.target;
if (!(target instanceof Element)) return;
if (target.closest(FORM_SELECTOR)) return;
const onHandle = target.closest(HANDLE_SELECTOR);
// Header controls stay tappable instead of starting a drag.
if (onHandle && target.closest(HEADER_CONTROL_SELECTOR)) return;
const content = target.closest('.sidebar-content');
let overscroll = false;
if (!onHandle) {
// Below the largest detent the whole content is a drag surface. At the
// largest detent it scrolls instead — unless it is scrolled to the top,
// where a downward pull shrinks the sheet (overscroll).
if (!content) return;
if (this.isAtMax()) {
if (content.scrollTop > 0) return;
overscroll = true;
}
}
this.pointerId = event.pointerId;
this.pending = true;
this.dragging = false;
this.overscroll = overscroll;
this.gestureStartY = event.clientY;
this.startY = event.clientY;
this.startOffset = this.currentOffset;
this.samples = [{ y: event.clientY, t: performance.now() }];
window.addEventListener('pointermove', this.onPointerMove, {
passive: false,
});
window.addEventListener('pointerup', this.onPointerUp);
window.addEventListener('pointercancel', this.onPointerCancel);
};
// A non-passive touchmove listener (see activate) that keeps the browser from
// claiming the pan while an overscroll pull is in progress, so the pointer
// drag can shrink the sheet instead.
onTouchMove = (event) => {
if (!this.overscroll || !(this.pending || this.dragging)) return;
const touch = event.touches?.[0];
if (!touch) return;
if (touch.clientY > this.gestureStartY && event.cancelable) {
event.preventDefault();
}
};
onPointerMove = (event) => {
if (event.pointerId !== this.pointerId) return;
if (this.pending) {
const thresholdDy = event.clientY - this.startY;
if (Math.abs(thresholdDy) < DRAG_THRESHOLD_PX) return;
// An upward pull at the top of the content should scroll it, not resize
// the sheet, so hand the gesture back to the browser.
if (this.overscroll && thresholdDy < 0) {
this.endGesture();
return;
}
this.pending = false;
this.dragging = true;
this.element.classList.add('sheet-dragging');
// Rebase on the live visual position. While a snap or the entrance
// transition is still interpolating, currentOffset already points at the
// target, so using it here would make the sheet jump. Reading the actual
// transform keeps the gesture continuous.
this.startY = event.clientY;
this.startOffset = this.readLiveOffset();
this.samples = [{ y: event.clientY, t: performance.now() }];
}
if (event.cancelable) event.preventDefault();
this.recordSample(event.clientY);
this.applyOffset(this.startOffset + (event.clientY - this.startY));
};
onPointerUp = (event) => {
if (event.pointerId !== this.pointerId) return;
// A press that never crossed the threshold is a tap: leave it to the
// browser so header buttons keep working.
if (this.pending) {
this.endGesture();
return;
}
const velocity = this.computeVelocity();
const target = resolveSnap({
offset: this.currentOffset,
velocity,
layout: this.layout,
sheetHeight: this.sheetHeight,
});
this.endGesture();
if (target === 'dismissed') {
this.dismiss();
} else {
const detent = findDetent(this.layout, target);
if (detent) this.settleAt(detent);
}
};
onPointerCancel = (event) => {
if (event.pointerId !== this.pointerId) return;
const wasDragging = this.dragging;
this.endGesture();
if (!wasDragging) return;
const detent =
this.layout[nearestDetentIndex(this.layout, this.currentOffset)];
if (detent) this.settleAt(detent);
};
dismiss() {
this.element.classList.remove('sheet-dragging');
this.currentOffset = this.sheetHeight;
this.element.style.setProperty('--sheet-offset', `${this.sheetHeight}px`);
this.syncAtMaxClass();
this.queueInset(0);
// A drag-dismiss forgets this sheet: the next time it opens it should use
// its declared default, not the position the user dragged it to.
this.mapUi.setSheetDetent(this.sheetKey(), null);
const onDismiss = this.named.onDismiss;
const delay = this.reducedMotionQuery.matches ? 0 : TRANSITION_MS;
this.dismissTimer = setTimeout(() => {
this.dismissTimer = null;
if (typeof onDismiss === 'function') onDismiss();
}, delay);
}
endGesture() {
window.removeEventListener('pointermove', this.onPointerMove);
window.removeEventListener('pointerup', this.onPointerUp);
window.removeEventListener('pointercancel', this.onPointerCancel);
this.pointerId = null;
this.pending = false;
this.dragging = false;
this.overscroll = false;
}
cancelDrag() {
if (this.dismissTimer) {
clearTimeout(this.dismissTimer);
this.dismissTimer = null;
}
this.endGesture();
this.element?.classList.remove('sheet-dragging');
}
// The sheet's current visual offset in px, read from the rendered transform.
// Differs from currentOffset while a CSS transition is still interpolating.
readLiveOffset() {
const transform = getComputedStyle(this.element).transform;
if (!transform || transform === 'none') {
return this.currentOffset;
}
try {
const matrix = new DOMMatrixReadOnly(transform);
return clamp(matrix.m42, 0, this.sheetHeight);
} catch {
return this.currentOffset;
}
}
recordSample(y) {
const now = performance.now();
this.samples.push({ y, t: now });
while (
this.samples.length > 2 &&
now - this.samples[0].t > VELOCITY_WINDOW_MS * 1.5
) {
this.samples.shift();
}
}
computeVelocity() {
const now = performance.now();
const recent = this.samples.filter(
(sample) => now - sample.t <= VELOCITY_WINDOW_MS
);
if (recent.length < 2) return 0;
const first = recent[0];
const last = recent[recent.length - 1];
const dt = last.t - first.t;
if (dt <= 0) return 0;
// Positive velocity means the pointer moved downward.
return (last.y - first.y) / dt;
}
}