Merge pull request 'Add a swipeable, stacked mobile bottom drawer' (#141) from feature/bottom_drawer_swiping into master
CI / Lint (push) Successful in 54s
CI / Test (push) Successful in 1m24s

Reviewed-on: #141
This commit was merged in pull request #141.
This commit is contained in:
raucao committed 2026-11-30 14:29:38 +00:00
commit e6e33ba2d2
34 files changed
+2591 -326

No files matched your search

+9 -15
View File
@@ -3,6 +3,7 @@ import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';
import Icon from './icon';
import DrawerHeader from './drawer-header';
import TabNav from './tab-nav';
import ActivityZapItem from './activity-zap-item';
import ActivityPhotoItem from './activity-photo-item';
@@ -13,6 +14,7 @@ import eq from 'ember-truth-helpers/helpers/eq';
import and from 'ember-truth-helpers/helpers/and';
import restoreScroll from '../modifiers/restore-scroll';
import observeIntersection from '../modifiers/observe-intersection';
import bottomSheet from '../modifiers/bottom-sheet';
export default class ActivityTimelineComponent extends Component {
@tracked isNostrConnectModalOpen = false;
@@ -40,21 +42,13 @@ export default class ActivityTimelineComponent extends Component {
}
<template>
<div class="sidebar">
<div class="sidebar-header has-back-btn">
<button type="button" class="back-btn" {{on "click" @onBack}}>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
<h2 class="sidebar-header-text-centered">
<span class="sidebar-header-icon-wrapper">
<Icon @name="activity" @size={{20}} @color="#898989" />
</span>
Activity
</h2>
<button type="button" class="close-btn" {{on "click" @onClose}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<div class="sidebar" {{bottomSheet detent="medium" onDismiss=@onClose}}>
<DrawerHeader
@title="Activity"
@icon="activity"
@onBack={{@onBack}}
@onClose={{@onClose}}
/>
<TabNav
@tabs={{this.tabs}}
+2 -10
View File
@@ -1,17 +1,9 @@
import { on } from '@ember/modifier';
import Icon from '#components/icon';
import DrawerHeader from '#components/drawer-header';
<template>
{{! template-lint-disable no-nested-interactive }}
<div class="sidebar-header has-back-btn">
<button type="button" class="back-btn" {{on "click" @onBack}}>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
<h2 class="sidebar-header-text-centered">About</h2>
<button type="button" class="close-btn" {{on "click" @onClose}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<DrawerHeader @title="About" @onBack={{@onBack}} @onClose={{@onClose}} />
<div class="sidebar-content">
<section class="about-section">
+6 -11
View File
@@ -2,20 +2,15 @@ import { on } from '@ember/modifier';
import { fn } from '@ember/helper';
import { htmlSafe } from '@ember/template';
import Icon from '#components/icon';
import DrawerHeader from '#components/drawer-header';
import iconRounded from '../../icons/icon-rounded.svg?raw';
<template>
<div class="sidebar-header">
<h2>
<span class="app-logo-icon">
{{htmlSafe iconRounded}}
</span>
Marco
</h2>
<button type="button" class="close-btn" {{on "click" @onClose}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<DrawerHeader
@logo={{htmlSafe iconRounded}}
@title="Marco"
@onClose={{@onClose}}
/>
<div class="sidebar-content">
<ul class="app-menu">
+5 -1
View File
@@ -4,6 +4,7 @@ import { tracked } from '@glimmer/tracking';
import { fn } from '@ember/helper';
import { service } from '@ember/service';
import eq from 'ember-truth-helpers/helpers/eq';
import bottomSheet from '../../modifiers/bottom-sheet';
import AppMenuHome from './home';
import AppMenuSettings from './settings';
@@ -34,7 +35,10 @@ export default class AppMenu extends Component {
}
<template>
<div class="sidebar app-menu-pane">
<div
class="sidebar app-menu-pane"
{{bottomSheet detent="medium" onDismiss=@onClose background=@background}}
>
{{#if (eq this.currentView "menu")}}
<AppMenuHome
@onNavigate={{this.setView}}
+2 -11
View File
@@ -1,8 +1,7 @@
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { action } from '@ember/object';
import { service } from '@ember/service';
import Icon from '#components/icon';
import DrawerHeader from '#components/drawer-header';
import AppMenuSettingsMapUi from './settings/map-ui';
import AppMenuSettingsApis from './settings/apis';
import AppMenuSettingsNostr from './settings/nostr';
@@ -21,15 +20,7 @@ export default class AppMenuSettings extends Component {
}
<template>
<div class="sidebar-header has-back-btn">
<button type="button" class="back-btn" {{on "click" @onBack}}>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
<h2 class="sidebar-header-text-centered">Settings</h2>
<button type="button" class="close-btn" {{on "click" @onClose}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<DrawerHeader @title="Settings" @onBack={{@onBack}} @onClose={{@onClose}} />
<div class="sidebar-content">
<section class="settings-section">
+60
View File
@@ -0,0 +1,60 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import eq from 'ember-truth-helpers/helpers/eq';
import PlacesSidebar from './places-sidebar';
import AppMenu from './app-menu/index';
import ListsIndexSheet from './lists-index-sheet';
import { parentSheetFor } from '../utils/sheet-parent';
// Renders the parent ("background") sheet behind the current route's top sheet
// on mobile. It lives in application.gjs, before {{outlet}}, so it survives the
// route transition and paints below the top sheet at equal z-index (DOM order
// is the tiebreaker).
//
// The stack is derived from the URL + session flags; nothing is pushed or
// popped imperatively. Only service-driven parents are rendered in v1 (see
// utils/sheet-parent.js).
export default class BackgroundSheetsComponent extends Component {
@service mapUi;
@service router;
get parentType() {
return (
parentSheetFor(this.router.currentRouteName, this.mapUi)?.type ?? null
);
}
get shouldRender() {
return (
this.args.isMobile &&
this.mapUi.isSidebarVisible &&
this.parentType !== null
);
}
@action
noop() {}
<template>
{{#if this.shouldRender}}
{{! inert makes the whole subtree non-interactive and hidden from
assistive tech, so taps and focus fall through to the top sheet. }}
<div class="sheet-background-layer" inert>
{{#if (eq this.parentType "search")}}
<PlacesSidebar
@places={{this.mapUi.searchResults}}
@scrollTop={{this.mapUi.getScrollPosition "search"}}
@background={{true}}
@onClose={{this.noop}}
@onSelect={{this.noop}}
/>
{{else if (eq this.parentType "lists-index")}}
<ListsIndexSheet @background={{true}} />
{{else if (eq this.parentType "menu")}}
<AppMenu @background={{true}} @onClose={{this.noop}} />
{{/if}}
</div>
{{/if}}
</template>
}
+9 -15
View File
@@ -3,12 +3,14 @@ import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';
import Icon from './icon';
import DrawerHeader from './drawer-header';
import ContributionPhoto from './contribution-photo';
import Modal from './modal';
import NostrConnect from './nostr-connect';
import eq from 'ember-truth-helpers/helpers/eq';
import not from 'ember-truth-helpers/helpers/not';
import restoreScroll from '../modifiers/restore-scroll';
import bottomSheet from '../modifiers/bottom-sheet';
export default class ContributionsTimelineComponent extends Component {
@tracked isNostrConnectModalOpen = false;
@@ -31,21 +33,13 @@ export default class ContributionsTimelineComponent extends Component {
}
<template>
<div class="sidebar">
<div class="sidebar-header has-back-btn">
<button type="button" class="back-btn" {{on "click" @onBack}}>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
<h2 class="sidebar-header-text-centered">
<span class="sidebar-header-icon-wrapper">
<Icon @name="user-check" @size={{20}} @color="#898989" />
</span>
My Contributions
</h2>
<button type="button" class="close-btn" {{on "click" @onClose}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<div class="sidebar" {{bottomSheet detent="medium" onDismiss=@onClose}}>
<DrawerHeader
@title="My Contributions"
@icon="user-check"
@onBack={{@onBack}}
@onClose={{@onClose}}
/>
<div class="sidebar-content" {{restoreScroll @scrollTop}}>
{{#if @isLoading}}
+114
View File
@@ -0,0 +1,114 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import Icon from './icon';
// The header row shared by every drawer/sidebar sheet.
//
// Desktop keeps the original two-button layout (optional back on the left,
// centered title, close on the right). On mobile the back button is dropped and
// the title is left-aligned, leaving a single trailing X that dismisses the top
// sheet: it goes back one level when there is a parent, otherwise it closes.
export default class DrawerHeaderComponent extends Component {
@service viewport;
get isMobile() {
return this.viewport.isMobile;
}
get hasBack() {
return typeof this.args.onBack === 'function';
}
// Only desktop keeps the back button (and the centered title it implies).
get desktopWithBack() {
return !this.isMobile && this.hasBack;
}
get iconColor() {
return this.args.iconColor ?? '#898989';
}
get variantClass() {
return this.args.variant ? `sidebar-header-${this.args.variant}` : '';
}
// The trailing X. On mobile it is the "back" affordance.
get primaryAction() {
if (this.isMobile && this.hasBack) {
return this.args.onBack;
}
return this.args.onClose;
}
get primaryActionLabel() {
if (this.isMobile && this.hasBack) {
return 'Back';
}
return 'Close';
}
<template>
<div
class="sidebar-header
{{if @noBorder 'no-border'}}
{{if this.desktopWithBack 'has-back-btn'}}
{{this.variantClass}}"
>
{{#if this.desktopWithBack}}
<button
type="button"
class="back-btn"
aria-label="Back"
{{on "click" @onBack}}
>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
{{/if}}
{{#if this.isMobile}}
{{#if @title}}
<h2 class="sidebar-header-title">
{{#if @logo}}
<span class="app-logo-icon">{{@logo}}</span>
{{/if}}
{{#if @icon}}
<Icon @name={{@icon}} @size={{20}} @color={{this.iconColor}} />
{{/if}}
<span class="sidebar-header-title-text">{{@title}}</span>
</h2>
{{/if}}
{{else if this.desktopWithBack}}
{{#if @title}}
<h2 class="sidebar-header-text-centered">
{{#if @icon}}
<span class="sidebar-header-icon-wrapper">
<Icon @name={{@icon}} @size={{20}} @color={{this.iconColor}} />
</span>
{{/if}}
{{@title}}
</h2>
{{/if}}
{{else if @title}}
<h2>
{{#if @logo}}
<span class="app-logo-icon">{{@logo}}</span>
{{/if}}
{{#if @icon}}
<Icon @name={{@icon}} @size={{20}} @color={{this.iconColor}} />
{{/if}}
{{@title}}
</h2>
{{/if}}
<button
type="button"
class="close-btn"
aria-label={{this.primaryActionLabel}}
{{on "click" this.primaryAction}}
>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
</template>
}
+133
View File
@@ -0,0 +1,133 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { htmlSafe } from '@ember/template';
import DrawerHeader from './drawer-header';
import restoreScroll from '../modifiers/restore-scroll';
import bottomSheet from '../modifiers/bottom-sheet';
// The "Saved Places" collections index. Extracted from the route template so
// it can render both as the interactive top sheet and as an inert background
// sheet behind a list (see components/background-sheets.gjs).
export default class ListsIndexSheetComponent extends Component {
@service storage;
@service router;
@service mapUi;
savedList = {
id: 'saved',
title: 'Saved',
color: 'var(--default-list-color)',
};
styleFor(color) {
const finalColor =
color ||
getComputedStyle(document.documentElement)
.getPropertyValue('--default-list-color')
.trim();
return htmlSafe(`background-color: ${finalColor}`);
}
get scrollTop() {
return this.mapUi.getScrollPosition('lists-index');
}
@action
selectList(listId) {
// Scope to the interactive top sheet: a background parent may also have a
// .sidebar-content, and that is not the element being scrolled.
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
if (sidebarContent) {
this.mapUi.saveScrollPosition('lists-index', sidebarContent.scrollTop);
}
this.router.transitionTo('lists.list', listId);
}
@action
close() {
this.router.transitionTo('index');
}
@action
backToMenu() {
this.router.transitionTo('menu');
}
<template>
<div
class="sidebar"
{{bottomSheet
detent="medium"
onDismiss=this.close
background=@background
}}
>
<DrawerHeader
@title="Saved Places"
@icon="bookmark"
@onBack={{this.backToMenu}}
@onClose={{this.close}}
/>
<div class="sidebar-content" {{restoreScroll this.scrollTop}}>
<ul class="places-list">
<li>
<button
type="button"
class="lists-index-item"
{{on "click" (fn this.selectList this.savedList.id)}}
>
<div class="lists-index-item-left">
{{! template-lint-disable no-inline-styles }}
<span
class="list-color-dot"
style={{this.styleFor this.savedList.color}}
></span>
<div class="lists-index-name">{{this.savedList.title}}</div>
</div>
<div class="lists-index-count">
{{#if this.storage.savedPlaces.length}}
{{this.storage.savedPlaces.length}}
places
{{else}}
empty
{{/if}}
</div>
</button>
</li>
{{#each this.storage.lists as |list|}}
<li>
<button
type="button"
class="lists-index-item"
{{on "click" (fn this.selectList list.id)}}
>
<div class="lists-index-item-left">
{{! template-lint-disable no-inline-styles }}
<span
class="list-color-dot"
style={{this.styleFor list.color}}
></span>
<div class="lists-index-name">{{list.title}}</div>
</div>
<div class="lists-index-count">
{{#if list.placeRefs.length}}
{{list.placeRefs.length}}
places
{{else}}
empty
{{/if}}
</div>
</button>
</li>
{{/each}}
</ul>
</div>
</div>
</template>
}
+39 -16
View File
@@ -42,6 +42,7 @@ export default class MapComponent extends Component {
crosshairElement;
crosshairOverlay;
ignoreNextMapClick = false;
lastSheetSnapSeq;
setupMap = modifier((element) => {
if (this.mapInstance) return;
@@ -718,13 +719,12 @@ export default class MapComponent extends Component {
size[0] * 0.15, // Left
];
// Mobile: Bottom sheet covers 50% of the screen height
// Mobile: the bottom sheet covers `sheetInsetPx` pixels from the bottom.
if (size[0] <= 768) {
// We want the geometry to be centered in the top 50% of the screen.
// Top padding: 15% of the VISIBLE height (size[1] * 0.5)
const visibleHeight = size[1] * 0.5;
const inset = this.mapUi.sheetInsetPx;
const visibleHeight = Math.max(size[1] - inset, 1);
const topPadding = visibleHeight * 0.15;
const bottomPadding = size[1] * 0.5 + visibleHeight * 0.15; // Sheet + padding
const bottomPadding = inset + visibleHeight * 0.15;
padding[0] = topPadding;
padding[2] = bottomPadding;
@@ -801,17 +801,19 @@ export default class MapComponent extends Component {
let targetCenter = coords;
// Check if mobile (width <= 768px matches CSS)
// Mobile (width <= 768px matches CSS). The desktop sidebar branch below
// must never run here: it shifts the map center left to make room for the
// sidebar, which pushes the pin to the right edge on a phone. `inset` is 0
// until the sheet publishes its height, which is fine — it just centers.
if (size[0] <= 768) {
// On mobile, the bottom 50% is covered by the sheet.
// We want the pin to be in the center of the TOP 50% (visible area), minus the header.
const height = size[1];
const inset = this.mapUi.sheetInsetPx;
const headerEl = document.querySelector('.app-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 60;
// Visible area is from headerHeight to height / 2 (bottom sheet covers bottom 50%)
const visibleCenterY = headerHeight + (height / 2 - headerHeight) / 2;
// Visible area runs from the header down to the top of the sheet.
const visibleHeight = height - inset;
const visibleCenterY = headerHeight + (visibleHeight - headerHeight) / 2;
// The map center is at y = height * 0.50.
// So the pin is "above" the center by (height/2 - visibleCenterY) pixels.
@@ -879,14 +881,17 @@ export default class MapComponent extends Component {
const headerEl = document.querySelector('.app-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 60;
// 1. Mobile Bottom Sheet Logic (Screen <= 768px)
// 1. Mobile Bottom Sheet Logic (Screen <= 768px). Always taken on mobile so
// the desktop sidebar branch (which shifts the pin right) can never run
// there, even before the sheet has published its inset.
if (size[0] <= 768) {
const height = size[1];
const splitPoint = height / 2;
const inset = this.mapUi.sheetInsetPx;
const visibleHeight = height - inset;
// If in bottom half
if (pixel[1] > splitPoint) {
targetPixelY = headerHeight + (height / 2 - headerHeight) / 2; // Target: Center of visible area above bottom sheet
// If obscured by the bottom sheet
if (pixel[1] > visibleHeight) {
targetPixelY = headerHeight + (visibleHeight - headerHeight) / 2; // Target: Center of visible area above bottom sheet
needsPan = true;
}
}
@@ -1006,6 +1011,23 @@ export default class MapComponent extends Component {
}
});
// Keep the CSS `--sheet-inset` custom property on the map container in sync
// with the mobile bottom sheet. The crosshair (a child of the map container)
// reads it via CSS. When a drag settles (snapSeq changes) we pan the selected
// pin back into the visible area, but never per drag frame.
syncSheetInset = modifier((element, [inset, snapSeq]) => {
element.style.setProperty('--sheet-inset', `${inset || 0}px`);
const isInitialRun = this.lastSheetSnapSeq === undefined;
if (!isInitialRun && snapSeq !== this.lastSheetSnapSeq) {
const place = this.mapUi.selectedPlace;
if (place && place.lat && place.lon) {
this.panIfObscured(fromLonLat([place.lon, place.lat]));
}
}
this.lastSheetSnapSeq = snapSeq;
});
decodeVectorTileOsmFeature(feature) {
if (!feature?.getId || !feature?.get) {
return { decoded: null, reason: 'feature does not expose get()/getId()' };
@@ -1387,6 +1409,7 @@ export default class MapComponent extends Component {
{{this.updateSelectedPin}}
{{this.syncPulse}}
{{this.syncCreationMode}}
{{this.syncSheetInset this.mapUi.sheetInsetPx this.mapUi.sheetSnapSeq}}
></div>
</template>
}
+25 -1
View File
@@ -38,6 +38,7 @@ export default class PlaceDetails extends Component {
@service mapUi;
@service toast;
@service router;
@service viewport;
@tracked isEditing = false;
@tracked showLists = false;
@tracked showShareMenu = false;
@@ -105,7 +106,7 @@ export default class PlaceDetails extends Component {
// Allow DOM to update first, then scroll to the top to show the new photo in the carousel
setTimeout(() => {
const sidebar = document.querySelector('.sidebar-content');
const sidebar = document.querySelector('.sheet-top .sidebar-content');
if (sidebar) {
sidebar.scrollTop = 0;
}
@@ -132,6 +133,10 @@ export default class PlaceDetails extends Component {
return this.args.place || {};
}
get isMobile() {
return this.viewport.isMobile;
}
get saveablePlace() {
if (this.place.createdAt) {
return this.place;
@@ -603,6 +608,25 @@ export default class PlaceDetails extends Component {
@onSave={{this.saveChanges}}
@onCancel={{this.cancelEditing}}
/>
{{else if this.isMobile}}
{{! Mobile: the name is the drawer header title, so the body starts at
the type and the photos sit directly below it. }}
<p class="place-type">
{{this.type}}
</p>
<PhotoCarousel
@variant="inline"
@photos={{this.photos}}
@name={{this.name}}
@resetKey={{this.place.osmId}}
@scrollToEventId={{this.focusPhotoEventId}}
@onPhotoClick={{this.openGallery}}
/>
{{#if this.showDescription}}
<p class="place-description">
{{this.place.description}}
</p>
{{/if}}
{{else}}
<PhotoCarousel
@variant="inline"
+53 -51
View File
@@ -5,20 +5,21 @@ import { on } from '@ember/modifier';
import { fn } from '@ember/helper';
import or from 'ember-truth-helpers/helpers/or';
import eq from 'ember-truth-helpers/helpers/eq';
import and from 'ember-truth-helpers/helpers/and';
import not from 'ember-truth-helpers/helpers/not';
import PlaceDetails from './place-details';
import DrawerHeader from './drawer-header';
import Icon from './icon';
import humanizeOsmTag from '../helpers/humanize-osm-tag';
import { getLocalizedName, getPlaceType } from '../utils/osm';
import { getLocalizedName, getPlaceName, getPlaceType } from '../utils/osm';
import { NEARBY_CATEGORY } from '../utils/poi-categories';
import restoreScroll from '../modifiers/restore-scroll';
import bottomSheet from '../modifiers/bottom-sheet';
export default class PlacesSidebar extends Component {
@service storage;
@service router;
@service mapUi;
@service nostrData;
@service viewport;
@action
createNewPlace() {
@@ -158,6 +159,16 @@ export default class PlacesSidebar extends Component {
);
}
get isMobile() {
return this.viewport.isMobile;
}
// The place-details drawer header shows the place name as its title on
// mobile; on desktop the name stays in the body above the photo carousel.
get placeName() {
return getPlaceName(this.args.selectedPlace);
}
get hasHeaderPhoto() {
return (
this.args.selectedPlace &&
@@ -167,55 +178,46 @@ export default class PlacesSidebar extends Component {
}
<template>
<div class="sidebar">
<div
class="sidebar-header
{{if this.hasHeaderPhoto 'no-border'}}
{{if (and (not @selectedPlace) @onBack) 'has-back-btn'}}"
>
{{#if @selectedPlace}}
<button
type="button"
class="back-btn"
{{on "click" this.clearSelection}}
><Icon @name="arrow-left" @size={{20}} @color="#333" /></button>
{{else}}
{{#if @onBack}}
<button type="button" class="back-btn" {{on "click" @onBack}}><Icon
@name="arrow-left"
@size={{20}}
@color="#333"
/></button>
{{/if}}
{{#if @onBack}}
<h2 class="sidebar-header-text-centered">
<span class="sidebar-header-icon-wrapper">
<Icon
@name="bookmark"
@size={{20}}
@color={{or @color "#898989"}}
/>
</span>
{{@title}}
</h2>
{{else}}
{{#if this.isNearbySearch}}
<h2><Icon @name="target" @size={{20}} @color="#ea4335" />
Nearby</h2>
{{else}}
<h2><Icon @name="search" @size={{20}} @color="#333" />
Results</h2>
{{/if}}
{{/if}}
{{/if}}
<button type="button" class="close-btn" {{on "click" @onClose}}><Icon
@name="x"
@size={{20}}
@color="#333"
/></button>
</div>
<div
class="sidebar"
{{bottomSheet detent="medium" onDismiss=@onClose background=@background}}
>
{{#if @selectedPlace}}
<DrawerHeader
@title={{if this.isMobile this.placeName null}}
@variant="place"
@onBack={{this.clearSelection}}
@onClose={{@onClose}}
@noBorder={{or this.hasHeaderPhoto this.isMobile}}
/>
{{else if @onBack}}
<DrawerHeader
@title={{@title}}
@icon="bookmark"
@iconColor={{or @color "#898989"}}
@onBack={{@onBack}}
@onClose={{@onClose}}
/>
{{else if this.isNearbySearch}}
<DrawerHeader
@title="Nearby"
@icon="target"
@iconColor="#ea4335"
@onClose={{@onClose}}
/>
{{else}}
<DrawerHeader
@title="Results"
@icon="search"
@iconColor="#333"
@onClose={{@onClose}}
/>
{{/if}}
<div class="sidebar-content" {{restoreScroll @scrollTop}}>
<div
class="sidebar-content {{if @selectedPlace 'sidebar-content-place'}}"
{{restoreScroll @scrollTop}}
>
{{#if @selectedPlace}}
<PlaceDetails
@place={{@selectedPlace}}
+3 -1
View File
@@ -55,7 +55,9 @@ export default class ActivityController extends Controller {
selectItem(item) {
if (!item || !item.placeIdentifier) return;
const sidebarContent = document.querySelector('.sidebar-content');
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
if (sidebarContent) {
this.mapUi.saveScrollPosition('activity', sidebarContent.scrollTop);
}
+3 -1
View File
@@ -31,7 +31,9 @@ export default class ContributionsController extends Controller {
selectContribution(item) {
if (!item) return;
const sidebarContent = document.querySelector('.sidebar-content');
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
if (sidebarContent) {
this.mapUi.saveScrollPosition('contributions', sidebarContent.scrollTop);
}
+3 -1
View File
@@ -123,7 +123,9 @@ export default class ListsListController extends Controller {
@action
selectPlace(place) {
if (place) {
const sidebarContent = document.querySelector('.sidebar-content');
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
if (sidebarContent) {
this.mapUi.saveScrollPosition(
`list-${this.listId}`,
+646
View File
@@ -0,0 +1,646 @@
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;
}
}
+78
View File
@@ -22,6 +22,25 @@ export default class MapUiService extends Service {
@tracked loadingState = null;
@tracked isSidebarVisible = false;
@tracked isSidebarOpening = false;
// Mobile bottom-sheet state. `sheetInsetPx` is how many pixels the sheet
// currently covers from the bottom of the viewport, and `sheetSnapSeq` bumps
// whenever a drag settles so the map can react once (not per frame).
//
// `sheetDetents` remembers the detent per sheet, keyed by sheet identity
// (route name), so a sheet reopens at the size the user last dragged it to.
// `sheetDetent` mirrors the interactive (top) sheet's current detent. Both
// are intentionally NOT tracked: the modifier reads them while setting up to
// restore the previous position, and reading a tracked value there would
// re-run setup on every drag frame.
@tracked sheetInsetPx = 0;
@tracked sheetSnapSeq = 0;
sheetDetents = {};
sheetDetent = null;
// The modifier that currently owns the covered-height signal. A plain field
// so it is safe to write during render. Writes to sheetInsetPx/sheetSnapSeq
// are gated on this owner so a stale modifier can never corrupt the value
// (see the ownership-token note on the setters below).
sheetInsetOwner = null;
scrollPositions = {};
@@ -48,6 +67,65 @@ export default class MapUiService extends Service {
hideSidebar() {
this.isSidebarVisible = false;
this.isSidebarOpening = false;
this.resetSheet();
}
// --- Bottom-sheet covered-height signal ----------------------------------
//
// The Map reads sheetInsetPx during render, so the modifier must never write
// it (or sheetSnapSeq) while a render is in progress. Instead the modifier
// owns the slot and writes through an afterRender flush. Ownership makes the
// result independent of the order in which a stale modifier's release and a
// live modifier's flush land in the afterRender queue.
claimSheetInset(owner) {
this.sheetInsetOwner = owner;
}
setSheetInsetFor(owner, px) {
if (owner !== this.sheetInsetOwner) return;
const next = Math.max(0, Math.round(px));
// Guard against no-op writes: this build's tracked setter invalidates even
// when the value is unchanged, and the drag calls this per frame.
if (next !== this.sheetInsetPx) {
this.sheetInsetPx = next;
}
}
snapSheetFor(owner) {
if (owner !== this.sheetInsetOwner) return;
this.sheetSnapSeq++;
}
releaseSheetInset(owner) {
if (owner !== this.sheetInsetOwner) return;
this.sheetInsetOwner = null;
if (this.sheetInsetPx !== 0) {
this.sheetInsetPx = 0;
}
}
getSheetDetent(key) {
return this.sheetDetents[key] ?? null;
}
// A null name forgets the sheet (used when a drag dismisses it), so the next
// open falls back to the sheet's declared default.
setSheetDetent(key, name) {
if (key == null) return;
if (name == null) {
delete this.sheetDetents[key];
} else {
this.sheetDetents[key] = name;
}
this.sheetDetent = name ?? null;
}
resetSheet() {
this.sheetInsetOwner = null;
this.sheetInsetPx = 0;
this.sheetDetents = {};
this.sheetDetent = null;
}
selectPlace(place, options = {}) {
+33
View File
@@ -0,0 +1,33 @@
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';
// Must match the CSS `width <= 768px` query and the modifier's MOBILE_QUERY.
const MOBILE_QUERY = '(max-width: 768px)';
// Tracked breakpoint state so "desktop renders one sheet, mobile renders the
// stack" can re-render when the viewport crosses the breakpoint. Backed by
// matchMedia rather than a resize listener so it stays in sync with the CSS
// media queries that drive the sheet layout.
export default class ViewportService extends Service {
@tracked isMobile = false;
mediaQuery = null;
constructor() {
super(...arguments);
if (typeof window === 'undefined' || !window.matchMedia) return;
this.mediaQuery = window.matchMedia(MOBILE_QUERY);
this.isMobile = this.mediaQuery.matches;
this.onChange = (event) => {
this.isMobile = event.matches;
};
this.mediaQuery.addEventListener('change', this.onChange);
}
willDestroy() {
if (this.mediaQuery && this.onChange) {
this.mediaQuery.removeEventListener('change', this.onChange);
}
super.willDestroy(...arguments);
}
}
+111 -20
View File
@@ -23,6 +23,12 @@ html,
body {
height: 100%;
overscroll-behavior: none; /* Prevent pull-to-refresh on mobile */
/* The mobile bottom sheet is translated below the viewport edge while
collapsed/dragging; without this the page becomes scrollable. `hidden`
(not `clip`) keeps the viewport a scroll container so focused inputs can
still be scrolled into view when the mobile keyboard opens. */
overflow: hidden;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
@@ -471,7 +477,6 @@ body {
width: 100%;
right: 0;
border-radius: 16px 16px 0 0;
height: 66vh;
top: auto;
bottom: 0;
}
@@ -1115,15 +1120,23 @@ abbr[title] {
@media (width <= 768px) {
.photo-carousel.inline .photo-carousel-track {
scroll-snap-type: none;
gap: 2px;
gap: 6px;
background-color: var(--primary-background-color);
}
/* On mobile the inline carousel sits below the place type, not at the top of
the content, so it must not bleed upward — or sideways, so the photos line
up with the rest of the content. */
.photo-carousel.inline {
margin: 0 0 1rem;
}
.photo-carousel.inline .carousel-slide {
flex: 0 0 auto;
height: 100px;
width: auto;
scroll-snap-align: none;
border-radius: 4px; /* Match the action buttons below */
}
.photo-carousel.inline .carousel-slide.landscape {
@@ -1555,12 +1568,12 @@ span.icon {
}
@media (width <= 768px) {
/* Sidebar/Bottom Sheet is open (Mobile: Bottom 50%) */
/* Center Y = (height/2) / 2 = height/4 = 25% + half header height */
/* Sidebar/Bottom Sheet is open (Mobile). Center the crosshair in the area
above the sheet, whose covered height is exposed as --sheet-inset by the
map container's syncSheetInset modifier. */
.map-container.sidebar-open .map-crosshair {
left: 50%; /* Reset desktop shift */
top: calc(25% + 30px); /* 30px approx half header height */
top: calc((100% - var(--sheet-inset, 50vh)) / 2 + 30px);
}
}
@@ -1585,24 +1598,82 @@ button.create-place {
@media (width <= 768px) {
.sidebar {
width: 100%;
height: 50vh;
height: var(--sheet-height, 50vh);
box-shadow: 0 -2px 10px rgb(0 0 0 / 10%);
border-top-left-radius: 16px;
border-top-right-radius: 16px;
inset: auto 0 0;
transform: translateY(var(--sheet-offset, 0));
transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
touch-action: pan-y;
}
/* The bottom-sheet modifier owns the mobile entrance, so the desktop
slide-up keyframe must not run here. This selector matches the desktop
rule's specificity (0,2,0) and comes later in the file, so it wins. */
.sidebar-opening .sidebar {
animation: sidebar-slide-up-bottom 0.18s cubic-bezier(0.16, 1, 0.3, 1)
forwards;
animation: none;
}
/* While a drag is in progress the sheet must track the pointer exactly. */
.sidebar.sheet-dragging {
transition: none;
}
/* Injected by app/modifiers/bottom-sheet.js as the first child of the sheet.
Keep the gap above the bar, but tighten the gap toward the content. */
.sheet-handle {
display: flex;
flex: 0 0 auto;
align-items: flex-start;
justify-content: center;
box-sizing: border-box;
height: 16px;
padding-top: 9px;
background: transparent;
cursor: grab;
touch-action: none;
}
.sheet-handle::before {
content: '';
width: 40px;
height: 4px;
border-radius: 999px;
background: #ccc;
}
/* The header doubles as a drag surface; disable native scrolling there so
the gesture is not cancelled. The content is only scrollable while the
sheet is at its largest detent — below that, dragging anywhere on it
resizes the sheet (see the bottom-sheet modifier). */
.sidebar-header {
touch-action: none;
}
.sidebar-content {
touch-action: none;
overflow-y: auto;
/* Ensure content doesn't get hidden behind bottom safe areas on mobile */
padding-bottom: env(safe-area-inset-bottom, 20px);
}
.sidebar.sheet-at-max .sidebar-content {
touch-action: pan-y;
}
/* A background (parent) sheet sits behind the interactive top sheet. Its
z-index must stay below .sidebar (3100) and below the app menu's desktop
3200, and it must not react to pointer events (it is also `inert`). */
.sidebar.sheet-background {
z-index: 3050;
pointer-events: none;
}
.sheet-background-layer {
pointer-events: none;
}
}
/* Search Box Component */
@@ -2451,17 +2522,6 @@ button.create-place {
}
}
/* Snappy slide-up from bottom (Mobile) */
@keyframes sidebar-slide-up-bottom {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
/* Lists Index Sidebar Menu */
.lists-index-item {
width: 100%;
@@ -2546,6 +2606,37 @@ button.create-place {
align-items: center;
}
/* Left-aligned title used by the mobile header. The text is clipped with an
ellipsis so a long place name can't push the trailing button off-screen. */
.sidebar-header-title {
min-width: 0;
}
.sidebar-header-title-text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Place details uses the mobile header as a content title, not a nav bar:
it is compact, borderless (via no-border) and sized like the body title. */
@media (width <= 768px) {
.sidebar-header-place {
height: auto;
padding: 0.5rem 1rem 0.25rem;
}
.sidebar-header-place .sidebar-header-title {
font-size: 1.2rem;
}
/* The type sits directly under the name, so the content needs no top gap. */
.sidebar-content-place {
padding-top: 0;
}
}
/* Sidebar Loading State */
.sidebar-loading {
display: flex;
+52 -20
View File
@@ -3,14 +3,17 @@ import { pageTitle } from 'ember-page-title';
import Map from '#components/map';
import AppHeader from '#components/app-header';
import Toast from '#components/toast';
import BackgroundSheets from '#components/background-sheets';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { parentTransitionFor } from '../utils/sheet-parent';
export default class ApplicationComponent extends Component {
@service storage;
@service mapUi;
@service router;
@service viewport;
get isSidebarOpen() {
// We consider the sidebar "open" if we are in search, menu, lists, contributions or place routes AND it's visible.
@@ -47,35 +50,61 @@ export default class ApplicationComponent extends Component {
@action
handleOutsideClick() {
const name = this.router.currentRouteName;
if (
const isSheetRoute =
name === 'search' ||
name === 'place' ||
name === 'menu' ||
name === 'contributions' ||
name === 'activity' ||
name.startsWith('lists');
if (!isSheetRoute) return;
this.mapUi.clearSelection();
// Mobile: pop to the parent sheet and keep the session (and its remembered
// detent) alive, so the parent is revealed underneath instead of the whole
// stack being torn down. Routes with no parent fall through to close-all.
if (this.viewport.isMobile) {
const parent = parentTransitionFor(name, this.mapUi);
if (parent) {
this.transitionToParent(parent);
return;
}
}
// Desktop, or a mobile route with no parent: today's close-all.
this.mapUi.hideSidebar();
if (
name === 'menu' ||
name === 'contributions' ||
name === 'activity' ||
name.startsWith('lists')
) {
this.mapUi.clearSelection();
this.mapUi.hideSidebar();
if (
name === 'menu' ||
name === 'contributions' ||
name === 'activity' ||
name.startsWith('lists')
) {
this.router.transitionTo('index');
} else if (name === 'place') {
if (this.mapUi.returnToSearch && this.mapUi.currentSearch) {
this.router.transitionTo('search', {
queryParams: this.mapUi.currentSearch,
});
} else {
this.router.transitionTo('index');
} else if (name === 'place') {
if (this.mapUi.returnToSearch && this.mapUi.currentSearch) {
this.router.transitionTo('search', {
queryParams: this.mapUi.currentSearch,
});
} else {
this.router.transitionTo('index');
}
} else if (name === 'search' && this.mapUi.searchResults.length === 0) {
// An empty search has no markers worth keeping, so clear the route
this.router.replaceWith('index');
}
} else if (name === 'search' && this.mapUi.searchResults.length === 0) {
// An empty search has no markers worth keeping, so clear the route
this.router.replaceWith('index');
}
}
transitionToParent(parent) {
if (parent.model !== undefined) {
this.router.transitionTo(parent.name, parent.model);
} else if (parent.queryParams) {
this.router.transitionTo(parent.name, {
queryParams: parent.queryParams,
});
} else {
this.router.transitionTo(parent.name);
}
}
@@ -110,6 +139,9 @@ export default class ApplicationComponent extends Component {
<Toast />
{{! Rendered before the outlet so the top sheet paints above it. }}
<BackgroundSheets @isMobile={{this.viewport.isMobile}} />
{{outlet}}
</div>
</template>
+2 -117
View File
@@ -1,128 +1,13 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import Icon from '#components/icon';
import { htmlSafe } from '@ember/template';
import restoreScroll from '../../modifiers/restore-scroll';
import ListsIndexSheet from '#components/lists-index-sheet';
export default class ListsIndexTemplate extends Component {
@service storage;
@service router;
@service mapUi;
savedList = {
id: 'saved',
title: 'Saved',
color: 'var(--default-list-color)',
};
styleFor(color) {
const finalColor =
color ||
getComputedStyle(document.documentElement)
.getPropertyValue('--default-list-color')
.trim();
return htmlSafe(`background-color: ${finalColor}`);
}
get scrollTop() {
return this.mapUi.getScrollPosition('lists-index');
}
@action
selectList(listId) {
const sidebarContent = document.querySelector('.sidebar-content');
if (sidebarContent) {
this.mapUi.saveScrollPosition('lists-index', sidebarContent.scrollTop);
}
this.router.transitionTo('lists.list', listId);
}
@action
close() {
this.router.transitionTo('index');
}
@action
backToMenu() {
this.router.transitionTo('menu');
}
<template>
{{#if this.mapUi.isSidebarVisible}}
<div class="sidebar">
<div class="sidebar-header has-back-btn">
<button type="button" class="back-btn" {{on "click" this.backToMenu}}>
<Icon @name="arrow-left" @size={{20}} @color="#333" />
</button>
<h2 class="sidebar-header-text-centered">
<span class="sidebar-header-icon-wrapper">
<Icon @name="bookmark" @size={{20}} @color="#898989" />
</span>
Saved Places
</h2>
<button type="button" class="close-btn" {{on "click" this.close}}>
<Icon @name="x" @size={{20}} @color="#333" />
</button>
</div>
<div class="sidebar-content" {{restoreScroll this.scrollTop}}>
<ul class="places-list">
<li>
<button
type="button"
class="lists-index-item"
{{on "click" (fn this.selectList this.savedList.id)}}
>
<div class="lists-index-item-left">
{{! template-lint-disable no-inline-styles }}
<span
class="list-color-dot"
style={{this.styleFor this.savedList.color}}
></span>
<div class="lists-index-name">{{this.savedList.title}}</div>
</div>
<div class="lists-index-count">
{{#if this.storage.savedPlaces.length}}
{{this.storage.savedPlaces.length}}
places
{{else}}
empty
{{/if}}
</div>
</button>
</li>
{{#each this.storage.lists as |list|}}
<li>
<button
type="button"
class="lists-index-item"
{{on "click" (fn this.selectList list.id)}}
>
<div class="lists-index-item-left">
{{! template-lint-disable no-inline-styles }}
<span
class="list-color-dot"
style={{this.styleFor list.color}}
></span>
<div class="lists-index-name">{{list.title}}</div>
</div>
<div class="lists-index-count">
{{#if list.placeRefs.length}}
{{list.placeRefs.length}}
places
{{else}}
empty
{{/if}}
</div>
</button>
</li>
{{/each}}
</ul>
</div>
</div>
<ListsIndexSheet />
{{/if}}
</template>
}
+9 -12
View File
@@ -1,9 +1,9 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import PlaceEditForm from '#components/place-edit-form';
import Icon from '#components/icon';
import DrawerHeader from '#components/drawer-header';
import bottomSheet from '../../modifiers/bottom-sheet';
export default class PlaceNewTemplate extends Component {
@service router;
@@ -57,16 +57,13 @@ export default class PlaceNewTemplate extends Component {
<template>
{{#if this.mapUi.isSidebarVisible}}
<div class="sidebar">
<div class="sidebar-header">
<h2><Icon @name="plus-circle" @size={{20}} @color="#ea4335" />
New Place</h2>
<button
type="button"
class="close-btn"
{{on "click" this.close}}
><Icon @name="x" @size={{20}} @color="#333" /></button>
</div>
<div class="sidebar" {{bottomSheet detent="medium" onDismiss=this.close}}>
<DrawerHeader
@title="New Place"
@icon="plus-circle"
@iconColor="#ea4335"
@onClose={{this.close}}
/>
<div class="sidebar-content">
<p class="helper-text">
+3 -1
View File
@@ -10,7 +10,9 @@ export default class SearchTemplate extends Component {
@action
selectPlace(place) {
if (place) {
const sidebarContent = document.querySelector('.sidebar-content');
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
if (sidebarContent) {
this.mapUi.saveScrollPosition('search', sidebarContent.scrollTop);
}
+8
View File
@@ -33,6 +33,14 @@ export function getLocalizedName(tags, defaultName = 'Untitled Place') {
return defaultName;
}
// The display name for a place: an explicit title (saved places) wins, then the
// localized OSM name. Shared by the place details body and the drawer header so
// both agree on the title.
export function getPlaceName(place) {
if (!place) return 'Untitled Place';
return place.title || getLocalizedName(place.osmTags);
}
const PLACE_TYPE_KEYS = [
'craft',
'amenity',
+125
View File
@@ -0,0 +1,125 @@
// Pure geometry and snap math for the mobile bottom sheet.
//
// Kept free of DOM and service dependencies so the drag/snap behaviour can be
// unit tested directly. The modifier in app/modifiers/bottom-sheet.js owns the
// DOM and gesture wiring and delegates every decision here.
//
// The sheet is positioned with `transform: translateY(--sheet-offset)`, where
// the offset is the number of pixels pushed below the bottom of the viewport.
// An offset of 0 is fully expanded; an offset equal to the sheet height is
// fully hidden.
// Visible height of the sheet at each detent, as a fraction of the viewport.
// The expanded stop is the whole sheet, whose height is the viewport minus the
// small gap kept above it (see computeSheetHeight).
export const DETENT_FRACTIONS = {
expanded: 1,
medium: 0.55,
collapsed: 0.3,
};
// Fling speed (px/ms) at or above which a release moves one detent in the
// direction of the gesture instead of snapping to the nearest detent.
export const FLING_THRESHOLD = 0.5;
// How far (as a fraction of the sheet height) the user must drag past the
// collapsed detent to dismiss the sheet on release.
export const DISMISS_EXTRA_FRACTION = 0.15;
export function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
// The sheet fills the viewport down from `topGap` pixels, so a fully expanded
// sheet reaches up to the top of the search field while leaving that strip
// visible above it.
export function computeSheetHeight(viewportHeight, topGap = 0) {
return Math.max(0, Math.round(viewportHeight - topGap));
}
// Build the list of reachable detents for a given viewport and sheet height.
// Returns entries sorted by ascending offset (expanded first) with any
// duplicate offsets removed, so a very short sheet cannot produce two identical
// stops.
export function computeDetentLayout({
viewportHeight,
sheetHeight,
detents = DETENT_FRACTIONS,
}) {
const entries = Object.entries(detents).map(([name, fraction]) => {
const visibleHeight = Math.min(
Math.round(fraction * viewportHeight),
sheetHeight
);
const offset = clamp(sheetHeight - visibleHeight, 0, sheetHeight);
return { name, fraction, visibleHeight, offset };
});
entries.sort((a, b) => a.offset - b.offset);
const seen = new Set();
const layout = entries.filter((entry) => {
if (seen.has(entry.offset)) return false;
seen.add(entry.offset);
return true;
});
// Floor rule: a sheet always has at least one reachable open position.
if (layout.length === 0) {
layout.push({
name: 'collapsed',
fraction: detents.collapsed,
visibleHeight: sheetHeight,
offset: 0,
});
}
return layout;
}
export function findDetent(layout, name) {
return layout.find((detent) => detent.name === name) ?? null;
}
export function nearestDetentIndex(layout, offset) {
let nearest = 0;
let best = Infinity;
layout.forEach((detent, index) => {
const distance = Math.abs(detent.offset - offset);
if (distance < best) {
best = distance;
nearest = index;
}
});
return nearest;
}
// Resolve where a released drag should settle.
//
// `velocity` is in px/ms and positive means downward. Returns a detent name, or
// the string 'dismissed' when the sheet should close instead of snapping.
export function resolveSnap({
offset,
velocity,
layout,
sheetHeight,
flingThreshold = FLING_THRESHOLD,
dismissExtraFraction = DISMISS_EXTRA_FRACTION,
}) {
const collapsed = layout[layout.length - 1];
const dismissOffset = collapsed.offset + dismissExtraFraction * sheetHeight;
if (offset >= dismissOffset) return 'dismissed';
if (velocity >= flingThreshold && offset > collapsed.offset) {
return 'dismissed';
}
const nearest = nearestDetentIndex(layout, offset);
if (velocity <= -flingThreshold) {
return layout[Math.max(0, nearest - 1)].name;
}
if (velocity >= flingThreshold) {
return layout[Math.min(layout.length - 1, nearest + 1)].name;
}
return layout[nearest].name;
}
+65
View File
@@ -0,0 +1,65 @@
// Which sheet sits behind the current route's sheet on mobile.
//
// The URL stays authoritative: the stack is derived from the current route plus
// the map-ui session flags, never pushed or popped imperatively. This module is
// the single source of truth for both the background renderer
// (components/background-sheets.gjs) and the mobile outside-tap behaviour
// (templates/application.gjs).
//
// v1 only renders service-driven parents: the search results (map-ui), the
// lists index (storage) and the app menu (self-contained). A place opened from
// a list / contributions / activity timeline is deliberately parentless: those
// parents are controller-driven, so revealing them needs a data hand-off that
// is out of scope here. The pop still navigates to them; it just hard-cuts
// instead of revealing a background sheet.
// Routes whose parent sheet is the app menu.
const MENU_CHILD_ROUTES = new Set(['lists.index', 'contributions', 'activity']);
// The parent sheet to render behind `routeName`, or null when there is none.
// Returns { type: 'search' | 'lists-index' | 'menu' }.
export function parentSheetFor(routeName, mapUi) {
if (routeName === 'place') {
if (mapUi.returnToSearch && mapUi.currentSearch) {
return { type: 'search' };
}
return null;
}
if (routeName === 'lists.list') {
return { type: 'lists-index' };
}
if (MENU_CHILD_ROUTES.has(routeName)) {
return { type: 'menu' };
}
return null;
}
// The route an outside tap should pop to on mobile, or null when the current
// route has no parent (the sheet should close instead). This is broader than
// parentSheetFor: it also covers controller-driven parents that are not
// rendered as background sheets, so the session still survives the pop.
// Returns a transition descriptor: { name, model? } or { name, queryParams }.
export function parentTransitionFor(routeName, mapUi) {
if (routeName === 'place') {
if (mapUi.returnToSearch && mapUi.currentSearch) {
return { name: 'search', queryParams: mapUi.currentSearch };
}
if (mapUi.returnToRoute) {
return { ...mapUi.returnToRoute };
}
return null;
}
if (routeName === 'lists.list') {
return { name: 'lists.index' };
}
if (MENU_CHILD_ROUTES.has(routeName)) {
return { name: 'menu' };
}
return null;
}
+6 -4
View File
@@ -99,8 +99,10 @@ module('Acceptance | activity', function (hooks) {
await visit('/activity');
assert.strictEqual(currentURL(), '/activity');
assert.dom('.sidebar').exists('Sidebar is rendered');
assert.dom('.sidebar-header-text-centered').includesText('Activity');
assert.dom('.sheet-top').exists('Sidebar is rendered');
assert
.dom('.sheet-top .sidebar-header-text-centered')
.includesText('Activity');
});
test('activity items are rendered as zap rows', async function (assert) {
@@ -118,14 +120,14 @@ module('Acceptance | activity', function (hooks) {
await visit('/activity');
assert.strictEqual(currentURL(), '/activity');
await click('.sidebar-header .close-btn');
await click('.sheet-top .sidebar-header .close-btn');
assert.strictEqual(currentURL(), '/', 'Returns to index');
});
test('clicking back button returns to menu', async function (assert) {
await visit('/activity');
await click('.sidebar-header .back-btn');
await click('.sheet-top .sidebar-header .back-btn');
assert.strictEqual(currentURL(), '/menu', 'Returns to menu');
});
+602
View File
@@ -0,0 +1,602 @@
import { module, test } from 'qunit';
import {
visit,
click,
currentURL,
triggerEvent,
waitFor,
waitUntil,
} from '@ember/test-helpers';
import { setupApplicationTest } from 'marco/tests/helpers';
import { computeDetentLayout } from 'marco/utils/sheet-detents';
import Service from '@ember/service';
import sinon from 'sinon';
class MockOsmService extends Service {
async getNearbyPois() {
return [
{
osmId: '123',
lat: 1,
lon: 1,
osmTags: { name: 'Test Place', amenity: 'cafe' },
osmType: 'node',
},
];
}
async getPoiById() {
return null;
}
async fetchOsmObject(id, type) {
return {
osmId: id,
osmType: type,
lat: 1,
lon: 1,
osmTags: { name: 'Test Place' },
title: 'Test Place',
};
}
}
class MockStorageService extends Service {
initialSyncDone = true;
savedPlaces = [];
findPlaceById() {
return null;
}
isPlaceSaved() {
return false;
}
loadPlacesInBounds() {
return [];
}
get placesInView() {
return [];
}
rs = {
on: () => {},
};
}
const MOBILE_QUERY = '(max-width: 768px)';
// @ember/test-helpers 5.4 has no setViewport helper, so simulate the mobile
// media query directly. The bottom-sheet modifier reads window.matchMedia at
// setup, so this must be installed before the route is visited.
function installMobileMatchMedia() {
return sinon.stub(window, 'matchMedia').callsFake((query) => ({
matches: typeof query === 'string' && query.includes(MOBILE_QUERY),
media: query,
onchange: null,
addEventListener() {},
removeEventListener() {},
addListener() {},
removeListener() {},
dispatchEvent() {
return false;
},
}));
}
module('Acceptance | bottom sheet', function (hooks) {
setupApplicationTest(hooks);
hooks.beforeEach(function () {
this.owner.register('service:osm', MockOsmService);
this.owner.register('service:storage', MockStorageService);
});
test('does not inject the drag handle at desktop width', async function (assert) {
await visit('/menu');
assert.dom('.sidebar').exists('sheet is rendered');
assert
.dom('[data-test-sheet-handle]')
.doesNotExist('no drag handle on desktop');
});
test('injects a handle and a pixel offset on mobile', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/menu');
await waitUntil(() => mapUi.sheetDetent !== null);
assert.dom('[data-test-sheet-handle]').exists('drag handle is injected');
const sheet = document.querySelector('.sidebar');
const offset = sheet.style.getPropertyValue('--sheet-offset');
assert.true(
/px$/.test(offset),
`--sheet-offset is a pixel value (${offset})`
);
assert.strictEqual(
mapUi.sheetDetent,
'medium',
'the app menu opens at the medium detent'
);
} finally {
matchMediaStub.restore();
}
});
test('dragging the handle moves the sheet to another detent', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/menu');
await waitUntil(() => mapUi.sheetDetent !== null);
const sheet = document.querySelector('.sidebar');
const handle = sheet.querySelector('[data-test-sheet-handle]');
const before = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
// Drag downward well past the threshold. Pointer events bubble to the
// window-level listeners the modifier installs on pointerdown. The first
// small move crosses the drag threshold (which rebases the gesture on the
// live offset); the second move performs the actual drag.
await triggerEvent(handle, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 100,
button: 0,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 110,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 370,
});
await triggerEvent(handle, 'pointerup', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 370,
});
const after = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
assert.true(after > before, `sheet moved down (${before} -> ${after})`);
assert.notStrictEqual(
mapUi.sheetDetent,
'medium',
'sheet left its opening detent'
);
// The inset is published on a deferred animation-frame flush.
await waitUntil(() => mapUi.sheetInsetPx > 0);
assert.true(mapUi.sheetInsetPx > 0, 'map inset is reported');
} finally {
matchMediaStub.restore();
}
});
test('dragging the content resizes the sheet below the largest detent', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/menu');
await waitUntil(() => mapUi.sheetDetent === 'medium');
const sheet = document.querySelector('.sheet-top');
assert
.dom('.sheet-top')
.doesNotHaveClass('sheet-at-max', 'not at the largest detent');
const content = sheet.querySelector('.sidebar-content');
const before = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
// Drag the content itself (not the handle) downward.
await triggerEvent(content, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 100,
button: 0,
});
await triggerEvent(content, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 110,
});
await triggerEvent(content, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 300,
});
await triggerEvent(content, 'pointerup', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 300,
});
const after = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
assert.true(after > before, `sheet moved down (${before} -> ${after})`);
assert.notStrictEqual(
mapUi.sheetDetent,
'medium',
'sheet left its opening detent'
);
} finally {
matchMediaStub.restore();
}
});
test('dragging a list row resizes the sheet (mobile)', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/search?lat=1&lon=1');
await waitUntil(() => mapUi.sheetDetent === 'medium');
const sheet = document.querySelector('.sheet-top');
const row = sheet.querySelector('.place-item');
const before = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
// A list row is a <button>; it must still start a sheet drag.
await triggerEvent(row, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 100,
button: 0,
});
await triggerEvent(row, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 110,
});
await triggerEvent(row, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 300,
});
await triggerEvent(row, 'pointerup', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 300,
});
const after = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
assert.true(after > before, `sheet moved down (${before} -> ${after})`);
assert.notStrictEqual(
mapUi.sheetDetent,
'medium',
'sheet left its opening detent'
);
} finally {
matchMediaStub.restore();
}
});
test('pulling the content down at the largest detent shrinks the sheet', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
// Open the menu at its largest detent.
mapUi.setSheetDetent('menu', 'expanded');
await visit('/menu');
await waitUntil(() => mapUi.sheetDetent === 'expanded');
const sheet = document.querySelector('.sheet-top');
assert
.dom('.sheet-top')
.hasClass('sheet-at-max', 'marked as at the largest detent');
const content = sheet.querySelector('.sidebar-content');
assert.strictEqual(
content.scrollTop,
0,
'content is scrolled to the top'
);
const before = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
// Pull the content down: overscroll shrinks the sheet instead of scrolling.
await triggerEvent(content, 'pointerdown', {
pointerId: 2,
pointerType: 'touch',
isPrimary: true,
clientY: 100,
button: 0,
});
await triggerEvent(content, 'pointermove', {
pointerId: 2,
pointerType: 'touch',
isPrimary: true,
clientY: 110,
});
await triggerEvent(content, 'pointermove', {
pointerId: 2,
pointerType: 'touch',
isPrimary: true,
clientY: 400,
});
await triggerEvent(content, 'pointerup', {
pointerId: 2,
pointerType: 'touch',
isPrimary: true,
clientY: 400,
});
const after = parseFloat(sheet.style.getPropertyValue('--sheet-offset'));
assert.true(after > before, `sheet shrank (${before} -> ${after})`);
assert.notStrictEqual(
mapUi.sheetDetent,
'expanded',
'sheet left the largest detent'
);
} finally {
matchMediaStub.restore();
}
});
test('opening a place from search results does not crash (mobile)', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/search?lat=1&lon=1');
assert.dom('.place-item').exists('search results are rendered');
// This is the search→place transition that used to throw the
// backtracking assertion (Map re-renders in the same pass that installs
// the new sheet's modifier). click() already settles.
await click('.place-item');
assert.dom('.sheet-top').exists('the place sheet is rendered');
assert.ok(currentURL().includes('/place/'), 'navigated to the place');
await waitUntil(() => mapUi.sheetInsetPx > 0);
assert.true(
mapUi.sheetInsetPx > 0,
'the map inset reflects the open sheet'
);
} finally {
matchMediaStub.restore();
}
});
test('opening a place keeps the search sheet stacked behind it (mobile)', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/search?lat=1&lon=1');
assert.dom('.place-item').exists('search results are rendered');
await click('.place-item');
await waitUntil(() => mapUi.sheetDetent === 'medium');
assert.dom('.sheet-top').exists('the interactive top sheet is marked');
assert
.dom('.sheet-top.sheet-background')
.doesNotExist('the top sheet is not a background sheet');
assert
.dom('.sheet-background')
.exists('the parent sheet is rendered behind the top sheet');
assert
.dom('.sheet-background-layer[inert]')
.exists('the background layer is inert');
assert
.dom('.sheet-background .place-item')
.exists('the parent shows the search results');
// Place details opens at medium, and the background is pinned to the
// minimum so it can never peek above the top sheet. Read the sheet height
// the modifier wrote rather than recomputing the geometry.
const top = document.querySelector('.sheet-top');
const background = document.querySelector('.sheet-background');
const sheetHeight = parseFloat(
top.style.getPropertyValue('--sheet-height')
);
const layout = computeDetentLayout({
viewportHeight: window.innerHeight,
sheetHeight,
});
const mediumOffset = layout.find((d) => d.name === 'medium')?.offset;
const minimumOffset = layout[layout.length - 1].offset;
await waitUntil(
() =>
parseFloat(top.style.getPropertyValue('--sheet-offset')) ===
mediumOffset
);
assert.strictEqual(
parseFloat(top.style.getPropertyValue('--sheet-offset')),
mediumOffset,
'place details opens at the medium detent'
);
assert.strictEqual(
parseFloat(background.style.getPropertyValue('--sheet-offset')),
minimumOffset,
'the background sheet is minimized'
);
} finally {
matchMediaStub.restore();
}
});
test('background sheets stay minimized when the top sheet is taller (mobile)', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/search?lat=1&lon=1');
await click('.place-item');
await waitUntil(() => mapUi.sheetDetent === 'medium');
const top = document.querySelector('.sheet-top');
const handle = top.querySelector('[data-test-sheet-handle]');
const background = document.querySelector('.sheet-background');
const backgroundBefore = parseFloat(
background.style.getPropertyValue('--sheet-offset')
);
const topBefore = parseFloat(
top.style.getPropertyValue('--sheet-offset')
);
// Drag the top sheet all the way up.
await triggerEvent(handle, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 1000,
button: 0,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 990,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 0,
});
await triggerEvent(handle, 'pointerup', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 0,
});
await waitUntil(() => mapUi.sheetDetent !== 'medium');
const topAfter = parseFloat(top.style.getPropertyValue('--sheet-offset'));
const backgroundAfter = parseFloat(
background.style.getPropertyValue('--sheet-offset')
);
assert.true(topAfter < topBefore, 'the top sheet expanded');
assert.true(
topAfter < backgroundAfter,
'the top sheet is more visible than the background'
);
assert.strictEqual(
backgroundAfter,
backgroundBefore,
'the background stayed minimized'
);
} finally {
matchMediaStub.restore();
}
});
test('tapping the map on mobile pops to the parent search sheet (mobile)', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
window.localStorage.setItem(
'marco:map-view',
JSON.stringify({ center: [13.4, 52.5], zoom: 18 })
);
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/search?lat=1&lon=1');
await click('.place-item');
assert.ok(currentURL().includes('/place/'), 'on the place sheet');
await waitUntil(() => mapUi.sheetDetent === 'medium');
assert.strictEqual(
mapUi.sheetDetent,
'medium',
'place details opened at the medium detent'
);
await waitFor('canvas', { timeout: 2000 });
const canvas = document.querySelector('canvas');
await triggerEvent(canvas, 'pointerdown', {
clientX: 200,
clientY: 120,
button: 0,
isPrimary: true,
});
await triggerEvent(canvas, 'pointerup', {
clientX: 200,
clientY: 120,
button: 0,
isPrimary: true,
});
await triggerEvent(canvas, 'click', {
clientX: 200,
clientY: 120,
bubbles: true,
});
await waitUntil(() => currentURL().includes('/search'));
assert.ok(
currentURL().includes('/search'),
'the outside tap popped back to the search route'
);
await waitUntil(() => mapUi.sheetDetent === 'medium');
assert.strictEqual(
mapUi.sheetDetent,
'medium',
'the search sheet returns to its remembered medium detent'
);
assert.dom('.sheet-top').exists('a top sheet is still open');
} finally {
matchMediaStub.restore();
window.localStorage.removeItem('marco:map-view');
}
});
test('dragging past the collapsed detent dismisses the sheet', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
const mapUi = this.owner.lookup('service:map-ui');
await visit('/menu');
await waitUntil(() => mapUi.sheetDetent !== null);
const sheet = document.querySelector('.sidebar');
const handle = sheet.querySelector('[data-test-sheet-handle]');
await triggerEvent(handle, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 100,
button: 0,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 110,
});
await triggerEvent(handle, 'pointermove', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 1400,
});
await triggerEvent(handle, 'pointerup', {
pointerId: 1,
pointerType: 'touch',
isPrimary: true,
clientY: 1400,
});
assert.strictEqual(
mapUi.sheetDetent,
null,
'the remembered detent is cleared on dismiss'
);
// dismiss() waits for the slide-out transition before calling onDismiss,
// so settled() is not enough.
await waitUntil(() => !document.querySelector('.sidebar'), {
timeout: 3000,
});
assert.dom('.sidebar').doesNotExist('the sheet closed after dismissing');
} finally {
matchMediaStub.restore();
}
});
});
+11 -9
View File
@@ -79,7 +79,7 @@ module('Acceptance | collections navigation', function (hooks) {
// 2. Open the App Menu overlay
await click('.menu-btn-integrated');
assert.dom('.sidebar.app-menu-pane').exists('App menu sidebar is open');
assert.dom('.sheet-top.app-menu-pane').exists('App menu sidebar is open');
assert
.dom('.app-menu')
.includesText('Saved Places', 'Menu contains Saved Places link');
@@ -88,7 +88,7 @@ module('Acceptance | collections navigation', function (hooks) {
await click(document.querySelectorAll('.app-menu button')[0]); // Click "Saved Places"
assert.strictEqual(currentURL(), '/lists', 'Transitions to /lists index');
assert
.dom('.sidebar-header-text-centered')
.dom('.sheet-top .sidebar-header-text-centered')
.includesText(
'Saved Places',
'Header is centered and titled Saved Places'
@@ -120,7 +120,7 @@ module('Acceptance | collections navigation', function (hooks) {
.hasText('Mountain Trail', 'Saved Places includes all saved places');
// 5. Go back to the Saved Places index
await click('.sidebar-header .back-btn');
await click('.sheet-top .sidebar-header .back-btn');
assert.strictEqual(currentURL(), '/lists', 'Goes back to /lists index');
// 6. Transition to a specific real list (Want to go)
@@ -141,15 +141,15 @@ module('Acceptance | collections navigation', function (hooks) {
.hasText('Saved place', 'Place type displays Saved place correctly');
// 8. Click back button in collection list header
await click('.sidebar-header .back-btn');
await click('.sheet-top .sidebar-header .back-btn');
assert.strictEqual(currentURL(), '/lists', 'Goes back to /lists index');
// 9. Click back button in collections index header
await click('.sidebar-header .back-btn');
await click('.sheet-top .sidebar-header .back-btn');
assert.strictEqual(currentURL(), '/menu', 'Goes back to main menu route');
// 10. Close sidebar
await click('.sidebar-header .close-btn');
await click('.sheet-top .sidebar-header .close-btn');
assert.strictEqual(currentURL(), '/', 'Sidebar closed and returned home');
});
@@ -325,7 +325,9 @@ module('Acceptance | collections navigation', function (hooks) {
await visit('/lists/to-go');
await waitFor('.places-list');
const sidebarContent = document.querySelector('.sidebar-content');
const sidebarContent = document.querySelector(
'.sheet-top .sidebar-content'
);
sidebarContent.scrollTop = 300;
assert.strictEqual(sidebarContent.scrollTop, 300, 'List is scrolled');
@@ -334,7 +336,7 @@ module('Acceptance | collections navigation', function (hooks) {
// then return via the back button.
const visibleItem = document.querySelectorAll('.place-item')[5];
await click(visibleItem);
await waitFor('.sidebar-content');
await waitFor('.sheet-top .sidebar-content');
await click('.back-btn');
await waitFor('.places-list');
@@ -342,7 +344,7 @@ module('Acceptance | collections navigation', function (hooks) {
await new Promise((resolve) => requestAnimationFrame(resolve));
await new Promise((resolve) => requestAnimationFrame(resolve));
const restored = document.querySelector('.sidebar-content');
const restored = document.querySelector('.sheet-top .sidebar-content');
assert.strictEqual(
restored.scrollTop,
300,
+4 -4
View File
@@ -94,7 +94,7 @@ module('Acceptance | contributions navigation', function (hooks) {
// Open the app menu
await click('.menu-btn-integrated');
assert.dom('.sidebar.app-menu-pane').exists('App menu sidebar is open');
assert.dom('.sheet-top.app-menu-pane').exists('App menu sidebar is open');
// Click "My Contributions"
const buttons = document.querySelectorAll('.app-menu button');
@@ -109,7 +109,7 @@ module('Acceptance | contributions navigation', function (hooks) {
'Transitions to /contributions'
);
assert
.dom('.sidebar-header-text-centered')
.dom('.sheet-top .sidebar-header-text-centered')
.includesText('My Contributions', 'Header shows the title');
// Contribution item should be visible
@@ -117,7 +117,7 @@ module('Acceptance | contributions navigation', function (hooks) {
assert.dom('.contribution-place').includesText('Test Place');
// Click back button -> returns to menu
await click('.sidebar-header .back-btn');
await click('.sheet-top .sidebar-header .back-btn');
assert.strictEqual(currentURL(), '/menu', 'Goes back to /menu');
});
@@ -152,7 +152,7 @@ module('Acceptance | contributions navigation', function (hooks) {
await visit('/contributions');
await waitFor('.sidebar');
await click('.sidebar-header .close-btn');
await click('.sheet-top .sidebar-header .close-btn');
assert.strictEqual(currentURL(), '/', 'Returns to index');
});
+222
View File
@@ -0,0 +1,222 @@
import { module, test } from 'qunit';
import { visit, click, currentURL, waitUntil } from '@ember/test-helpers';
import { setupApplicationTest } from 'marco/tests/helpers';
import Service from '@ember/service';
import sinon from 'sinon';
class MockOsmService extends Service {
async getNearbyPois() {
return [
{
osmId: '123',
lat: 1,
lon: 1,
osmTags: { name: 'Test Place', amenity: 'cafe' },
osmType: 'node',
},
];
}
async getPoiById() {
return null;
}
async fetchOsmObject(id, type) {
return {
osmId: id,
osmType: type,
lat: 1,
lon: 1,
osmTags: { name: 'Test Place' },
title: 'Test Place',
};
}
}
class MockStorageService extends Service {
initialSyncDone = true;
savedPlaces = [];
findPlaceById() {
return null;
}
isPlaceSaved() {
return false;
}
loadPlacesInBounds() {
return [];
}
get placesInView() {
return [];
}
rs = { on: () => {} };
}
const MOBILE_QUERY = '(max-width: 768px)';
// @ember/test-helpers 5.4 has no setViewport helper, so simulate the mobile
// media query directly. The viewport service reads window.matchMedia when it is
// first instantiated (during the application render), so this must be installed
// before the route is visited.
function installMobileMatchMedia() {
return sinon.stub(window, 'matchMedia').callsFake((query) => ({
matches: typeof query === 'string' && query.includes(MOBILE_QUERY),
media: query,
onchange: null,
addEventListener() {},
removeEventListener() {},
addListener() {},
removeListener() {},
dispatchEvent() {
return false;
},
}));
}
function makePhoto(id) {
return {
id,
pubkey: 'a'.repeat(64),
kind: 360,
created_at: 1,
tags: [
['i', 'osm:node:123'],
[
'imeta',
'url data:image/gif;base64,R0lGODlhAQABAAAAACw=',
'dim 800x600',
],
],
};
}
function clickSavedPlaces() {
const button = Array.from(document.querySelectorAll('.app-menu button')).find(
(b) => b.textContent.includes('Saved Places')
);
return click(button);
}
module('Acceptance | drawer header', function (hooks) {
setupApplicationTest(hooks);
hooks.beforeEach(function () {
this.owner.register('service:osm', MockOsmService);
this.owner.register('service:storage', MockStorageService);
});
test('mobile top-level drawer drops the back button and the X closes it', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
await visit('/menu');
assert.dom('.sheet-top .sidebar-header').exists('menu header is shown');
assert
.dom('.sheet-top .sidebar-header .back-btn')
.doesNotExist('no back button on mobile');
assert
.dom('.sheet-top .sidebar-header-title')
.includesText('Marco', 'title is shown');
await click('.sheet-top .sidebar-header .close-btn');
assert.strictEqual(
currentURL(),
'/',
'the X closed the top-level drawer'
);
} finally {
matchMediaStub.restore();
}
});
test('mobile X on a child drawer goes back to its parent', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
await visit('/menu');
await clickSavedPlaces();
assert.strictEqual(currentURL(), '/lists', 'on the lists index');
assert
.dom('.sheet-top .sidebar-header .back-btn')
.doesNotExist('no back button on mobile');
assert
.dom('.sheet-top .sidebar-header-title')
.includesText('Saved Places', 'title is shown');
await click('.sheet-top .sidebar-header .close-btn');
assert.strictEqual(
currentURL(),
'/menu',
'the X went back to the parent (menu), not index'
);
} finally {
matchMediaStub.restore();
}
});
test('mobile place details uses the place name as the header title', async function (assert) {
const matchMediaStub = installMobileMatchMedia();
try {
this.owner.lookup('service:nostr-data').placePhotos = [makePhoto('p1')];
await visit('/search?lat=1&lon=1');
await click('.place-item');
await waitUntil(() =>
document.querySelector('.sheet-top .sidebar-header-title')
);
assert
.dom('.sheet-top .sidebar-header-title')
.includesText('Test Place', 'the place name is the header title');
assert
.dom('.sheet-top .sidebar-header-place')
.exists('the header uses the compact place variant');
assert
.dom('.sheet-top .sidebar-content-place')
.exists('the content uses the place spacing');
assert
.dom('.sheet-top .sidebar-header .back-btn')
.doesNotExist('no back button on mobile');
assert
.dom('.sheet-top .sidebar-header.no-border')
.exists('the place details header is borderless');
assert
.dom('.sheet-top .place-details h3')
.doesNotExist('the name is not repeated in the body');
const type = document.querySelector(
'.sheet-top .place-details .place-type'
);
const carousel = document.querySelector(
'.sheet-top .place-details .photo-carousel'
);
assert.ok(type && carousel, 'the type and photo carousel are rendered');
assert.true(
Boolean(
type.compareDocumentPosition(carousel) &
Node.DOCUMENT_POSITION_FOLLOWING
),
'the photo carousel sits below the place type'
);
await click('.sheet-top .sidebar-header .close-btn');
await waitUntil(() => currentURL().includes('/search'));
assert.ok(
currentURL().includes('/search'),
'the X popped back to the search sheet'
);
} finally {
matchMediaStub.restore();
}
});
test('desktop keeps the back button and centered title', async function (assert) {
await visit('/menu');
await clickSavedPlaces();
assert.strictEqual(currentURL(), '/lists', 'on the lists index');
assert
.dom('.sheet-top .sidebar-header .back-btn')
.exists('back button is present on desktop');
assert
.dom('.sheet-top .sidebar-header-text-centered')
.includesText('Saved Places', 'title stays centered on desktop');
});
});
+1 -1
View File
@@ -61,7 +61,7 @@ module('Acceptance | map search reset', function (hooks) {
// 1. Visit a category search URL
await visit('/search?category=coffee&lat=52.52&lon=13.405');
assert.dom('.sidebar-header').includesText('Results');
assert.dom('.sheet-top .sidebar-header').includesText('Results');
assert.ok(
currentURL().includes('category=coffee'),
'URL should have category param'
+4 -4
View File
@@ -69,7 +69,7 @@ module('Acceptance | search', function (hooks) {
await visit('/search?q=Berlin');
assert.strictEqual(currentURL(), '/search?q=Berlin');
assert.dom('.sidebar-header h2').includesText('Results');
assert.dom('.sheet-top .sidebar-header h2').includesText('Results');
assert.dom('.places-list li').exists({ count: 2 });
assert.dom('.places-list li:first-child .place-name').hasText('Berlin');
});
@@ -116,7 +116,7 @@ module('Acceptance | search', function (hooks) {
await visit('/search?lat=52.52&lon=13.405');
assert.strictEqual(currentURL(), '/search?lat=52.52&lon=13.405');
assert.dom('.sidebar-header h2').includesText('Nearby');
assert.dom('.sheet-top .sidebar-header h2').includesText('Nearby');
assert.dom('.places-list li').exists({ count: 1 });
assert.dom('.places-list li .place-name').hasText('Nearby Cafe');
});
@@ -226,7 +226,7 @@ module('Acceptance | search', function (hooks) {
assert.dom('.places-list li').exists({ count: 1 });
assert.dom('.places-list li .place-name').hasText('Latte Art Cafe');
// Ensure it shows "Results" not "Nearby"
assert.dom('.sidebar-header h2').includesText('Results');
assert.dom('.sheet-top .sidebar-header h2').includesText('Results');
});
test('search error handling prevents opening empty panel and shows toast', async function (assert) {
@@ -441,7 +441,7 @@ module('Acceptance | search', function (hooks) {
await visit('/search?category=nearby&lat=52.52&lon=13.405');
assert.dom('.sidebar-header h2').includesText('Nearby');
assert.dom('.sheet-top .sidebar-header h2').includesText('Nearby');
assert.dom('.search-input').hasValue('Nearby', 'Input indicates Nearby');
// Closing the sidebar keeps the search (and its markers) active, so the
+143
View File
@@ -0,0 +1,143 @@
import { module, test } from 'qunit';
import {
computeDetentLayout,
computeSheetHeight,
findDetent,
nearestDetentIndex,
resolveSnap,
} from 'marco/utils/sheet-detents';
const VIEWPORT = 800;
// No top gap, so the sheet fills the viewport.
const SHEET = computeSheetHeight(VIEWPORT); // 800
// expanded: 800 - 800 = 0, medium: 800 - 440 = 360, collapsed: 800 - 240 = 560
const LAYOUT = computeDetentLayout({
viewportHeight: VIEWPORT,
sheetHeight: SHEET,
});
module('Unit | Utility | sheet-detents', function () {
test('computeSheetHeight fills the viewport minus the top gap', function (assert) {
assert.strictEqual(computeSheetHeight(800), 800);
assert.strictEqual(computeSheetHeight(800, 8), 792);
assert.strictEqual(computeSheetHeight(100, 200), 0, 'never negative');
});
test('computeDetentLayout produces ascending offsets with expanded first', function (assert) {
assert.deepEqual(
LAYOUT.map((detent) => detent.name),
['expanded', 'medium', 'collapsed'],
'detents are ordered by ascending offset'
);
assert.strictEqual(findDetent(LAYOUT, 'expanded').offset, 0);
assert.strictEqual(findDetent(LAYOUT, 'medium').offset, 360);
assert.strictEqual(findDetent(LAYOUT, 'collapsed').offset, 560);
});
test('computeDetentLayout keeps a single clamped detent for short sheets', function (assert) {
const layout = computeDetentLayout({
viewportHeight: VIEWPORT,
sheetHeight: 100,
});
assert.strictEqual(layout.length, 1, 'only one reachable position remains');
assert.strictEqual(
layout[0].offset,
0,
'the remaining detent is fully open'
);
assert.strictEqual(layout[0].visibleHeight, 100);
});
test('nearestDetentIndex picks the closest offset', function (assert) {
assert.strictEqual(nearestDetentIndex(LAYOUT, 10), 0, 'near expanded');
assert.strictEqual(nearestDetentIndex(LAYOUT, 300), 1, 'near medium');
assert.strictEqual(nearestDetentIndex(LAYOUT, 480), 2, 'near collapsed');
});
test('resolveSnap snaps to the nearest detent without velocity', function (assert) {
assert.strictEqual(
resolveSnap({
offset: 100,
velocity: 0,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'expanded'
);
assert.strictEqual(
resolveSnap({
offset: 290,
velocity: 0,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'medium'
);
assert.strictEqual(
resolveSnap({
offset: 490,
velocity: 0,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'collapsed'
);
});
test('resolveSnap flings one detent in the gesture direction', function (assert) {
assert.strictEqual(
resolveSnap({
offset: 300,
velocity: -0.8,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'expanded',
'a fast upward flick moves to the next detent up'
);
assert.strictEqual(
resolveSnap({
offset: 290,
velocity: 0.8,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'collapsed',
'a fast downward flick moves to the next detent down'
);
});
test('resolveSnap dismisses past the collapsed threshold', function (assert) {
assert.strictEqual(
resolveSnap({
offset: 700,
velocity: 0,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'dismissed',
'dragging well past collapsed dismisses'
);
assert.strictEqual(
resolveSnap({
offset: 570,
velocity: 0.6,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'dismissed',
'a fast downward flick past collapsed dismisses'
);
assert.strictEqual(
resolveSnap({
offset: 500,
velocity: 0,
layout: LAYOUT,
sheetHeight: SHEET,
}),
'collapsed',
'the same offset without velocity just collapses'
);
});
});